Referral layer: guest play from share links (/r/<username>), guest clears paid on sign-in, sharer's link via their IAP join page, 10% referrer slice of each referral refuel's pool income (IAP sponsor), share buttons + stats in the lobby and on chapter clears, wallet-less progress follows the member once a wallet is linked; 11 new checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-09-30 17:14:08 -05:00
parent 83da8c33f2
commit 06daa4ef0a
10 changed files with 203 additions and 25 deletions
+32 -2
View File
@@ -94,8 +94,9 @@ function events(me, runId, t, list, 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);
const grant = me.guest ? { pol: 0, reason: 'guest' } : ledger.chapterDrip(me, ch, first && !out.flagged);
if (first && out.flagged) grant.reason = 'flagged';
if (me.guest && first && !out.flagged) updPlayer(me.memberId, x => { x.pending = Array.from(new Set([...(x.pending || []), ch])); }); // paid when they sign in
updPlayer(me.memberId, x => { x.cleared[ch] = true; if (x.chapter <= ch) x.chapter = ch + 1; });
updRun(runId, x => { x.cleared.push(ch); x.chapter = ch + 1; x.chapDrips = 0; x.goal = spawn.goalFor(ch + 1); });
res.cleared = { chapter: ch, first, pol: grant.pol, reason: grant.reason, next: ch + 1, nextGoal: spawn.goalFor(ch + 1), playTime: Math.round(out.t) };
@@ -129,6 +130,35 @@ function buy(me, item) {
}
return { error: 'No such item.' };
}
// Move everything one id owns onto another (a guest who signs in, or a wallet-less member who links a wallet).
// Returns the chapters the old id cleared as a guest that the new id has never cleared: the caller pays those.
function adopt(fromId, toId) {
fromId = Number(fromId); toId = Number(toId); if (!fromId || fromId === toId) return { moved: false, pending: [] };
const all = store.read('players', {}); const a = all[String(fromId)]; if (!a) return { moved: false, pending: [] };
const b = all[String(toId)]; const pending = (a.pending || []).filter(ch => !(b && b.cleared && b.cleared[ch]));
store.update('players', {}, ps => {
const src = ps[String(fromId)]; const dst = ps[String(toId)];
if (!dst) { ps[String(toId)] = Object.assign({}, src, { memberId: toId, pending: [] }); }
else { dst.bank += src.bank; dst.runs += src.runs; dst.best = Math.max(dst.best, src.best); dst.chapter = Math.max(dst.chapter, src.chapter); dst.cleared = Object.assign({}, src.cleared, dst.cleared); dst.items = Object.assign({}, src.items, dst.items); }
delete ps[String(fromId)]; return ps;
});
for (const name of ['drips', 'spends', 'refuels', 'payouts']) store.update(name, [], rows => { for (const r of rows) if (r.memberId === fromId) r.memberId = toId; return rows; });
store.update('accounts', {}, acc => { const x = acc[String(fromId)]; if (x) { const y = acc[String(toId)]; if (y) { y.unpaid = Math.round((y.unpaid + x.unpaid) * 10000) / 10000; y.earnedTotal = Math.round(((y.earnedTotal || 0) + (x.earnedTotal || 0)) * 10000) / 10000; y.spentTotal = Math.round(((y.spentTotal || 0) + (x.spentTotal || 0)) * 10000) / 10000; } else acc[String(toId)] = Object.assign({}, x, { memberId: toId }); delete acc[String(fromId)]; } return acc; });
store.update('runs', {}, rs => { for (const k of Object.keys(rs)) if (rs[k].memberId === fromId) rs[k].memberId = toId; return rs; });
store.update('posted', {}, ps => { if (ps[String(fromId)]) { ps[String(toId)] = Array.from(new Set([...(ps[String(toId)] || []), ...ps[String(fromId)]])); delete ps[String(fromId)]; } return ps; });
return { moved: true, pending };
}
// the players whose InstantAdPay sponsor is this member (their referrals in the game)
function referralsOf(me) {
const keys = [String(me.memberId), String(me.username || '').toLowerCase()].filter(Boolean);
return Object.values(store.read('players', {})).filter(p => p.memberId > 0 && p.sponsorRef && keys.includes(String(p.sponsorRef).toLowerCase()));
}
// the game player a sponsorRef points at (username, or on-chain member id)
function byRef(ref) {
const r = String(ref || '').trim().toLowerCase(); if (!r) return null;
return Object.values(store.read('players', {})).find(p => p.memberId > 0 && ((p.username && p.username.toLowerCase() === r) || String(p.memberId) === r)) || null;
}
function byUsername(u) { const r = String(u || '').trim().toLowerCase().replace(/^@/, ''); return r ? Object.values(store.read('players', {})).find(p => p.username && p.username.toLowerCase() === r) || null : null; }
function recent(n) { return Object.values(runs()).sort((a, b) => b.startedAt - a.startedAt).slice(0, n || 50).map(r => Object.assign({}, r, { collected: r.collected.length })); }
module.exports = { player, updPlayer, view, run, start, events, end, refuelled, buy, recent, prune };
module.exports = { player, updPlayer, view, run, start, events, end, refuelled, buy, recent, prune, adopt, referralsOf, byRef, byUsername };
+14 -1
View File
@@ -24,6 +24,7 @@ const DEFAULTS = {
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'
@@ -58,6 +59,17 @@ async function refuel(me, info) {
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); }
@@ -125,9 +137,10 @@ function balance(memberId) {
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), threshold: Number(s.thresholdPol), history: hist, wallet: a.wallet || null };
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 };
+19 -3
View File
@@ -16,7 +16,24 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
const sign = payload => b64u(crypto.createHmac('sha256', SECRET).update(payload).digest());
const secure = () => process.env.NODE_ENV === 'production' ? '; Secure' : '';
function enabled() { return SECRET.length >= 32; }
// the temporary id of a member with no on-chain id yet (no wallet): negative, derived from the email
function emailId(email) { return -parseInt(crypto.createHash('sha256').update(String(email).toLowerCase()).digest('hex').slice(0, 11), 16); }
// guests (a share link, no sign-in yet): their own negative range, far below any email id
function guestFrom(req) {
const m = /(?:^|;\s*)dr\.gid=([a-f0-9]{32})/.exec(req.headers.cookie || ''); if (!m) return null;
const g = store.read('guests', {})[m[1]]; if (!g) return null;
return { gid: m[1], memberId: g.memberId, guest: true, username: null, wallet: null, email: null, ref: g.ref || null };
}
function startGuest(ref) {
const gid = crypto.randomBytes(16).toString('hex'); const memberId = -(2 ** 45 + crypto.randomInt(2 ** 40));
store.update('guests', {}, g => { const cut = Date.now() - 30 * 86400000; for (const k of Object.keys(g)) if (g[k].since < cut) delete g[k]; g[gid] = { memberId, since: Date.now(), ref: ref || null }; return g; });
return { gid, memberId };
}
function endGuest(gid) { store.update('guests', {}, g => { delete g[gid]; return g; }); }
function guestCookie(gid) { return 'dr.gid=' + gid + '; Path=/; Max-Age=' + 30 * 86400 + '; HttpOnly; SameSite=Lax' + secure(); }
function clearGuestCookie() { return 'dr.gid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax' + secure(); }
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);
@@ -39,7 +56,7 @@ function verify(token) {
const c = r.claims;
if (!c.email) return { error: 'That sign-in link is missing your account.' };
// a free member with no wallet has no on-chain id yet: key them on their email until they link one
if (!(Number(c.memberId) > 0)) c.memberId = -parseInt(crypto.createHash('sha256').update(String(c.email).toLowerCase()).digest('hex').slice(0, 11), 16);
if (!(Number(c.memberId) > 0)) c.memberId = emailId(c.email);
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);
@@ -55,7 +72,6 @@ function startSession(claims) {
});
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) {
@@ -68,4 +84,4 @@ function fromRequest(req) {
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 };
module.exports = { enabled, mint, open, verify, startSession, cookie, clearCookie, fromRequest, endSession, refresh, emailId, guestFrom, startGuest, endGuest, guestCookie, clearGuestCookie };
+1
View File
@@ -27,6 +27,7 @@ async function list(settings) {
'Only the first clear of a chapter pays a drip (' + fmt(drip) + ' POL). Replays are for practice and for drips to spend in the hangar.',
'Your first $20 buyer on InstantAdPay pays you 50 percent. Your second opens level 2: 20 percent of everything their people buy.',
'InstantAdPay packages are bought with POL and pay your sponsor on the spot, on chain. Nothing to withdraw, nothing to wait for.',
'Share your Drip Runner link from the lobby. When the people you bring in refuel, ' + (Number(settings.refSharePct) || 0) + ' percent of what each refuel adds to the pool goes to your game balance.',
];
if (p20) tips.push('A $20 InstantAdPay package is about ' + fmt(p20.pol) + ' POL today. Half of it goes to the sponsor, on chain, the moment it is bought.');
if (p5) tips.push('$5 on InstantAdPay is ' + fmt(p5.credits) + ' credits, about ' + fmt(p5.pol) + ' POL today. That runs ' + Math.floor(p5.credits / RATES.visitCost) + ' verified visits to your own page.');