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.');
+1
View File
@@ -26,6 +26,7 @@
<div><label>Daily cap on drips (POL)</label><input name="dailyCapPol" type="number" step="0.01" min="0"></div>
<div><label>Payout threshold (POL)</label><input name="thresholdPol" type="number" step="0.01" min="0"></div>
<div><label>Seed float (POL, on purpose)</label><input name="seedPol" type="number" step="0.01" min="0"></div>
<div><label>Referrer slice of refuel income (%)</label><input name="refSharePct" type="number" step="1" min="0" max="50"></div>
<div><label>Pool share of ad spend (%)</label><input name="poolSharePct" type="number" step="1" min="0" max="100"></div>
<div><label>Credits per visit</label><input name="creditsPerVisit" type="number" step="1" min="0"></div>
<div><label>USD per credit</label><input name="usdPerCredit" type="number" step="0.001" min="0"></div>
+2 -2
View File
@@ -20,7 +20,7 @@ function load() {
$('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]; });
['refSharePct', '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'); form.elements.trial.value = s.trial === false ? 'off' : 'on';
table('players', [['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : '') + '<br><span class="muted">' + esc(r.email || '') + '</span>'; }], ['Wallet', function (r) { return r.wallet ? r.wallet.slice(0, 6) + '…' + r.wallet.slice(-4) : '<span style="color:var(--sig)">none</span>'; }], ['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);
@@ -33,7 +33,7 @@ function load() {
}
$('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; });
['refSharePct', '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.trial = f.trial.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(); });
+10 -2
View File
@@ -5,6 +5,10 @@
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover,user-scalable=no">
<meta name="robots" content="noindex,nofollow">
<title>Drip Runner</title>
<meta property="og:title" content="Drip Runner: hop the network, get paid in POL">
<meta property="og:description" content="A fast little runner game for InstantAdPay members. Clear chapters, refuel on sponsor pages, collect POL.">
<meta property="og:image" content="https://driprunner.saasy.top/badges/ch1.jpg">
<meta name="twitter:card" content="summary_large_image">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron:wght@600;800;900&family=Manrope:wght@400;600;800&family=JetBrains+Mono:wght@500;700&display=swap">
<style>
: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;
@@ -77,6 +81,7 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
.led{display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--ink2);padding:7px 2px;border-top:1px solid var(--line)}.led:first-child{border-top:0}.led .m{font:700 12px var(--mono);color:var(--gold);white-space:nowrap}.led .m.ok{color:var(--ok)}.led .m.neg{color:var(--sig)}.led a{color:var(--cyan2)}
.prog{height:8px;background:rgba(255,255,255,.08);border-radius:4px;overflow:hidden;margin-top:8px}.prog i{display:block;height:100%;background:linear-gradient(90deg,var(--cyan),var(--gold));box-shadow:0 0 10px rgba(255,194,75,.5)}
.tip{margin:12px 0 0;padding:10px 12px;border-radius:10px;background:rgba(34,211,238,.07);border:1px solid rgba(34,211,238,.25);font-size:12px;line-height:1.45;color:var(--ink2);text-align:left}.tip b{display:block;font:700 9px var(--body);letter-spacing:.16em;text-transform:uppercase;color:var(--cyan);margin-bottom:3px}
.shr{margin-top:10px;padding:10px 12px;border-radius:10px;border:1px solid var(--line);background:rgba(14,23,45,.6);font-size:11px;color:var(--muted);text-align:center}.shr b{color:var(--gold)}.shr .btn{margin-top:8px}
.toast{position:absolute;left:50%;bottom:calc(70px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);z-index:20;background:var(--panel2);border:1px solid var(--line);color:var(--ink);font-size:12px;padding:8px 12px;border-radius:10px;opacity:0;transition:opacity .2s;pointer-events:none;max-width:92%;text-align:center}
.toast.on{opacity:1}
.tapdesk{position:absolute;bottom:calc(14px + env(safe-area-inset-bottom,0px));left:14px;z-index:5;font:600 10px var(--body);letter-spacing:.14em;text-transform:uppercase;color:var(--muted);pointer-events:none}
@@ -110,18 +115,21 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
<button class="btn" id="bPlay" type="button">Play</button>
<div class="row2"><button class="btn ghost" id="bHangar" type="button">Hangar</button><button class="btn ghost" id="bBalance" type="button">Balance</button></div>
<a class="btn gold" id="bLevel" href="https://instantadpay.com/my#buy" style="text-decoration:none;text-align:center;font-size:13px;padding:11px">Level up on InstantAdPay</a>
<a class="btn" id="bSignin" href="#" hidden style="text-decoration:none;text-align:center">Sign in to keep progress</a>
<div class="shr" id="lShare" hidden><div id="lShareStat"></div><button class="btn ghost" id="bShare" type="button">Share your link</button></div>
<div class="member" id="lMember"><i></i>connecting…</div>
<div class="member" style="margin-top:6px"><a id="lIap" href="https://instantadpay.com/my" style="color:var(--muted)">InstantAdPay dashboard</a> · <a href="/" style="color:var(--muted)">tester briefing</a></div>
</div>
</div>
<div class="ov" id="ovLoad"><div class="card"><div class="eyebrow">Drip Runner</div><h2 id="loadTitle">Connecting…</h2><p id="loadText">Checking your InstantAdPay sign-in.</p><a class="btn" id="loadBtn" href="/" hidden>Tester page</a></div></div>
<div class="ov" id="ovLoad"><div class="card"><div class="eyebrow">Drip Runner</div><h2 id="loadTitle">Connecting…</h2><p id="loadText">Checking your InstantAdPay sign-in.</p><button class="btn" id="loadGuest" type="button" hidden>Play now</button><a class="btn" id="loadBtn" href="/" hidden>Tester page</a></div></div>
<div class="ov" id="ovClear" hidden><div class="card">
<div class="eyebrow" id="cEyebrow">Chapter cleared</div><h2 id="cTitle">Banked 20 drips</h2>
<div class="big" id="cBig">+0.010<small>POL</small></div><p id="cText"></p><span class="chip ok" id="cChip"></span>
<div class="tip" id="cTip" hidden></div>
<button class="btn gold" id="bNext" type="button">Next chapter</button><button class="btn ghost" id="bLobby1" type="button">Back to lobby</button>
<button class="btn gold" id="bNext" type="button">Next chapter</button>
<div class="row2"><button class="btn ghost" id="bShareClear" type="button" hidden>Share this</button><a class="btn ghost" id="bClearSignin" href="#" hidden style="text-decoration:none;text-align:center">Sign in to collect</a></div><button class="btn ghost" id="bLobby1" type="button">Back to lobby</button>
</div></div>
<div class="ov" id="ovOver" hidden><div class="card">
+37 -5
View File
@@ -44,13 +44,31 @@ var hudCache = {}; function setHud() { if (!R) return; var v = { d: R.drips, c:
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; TIPS = r.tips || []; return r; }); }
var ME_EXTRA = {};
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; TIPS = r.tips || []; ME_EXTRA = { signin: r.signin, share: r.share, referrals: r.referrals }; return r; }); }
// share: the phone's share sheet where there is one, else copy the link
function share(text) {
var url = ME_EXTRA.share; if (!url) return toast('Set a username on InstantAdPay to get a share link.');
if (navigator.share) { navigator.share({ title: 'Drip Runner', text: text, url: url }).catch(function () {}); return; }
var full = text + ' ' + url;
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(full).then(function () { toast('Link copied. Paste it anywhere.'); }, function () { window.prompt('Copy your link', url); });
else window.prompt('Copy your link', url);
}
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 <b>' + f3(POOL.available) + '</b> · today’s cap left <b>' + f3(POOL.capLeft) + '</b> · a chapter drip is <b>' + f3(POOL.dripPol) + '</b>';
$('lIap').href = IAP + '/my'; $('bLevel').href = IAP + '/my#buy'; tip('lTip');
$('lMember').innerHTML = '<i class="' + (ME.wallet ? '' : 'no') + '"></i>InstantAdPay · ' + (ME.username ? '@' + ME.username : '#' + ME.memberId) + ' · ' + (ME.wallet ? ME.wallet.slice(0, 6) + '…' + ME.wallet.slice(-4) : 'no wallet on file');
if (ME.guest) {
$('lMember').innerHTML = '<i class="no"></i>Playing as a guest · sign in to keep your progress and collect POL';
$('bSignin').hidden = false; $('bSignin').href = ME_EXTRA.signin || (IAP + '/api/my/driprunner'); $('lShare').hidden = true;
} else {
$('lMember').innerHTML = '<i class="' + (ME.wallet ? '' : 'no') + '"></i>InstantAdPay · ' + (ME.username ? '@' + ME.username : '#' + ME.memberId) + ' · ' + (ME.wallet ? ME.wallet.slice(0, 6) + '…' + ME.wallet.slice(-4) : 'no wallet on file');
$('bSignin').hidden = true;
var rf = ME_EXTRA.referrals || {};
$('lShare').hidden = !ME_EXTRA.share;
$('lShareStat').innerHTML = 'Your link: <b>' + (rf.clicks || 0) + '</b> visits · <b>' + (rf.count || 0) + '</b> players on your team · <b>' + f3(rf.earned) + '</b> POL earned from their refuels (' + (rf.pct || 0) + '% of each)';
}
show('ovLobby');
}
@@ -122,13 +140,17 @@ function cleared() {
$('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) + '<small>POL</small>'; $('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.' };
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.', guest: 'You are playing as a guest. Sign in with InstantAdPay and this clear pays ' + f3(POOL.dripPol) + ' POL into your balance. Your progress comes with you.' };
$('bShareClear').hidden = !!ME.guest || !ME_EXTRA.share; $('bShareClear').dataset.text = 'I just cleared Chapter ' + c.chapter + ' in Drip Runner' + (c.pol ? ' and it paid ' + f3(c.pol) + ' POL' : '') + '. Hop the network, dodge the bots:';
$('bClearSignin').hidden = !ME.guest; if (ME.guest) $('bClearSignin').href = ME_EXTRA.signin || (IAP + '/api/my/driprunner');
$('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;
tip('cTip'); setTimeout(function () { show('ovClear'); }, 500);
});
}
$('bNext').addEventListener('click', function () { if (!R) return; R.paused = false; R.inv = 1.5; hideAll(); });
$('bShareClear').addEventListener('click', function () { share(this.dataset.text || 'Play Drip Runner with me:'); });
$('bShare').addEventListener('click', function () { share('I am playing Drip Runner, a game that pays in POL. Hop the network, dodge the bots:'); });
$('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); }); });
@@ -141,7 +163,9 @@ function snapshot(nonce) {
try { sessionStorage.setItem('dr.snap', JSON.stringify(s)); } catch (e) {}
}
$('bRefuel').addEventListener('click', function () {
if (!R) return; $('bRefuel').disabled = true;
if (!R) return;
if (ME.guest) { location.href = ME_EXTRA.signin || (IAP + '/api/my/driprunner'); return; } // guests sign in first; their progress follows them
$('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.');
@@ -224,8 +248,16 @@ resize(); requestAnimationFrame(loop);
loadMe().then(function () {
var q = new URLSearchParams(location.search);
if (q.get('resume')) { history.replaceState(null, '', '/play'); return tryResume(q); }
if (q.get('collected')) { history.replaceState(null, '', '/play'); setTimeout(function () { toast('Signed in. Your guest clears paid ' + q.get('collected') + ' drip' + (q.get('collected') === '1' ? '' : 's') + ' into your balance.'); }, 600); }
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';
var b = $('loadBtn'); b.hidden = false; b.href = (r && (r.signin || r.iap)) || IAP + '/api/my/driprunner';
if (r && r.guestOk) { // came through a share or tester link: play first, sign in later
$('loadTitle').textContent = 'Ready to run'; $('loadText').textContent = 'Play a run right now, no sign-in. Sign in with InstantAdPay when you want to keep your progress, refuel, and collect POL.';
b.textContent = 'Sign in with InstantAdPay'; b.className = 'btn ghost'; var g = $('loadGuest'); g.hidden = false;
g.onclick = function () { g.disabled = true; api('/api/guest', {}).then(function (x) { if (x._status !== 200) { g.disabled = false; return toast(x.error || 'Could not start a guest run.'); } return loadMe().then(function () { lobby(); newRun(); }); }); };
return;
}
$('loadTitle').textContent = 'Sign in first'; $('loadText').textContent = (r && r.error) || 'Open Drip Runner from your InstantAdPay dashboard.'; b.textContent = 'Open through InstantAdPay';
});
})();
+51 -10
View File
@@ -149,7 +149,8 @@ const intents = { get: n => store.read('refuel-intents', {})[n] || null, set: (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));
const pl = game.player(intent.memberId) || {}; const sp = pl.sponsorRef ? game.byRef(pl.sponsorRef) : null;
const row = await ledger.refuel(me, Object.assign({ nonce, referrer: sp ? { memberId: sp.memberId, username: sp.username, wallet: sp.wallet } : null }, 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);
@@ -171,11 +172,29 @@ const server = http.createServer(async (req, res) => {
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);
// progress follows the person: a guest who signs in, and a wallet-less member who has since linked a wallet
const existedBefore = !!(game.player(r.claims.memberId) || {}).email; // a guest record adopted below has no email yet
const adopted = [];
const guest = sso.guestFrom(req);
if (Number(r.claims.memberId) > 0) { const ad = game.adopt(sso.emailId(r.claims.email), r.claims.memberId); if (ad.moved) adopted.push('wallet-less history'); }
const pendingClears = guest ? game.adopt(guest.memberId, r.claims.memberId).pending : [];
if (guest) sso.endGuest(guest.gid);
const first = !existedBefore;
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();
game.updPlayer(r.claims.memberId, x => { if (!x.sponsorRef && r.claims.sponsorRef) x.sponsorRef = String(r.claims.sponsorRef).toLowerCase(); if (r.claims.joinedRef && !x.joinedRef) x.joinedRef = r.claims.joinedRef; });
const meNow = { memberId: Number(r.claims.memberId), username: r.claims.username || null, wallet: r.claims.wallet ? String(r.claims.wallet).toLowerCase() : null };
for (const ch of pendingClears) { const g = ledger.chapterDrip(meNow, ch, true); if (g.pol) announceChapter(meNow, ch, g.pol); } // clears made as a guest pay now
if (first) notify('signin', { memberId: r.claims.memberId, username: r.claims.username, wallet: r.claims.wallet, via: guest ? 'a share link' : null }).catch(() => {});
res.writeHead(302, { Location: '/play' + (pendingClears.length ? '?collected=' + pendingClears.length : ''), 'Set-Cookie': [sso.cookie(sid)].concat(guest ? [sso.clearGuestCookie()] : []), 'Cache-Control': 'no-store' }); return res.end();
}
{ const mr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); if (mr) {
const sharer = game.byUsername(mr[1]);
if (!sharer) { res.writeHead(302, { Location: '/', 'Cache-Control': 'no-store' }); return res.end(); }
const ck = ['dr.ref=' + encodeURIComponent(sharer.username.toLowerCase()) + '; Path=/; Max-Age=' + 30 * 86400 + '; SameSite=Lax' + (IS_PROD ? '; Secure' : '')];
if (CURTAIN) ck.push('dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : '')); // a player's link is a pass during the trial
store.update('share-hits', {}, h => { const k = sharer.username.toLowerCase(); h[k] = (h[k] || 0) + 1; return h; });
res.writeHead(302, { Location: '/play', 'Set-Cookie': ck, '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) ----
@@ -209,7 +228,7 @@ const server = http.createServer(async (req, res) => {
}
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]);
for (const k of ['refSharePct', 'usdPerCredit', 'creditsPerVisit', 'poolSharePct', 'usdPerPolFallback', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'lowBalancePol']) if (body[k] != null && body[k] !== '') patch[k] = Number(body[k]);
if (body.signups && ['testers', 'key', 'open', 'closed'].includes(body.signups)) patch.signups = body.signups;
if (body.trial === 'on' || body.trial === 'off') patch.trial = body.trial === 'on';
if (Array.isArray(body.testers)) patch.testers = body.testers.map(x => String(x).trim().toLowerCase()).filter(Boolean).slice(0, 500);
@@ -232,18 +251,41 @@ const server = http.createServer(async (req, res) => {
}
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/guest' && req.method === 'POST') {
if (me) return json(res, 200, { ok: true, already: true });
if (CURTAIN && !hasPass(req)) return json(res, 403, { error: 'Open the tester link or a player\u2019s share link first.' });
const g = sso.startGuest(refCookie(req)); return json(res, 200, { ok: true }, { 'Set-Cookie': sso.guestCookie(g.gid) });
}
const who = me || sso.guestFrom(req);
if (!who) return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner', guestOk: !CURTAIN || hasPass(req), signin: signinUrl(req) });
return memberApi(req, res, u, p, who);
}
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.' });
}
});
function refCookie(req) { const m = /(?:^|;\s*)dr\.ref=([^;]+)/.exec(req.headers.cookie || ''); const r = m ? decodeURIComponent(m[1]) : ''; return /^[a-z0-9_.-]{1,40}$/.test(r) ? r : null; }
// where a guest signs in: through the sharer's InstantAdPay join link when they came from one (new people land under the sharer), else the plain hand-off
function signinUrl(req) { const r = refCookie(req); return r ? IAP + '/join/' + encodeURIComponent(r) + '?from=driprunner' : IAP + '/api/my/driprunner'; }
async function memberApi(req, res, u, p, me) {
try {
{
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, tips: await tips.list(ledger.settings()) });
const refs = me.guest ? [] : game.referralsOf(me);
return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest }, 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, tips: await tips.list(ledger.settings()),
signin: me.guest ? signinUrl(req) : null, share: (!me.guest && me.username) ? SITE + '/r/' + encodeURIComponent(me.username) : null, referrals: { count: refs.length, clicks: (store.read('share-hits', {})[String(me.username || '').toLowerCase()] || 0), earned: ledger.balance(me.memberId).refTotal, pct: Number(ledger.settings().refSharePct) || 0 } });
}
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; if (r.cleared.first) announceChapter(me, r.cleared.chapter, r.cleared.pol); } return json(res, r.error ? 400 : 200, r); }
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; if (r.cleared.first && !me.guest) announceChapter(me, r.cleared.chapter, r.cleared.pol); } 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 (me.guest) return json(res, 403, { error: 'Sign in with InstantAdPay to refuel. Your run and progress come with you.', signin: signinUrl(req) });
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 });
@@ -263,11 +305,10 @@ const server = http.createServer(async (req, res) => {
if (p === '/api/hangar/buy' && req.method === 'POST') { const { body } = await readBody(req); const item = String(body.item || ''); const r = game.buy(me, item); if (!r.error) { r.player = game.view(me); r.balance = ledger.balance(me.memberId); announceUnlock(me, item, r.paid); } 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); }
+36
View File
@@ -94,6 +94,42 @@ const spawnLib = require('../lib/spawn');
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');
// ---- referral layer (2026-09-30): share link, guest play, adoption on sign-in, the referrer's slice ----
const hit = async (p, opt = {}, ck = '') => { const r = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: ck, 'Content-Type': 'application/json' }, opt.headers || {}) })); const set = r.headers.getSetCookie ? r.headers.getSetCookie() : []; let body = null; try { body = await r.json(); } catch (e) {} return { status: r.status, body, set, loc: r.headers.get('location') }; };
const jarAdd = (ck, set) => { const parts = ck ? ck.split('; ') : []; for (const c of set) { const m = /^([^=]+)=([^;]*)/.exec(c); if (!m) continue; const i = parts.findIndex(x => x.startsWith(m[1] + '=')); if (i >= 0) parts.splice(i, 1); if (m[2]) parts.push(m[1] + '=' + m[2]); } return parts.join('; '); };
await admin('/api/admin/settings', { signups: 'open', thresholdPol: 5, refSharePct: 10 });
eq((await hit('/r/nobody')).loc, '/', 'a share link for an unknown player goes to the landing page');
const sh = await hit('/r/runner42'); eq([sh.status, sh.loc, sh.set.some(c => /^dr\.ref=runner42/.test(c))], [302, '/play', true], 'a player share link sets the referrer and opens the game');
let g = jarAdd('', sh.set);
const me401 = await hit('/api/me', {}, g); eq([me401.status, me401.body.guestOk, /join\/runner42\?from=driprunner/.test(me401.body.signin)], [401, true, true], 'a newcomer is offered guest play, sign-in goes through the sharer’s join link');
const gs = await hit('/api/guest', { method: 'POST', body: '{}' }, g); g = jarAdd(g, gs.set); eq(gs.status, 200, 'guest session starts');
const gme = await hit('/api/me', {}, g); eq([gme.status, gme.body.me.guest, gme.body.player.chapter], [200, true, 1], 'guest plays chapter 1');
const gr = (await hit('/api/run/start', { method: 'POST', body: JSON.stringify({ W, H }) }, g)).body;
const ggen = spawnLib.drips(gr.seed, W, H); const gcl = []; let gT = 0; while (gcl.length < 20) { const gg = ggen(); for (const d of gg.drips) if (gcl.length < 20) { gT = spawnLib.arrival(gg.t, d.x0, W, gr.speed) + 0.1; gcl.push({ k: 'd', i: d.i, t: Math.round(gT * 1000) / 1000 }); } }
backdate(gr.runId, gT + 5);
const gev = (await hit('/api/run/events', { method: 'POST', body: JSON.stringify({ runId: gr.runId, t: gT + 0.2, events: gcl, goal: true }) }, g)).body;
eq([gev.cleared.chapter, gev.cleared.pol, gev.cleared.reason], [1, 0, 'guest'], 'a guest clear pays nothing yet (reason guest)');
eq((await hit('/api/refuel/start', { method: 'POST', body: JSON.stringify({ runId: gr.runId }) }, g)).status, 403, 'a guest cannot refuel before signing in');
// the newcomer joins IAP under runner42 and signs in: the guest run is adopted and the clear pays
const tokN = sso.mint({ memberId: 77, email: 'newbie@example.com', wallet: '0x' + 'cd'.repeat(20), username: 'newbie', sponsorRef: 'runner42' });
const au = await hit('/auth?t=' + tokN, {}, g); g = jarAdd(g, au.set);
eq([au.status, au.loc], [302, '/play?collected=1'], 'sign-in adopts the guest and pays the pending clear');
const nme = (await hit('/api/me', {}, g)).body; eq([nme.me.guest, nme.player.chapter, nme.player.bank, nme.balance.unpaid], [false, 2, 20, 0.01], 'progress and the drip followed the newcomer');
// the newcomer refuels: runner42 (their IAP sponsor) gets the slice
const nr = (await hit('/api/run/start', { method: 'POST', body: JSON.stringify({ W, H }) }, g)).body;
const nrf = (await hit('/api/refuel/start', { method: 'POST', body: JSON.stringify({ runId: nr.runId }) }, g)).body;
const body2 = JSON.stringify({ nonce: nrf.nonce, memberId: 77, campaignId: 88, credits: 3 }); const ts2 = String(Date.now());
await hit('/api/refuel/callback', { method: 'POST', body: body2, headers: { 'X-DR-Ts': ts2, 'X-DR-Sig': crypto.createHmac('sha256', SECRET).update(ts2 + '\n' + body2).digest('hex') } });
const stR = (await admin('/api/admin/state')).body; const refuelPol = stR.refuels[0].pol; const slice = Math.round(refuelPol * 0.10 * 10000) / 10000;
const runnerAcct = stR.accounts.find(a => a.memberId === 42); eq(runnerAcct.refTotal, slice, 'the sponsor earned 10% of the referral’s refuel pool income (' + slice + ' POL)');
const rme = await call('/api/me'); eq([rme.body.referrals.count, rme.body.referrals.clicks, /\/r\/runner42$/.test(rme.body.share)], [1, 1, true], 'the sharer sees one referral, one link visit, and their share link');
// wallet-less member later links a wallet: the email-derived history moves to the on-chain id
const tokW = sso.mint({ memberId: 0, email: 'free@example.com', wallet: null, username: 'freebie' }); let w = '';
const aw = await hit('/auth?t=' + tokW); w = jarAdd(w, aw.set); const wme = (await hit('/api/me', {}, w)).body; eq(wme.me.memberId < 0, true, 'a wallet-less member plays on a temporary id');
process.env.DATA_DIR = DIR; const gameLib = require('../lib/game'); gameLib.updPlayer(wme.me.memberId, x => { x.bank = 33; x.chapter = 4; x.cleared = { 1: true, 2: true, 3: true }; });
const tokW2 = sso.mint({ memberId: 91, email: 'free@example.com', wallet: '0x' + 'ef'.repeat(20), username: 'freebie' });
await hit('/auth?t=' + tokW2); const moved = gameLib.player(91); eq([moved && moved.chapter, moved && moved.bank, !!gameLib.player(wme.me.memberId)], [4, 33, false], 'after the wallet is linked, progress moves to the on-chain id');
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); });