// 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) refSharePct: 10, // the referrer's slice of each refuel's pool income (their referrals' refuels), paid into the referrer's game balance testers: [], // emails or member ids allowed through the hand-off while signups = 'testers' trial: true, // posts say 'coming soon, in testing' and 'would have earned' until Marty flips it signups: 'testers' // 'testers' | 'key' (tester list or the curtain pass) | '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(); // IAP reports 0 for a house-ad visit (nobody paid): keep it 0, never fall back to the visit price (2026-10-03) const credits = Math.max(0, (info.credits != null && info.credits !== '' && isFinite(Number(info.credits))) ? 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); // the referral slice: a cut of THIS refuel's pool income, so it can never cost more than the refuel brought in const ref = info.referrer; const pct = Number(s.refSharePct) || 0; if (ref && ref.memberId > 0 && ref.memberId !== Number(me.memberId) && pct > 0) { const slice = r4(pol * pct / 100); if (slice > 0) { poolAdd('out', slice); updAccount(ref.memberId, a => { a.unpaid += slice; a.earnedTotal = r4((a.earnedTotal || 0) + slice); a.refTotal = r4((a.refTotal || 0) + slice); a.wallet = a.wallet || ref.wallet || null; a.username = a.username || ref.username || null; }); store.update('refslices', [], all => { all.push({ id: id(), refuelId: row.id, memberId: ref.memberId, fromMemberId: Number(me.memberId), fromUsername: me.username || null, pol: slice, day: ctDay(), ts: Date.now() }); return all; }); row.slice = { to: ref.memberId, pol: slice }; } } 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 }; } // ---- Game Pass (GAMEPASS=on, docs/GAME-PASS.md 3a): InstantAdPay's account-wide caps decide what a member is paid; the // local cap and pool above stay as a backstop and are never raised. The only POL Drip Runner pays is a chapter's first clear, // once per member, so every reward here is 'progress': what today's cap does not allow is deferred on IAP and folded into a // later answer. A member with no wallet has a negative local id (sso.emailId): IAP gets memberId 0 and the email instead. const gp = require('./polgrant'); const kindOf = key => 'progress'; // refs: chapter: const iapId = me => Number(me.memberId) > 0 ? Number(me.memberId) : 0; const passActive = me => !!(gp.on() && me && !me.guest && gp.passOf(iapId(me), me.email).active); // the same checks as chapterDrip() up to (not including) the ledger write -> { pol, key, chapter } or { pol: 0, reason } function quote(me, chapter, eligible) { const s = settings(); const pol = r4(Number(s.dripPol)); if (!eligible) return { pol: 0, reason: 'replay' }; if (!(pol > 0)) return { pol: 0, reason: 'none' }; const p = pool(); if (p.capLeft < pol) return { pol: 0, reason: 'cap' }; if (p.available < pol) return { pol: 0, reason: 'pool' }; return { pol, key: 'chapter:' + chapter, chapter }; } // IAP answered: the ledger gets exactly what was allowed (0 included, so the chapter counts as handled); `carried` (inside // allowed) is what IAP paid from an earlier deferral; the account tracks what IAP still owes. function settleGrant(me, q, r, gkind) { const allowed = r4(r.allowed), extra = r.carried > 0 ? r4(r.carried) : r4(Math.max(0, allowed - q.pol)); const row = { id: id(), memberId: Number(me.memberId), username: me.username || null, wallet: me.wallet || null, pol: allowed, chapter: q.chapter, day: ctDay(), ts: Date.now(), status: 'granted', gp: { kind: gkind, ref: q.key, nominal: q.pol, deferred: r4(r.deferred || 0), pass: !!r.pass } }; store.update('drips', [], all => { if (!all.some(d => d.memberId === row.memberId && d.gp && d.gp.ref === q.key)) all.push(row); return all; }); if (allowed > 0) poolAdd('out', allowed); updAccount(me.memberId, a => { a.unpaid += allowed; a.earnedTotal = r4((a.earnedTotal || 0) + allowed); a.wallet = me.wallet || a.wallet || null; a.username = me.username || a.username || null; a.email = me.email || a.email || null; a.gpOwed = r4(Math.max(0, (a.gpOwed || 0) + (Number(r.deferred) || 0) - extra)); }); return { pol: allowed, reason: allowed > 0 ? 'paid' : (gkind === 'daily' ? 'capday' : 'deferred'), nominal: q.pol, deferred: r4(r.deferred || 0), pass: !!r.pass, note: gp.note(r, gkind, q.pol), id: row.id }; } // chapterDrip() with IAP in front of it. Switch off, or a guest: the plain chapterDrip, unchanged. Fail closed: no answer from // IAP = nothing paid now, the ref queued and retried (polgrant.js), the player told it is recorded. async function chapterDripGated(me, chapter, eligible) { if (!gp.on() || me.guest || !gp.whoOf(iapId(me), me.email)) return chapterDrip(me, chapter, eligible); const q = quote(me, chapter, eligible); if (q.reason) return q; if (gp.queued(iapId(me), me.email, q.key)) return { pol: 0, reason: 'iap', nominal: q.pol }; const gkind = kindOf(q.key), r = await gp.grant({ memberId: iapId(me), email: me.email, kind: gkind, pol: q.pol, ref: q.key }); if (r.retry) { gp.enqueue({ memberId: iapId(me), email: me.email, ref: q.key, kind: gkind, pol: q.pol, me: { memberId: Number(me.memberId), username: me.username || null, wallet: me.wallet || null, email: me.email || null }, q }); return { pol: 0, reason: 'iap', nominal: q.pol, note: gp.note(r, gkind, q.pol) }; } return settleGrant(me, q, r, gkind); } const payQueued = (item, r) => settleGrant(item.me, item.q, r, item.kind); // a queued ref finally answered // once a Central day per account IAP still owes: a zero-POL progress call collects the carry-forward (IAP folds it into `allowed`) async function carrySweep() { if (!gp.on()) return 0; const today = ctDay(), accts = store.read('accounts', {}); let got = 0; for (const k of Object.keys(accts)) { const a = accts[k]; if (!(a.gpOwed > 0) || a.gpCarryDay === today) continue; const me = { memberId: a.memberId, email: a.email || null, username: a.username, wallet: a.wallet }; if (!gp.whoOf(iapId(me), me.email)) continue; const r = await gp.grant({ memberId: iapId(me), email: me.email, kind: 'progress', pol: 0, ref: 'carry:' + today }); if (r.retry) continue; updAccount(a.memberId, x => { x.gpCarryDay = today; }); if (r.allowed > 0) { settleGrant(me, { pol: 0, key: 'carry:' + today, chapter: 0 }, r, 'progress'); got += r.allowed; } } return got; } // ---- payouts ---------------------------------------------------------------------------------- // a member whose unpaid balance reached the threshold gets one payout row for the whole amount; // the balance moves to the row so drips earned meanwhile start a fresh count 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: !d.chapter ? 'Carried-over reward paid' : 'Chapter ' + d.chapter + ' · first clear' + (d.gp && d.gp.deferred > 0 ? ' (' + d.gp.deferred + ' POL paying out over the next days)' : ''), pol: d.pol }))) .concat(store.read('spends', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'spend', label: 'Hangar · ' + d.item, pol: -d.pol }))) .concat(store.read('refslices', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'ref', label: 'Referral · ' + (d.fromUsername ? '@' + d.fromUsername : 'a player') + ' refuelled', pol: d.pol }))) .concat(store.read('payouts', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'payout', label: d.status === 'paid' ? 'Paid to your wallet' : d.status === 'failed' ? 'Payout failed: ' + (d.error || '') : 'Payout on its way', pol: d.pol, status: d.status, tx: d.tx || null }))) .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), refTotal: r4(a.refTotal || 0), refSharePct: Number(s.refSharePct) || 0, threshold: Number(s.thresholdPol), history: hist, wallet: a.wallet || null }; } module.exports = { DEFAULTS, settings, setSettings, ctDay, pool, refuel, refuelsToday, account, chapterDrip, chapterDripGated, quote, settleGrant, kindOf, passActive, iapId, payQueued, carrySweep, gp, spend, sweep, payable, mark, balance, usdPerPol, r4 };