From 903b5065b95ad57d054d0bea7745cc1ddd9438de Mon Sep 17 00:00:00 2001 From: martbost Date: Wed, 30 Sep 2026 13:21:39 -0500 Subject: [PATCH] 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 --- .gitignore | 5 + Dockerfile | 10 ++ lib/faucet.js | 79 ++++++++++++++++ lib/game.js | 134 +++++++++++++++++++++++++++ lib/ledger.js | 132 ++++++++++++++++++++++++++ lib/polusd.js | 89 ++++++++++++++++++ lib/spawn.js | 43 +++++++++ lib/sso.js | 69 ++++++++++++++ lib/store.js | 28 ++++++ package-lock.json | 124 +++++++++++++++++++++++++ package.json | 14 +++ public/admin.html | 53 +++++++++++ public/admin.js | 41 +++++++++ public/index.html | 54 +++++++++++ public/play.html | 149 ++++++++++++++++++++++++++++++ public/play.js | 229 ++++++++++++++++++++++++++++++++++++++++++++++ public/site.css | 34 +++++++ server.js | 215 +++++++++++++++++++++++++++++++++++++++++++ test/run.js | 99 ++++++++++++++++++++ 19 files changed, 1601 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 lib/faucet.js create mode 100644 lib/game.js create mode 100644 lib/ledger.js create mode 100644 lib/polusd.js create mode 100644 lib/spawn.js create mode 100644 lib/sso.js create mode 100644 lib/store.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/admin.html create mode 100644 public/admin.js create mode 100644 public/index.html create mode 100644 public/play.html create mode 100644 public/play.js create mode 100644 public/site.css create mode 100644 server.js create mode 100644 test/run.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5fd76c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +data/ +data-test/ +*.log +.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4dc953c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM node:22-alpine +WORKDIR /app +COPY package.json ./ +RUN npm install --omit=dev --no-audit --no-fund +COPY . . +RUN mkdir -p /app/data +ENV NODE_ENV=production +ENV PORT=3000 +EXPOSE 3000 +CMD ["node","server.js"] diff --git a/lib/faucet.js b/lib/faucet.js new file mode 100644 index 0000000..848fa83 --- /dev/null +++ b/lib/faucet.js @@ -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 }; diff --git a/lib/game.js b/lib/game.js new file mode 100644 index 0000000..31bef5d --- /dev/null +++ b/lib/game.js @@ -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 }; diff --git a/lib/ledger.js b/lib/ledger.js new file mode 100644 index 0000000..77d5183 --- /dev/null +++ b/lib/ledger.js @@ -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 }; diff --git a/lib/polusd.js b/lib/polusd.js new file mode 100644 index 0000000..de5a3c6 --- /dev/null +++ b/lib/polusd.js @@ -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 }; diff --git a/lib/spawn.js b/lib/spawn.js new file mode 100644 index 0000000..7e425ee --- /dev/null +++ b/lib/spawn.js @@ -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 }; +}); diff --git a/lib/sso.js b/lib/sso.js new file mode 100644 index 0000000..d65106c --- /dev/null +++ b/lib/sso.js @@ -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 }; diff --git a/lib/store.js b/lib/store.js new file mode 100644 index 0000000..044a2f0 --- /dev/null +++ b/lib/store.js @@ -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 }; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e82f1bb --- /dev/null +++ b/package-lock.json @@ -0,0 +1,124 @@ +{ + "name": "drip-runner", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "drip-runner", + "version": "0.1.0", + "dependencies": { + "ethers": "^6.13.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@noble/curves": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz", + "integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz", + "integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@types/node": { + "version": "22.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz", + "integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/aes-js": { + "version": "4.0.0-beta.5", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz", + "integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==", + "license": "MIT" + }, + "node_modules/ethers": { + "version": "6.17.0", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.17.0.tgz", + "integrity": "sha512-BpyrpIPJ3ydEVow8zGaz1DuPS7YU8DcWxuBnY9a0UA/lvAPwrMr+EPXsfrul628SRaekPNeIM4UFh/91GWZang==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "1.11.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.2", + "@types/node": "22.7.5", + "aes-js": "4.0.0-beta.5", + "tslib": "2.7.0", + "ws": "8.21.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tslib": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", + "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", + "license": "0BSD" + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..63963da --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "drip-runner", + "version": "0.1.0", + "private": true, + "description": "Drip Runner: a hop-and-collect game for InstantAdPay members, paid in POL, funded by verified visits.", + "main": "server.js", + "scripts": { + "start": "node server.js", + "dev": "node --watch server.js", + "test": "node test/run.js" + }, + "engines": { "node": ">=20" }, + "dependencies": { "ethers": "^6.13.0" } +} diff --git a/public/admin.html b/public/admin.html new file mode 100644 index 0000000..ccfcf89 --- /dev/null +++ b/public/admin.html @@ -0,0 +1,53 @@ + + + + + + +Drip Runner · admin + + + + +
+ + +

Pool

+
+

Faucet

+
+

+ +

Settings

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+
+ +

Players

+

Refuels (income)

+

Drips granted

+

Hangar spends (back to the pool)

+

Payouts

+

Recent runs

+
+ + + diff --git a/public/admin.js b/public/admin.js new file mode 100644 index 0000000..71ee376 --- /dev/null +++ b/public/admin.js @@ -0,0 +1,41 @@ +(function () { +'use strict'; +var $ = function (id) { return document.getElementById(id); }; +var KEY = new URLSearchParams(location.search).get('key') || ''; try { if (KEY) sessionStorage.setItem('dr.admin', KEY); else KEY = sessionStorage.getItem('dr.admin') || ''; } catch (e) {} +if (new URLSearchParams(location.search).get('key')) history.replaceState(null, '', '/admin'); +function api(p, body) { return fetch(p, { method: body ? 'POST' : 'GET', headers: { 'Content-Type': 'application/json', 'X-Admin-Key': KEY }, body: body ? JSON.stringify(body) : undefined }).then(function (r) { return r.json(); }); } +var esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }; +var ct = function (ts) { return ts ? new Date(ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : ''; }; +var f4 = function (n) { return Number(n || 0).toFixed(4); }; +function stat(label, val) { return '
' + label + '' + val + '
'; } +function table(id, cols, rows) { var h = '' + cols.map(function (c) { return '' + c[0] + ''; }).join('') + ''; if (!rows.length) h += 'nothing yet'; rows.forEach(function (r) { h += '' + cols.map(function (c) { var v = typeof c[1] === 'function' ? c[1](r) : r[c[1]]; return '' + (v == null ? '' : v) + ''; }).join('') + ''; }); $(id).innerHTML = h; } +var S = null; +function load() { + return api('/api/admin/state').then(function (d) { + if (d.error) { document.body.innerHTML = '

' + esc(d.error) + '

'; return; } + S = d; var p = d.pool; + $('links').innerHTML = 'Tester page: ' + esc(d.curtain) + ' · POL $' + f4(d.usdPerPol) + ' (from the IAP contract)'; + $('pool').innerHTML = stat('Available now', f4(p.available) + ' POL') + stat('In from refuels', f4(p.in)) + stat('Back from spends', f4(p.spends)) + stat('Out as drips', f4(p.out)) + stat('Seed float', f4(p.seed)) + stat('Granted today', f4(p.grantedToday) + ' / ' + f4(p.dailyCapPol)); + var f = d.faucet; $('faucet').innerHTML = stat('Mode', f.enabled ? (f.dryRun ? 'DRY RUN' : 'LIVE') : 'off') + stat('Wallet', f.address ? f.address.slice(0, 8) + '…' + f.address.slice(-6) : '–') + stat('Balance', f.balance != null ? f4(f.balance) + ' POL' : '–') + stat('Last check', ct(f.checkedAt) || '–') + stat('Last tick', f.lastTick ? esc(JSON.stringify(f.lastTick)) : '–'); + var s = d.settings, form = $('settings'); + ['dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { form.elements[k].value = s[k]; }); + form.elements.item_shield.value = s.itemPol.shield; form.elements.item_slow.value = s.itemPol.slow; form.elements.item_magnet.value = s.itemDrips.magnet; form.elements.item_ship.value = s.itemDrips.ship; + form.elements.testers.value = (s.testers || []).join('\n'); + table('players', [['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : '') + '
' + esc(r.email || '') + ''; }], ['Wallet', function (r) { return r.wallet ? r.wallet.slice(0, 6) + '…' + r.wallet.slice(-4) : 'none'; }], ['Chapter', 'chapter', 1], ['Drips', 'bank', 1], ['Best', 'best', 1], ['Runs', 'runs', 1], ['Armed', function (r) { return Object.keys(r.items || {}).join(', '); }], ['Last seen', function (r) { return ct(r.lastSeen); }]], d.players); + table('refuels', [['When', function (r) { return ct(r.ts); }], ['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : ''); }], ['Campaign', 'campaignId'], ['Credits', 'credits', 1], ['Ad $', function (r) { return f4(r.usd); }, 1], ['Share $', function (r) { return f4(r.share); }, 1], ['POL to pool', function (r) { return f4(r.pol); }, 1], ['Via', 'via']], d.refuels); + table('drips', [['When', function (r) { return ct(r.ts); }], ['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : ''); }], ['Chapter', 'chapter', 1], ['POL', function (r) { return f4(r.pol); }, 1]], d.drips); + table('spends', [['When', function (r) { return ct(r.ts); }], ['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : ''); }], ['Item', 'item'], ['POL', function (r) { return f4(r.pol); }, 1]], d.spends); + table('payouts', [['When', function (r) { return ct(r.ts); }], ['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : ''); }], ['Wallet', function (r) { return r.wallet ? r.wallet.slice(0, 6) + '…' + r.wallet.slice(-4) : ''; }], ['POL', function (r) { return f4(r.pol); }, 1], ['Status', function (r) { return esc(r.status) + (r.error ? ' · ' + esc(r.error) : ''); }], ['Tx', function (r) { return r.tx ? '' + r.tx.slice(0, 10) + '…' : ''; }]], d.payouts); + table('runs', [['Started', function (r) { return ct(r.startedAt); }], ['Member', function (r) { return '#' + r.memberId; }], ['Chapter', function (r) { return r.chapter + (r.cleared && r.cleared.length ? ' (cleared ' + r.cleared.join(',') + ')' : ''); }], ['Drips', 'drips', 1], ['Refused', 'bad', 1], ['Refuels', 'refuels', 1], ['Status', function (r) { return esc(r.status) + (r.flagged ? ' · FLAGGED' : ''); }], ['t', function (r) { return Math.round(r.t) + ' s'; }, 1]], d.runs); + }); +} +$('settings').addEventListener('submit', function (e) { + e.preventDefault(); var f = e.target.elements; var body = {}; + ['dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { body[k] = f[k].value; }); + body.itemPol = { shield: Number(f.item_shield.value), slow: Number(f.item_slow.value) }; body.itemDrips = { magnet: Number(f.item_magnet.value), ship: Number(f.item_ship.value) }; + body.testers = f.testers.value.split(/\r?\n/).map(function (x) { return x.trim(); }).filter(Boolean); + api('/api/admin/settings', body).then(function (r) { $('saveOut').textContent = r.ok ? 'Saved.' : (r.error || 'Failed'); load(); }); +}); +$('tick').addEventListener('click', function () { $('tickOut').textContent = 'running…'; api('/api/admin/faucet/tick', {}).then(function (r) { $('tickOut').textContent = JSON.stringify(r); load(); }); }); +load(); +})(); diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..0466bd1 --- /dev/null +++ b/public/index.html @@ -0,0 +1,54 @@ + + + + + + +Drip Runner · tester briefing + + + + +
+ +

closed trial InstantAdPay members only

+

Thanks for testing. Drip Runner is a small game that pays real POL, and the POL comes from the ads you watch inside it. You are here to find out whether that loop feels good and whether it holds up. Nothing is polished yet, so say what you see.

+ +
+

Get in

+
    +
  1. Sign in to InstantAdPay firstOpen instantadpay.com/my in this same browser and sign in the usual way (email code).
  2. +
  3. Then tap this buttonInstantAdPay signs you across. No new account, no new password.
    Open Drip Runner
  4. +
  5. Have a wallet on your IAP accountYou can play without one, but POL payouts go to the wallet on file at InstantAdPay. Link it under Wallet on your IAP dashboard.
  6. +
+

If you see "not on the tester list", your IAP account has not been added yet. Tell Marty which username you use.

+
+ +

How it plays

+
    +
  • Tap to hop. The courier drops when you do nothing and hops when you tap. Space bar works on a computer.
  • +
  • Gold drips are the score. Magenta bots end the run. From chapter 2, orange firewalls have to be threaded through the gap.
  • +
  • Fuel drains all the time. Every drip tops it up a little. Empty tank, run over.
  • +
  • Chapters. Each chapter has a drip goal for one run. Clear it and you move up. The first time you clear a chapter, a drip of POL lands in your game balance.
  • +
+ +

Where the POL comes from

+
    +
  • When a run ends you can refuel instead of restarting. Refuel opens a real InstantAdPay verified visit: a member's page, a short timer, a quick icon check. Then your run continues where it died, fuel full.
  • +
  • That visit is paid for by the advertiser. A share of it goes into the game's POL pool, and the pool is the only thing chapter drips are paid from. No refuels, no pool, no POL. That is the whole experiment.
  • +
  • Your game balance pays out to your wallet once it reaches the threshold shown on the Balance screen. Payouts run every couple of minutes, and the transaction link shows up in your history.
  • +
  • In the hangar, drips buy the magnet and the Mk II courier. The shield and the slow field cost POL, taken from your game balance before it pays out.
  • +
+ +

What to tell Marty

+
    +
  • Did the refuel work the first time, and did the run really continue where it stopped?
  • +
  • Did the sponsor page load inside the refuel screen, or did you get a blank frame?
  • +
  • Did a chapter drip show up in your balance after your first clear? If it said the pool was empty, say so, that is expected until refuels have happened.
  • +
  • Anything on your phone that looked wrong: text cut off, buttons you could not reach, a run that ended for no reason.
  • +
  • Honest one: would you refuel again just to keep a run alive?
  • +
+

Amounts are trial placeholders and can change during the test. Nothing here is a promise of income.

+
+ + diff --git a/public/play.html b/public/play.html new file mode 100644 index 0000000..892b938 --- /dev/null +++ b/public/play.html @@ -0,0 +1,149 @@ + + + + + + +Drip Runner + + + + +
+ +
+
Drips0
+
Chapter1
+
Best0
+
+
Chapter goal0 / 20 drips
+
+
+ + +
+ + + +
Drip Runner

Connecting…

Checking your InstantAdPay sign-in.

+ + + + + + + + +
+ + + + diff --git a/public/play.js b/public/play.js new file mode 100644 index 0000000..d747fad --- /dev/null +++ b/public/play.js @@ -0,0 +1,229 @@ +/* Drip Runner client. The server owns the run (seed, drip claims, chapter clears, money); + this file draws it, takes taps, and reports what happened. */ +(function () { +'use strict'; +var $ = function (id) { return document.getElementById(id); }; +var canvas = $('game'), ctx = canvas.getContext('2d'); +var W = 390, H = 760, DPR = 1, floorY = H - DRSpawn.FLOOR; +var player = { x: 100, y: 300, vy: 0, r: 13, tilt: 0 }; +var ME = null, P = null, BAL = null, POOL = null, IAP = 'https://instantadpay.com'; +var R = null; // the live run +var muted = false; try { muted = localStorage.getItem('dr.muted') === '1'; } catch (e) {} + +function api(path, body) { + return fetch(path, body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : {}).then(function (r) { return r.json().then(function (j) { j._status = r.status; return j; }); }); +} +function resize() { var r = $('phone').getBoundingClientRect(); W = Math.max(300, Math.round(r.width)); H = Math.max(500, Math.round(r.height)); DPR = Math.min(2, window.devicePixelRatio || 1); canvas.width = W * DPR; canvas.height = H * DPR; ctx.setTransform(DPR, 0, 0, DPR, 0, 0); floorY = H - DRSpawn.FLOOR; player.x = W * DRSpawn.PX; buildLayers(); } +window.addEventListener('resize', resize); + +/* ---------- audio ---------- */ +var AC = null; function ac() { if (muted) return null; try { if (!AC) AC = new (window.AudioContext || window.webkitAudioContext)(); if (AC.state === 'suspended') AC.resume(); return AC; } catch (e) { return null; } } +function tone(f, d, type, g, slide) { var a = ac(); if (!a) return; var o = a.createOscillator(), v = a.createGain(); o.type = type || 'square'; o.frequency.setValueAtTime(f, a.currentTime); if (slide) o.frequency.exponentialRampToValueAtTime(slide, a.currentTime + d); v.gain.setValueAtTime(g || .05, a.currentTime); v.gain.exponentialRampToValueAtTime(.0001, a.currentTime + d); o.connect(v); v.connect(a.destination); o.start(); o.stop(a.currentTime + d); } +var sfx = { hop: function () { tone(300, .09, 'square', .04, 520); }, coin: function () { tone(880, .08, 'sine', .05, 1320); setTimeout(function () { tone(1320, .1, 'sine', .04, 1760); }, 40); }, crash: function () { tone(180, .35, 'sawtooth', .08, 40); }, clear: function () { [523, 659, 784, 1047].forEach(function (f, i) { setTimeout(function () { tone(f, .18, 'triangle', .06); }, i * 90); }); }, shield: function () { tone(200, .2, 'triangle', .06, 600); }, buy: function () { tone(660, .08, 'sine', .04, 990); } }; +$('mute').textContent = muted ? '×' : '♪'; +$('mute').addEventListener('click', function () { muted = !muted; try { localStorage.setItem('dr.muted', muted ? '1' : '0'); } catch (e) {} $('mute').textContent = muted ? '×' : '♪'; }); + +/* ---------- sprites ---------- */ +function sprite(sz, draw) { var c = document.createElement('canvas'); c.width = sz * 2; c.height = sz * 2; var x = c.getContext('2d'); x.scale(2, 2); draw(x, sz); return c; } +var dripSpr = sprite(36, function (x, s) { var c = s / 2; var g = x.createRadialGradient(c, c, 2, c, c, c); g.addColorStop(0, 'rgba(255,194,75,.9)'); g.addColorStop(.35, 'rgba(255,194,75,.35)'); g.addColorStop(1, 'rgba(255,194,75,0)'); x.fillStyle = g; x.fillRect(0, 0, s, s); var d = x.createRadialGradient(c - 3, c - 3, 1, c, c, 8); d.addColorStop(0, '#FFF4CC'); d.addColorStop(.5, '#FFC24B'); d.addColorStop(1, '#D97706'); x.fillStyle = d; x.beginPath(); x.arc(c, c, 8, 0, 6.283); x.fill(); x.strokeStyle = 'rgba(255,255,255,.7)'; x.lineWidth = 1.2; x.beginPath(); x.arc(c, c, 5.5, 3.6, 5.2); x.stroke(); }); +var botSpr = sprite(56, function (x, s) { var c = s / 2; var g = x.createRadialGradient(c, c, 4, c, c, c); g.addColorStop(0, 'rgba(255,59,122,.7)'); g.addColorStop(.4, 'rgba(255,59,122,.25)'); g.addColorStop(1, 'rgba(255,59,122,0)'); x.fillStyle = g; x.fillRect(0, 0, s, s); x.translate(c, c); x.fillStyle = '#FF3B7A'; for (var i = 0; i < 4; i++) { x.rotate(Math.PI / 2); x.beginPath(); x.moveTo(0, -9); x.lineTo(5, -20); x.lineTo(-5, -20); x.closePath(); x.fill(); } var b = x.createLinearGradient(-10, -10, 10, 10); b.addColorStop(0, '#FF7AA6'); b.addColorStop(1, '#B3123F'); x.fillStyle = b; x.fillRect(-10, -10, 20, 20); x.fillStyle = '#070C18'; x.fillRect(-5, -5, 10, 10); x.fillStyle = '#FFE1EB'; x.fillRect(-2, -2, 4, 4); }); +function shipSpr(gold) { return sprite(64, function (x, s) { var c = s / 2; x.translate(c, c); var glow = gold ? '255,194,75' : '34,211,238'; var g = x.createRadialGradient(0, 0, 4, 0, 0, c); g.addColorStop(0, 'rgba(' + glow + ',.55)'); g.addColorStop(1, 'rgba(' + glow + ',0)'); x.fillStyle = g; x.fillRect(-c, -c, s, s); var h = x.createLinearGradient(0, -10, 0, 10); h.addColorStop(0, '#FFFFFF'); h.addColorStop(.5, '#DCE6F5'); h.addColorStop(1, '#8FA3C4'); x.fillStyle = h; x.beginPath(); x.moveTo(-16, -8); x.lineTo(10, -9); x.quadraticCurveTo(22, -6, 22, 0); x.quadraticCurveTo(22, 6, 10, 9); x.lineTo(-16, 8); x.quadraticCurveTo(-20, 0, -16, -8); x.fill(); x.fillStyle = gold ? '#FFC24B' : '#22D3EE'; x.beginPath(); x.arc(9, 0, 4, 0, 6.283); x.fill(); x.fillStyle = '#fff'; x.beginPath(); x.arc(8, -1, 1.5, 0, 6.283); x.fill(); x.fillStyle = gold ? '#E08A00' : '#0EA5C9'; x.fillRect(-14, -3, 8, 6); x.fillStyle = '#4E5F7A'; x.fillRect(-12, -12, 10, 4); x.fillRect(-12, 8, 10, 4); }); } +var shipA = shipSpr(false), shipB = shipSpr(true); + +/* ---------- background layers ---------- */ +var stars = [], nodes = [], cols = []; +function buildLayers() { stars = []; for (var i = 0; i < 70; i++) stars.push({ x: Math.random() * W, y: Math.random() * (H - 60), s: Math.random() * 1.4 + .3, a: Math.random() }); nodes = []; for (var j = 0; j < 14; j++) nodes.push({ x: Math.random() * W, y: 80 + Math.random() * (H - 200), r: 2 + Math.random() * 2 }); cols = []; for (var k = 0; k < 6; k++) cols.push({ x: Math.random() * W, w: 30 + Math.random() * 60, h: 40 + Math.random() * 90, a: .05 + Math.random() * .08 }); } + +/* ---------- ui helpers ---------- */ +function hideAll() { ['ovLobby', 'ovClear', 'ovOver', 'ovHangar', 'ovBal', 'ovLoad'].forEach(function (id) { $(id).hidden = true; }); } +function show(id) { hideAll(); $(id).hidden = false; } +var toastT = null; function toast(m) { $('toast').textContent = m; $('toast').classList.add('on'); clearTimeout(toastT); toastT = setTimeout(function () { $('toast').classList.remove('on'); }, 2600); } +function pill(m) { var p = $('pill'); p.textContent = m; p.classList.remove('on'); void p.offsetWidth; p.classList.add('on'); setTimeout(function () { p.classList.remove('on'); }, 900); } +var hudCache = {}; function setHud() { if (!R) return; var v = { d: R.drips, c: R.chapter, b: Math.max(P.best, R.drips), g: R.chapDrips, gg: R.goal }; if (v.d !== hudCache.d) $('hDrips').textContent = v.d; if (v.c !== hudCache.c) $('hChap').textContent = v.c; if (v.b !== hudCache.b) $('hBest').textContent = v.b; if (v.g !== hudCache.g) $('hGoalN').textContent = v.g; if (v.gg !== hudCache.gg) $('hGoal').textContent = v.gg; hudCache = v; $('fuelBar').style.width = Math.max(0, R.fuel) + '%'; $('fuel').classList.toggle('low', R.fuel < 22); } +function f3(n) { return Number(n || 0).toFixed(3); } + +/* ---------- lobby / me ---------- */ +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; return r; }); } +function lobby() { + R = null; $('hud').classList.remove('on'); $('tapdesk').hidden = true; + $('lChap').textContent = P.chapter; $('lDrips').textContent = P.bank.toLocaleString(); $('lPol').textContent = f3(BAL.unpaid); + $('lPool').innerHTML = 'POL pool ' + f3(POOL.available) + ' · today’s cap left ' + f3(POOL.capLeft) + ' · a chapter drip is ' + f3(POOL.dripPol) + ''; + $('lMember').innerHTML = 'InstantAdPay · ' + (ME.username ? '@' + ME.username : '#' + ME.memberId) + ' · ' + (ME.wallet ? ME.wallet.slice(0, 6) + '…' + ME.wallet.slice(-4) : 'no wallet on file'); + show('ovLobby'); +} + +/* ---------- the run ---------- */ +function newRun() { + ac(); + return api('/api/run/start', { W: W, H: H }).then(function (r) { + if (r._status !== 200) { toast(r.error || 'Could not start a run.'); return; } + R = { id: r.runId, seed: r.seed, speed: r.speed, chapter: r.chapter, goal: r.goal, on: true, paused: false, t: 0, dist: 0, drips: 0, chapDrips: 0, fuel: 100, ents: [], parts: [], shake: 0, inv: 2, shield: !!r.armed.shield, magnet: !!r.armed.magnet, slow: r.armed.slow ? 15 : 0, ship: r.ship, refuels: 0, pending: [], consumed: { d: 0, b: 0, g: 0 }, lastFlush: 0, W: W, H: H }; + makeGens(); player.y = floorY - 120; player.vy = 0; hudCache = {}; setHud(); $('hud').classList.add('on'); $('tapdesk').hidden = !matchMedia('(min-width:700px)').matches; hideAll(); + if (R.magnet) toast('Drip magnet on'); if (R.shield) toast('Shield core armed'); + }); +} +function makeGens() { R.gen = { d: DRSpawn.drips(R.seed, R.W, R.H), b: DRSpawn.bots(R.seed, R.chapter, R.H), g: DRSpawn.gates(R.seed, R.chapter, R.H) }; R.next = { d: R.gen.d(), b: R.gen.b(), g: R.gen.g() }; for (var i = 0; i < R.consumed.d; i++) R.next.d = R.gen.d(); for (var j = 0; j < R.consumed.b; j++) R.next.b = R.gen.b(); for (var k = 0; k < R.consumed.g; k++) R.next.g = R.gen.g(); } +function spawn() { + while (R.next.d.t <= R.t) { var g = R.next.d; for (var i = 0; i < g.drips.length; i++) { var d = g.drips[i]; R.ents.push({ k: 'd', i: d.i, x: d.x0 - (R.t - g.t) * R.speed, y: d.y, r: 9, ph: Math.random() * 6 }); } R.next.d = R.gen.d(); R.consumed.d++; } + while (R.next.b.t <= R.t) { var b = R.next.b; R.ents.push({ k: 'b', x: R.W + 60 - (R.t - b.t) * R.speed, y: b.y, r: 15, amp: b.amp, ph: b.ph, rot: 0 }); R.next.b = R.gen.b(); R.consumed.b++; } + while (R.next.g.t <= R.t) { var q = R.next.g; if (R.chapter >= 2) R.ents.push({ k: 'g', x: R.W + 60 - (R.t - q.t) * R.speed, y: q.y, gap: q.gap, w: 34 }); R.next.g = R.gen.g(); R.consumed.g++; } +} +function hop() { if (!R || !R.on || R.paused) return; player.vy = -(R.ship === 2 ? 500 : 520); sfx.hop(); burst(player.x - 12, player.y + 4, 4, R.ship === 2 ? '255,194,75' : '34,211,238', 60); } +canvas.addEventListener('pointerdown', function (e) { e.preventDefault(); ac(); hop(); }); +window.addEventListener('keydown', function (e) { if (e.code === 'Space' || e.code === 'ArrowUp') { if (R && R.on && !R.paused) { e.preventDefault(); hop(); } } }); +function burst(x, y, n, rgb, sp) { if (!R) return; for (var i = 0; i < n; i++) { var a = Math.random() * 6.283, s = sp * (.4 + Math.random()); R.parts.push({ x: x, y: y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, l: .5 + Math.random() * .4, c: rgb, r: 1.5 + Math.random() * 2 }); } } + +function flush(goal) { + if (!R) return Promise.resolve({}); + var evs = R.pending; R.pending = []; R.lastFlush = R.t; + if (!evs.length && !goal) return Promise.resolve({}); + return api('/api/run/events', { runId: R.id, t: R.t, events: evs, goal: !!goal }).then(function (r) { + if (r._status !== 200) { if (r.over && R) { R.on = false; } toast(r.error || 'Sync problem'); return r; } + if (R) { R.drips = r.drips; R.chapDrips = r.chapDrips; R.goal = r.goal; if (r.refused) toast('Server refused ' + r.refused + ' drip' + (r.refused > 1 ? 's' : '') + ' (' + (r.why || []).join(',') + ')'); } + return r; + }).catch(function () { R && (R.pending = evs.concat(R.pending)); return {}; }); +} + +function update(dt) { + if (!R || !R.on || R.paused) return; R.t += dt; var sp = R.speed; R.dist += sp * dt; if (R.slow > 0) R.slow -= dt; if (R.inv > 0) R.inv -= dt; + R.fuel -= dt * 2.4; if (R.fuel <= 0) { R.fuel = 0; return over('Out of fuel', 'The tank is dry.'); } + player.vy += 1500 * dt; if (player.vy > 900) player.vy = 900; player.y += player.vy * dt; + if (player.y > floorY - player.r) { player.y = floorY - player.r; if (player.vy > 200) burst(player.x, player.y + 8, 3, '34,211,238', 40); player.vy = 0; } + if (player.y < 70) { player.y = 70; player.vy = 0; } + player.tilt += ((player.vy / 900) * .6 - player.tilt) * Math.min(1, dt * 10); + spawn(); + var ents = R.ents, i; + for (i = ents.length - 1; i >= 0; i--) { var e = ents[i]; var es = e.k === 'b' && R.slow > 0 ? sp * .45 : sp; e.x -= es * dt; + if (e.k === 'd') { e.ph += dt * 4; if (R.magnet) { var dx = player.x - e.x, dy = player.y - e.y, dd = Math.hypot(dx, dy); if (dd < 150) { e.x += dx / dd * 420 * dt; e.y += dy / dd * 420 * dt; } } + if (Math.hypot(player.x - e.x, player.y - e.y) < player.r + e.r + 2) { ents.splice(i, 1); R.drips++; R.chapDrips++; R.fuel = Math.min(100, R.fuel + 3.5); sfx.coin(); burst(e.x, e.y, 8, '255,194,75', 140); R.pending.push({ k: 'd', i: e.i, t: Math.round(R.t * 1000) / 1000 }); + if (R.chapDrips >= R.goal) return cleared(); continue; } } + if (e.k === 'b') { e.rot += dt * 3; var by = e.y + (e.amp ? Math.sin(R.t * 2 + e.ph) * e.amp : 0); e.cy = by; if (R.inv <= 0 && Math.hypot(player.x - e.x, player.y - by) < player.r + e.r - 2) { if (R.shield) { R.shield = false; R.inv = 1.5; ents.splice(i, 1); sfx.shield(); burst(e.x, by, 20, '255,106,26', 220); pill('Shield!'); R.shake = .25; continue; } return crash(e.x, by); } } + if (e.k === 'g') { if (R.inv <= 0 && player.x + player.r > e.x && player.x - player.r < e.x + e.w && (player.y - player.r < e.y || player.y + player.r > e.y + e.gap)) { if (R.shield) { R.shield = false; R.inv = 1.5; sfx.shield(); pill('Shield!'); R.shake = .25; } else return crash(player.x, player.y); } } + if (e.x < -90) ents.splice(i, 1); } + var ps = R.parts; for (i = ps.length - 1; i >= 0; i--) { var p = ps[i]; p.l -= dt; p.x += p.vx * dt; p.y += p.vy * dt; p.vy += 300 * dt; if (p.l <= 0) ps.splice(i, 1); } + if (R.shake > 0) R.shake -= dt; + if (Math.random() < .9) R.parts.push({ x: player.x - 16, y: player.y + (Math.random() - .5) * 6, vx: -sp * .5 - 40, vy: (Math.random() - .5) * 30, l: .3, c: R.ship === 2 ? '255,194,75' : '34,211,238', r: 2 + Math.random() * 2 }); + if (R.t - R.lastFlush > 2.5 && R.pending.length) flush(false); + setHud(); +} +function crash(x, y) { sfx.crash(); burst(x, y, 36, '255,59,122', 260); burst(x, y, 14, '255,255,255', 160); R.shake = .5; over('Courier hit', 'A bot got you.'); } +function over(title, why) { + R.paused = true; flush(false); + setTimeout(function () { if (!R) return; $('oEyebrow').textContent = title; $('oTitle').textContent = 'Run over at ' + R.drips; $('oText').textContent = why + ' Refuel with a sponsor visit and keep this run, drips and chapter progress intact.'; $('bRefuel').hidden = false; $('oChip').hidden = false; show('ovOver'); }, 450); +} +function cleared() { + R.paused = true; pill('Verifying…'); + flush(true).then(function (r) { + if (!R) return; + if (!r.cleared) { R.paused = false; if (r.short) toast('Server count says ' + r.short + ' more to go'); return; } + var c = r.cleared; sfx.clear(); burst(player.x, player.y, 40, '255,194,75', 220); + $('cEyebrow').textContent = 'Chapter ' + c.chapter + ' cleared'; $('cTitle').textContent = 'Banked ' + (R.goal) + ' drips'; + var m = Math.floor(c.playTime / 60), s = c.playTime % 60; var tm = m + ':' + (s < 10 ? '0' : '') + s; + $('cBig').innerHTML = '+' + f3(c.pol) + 'POL'; $('cBig').classList.toggle('dim', !c.pol); + 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.' }; + $('cText').textContent = why[c.reason] || ''; $('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; + setTimeout(function () { show('ovClear'); }, 500); + }); +} +$('bNext').addEventListener('click', function () { if (!R) return; R.paused = false; R.inv = 1.5; hideAll(); }); +$('bRestart').addEventListener('click', function () { endRun().then(newRun); }); +function endRun() { var id = R && R.id; R = null; hideAll(); return id ? api('/api/run/end', { runId: id }).catch(function () {}) : Promise.resolve(); } +['bLobby1', 'bLobby2'].forEach(function (id) { $(id).addEventListener('click', function () { endRun().then(loadMe).then(lobby); }); }); +['bLobby3', 'bLobby4'].forEach(function (id) { $(id).addEventListener('click', function () { loadMe().then(lobby); }); }); +$('bPlay').addEventListener('click', function () { newRun(); }); + +/* ---------- refuel: hand the run to InstantAdPay and come back ---------- */ +function snapshot(nonce) { + var s = { runId: R.id, nonce: nonce, seed: R.seed, speed: R.speed, chapter: R.chapter, goal: R.goal, t: R.t, dist: R.dist, drips: R.drips, chapDrips: R.chapDrips, ents: R.ents.map(function (e) { var o = {}; for (var k in e) if (k !== 'cy') o[k] = e[k]; return o; }), consumed: R.consumed, y: player.y, shield: R.shield, magnet: R.magnet, slow: R.slow, ship: R.ship, refuels: R.refuels, pending: R.pending, W: R.W, H: R.H, at: Date.now() }; + try { sessionStorage.setItem('dr.snap', JSON.stringify(s)); } catch (e) {} +} +$('bRefuel').addEventListener('click', function () { + if (!R) return; $('bRefuel').disabled = true; + api('/api/refuel/start', { runId: R.id }).then(function (r) { + $('bRefuel').disabled = false; + if (r._status !== 200) return toast(r.error || 'Refuel is not available right now.'); + snapshot(r.nonce); location.href = r.url; + }); +}); +function tryResume(q) { + var snap = null; try { snap = JSON.parse(sessionStorage.getItem('dr.snap') || 'null'); } catch (e) {} + if (!snap || snap.runId !== q.get('resume')) { toast('That run could not be restored.'); return lobby(); } + return api('/api/refuel/resume', { runId: snap.runId, nonce: q.get('n') || snap.nonce, receipt: q.get('r') || '', none: q.get('none') === '1' }).then(function (r) { + try { sessionStorage.removeItem('dr.snap'); } catch (e) {} + R = { id: snap.runId, seed: snap.seed, speed: snap.speed, chapter: snap.chapter, goal: snap.goal, on: true, paused: true, t: snap.t, dist: snap.dist, drips: snap.drips, chapDrips: snap.chapDrips, fuel: 0, ents: snap.ents, parts: [], shake: 0, inv: 3, shield: snap.shield, magnet: snap.magnet, slow: snap.slow, ship: snap.ship, refuels: snap.refuels, pending: snap.pending || [], consumed: snap.consumed, lastFlush: snap.t, W: snap.W, H: snap.H }; + if (R.W !== W || R.H !== H) { var sx = W / R.W, sy = H / R.H; R.ents.forEach(function (e) { e.x *= sx; e.y *= sy; }); } + makeGens(); player.y = snap.y; player.vy = 0; hudCache = {}; $('hud').classList.add('on'); hideAll(); + if (!r.ok) { $('oEyebrow').textContent = r.reason === 'none' ? 'No sponsor pages right now' : 'Visit not verified'; $('oTitle').textContent = 'Run over at ' + R.drips; $('oText').textContent = r.reason === 'none' ? 'InstantAdPay had no verified-visit page for you at the moment. Restart, or try refuelling again later.' : 'The visit did not complete, so the tank stays empty. Refuel again or restart.'; $('bRefuel').hidden = r.reason === 'none'; $('oChip').hidden = r.reason === 'none'; setHud(); return show('ovOver'); } + R.fuel = 100; R.refuels++; R.ents = R.ents.filter(function (e) { return e.k === 'd' || e.x > player.x + 260; }); if (r.pool != null) POOL.available = r.pool; + setHud(); var n = 3; pill('Refuelled · ' + n); var iv = setInterval(function () { n--; if (n <= 0) { clearInterval(iv); pill('Go'); if (R) R.paused = false; if (R && R.pending.length) flush(false); } else pill('' + n); }, 800); + }); +} + +/* ---------- hangar / balance ---------- */ +function hangar() { + show('ovHangar'); $('hgBal').textContent = P.bank.toLocaleString() + ' drips · ' + f3(BAL.unpaid) + ' POL'; + var pr = P.prices; + set('itMagnet', 'magnet', P.items.magnet, P.bank >= pr.drips.magnet, pr.drips.magnet + ' drips', 'armed'); + set('itShip', 'ship', P.items.ship, P.bank >= pr.drips.ship, pr.drips.ship + ' drips', 'owned'); + set('itShield', 'shield', P.items.shield, BAL.unpaid >= pr.pol.shield, f3(pr.pol.shield) + ' POL', 'armed'); + set('itSlow', 'slow', P.items.slow, BAL.unpaid >= pr.pol.slow, f3(pr.pol.slow) + ' POL', 'armed'); + function set(id, key, own, can, label, ownLabel) { var it = $(id), b = it.querySelector('.buy'); it.classList.toggle('owned', !!own); b.className = 'buy' + (/POL/.test(label) ? ' pol' : '') + (own ? ' own' : (can ? '' : ' no')); b.textContent = own ? ownLabel : label; } +} +$('ovHangar').addEventListener('click', function (e) { var b = e.target.closest('[data-buy]'); if (!b) return; b.disabled = true; + api('/api/hangar/buy', { item: b.dataset.buy }).then(function (r) { b.disabled = false; if (r._status !== 200) return toast(r.error || 'Could not buy that.'); P = r.player; BAL = r.balance; sfx.buy(); toast('Paid ' + r.paid); hangar(); }); }); +function balance() { + show('ovBal'); api('/api/balance').then(function (b) { BAL = b; + $('bPol').textContent = f3(b.unpaid); var pct = Math.min(100, b.unpaid / b.threshold * 100); $('bProg').style.width = pct + '%'; + $('bNote').textContent = 'Pays to your wallet at ' + b.threshold + ' POL. ' + pct.toFixed(0) + '% of the way. Paid so far: ' + f3(b.paidTotal) + ' POL.'; + var h = ''; if (!b.history.length) h = '
No drips yet. Clear a chapter.0.000
'; + b.history.forEach(function (l) { var cls = l.kind === 'payout' ? (l.status === 'paid' ? 'm ok' : l.status === 'failed' ? 'm neg' : 'm') : (l.pol < 0 ? 'm neg' : 'm'); h += '
' + esc(l.label) + (l.tx ? ' · tx' : '') + '' + (l.kind === 'payout' ? '' : (l.pol < 0 ? '' : '+')) + f3(l.pol) + '
'; }); + $('ledger').innerHTML = h; + $('bWallet').textContent = b.wallet ? 'Wallet: ' + b.wallet + ' (from your InstantAdPay account).' : 'No wallet on your InstantAdPay account yet. Link one there or payouts cannot be sent.'; + }); +} +function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } +$('bHangar').addEventListener('click', hangar); $('bBalance').addEventListener('click', balance); + +/* ---------- draw ---------- */ +function draw() { + ctx.clearRect(0, 0, W, H); var t = R ? R.t : performance.now() / 1000, dist = R ? R.dist : performance.now() * .05; + var bg = ctx.createLinearGradient(0, 0, 0, H); bg.addColorStop(0, '#03060E'); bg.addColorStop(.6, '#0A1327'); bg.addColorStop(1, '#101C3C'); ctx.fillStyle = bg; ctx.fillRect(0, 0, W, H); + var s2 = ctx.createRadialGradient(W * .5, H * .85, 10, W * .5, H * .85, W * .9); s2.addColorStop(0, 'rgba(34,211,238,.12)'); s2.addColorStop(1, 'rgba(34,211,238,0)'); ctx.fillStyle = s2; ctx.fillRect(0, 0, W, H); + ctx.save(); if (R && R.shake > 0) ctx.translate((Math.random() - .5) * R.shake * 24, (Math.random() - .5) * R.shake * 24); + var i; for (i = 0; i < stars.length; i++) { var st = stars[i]; var sx = ((st.x - dist * .15) % W + W) % W; ctx.globalAlpha = .35 + .5 * Math.abs(Math.sin(t * 1.5 + st.a * 6)); ctx.fillStyle = '#CFE3FF'; ctx.fillRect(sx, st.y, st.s, st.s); } ctx.globalAlpha = 1; + for (i = 0; i < cols.length; i++) { var c = cols[i]; var cx = ((c.x - dist * .3) % (W + 120) + W + 120) % (W + 120) - 60; ctx.fillStyle = 'rgba(31,111,235,' + c.a + ')'; ctx.fillRect(cx, floorY - c.h, c.w, c.h); ctx.fillStyle = 'rgba(143,240,255,' + c.a * 1.5 + ')'; for (var wy = floorY - c.h + 8; wy < floorY - 6; wy += 12) for (var wx = cx + 5; wx < cx + c.w - 5; wx += 10) if (((wx * 7 + wy * 3) | 0) % 5 < 2) ctx.fillRect(wx, wy, 4, 5); } + ctx.lineWidth = 1; for (i = 0; i < nodes.length; i++) { var n = nodes[i]; n.sx = ((n.x - dist * .55) % (W + 80) + W + 80) % (W + 80) - 40; } + for (i = 0; i < nodes.length; i++) { var a = nodes[i]; for (var j = i + 1; j < nodes.length; j++) { var b = nodes[j], dd = Math.hypot(a.sx - b.sx, a.y - b.y); if (dd < 150) { ctx.strokeStyle = 'rgba(34,211,238,' + (0.16 * (1 - dd / 150)) + ')'; ctx.beginPath(); ctx.moveTo(a.sx, a.y); ctx.lineTo(b.sx, b.y); ctx.stroke(); } } } + for (i = 0; i < nodes.length; i++) { var q = nodes[i]; ctx.fillStyle = 'rgba(143,240,255,.5)'; ctx.beginPath(); ctx.arc(q.sx, q.y, q.r, 0, 6.283); ctx.fill(); } + ctx.strokeStyle = 'rgba(34,211,238,.08)'; var gx = -(dist * .8 % 44); for (var x = gx; x < W; x += 44) { ctx.beginPath(); ctx.moveTo(x, 60); ctx.lineTo(x, floorY); ctx.stroke(); } for (var y = 60; y < floorY; y += 44) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke(); } + var fg = ctx.createLinearGradient(0, floorY, 0, H); fg.addColorStop(0, '#0E1B3B'); fg.addColorStop(1, '#060B18'); ctx.fillStyle = fg; ctx.fillRect(0, floorY, W, H - floorY); + var rail = ctx.createLinearGradient(0, floorY - 6, 0, floorY + 6); rail.addColorStop(0, 'rgba(34,211,238,0)'); rail.addColorStop(.5, 'rgba(143,240,255,.9)'); rail.addColorStop(1, 'rgba(34,211,238,0)'); ctx.fillStyle = rail; ctx.fillRect(0, floorY - 6, W, 12); + ctx.strokeStyle = 'rgba(34,211,238,.35)'; ctx.lineWidth = 2; ctx.setLineDash([26, 18]); ctx.lineDashOffset = -(dist * 1.6 % 44); ctx.beginPath(); ctx.moveTo(0, floorY + 26); ctx.lineTo(W, floorY + 26); ctx.stroke(); ctx.setLineDash([]); + ctx.fillStyle = 'rgba(255,106,26,.5)'; for (var fx = -(dist * 2.2 % 60); fx < W; fx += 60) ctx.fillRect(fx, floorY + 48, 22, 3); + if (!R) { ctx.restore(); return; } + for (i = 0; i < R.ents.length; i++) { var e = R.ents[i]; + if (e.k === 'g') { var gg = ctx.createLinearGradient(e.x, 0, e.x + e.w, 0); gg.addColorStop(0, '#FF6A1A'); gg.addColorStop(.5, '#FFB088'); gg.addColorStop(1, '#D44E00'); ctx.fillStyle = gg; ctx.fillRect(e.x, 60, e.w, e.y - 60); ctx.fillRect(e.x, e.y + e.gap, e.w, floorY - e.y - e.gap); ctx.fillStyle = 'rgba(0,0,0,.35)'; for (var sy = 64 + (dist % 24); sy < e.y - 4; sy += 24) ctx.fillRect(e.x, sy, e.w, 8); for (sy = e.y + e.gap + 4 + (dist % 24); sy < floorY - 4; sy += 24) ctx.fillRect(e.x, sy, e.w, 8); ctx.fillStyle = '#FFE1CC'; ctx.shadowColor = '#FF6A1A'; ctx.shadowBlur = 18; ctx.fillRect(e.x - 3, e.y - 4, e.w + 6, 4); ctx.fillRect(e.x - 3, e.y + e.gap, e.w + 6, 4); ctx.shadowBlur = 0; } + else if (e.k === 'd') { var dy = e.y + Math.sin(e.ph) * 3, sc = 1 + Math.sin(e.ph * 1.3) * .08; ctx.drawImage(dripSpr, e.x - 18 * sc, dy - 18 * sc, 36 * sc, 36 * sc); } + else { ctx.save(); ctx.translate(e.x, e.cy || e.y); ctx.rotate(e.rot); if (R.slow > 0) ctx.globalAlpha = .75; ctx.drawImage(botSpr, -28, -28, 56, 56); ctx.restore(); } } + for (i = 0; i < R.parts.length; i++) { var p = R.parts[i]; ctx.globalAlpha = Math.max(0, Math.min(1, p.l * 2)); ctx.fillStyle = 'rgb(' + p.c + ')'; ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, 6.283); ctx.fill(); } ctx.globalAlpha = 1; + ctx.save(); ctx.translate(player.x, player.y); ctx.rotate(player.tilt); if (R.inv > 0 && Math.floor(R.t * 12) % 2 === 0) ctx.globalAlpha = .45; + if (R.magnet) { ctx.strokeStyle = 'rgba(255,194,75,.35)'; ctx.lineWidth = 1.5; ctx.setLineDash([4, 6]); ctx.beginPath(); ctx.arc(0, 0, 150, 0, 6.283); ctx.stroke(); ctx.setLineDash([]); } + ctx.drawImage(R.ship === 2 ? shipB : shipA, -32, -32, 64, 64); + if (R.shield) { ctx.strokeStyle = 'rgba(255,106,26,.85)'; ctx.lineWidth = 2; ctx.shadowColor = '#FF6A1A'; ctx.shadowBlur = 14; ctx.beginPath(); ctx.arc(0, 0, 22, 0, 6.283); ctx.stroke(); ctx.shadowBlur = 0; } + ctx.restore(); + if (R.slow > 0) { ctx.fillStyle = 'rgba(139,92,246,' + Math.min(.12, R.slow * .03) + ')'; ctx.fillRect(0, 0, W, H); } + ctx.restore(); +} +var last = performance.now(); function loop(now) { var dt = Math.min(.033, (now - last) / 1000); last = now; update(dt); draw(); requestAnimationFrame(loop); } + +/* ---------- boot ---------- */ +resize(); requestAnimationFrame(loop); +loadMe().then(function () { + var q = new URLSearchParams(location.search); + if (q.get('resume')) { history.replaceState(null, '', '/play'); return tryResume(q); } + lobby(); +}).catch(function (r) { + $('loadTitle').textContent = 'Sign in first'; $('loadText').textContent = (r && r.error) || 'Open Drip Runner from your InstantAdPay dashboard.'; var b = $('loadBtn'); b.hidden = false; b.textContent = 'Open through InstantAdPay'; b.href = (r && r.iap) || IAP + '/api/my/driprunner'; +}); +})(); diff --git a/public/site.css b/public/site.css new file mode 100644 index 0000000..b5da58d --- /dev/null +++ b/public/site.css @@ -0,0 +1,34 @@ +:root{color-scheme:dark;--page:#050912;--ink:#EEF3FA;--ink2:#AFC0D8;--muted:#6E82A3;--cyan:#22D3EE;--cyan2:#8FF0FF;--gold:#FFC24B;--gold2:#FFE9A8;--bot:#FF3B7A;--sig:#FF6A1A;--ok:#34D399;--violet:#8B5CF6;--panel:#0E172D;--panel2:#141F3A;--line:#24365F; + --display:"Orbitron","Segoe UI",system-ui,sans-serif;--body:"Manrope","Segoe UI",system-ui,sans-serif;--mono:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace} +*{box-sizing:border-box} +body{margin:0;background:var(--page);color:var(--ink);font:15px/1.55 var(--body);padding:0 16px 48px; + background-image:radial-gradient(ellipse 60% 50% at 50% 0%,rgba(34,211,238,.10),transparent 60%),radial-gradient(ellipse 40% 40% at 90% 100%,rgba(255,106,26,.08),transparent 60%),radial-gradient(ellipse 40% 40% at 5% 90%,rgba(139,92,246,.10),transparent 60%)} +body.plain{display:grid;place-items:center;min-height:100vh} +.wrap{max-width:760px;margin:0 auto;padding-top:28px} +.logo{font:900 40px/1 var(--display);letter-spacing:.06em;text-transform:uppercase;background:linear-gradient(180deg,#fff,var(--cyan2) 45%,var(--cyan) 60%,#0EA5C9);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 22px rgba(34,211,238,.45));margin:0} +.logo span{background:linear-gradient(180deg,var(--gold2),var(--gold) 55%,#E08A00);-webkit-background-clip:text;background-clip:text;color:transparent} +h1{font:900 26px/1.1 var(--display);letter-spacing:.05em;text-transform:uppercase;margin:0 0 10px} +h2{font:800 15px/1.2 var(--display);letter-spacing:.12em;text-transform:uppercase;color:var(--cyan);margin:26px 0 8px} +p{margin:0 0 10px;color:var(--ink2)} +.card{background:linear-gradient(180deg,rgba(20,31,58,.96),rgba(14,23,45,.98));border:1px solid var(--line);border-radius:18px;padding:20px 18px;box-shadow:0 30px 70px -20px rgba(0,0,0,.9);max-width:560px;margin:14px 0} +.btn{display:inline-block;padding:13px 18px;border-radius:12px;border:0;cursor:pointer;font:800 14px var(--display);letter-spacing:.1em;text-transform:uppercase;color:#07101F;text-decoration:none;background:linear-gradient(180deg,var(--cyan2),var(--cyan) 55%,#0EA5C9);box-shadow:0 0 0 1px rgba(255,255,255,.25) inset,0 8px 28px -8px rgba(34,211,238,.8)} +.btn.sig{background:linear-gradient(180deg,#FFB088,var(--sig) 55%,#D44E00);color:#fff} +.btn.ghost{background:rgba(14,23,45,.7);border:1px solid var(--line);color:var(--ink2);box-shadow:none} +ol,ul{color:var(--ink2);padding-left:22px;margin:0 0 10px}li{margin:6px 0} +.steps{display:grid;gap:10px;counter-reset:s;padding:0;list-style:none;margin:0 0 16px} +.steps li{display:grid;grid-template-columns:34px 1fr;gap:12px;align-items:start;background:rgba(5,9,18,.5);border:1px solid var(--line);border-radius:12px;padding:12px 12px} +.steps li:before{counter-increment:s;content:counter(s);width:34px;height:34px;border-radius:50%;display:grid;place-items:center;font:800 14px var(--display);color:#07101F;background:linear-gradient(180deg,var(--gold2),var(--gold))} +.steps b{display:block;color:var(--ink);font-weight:800;margin-bottom:2px} +.k{font:700 11px var(--mono);padding:2px 7px;border:1px solid var(--line);border-radius:5px;color:var(--ink);background:var(--panel)} +.chip{display:inline-block;font:700 10px var(--mono);letter-spacing:.06em;text-transform:uppercase;padding:3px 8px;border-radius:5px;border:1px solid var(--line);color:var(--ink2)} +.chip.ok{color:var(--ok);border-color:rgba(52,211,153,.4)}.chip.sig{color:var(--sig);border-color:rgba(255,106,26,.4)}.chip.gold{color:var(--gold);border-color:rgba(255,194,75,.4)} +.muted{color:var(--muted);font-size:13px} +table{width:100%;border-collapse:collapse;font-size:12px}th,td{text-align:left;padding:6px 6px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--muted);font-weight:600;letter-spacing:.08em;text-transform:uppercase;font-size:10px} +.num{text-align:right;font-family:var(--mono)} +.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px} +.stat{background:rgba(5,9,18,.5);border:1px solid var(--line);border-radius:12px;padding:10px 12px}.stat small{display:block;font:700 9px var(--body);letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}.stat b{font:800 20px var(--display);font-variant-numeric:tabular-nums} +input,select,textarea{background:#070C18;border:1px solid var(--line);color:var(--ink);border-radius:8px;padding:8px 10px;font:13px var(--body);width:100%} +label{display:block;font-size:12px;color:var(--muted);margin:8px 0 4px} +.row{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px} +.scroll{overflow-x:auto} +a{color:var(--cyan2)} diff --git a/server.js b/server.js new file mode 100644 index 0000000..2e5e285 --- /dev/null +++ b/server.js @@ -0,0 +1,215 @@ +// Drip Runner: a hop-and-collect game for InstantAdPay members, paid in POL, funded by the +// verified visits players make to refuel. Trial build (2026-09-30). +// +// Gates, all default-deny, all from the environment: +// CURTAIN= the tester page at / shows "Coming soon" to anyone without ?k= +// OUTBOUND=on required before anything leaves this server (Telegram to Marty). No mailer exists. +// DR_SSO_SECRET shared with InstantAdPay: hand-off tokens, refuel tokens, receipts, callbacks +// ADMIN_KEY the admin page and API +// IAP_URL https://instantadpay.com (where refuel visits happen) +// SITE_URL this app's public URL +// DR_WALLET_KEY / DR_RPC / DR_CHAIN_ID / DR_DRY_RUN the faucet (lib/faucet.js) +// DR_TG_TOKEN / DR_TG_CHAT Marty's private alerts (payouts, failures, low balance) +// Who may sign in is a setting (admin page): 'testers' (allowlist), 'open', 'closed'. +'use strict'; +const http = require('http'); +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const store = require('./lib/store'); +const sso = require('./lib/sso'); +const game = require('./lib/game'); +const ledger = require('./lib/ledger'); +const faucet = require('./lib/faucet'); +const spawn = require('./lib/spawn'); + +const PORT = Number(process.env.PORT || 3000); +const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data'); +const PUBLIC_DIR = path.join(__dirname, 'public'); +const CURTAIN = String(process.env.CURTAIN || '').trim(); +const ADMIN_KEY = String(process.env.ADMIN_KEY || '').trim(); +const SITE = String(process.env.SITE_URL || 'https://driprunner.saasy.top').replace(/\/+$/, ''); +const IAP = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''); +const SECRET = String(process.env.DR_SSO_SECRET || '').trim(); +const outbound = () => process.env.OUTBOUND === 'on'; +const IS_PROD = process.env.NODE_ENV === 'production'; + +store.init(DATA_DIR); +const faucetOn = faucet.init(); + +// ---- Telegram to Marty (outward: gated) ------------------------------------------------------- +async function telegram(text) { + if (!outbound()) return false; + const tok = process.env.DR_TG_TOKEN, chat = process.env.DR_TG_CHAT; if (!tok || !chat) return false; + try { const r = await fetch('https://api.telegram.org/bot' + tok + '/sendMessage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: chat, text, parse_mode: 'HTML', disable_web_page_preview: true }) }); return r.ok; } catch (e) { return false; } +} +const fmt = n => Number(n).toLocaleString('en-US', { maximumFractionDigits: 4 }); +const explorer = () => Number(process.env.DR_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com'; +async function notify(kind, p) { + const who = p && (p.username ? '@' + p.username : '#' + p.memberId); + if (kind === 'paid') return telegram('\u{1F3AE} Drip Runner · paid ' + who + ' ' + fmt(p.pol) + ' POL · verify'); + if (kind === 'failed') return telegram('❌ Drip Runner · payout to ' + who + ' failed: ' + p.error); + if (kind === 'low') return telegram('⚠️ Drip Runner wallet is low: ' + fmt(p.balance) + ' POL in ' + p.address + ' (needs ' + fmt(p.threshold) + ').'); + if (kind === 'signin') return telegram('\u{1F44B} Drip Runner · first sign-in: ' + who + ' (' + (p.wallet ? 'wallet on file' : 'NO wallet yet') + ')'); + if (kind === 'refuel') return telegram('⛽ Drip Runner · ' + who + ' refuelled on campaign #' + p.campaignId + ': +' + fmt(p.pol) + ' POL to the pool (' + p.credits + ' credits, $' + p.share + ' share)'); + return false; +} + +// ---- helpers --------------------------------------------------------------------------------- +const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' }; +const CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'"; +const SEC = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'Content-Security-Policy': CSP }; +function json(res, code, body, extra) { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, SEC, extra || {})); res.end(JSON.stringify(body)); } +function sendFile(res, file, extra) { + fs.readFile(file, (err, buf) => { + if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } + res.writeHead(200, Object.assign({ 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' }, SEC, extra || {})); + res.end(buf); + }); +} +function page(res, code, title, body, extra) { + res.writeHead(code, Object.assign({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, SEC, extra || {})); + res.end('' + title + '

' + title + '

' + body + '
'); +} +const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +function readBody(req) { + return new Promise(resolve => { let d = ''; req.on('data', c => { d += c; if (d.length > 200000) req.destroy(); }); req.on('end', () => { let j = {}; try { j = JSON.parse(d || '{}'); } catch (e) {} resolve({ raw: d, body: j }); }); }); +} +const CURTAIN_PAGE = 'Coming soon

Coming soon

This site is still being built.

'; +function curtained(req, res, u) { + if (!CURTAIN) return false; + if (u.searchParams.get('k') === CURTAIN) { u.searchParams.delete('k'); res.writeHead(302, { 'Set-Cookie': 'dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : ''), Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), 'Cache-Control': 'no-store' }); res.end(); return true; } + const m = /(?:^|;\s*)dr\.pass=([^;]+)/.exec(req.headers.cookie || ''); + if (m && decodeURIComponent(m[1]) === CURTAIN) return false; + res.writeHead(503, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }); res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); return true; +} +function admin(req, u) { const k = req.headers['x-admin-key'] || u.searchParams.get('key'); return !!(ADMIN_KEY && k && k.length === ADMIN_KEY.length && crypto.timingSafeEqual(Buffer.from(k), Buffer.from(ADMIN_KEY))); } +// who may come through the hand-off +function allowed(claims) { + const s = ledger.settings(); const mode = String(process.env.DR_SIGNUPS || s.signups || 'testers'); + if (mode === 'open') return true; if (mode === 'closed') return false; + const list = (s.testers || []).map(x => String(x).trim().toLowerCase()).filter(Boolean); + return list.includes(String(claims.email || '').toLowerCase()) || list.includes(String(claims.memberId)); +} +// the IAP -> game callback is signed over the timestamp and the raw body with the shared secret +function callbackOk(req, raw) { + const ts = String(req.headers['x-dr-ts'] || ''), sig = String(req.headers['x-dr-sig'] || ''); + if (!SECRET || !ts || !sig || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return false; + const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex'); + return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig)); +} +const intents = { get: n => store.read('refuel-intents', {})[n] || null, set: (n, v) => store.update('refuel-intents', {}, all => { const cut = Date.now() - 86400000; for (const k of Object.keys(all)) if (all[k].ts < cut) delete all[k]; all[n] = v; return all; }), upd: (n, fn) => store.update('refuel-intents', {}, all => { if (all[n]) fn(all[n]); return all; })[n] }; +async function creditRefuel(intent, nonce, info) { + if (intent.credited) return intent; + const me = { memberId: intent.memberId, username: intent.username, wallet: intent.wallet }; + const row = await ledger.refuel(me, Object.assign({ nonce }, info)); + intents.upd(nonce, x => { x.credited = row.id; x.done = true; x.campaignId = info.campaignId || null; x.pol = row.pol; }); + notify('refuel', Object.assign({}, me, { campaignId: info.campaignId, credits: row.credits, share: row.share, pol: row.pol })).catch(() => {}); + return intents.get(nonce); +} + +// ---- server ------------------------------------------------------------------------------------ +const server = http.createServer(async (req, res) => { + const u = new URL(req.url, 'http://x'); const p = u.pathname; + try { + if (p === '/health') return json(res, 200, { ok: true, outbound: outbound(), curtain: !!CURTAIN, sso: sso.enabled(), faucet: faucetOn, dryRun: faucet.dry(), chain: Number(process.env.DR_CHAIN_ID) || null, signups: String(process.env.DR_SIGNUPS || ledger.settings().signups) }); + + // ---- sign-in by hand-off (passes the curtain: the member already came through IAP) ---- + if (p === '/auth') { + const r = sso.verify(u.searchParams.get('t')); + if (r.error) return page(res, 400, 'Sign-in did not work', '

' + esc(r.error) + '

Try again from InstantAdPay

'); + if (!allowed(r.claims)) return page(res, 403, 'Not on the tester list yet', '

Drip Runner is in a closed trial. Your InstantAdPay account (' + esc(r.claims.username ? '@' + r.claims.username : '#' + r.claims.memberId) + ') is not on the tester list. Ask Marty to add you.

'); + const existing = sso.fromRequest(req); + let sid; + if (existing && existing.memberId === Number(r.claims.memberId)) { sso.refresh(existing.sid, r.claims); sid = existing.sid; } + else sid = sso.startSession(r.claims); + const first = !game.player(r.claims.memberId); + 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(); }); + if (first) notify('signin', { memberId: r.claims.memberId, username: r.claims.username, wallet: r.claims.wallet }).catch(() => {}); + res.writeHead(302, { Location: '/play', 'Set-Cookie': sso.cookie(sid), 'Cache-Control': 'no-store' }); return res.end(); + } + if (p === '/logout') { const s = sso.fromRequest(req); if (s) sso.endSession(s.sid); res.writeHead(302, { Location: '/', 'Set-Cookie': sso.clearCookie() }); return res.end(); } + + // ---- IAP -> game: the refuel visit completed (server to server, signed) ---- + if (p === '/api/refuel/callback' && req.method === 'POST') { + const { raw, body } = await readBody(req); + if (!callbackOk(req, raw)) return json(res, 401, { error: 'bad signature' }); + const it = intents.get(String(body.nonce || '')); + if (!it) return json(res, 404, { error: 'unknown refuel' }); + if (Number(body.memberId) !== it.memberId) return json(res, 400, { error: 'member mismatch' }); + const out = await creditRefuel(it, String(body.nonce), { campaignId: body.campaignId, credits: body.credits, via: 'callback' }); + return json(res, 200, { ok: true, pol: out.pol }); + } + + // ---- static + pages ---- + if (p === '/' || p === '/index.html') { if (curtained(req, res, u)) return; return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); } + if (p === '/play') return sendFile(res, path.join(PUBLIC_DIR, 'play.html')); + if (p === '/admin') { if (!admin(req, u)) return page(res, 403, 'Admin', '

Key required.

'); return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); } + if (p === '/spawn.js') return sendFile(res, path.join(__dirname, 'lib', 'spawn.js')); + if (/^\/[a-z0-9._-]+\.(css|js|png|jpg|svg|ico|webp|mp4)$/i.test(p) && !p.includes('..')) return sendFile(res, path.join(PUBLIC_DIR, p.slice(1))); + + // ---- member API ---- + if (p.startsWith('/api/')) { + const me = sso.fromRequest(req); + if (p.startsWith('/api/admin/')) { + if (!admin(req, u)) return json(res, 403, { error: 'admin key' }); + if (p === '/api/admin/state' && req.method === 'GET') { + const accounts = store.read('accounts', {}); const players = store.read('players', {}); + return json(res, 200, { settings: ledger.settings(), pool: ledger.pool(), usdPerPol: await ledger.usdPerPol(), faucet: faucet.state(), + refuels: store.read('refuels', []).slice(-100).reverse(), drips: store.read('drips', []).slice(-100).reverse(), spends: store.read('spends', []).slice(-100).reverse(), payouts: store.read('payouts', []).slice(-100).reverse(), + accounts: Object.values(accounts), players: Object.values(players).map(x => ({ memberId: x.memberId, username: x.username, email: x.email, wallet: x.wallet, chapter: x.chapter, bank: x.bank, best: x.best, runs: x.runs, lastSeen: x.lastSeen, items: x.items })), runs: game.recent(60), site: SITE, iap: IAP, curtain: CURTAIN ? SITE + '/?k=' + CURTAIN : SITE }); + } + if (p === '/api/admin/settings' && req.method === 'POST') { + const { body } = await readBody(req); const patch = {}; + for (const k of ['usdPerCredit', 'creditsPerVisit', 'poolSharePct', 'usdPerPolFallback', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'lowBalancePol']) if (body[k] != null && body[k] !== '') patch[k] = Number(body[k]); + if (body.signups && ['testers', 'open', 'closed'].includes(body.signups)) patch.signups = body.signups; + if (Array.isArray(body.testers)) patch.testers = body.testers.map(x => String(x).trim().toLowerCase()).filter(Boolean).slice(0, 500); + if (body.itemPol && typeof body.itemPol === 'object') patch.itemPol = Object.assign({}, ledger.settings().itemPol, body.itemPol); + if (body.itemDrips && typeof body.itemDrips === 'object') patch.itemDrips = Object.assign({}, ledger.settings().itemDrips, body.itemDrips); + return json(res, 200, { ok: true, settings: ledger.setSettings(patch) }); + } + if (p === '/api/admin/faucet/tick' && req.method === 'POST') return json(res, 200, await faucet.tick(notify)); + if (p === '/api/admin/handoff' && req.method === 'POST') { // a test token for a synthetic member (local checks only) + const { body } = await readBody(req); return json(res, 200, { url: SITE + '/auth?t=' + sso.mint({ memberId: Number(body.memberId) || 999001, email: body.email || 'tester@example.com', wallet: body.wallet || null, username: body.username || 'tester' }) }); + } + return json(res, 404, { error: 'no such admin route' }); + } + if (!me) return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner' }); + if (p === '/api/me' && req.method === 'GET') { + const pl = ledger.pool(); + return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet }, 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 }); + } + 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 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 }); } + 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; 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') { + const { body } = await readBody(req); const r = game.run(String(body.runId || '')); + if (!r || r.memberId !== me.memberId || r.status !== 'live') return json(res, 400, { error: 'That run cannot be refuelled.' }); + const nonce = crypto.randomBytes(12).toString('hex'); const ret = SITE + '/play?resume=' + r.id + '&n=' + nonce; + intents.set(nonce, { runId: r.id, memberId: me.memberId, username: me.username, wallet: me.wallet, email: me.email, ts: Date.now(), done: false, consumed: false }); + const tok = sso.mint({ kind: 'refuel', memberId: me.memberId, email: me.email, username: me.username, nonce, ret }, 15 * 60000); + return json(res, 200, { url: IAP + '/refuel?t=' + tok, nonce }); + } + if (p === '/api/refuel/resume' && req.method === 'POST') { + const { body } = await readBody(req); const nonce = String(body.nonce || ''); let it = intents.get(nonce); + if (!it || it.memberId !== me.memberId || it.runId !== String(body.runId || '')) return json(res, 400, { error: 'That refuel does not match this run.' }); + if (it.consumed) return json(res, 400, { error: 'That refuel was already used.' }); + // the browser may carry IAP's signed receipt: it counts even when the server callback was slow + if (!it.done && body.receipt) { const rc = sso.open(body.receipt); if (rc.ok && rc.claims.kind === 'refuel-receipt' && rc.claims.nonce === nonce) it = await creditRefuel(it, nonce, { campaignId: rc.claims.campaignId, credits: rc.claims.credits, via: 'receipt' }); } + if (!it.done) return json(res, 200, { ok: false, reason: body.none ? 'none' : 'unverified' }); + intents.upd(nonce, x => { x.consumed = true; }); game.refuelled(me, it.runId); + return json(res, 200, { ok: true, pool: ledger.pool().available }); + } + if (p === '/api/hangar/buy' && req.method === 'POST') { const { body } = await readBody(req); const r = game.buy(me, String(body.item || '')); if (!r.error) { r.player = game.view(me); r.balance = ledger.balance(me.memberId); } return json(res, r.error ? 400 : 200, r); } + return json(res, 404, { error: 'no such route' }); + } + res.writeHead(404, Object.assign({ 'Content-Type': 'text/plain' }, SEC)); res.end('Not found'); + } catch (e) { + console.error(req.method, p, e && e.stack || e); + if (!res.headersSent) json(res, 500, { error: 'Something broke on our side. Try again.' }); + } +}); +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); } diff --git a/test/run.js b/test/run.js new file mode 100644 index 0000000..87704c5 --- /dev/null +++ b/test/run.js @@ -0,0 +1,99 @@ +// End-to-end on a local boot: hand-off + allowlist, a run with drip claims checked against the +// schedule, a chapter clear with the pool empty (pays nothing), a refuel callback that funds the +// pool, a paid clear, a replay that pays nothing, refused claims, the hangar sink, the payout +// sweep. No faucet, no outbound. +'use strict'; +const { spawn } = require('child_process'); +const path = require('path'); +const fs = require('fs'); +const crypto = require('crypto'); + +const PORT = 8898, DIR = path.join(__dirname, '..', 'data-test'); +fs.rmSync(DIR, { recursive: true, force: true }); +const SECRET = 'y'.repeat(48); +const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DIR, DR_SSO_SECRET: SECRET, ADMIN_KEY: 'adminkey123', SITE_URL: 'http://127.0.0.1:' + PORT, IAP_URL: 'http://iap.test' }); +delete env.CURTAIN; delete env.OUTBOUND; delete env.DR_WALLET_KEY; delete env.DR_RPC; delete env.DR_SIGNUPS; +const child = spawn(process.execPath, [path.join(__dirname, '..', 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); +child.stderr.on('data', d => process.stderr.write(d)); +let fails = 0; +const eq = (a, b, m) => { const ok = JSON.stringify(a) === JSON.stringify(b); console.log((ok ? ' ok ' : ' FAIL ') + m + (ok ? '' : ' -> got ' + JSON.stringify(a) + ' want ' + JSON.stringify(b))); if (!ok) fails++; }; +const B = 'http://127.0.0.1:' + PORT; +let jar = ''; +const call = async (p, opt = {}) => { + const res = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: jar, 'Content-Type': 'application/json' }, opt.headers || {}) })); + const sc = res.headers.get('set-cookie'); if (sc && /dr\.sid=[a-f0-9]/.test(sc)) jar = sc.split(';')[0]; + let body = null; try { body = await res.json(); } catch (e) {} + return { status: res.status, body, headers: res.headers }; +}; +const post = (p, b, h) => call(p, { method: 'POST', body: JSON.stringify(b || {}), headers: h }); +const admin = (p, b) => call(p, Object.assign({ headers: { 'X-Admin-Key': 'adminkey123' } }, b ? { method: 'POST', body: JSON.stringify(b) } : {})); +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const spawnLib = require('../lib/spawn'); + +(async () => { + await sleep(1200); + process.env.DR_SSO_SECRET = SECRET; const sso = require('../lib/sso'); + const h = await call('/health'); eq([h.body.sso, h.body.faucet, h.body.signups], [true, false, 'testers'], 'posture: sso on, faucet off, testers mode'); + + // allowlist + const tok0 = sso.mint({ memberId: 42, email: 'runner@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'runner42' }); + const denied = await call('/auth?t=' + tok0); eq(denied.status, 403, 'a member not on the tester list is refused'); + const st = await admin('/api/admin/settings', { testers: ['runner@example.com'], thresholdPol: 0.02, dripPol: 0.01 }); eq(st.body.settings.testers, ['runner@example.com'], 'admin adds a tester'); + const tok = sso.mint({ memberId: 42, email: 'runner@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'runner42' }); + const a = await call('/auth?t=' + tok); eq([a.status, a.headers.get('location')], [302, '/play'], 'a listed member signs in and lands on the game'); + eq((await call('/auth?t=' + tok)).status, 400, 'the hand-off token cannot be replayed'); + const me = await call('/api/me'); eq([me.body.me.memberId, me.body.player.chapter, me.body.player.goal, me.body.balance.unpaid], [42, 1, 20, 0], '/api/me: chapter 1, goal 20, balance 0'); + + // a run: collect the first 20 drips exactly when the schedule says they cross the courier + const W = 390, H = 760; + const r1 = (await post('/api/run/start', { W, H })).body; eq([r1.chapter, r1.goal, r1.speed], [1, 20, 230], 'run starts on chapter 1 at speed 230'); + const gen = spawnLib.drips(r1.seed, W, H); const claims = []; let lastT = 0; + while (claims.length < 20) { const g = gen(); for (const d of g.drips) { if (claims.length < 20) { const t = spawnLib.arrival(g.t, d.x0, W, r1.speed) + 0.1; claims.push({ k: 'd', i: d.i, t: Math.round(t * 1000) / 1000 }); lastT = t; } } } + const bad = [{ k: 'd', i: 500, t: 1 }, { k: 'd', i: claims[0].i, t: claims[0].t }]; // a drip that has not spawned, and a duplicate + // the run clock cannot outrun the wall clock: move the start back instead of waiting 15 s + const backdate = (runId, secs) => { const runs = JSON.parse(fs.readFileSync(path.join(DIR, 'runs.json'), 'utf8')); runs[runId].startedAt = Date.now() - secs * 1000; fs.writeFileSync(path.join(DIR, 'runs.json'), JSON.stringify(runs)); }; + backdate(r1.runId, lastT + 5); + const ev = await post('/api/run/events', { runId: r1.runId, t: lastT + 0.2, events: claims.concat(bad), goal: true }); + eq([ev.body.ok, ev.body.refused, ev.body.why], [20, 2, ['early', 'dup']], '20 claims accepted, 2 refused with reasons'); + eq([ev.body.cleared.chapter, ev.body.cleared.first, ev.body.cleared.pol, ev.body.cleared.reason], [1, true, 0, 'pool'], 'first clear of chapter 1 with an empty pool: cleared, pays nothing'); + const me2 = await call('/api/me'); eq([me2.body.player.chapter, me2.body.player.bank], [2, 20], 'player is on chapter 2 with 20 drips banked'); + + // refuel: the game hands out a token, IAP calls back with a signed body, the pool fills + const rf = await post('/api/refuel/start', { runId: r1.runId }); eq([rf.status, rf.body.url.startsWith('http://iap.test/refuel?t=')], [200, true], 'refuel start mints an IAP link'); + const nonce = rf.body.nonce; + const raw = JSON.stringify({ nonce, memberId: 42, campaignId: 77, credits: 3 }); const ts = String(Date.now()); + const badSig = await call('/api/refuel/callback', { method: 'POST', body: raw, headers: { 'X-DR-Ts': ts, 'X-DR-Sig': 'nope' } }); eq(badSig.status, 401, 'an unsigned callback is refused'); + const sig = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex'); + const cb = await call('/api/refuel/callback', { method: 'POST', body: raw, headers: { 'X-DR-Ts': ts, 'X-DR-Sig': sig } }); eq([cb.status, cb.body.pol > 0], [200, true], 'a signed callback credits the pool'); + const stA = await admin('/api/admin/state'); const expectPol = Math.round((3 * 0.01 * 0.30 / stA.body.usdPerPol) * 10000) / 10000; eq(stA.body.pool.in, expectPol, 'pool in = 3 credits x $0.01 x 30% / usdPerPol (' + expectPol + ')'); + const rs = await post('/api/refuel/resume', { runId: r1.runId, nonce }); eq([rs.body.ok, rs.body.pool], [true, expectPol], 'the run resumes once the callback landed'); + eq((await post('/api/refuel/resume', { runId: r1.runId, nonce })).status, 400, 'a refuel cannot be consumed twice'); + + // chapter 2 (goal 32) in the same run: paid from the pool + const claims2 = []; let t2 = 0; let g2; while (claims2.length < 32) { g2 = gen(); for (const d of g2.drips) if (claims2.length < 32) { const t = spawnLib.arrival(g2.t, d.x0, W, r1.speed) - 0.3; claims2.push({ k: 'd', i: d.i, t: Math.round(t * 1000) / 1000 }); t2 = t; } } + // the run clock must have moved: patch startedAt back so the wall check passes without waiting + backdate(r1.runId, t2 + 5); + const ev2 = await post('/api/run/events', { runId: r1.runId, t: t2 + 0.2, events: claims2, goal: true }); + eq([ev2.body.ok, ev2.body.cleared.chapter, ev2.body.cleared.pol, ev2.body.cleared.reason], [32, 2, 0.01, 'paid'], 'chapter 2 clear pays 0.01 POL from the pool'); + const bal = await call('/api/balance'); eq([bal.body.unpaid, bal.body.history[0].kind], [0.01, 'drip'], 'balance shows the drip'); + await post('/api/run/end', { runId: r1.runId }); + + // a replay of chapter 1 pays nothing; the hangar sink works; the sweep makes a payout row + const r2 = (await post('/api/run/start', { W, H })).body; eq(r2.chapter, 3, 'a new run starts on chapter 3 (progress kept)'); + await post('/api/run/end', { runId: r2.runId }); + const buyNo = await post('/api/hangar/buy', { item: 'shield' }); eq(buyNo.status, 400, 'shield (0.05 POL) refused on a 0.01 balance'); + await admin('/api/admin/settings', { itemPol: { slow: 0.005 } }); + const buy = await post('/api/hangar/buy', { item: 'slow' }); eq([buy.status, buy.body.paid, buy.body.balance.unpaid], [200, '0.005 POL', 0.005], 'slow field bought from the POL balance'); + const stB = await admin('/api/admin/state'); eq(stB.body.pool.spends, 0.005, 'the spend went back to the pool'); + const magnet = await post('/api/hangar/buy', { item: 'magnet' }); eq(magnet.status, 400, 'magnet (250 drips) refused on 52 drips'); + await admin('/api/admin/settings', { thresholdPol: 0.005 }); + const stC = await admin('/api/admin/state'); // state does not sweep; the faucet does. call the ledger directly through a tick with no wallet: payable() is exercised by the sweep below + eq(stC.body.accounts[0].unpaid, 0.005, 'account unpaid is 0.005 before the sweep'); + process.env.DATA_DIR = DIR; const store = require('../lib/store'); store.init(DIR); const ledger = require('../lib/ledger'); + const due = ledger.payable(); eq([due.length, due[0].pol, due[0].wallet], [1, 0.005, '0x' + 'ab'.repeat(20)], 'the sweep turns a balance at threshold into one due payout row'); + eq(ledger.account(42).unpaid, 0, 'the balance moved onto the payout row'); + ledger.mark(due[0].id, { status: 'failed', error: 'test' }); eq(ledger.account(42).unpaid, 0.005, 'a failed payout returns the POL to the balance'); + + console.log(fails ? '\n' + fails + ' FAILED' : '\nall good'); + child.kill(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0); +})().catch(e => { console.error(e); child.kill(); process.exit(1); });