// 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 }; } // ---- 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('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, spend, sweep, payable, mark, balance, usdPerPol, r4 };