diff --git a/lib/game.js b/lib/game.js index b71b2d5..9fd2586 100644 --- a/lib/game.js +++ b/lib/game.js @@ -150,7 +150,7 @@ function adopt(fromId, toId) { 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('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; if (!y.wallet && x.wallet) y.wallet = x.wallet; } 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 }; diff --git a/public/play.html b/public/play.html index e60c9c7..dcc14ad 100644 --- a/public/play.html +++ b/public/play.html @@ -205,6 +205,6 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch - + diff --git a/public/play.js b/public/play.js index a669b3e..6aca722 100644 --- a/public/play.js +++ b/public/play.js @@ -42,6 +42,9 @@ var toastT = null; function toast(m) { $('toast').textContent = m; $('toast').cl 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); } +// a signed-in player's own wallet (the session's, or one InstantAdPay pushed since: me.hasWallet); POL with no wallet waits for the link (2026-10-27) +function hasW() { return !!(ME && !ME.guest && (ME.wallet || ME.hasWallet)); } +function linkW() { return 'Link your wallet to receive this POL'; } /* ---------- lobby / me ---------- */ var ME_EXTRA = {}; @@ -59,7 +62,7 @@ function lobby() { $('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) + ''; $('lIap').href = IAP + '/my'; $('bLevel').href = IAP + '/my#buy'; tip('lTip'); - try { if (BAL && BAL.unpaid > 0 && ME && !ME.wallet && !ME.guest && !sessionStorage.getItem('dr.walletnudge')) { sessionStorage.setItem('dr.walletnudge', '1'); toast(f3(BAL.unpaid) + ' POL is waiting. Link a wallet on InstantAdPay to get paid.'); } } catch (e) {} + try { if (BAL && BAL.unpaid > 0 && ME && !hasW() && !ME.guest && !sessionStorage.getItem('dr.walletnudge')) { sessionStorage.setItem('dr.walletnudge', '1'); toast(f3(BAL.unpaid) + ' POL is waiting. Link your wallet on InstantAdPay to receive this POL.'); } } catch (e) {} $('lPerk').hidden = !ME_EXTRA.perk; $('lPerk').textContent = ME_EXTRA.perk || ''; // member perk (2026-10-05) // Game Pass (InstantAdPay, all nine games): active until , or the link to get it; opens a new tab (the game may be framed) (function () { var g = ME_EXTRA.gamepass, el = $('lPass'); if (!el) { el = document.createElement('p'); el.id = 'lPass'; el.className = 'fine'; $('lPool').parentNode.insertBefore(el, $('lPool').nextSibling); } @@ -73,7 +76,7 @@ function lobby() { $('lMember').innerHTML = 'Playing as a guest · sign in to keep your progress and collect POL'; $('bSignin').hidden = false; $('bSignin').href = ME_EXTRA.signin || '/signin'; $('lShare').hidden = true; } else { - $('lMember').innerHTML = 'InstantAdPay · ' + (ME.username ? '@' + ME.username : '#' + ME.memberId) + ' · ' + (ME.wallet ? ME.wallet.slice(0, 6) + '…' + ME.wallet.slice(-4) : 'no wallet on file'); + $('lMember').innerHTML = 'InstantAdPay · ' + (ME.username ? '@' + ME.username : '#' + ME.memberId) + ' · ' + (ME.wallet ? ME.wallet.slice(0, 6) + '…' + ME.wallet.slice(-4) : hasW() ? 'wallet linked' : 'no wallet on file · ' + linkW()); $('bSignin').hidden = true; var rf = ME_EXTRA.referrals || {}; // the invite card shows for every signed-in player; without a username there is no link yet, so it says how to get one @@ -158,7 +161,7 @@ function cleared() { $('bClearSignin').hidden = !ME.guest; if (ME.guest) $('bClearSignin').href = ME_EXTRA.signin || '/signin'; $('cText').textContent = why[c.reason] || ''; // the Game Pass truth (deferred to later days, or recorded while InstantAdPay confirms) + the nudge, in a new tab (the game may be framed) - if (c.note) { var gpp = ME_EXTRA.gamepass; $('cText').innerHTML = esc(c.note) + (gpp && gpp.on && !gpp.active && /Get the Pass/.test(c.note) ? ' Get the Game Pass' : ''); } $('cChip').className = 'chip ' + (c.pol ? 'ok' : 'sig'); $('cChip').textContent = (c.pol ? 'verified' : c.reason) + ' · ' + tm + ' play time'; + if (c.note) { var gpp = ME_EXTRA.gamepass; $('cText').innerHTML = esc(c.note) + (gpp && gpp.on && !gpp.active && /Get the Pass/.test(c.note) ? ' Get the Game Pass' : ''); } if (c.pol && !ME.guest && !hasW()) $('cText').innerHTML += ' ' + linkW() + '.'; $('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'); if (r.starterOffer) starterOffer(r.starterOffer); }, 500); // the offer card fades in under the result (CSS delay) }); @@ -243,11 +246,14 @@ 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.'; - if (b.unpaid > 0 && !(ME && ME.wallet)) { $('bWallet').innerHTML = '' + f3(b.unpaid) + ' POL is waiting. No wallet is linked to your InstantAdPay account yet, so it cannot be paid out. Link a wallet (one free signature) and it pays out on the next sweep.'; } 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.'; + // no wallet yet (2026-10-27): the link, never a line that implies the POL was sent; a player with a wallet sees the same line as before + var wl = b.wallet || (ME && ME.wallet); + if (wl) $('bWallet').textContent = 'Wallet: ' + wl + ' (from your InstantAdPay account).'; + else if (hasW()) $('bWallet').textContent = 'Wallet linked on your InstantAdPay account. Your balance is sent to it at ' + b.threshold + ' POL.'; + else $('bWallet').innerHTML = (b.unpaid > 0 ? '' + f3(b.unpaid) + ' POL is waiting. ' : '') + '' + linkW() + ' (one free signature on InstantAdPay) and it is sent automatically, including everything earned so far.'; }); } function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } diff --git a/server.js b/server.js index e7d2523..069357b 100644 --- a/server.js +++ b/server.js @@ -192,20 +192,25 @@ const server = http.createServer(async (req, res) => { if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' }); let b; try { b = JSON.parse(raw); } catch (e) { return json(res, 400, { error: 'bad body' }); } const em = String((b && b.email) || '').trim().toLowerCase(), w = String((b && b.wallet) || '').trim(), uname = (b && b.username) ? String(b.username).slice(0, 40) : null; - const mid = Number(b && b.memberId) || 0; - if (!em || !(mid > 0) || !/^0x[a-f0-9]{40}$/i.test(w)) return json(res, 400, { error: 'bad email, member id or wallet' }); + const mid0 = Number(b && b.memberId) || 0; + // since 2026-10-27 IAP pushes the signature-linked wallet whether or not it is activated on chain: memberId is 0 (or missing) + // for a member who is not on chain yet, and that player lives here under sso.emailId(email), so the wallet goes there + if (!em || mid0 < 0 || !/^0x[a-f0-9]{40}$/i.test(w)) return json(res, 400, { error: 'bad email, member id or wallet' }); try { // Drip Runner keys players by member id; a wallet-less member played under sso.emailId(email) (negative). /auth moves that // history onto the real id with game.adopt; the push does the same, then fills the wallet on the account. - const wl = w.toLowerCase(), eid = sso.emailId(em), acc0 = store.read('accounts', {}), pls0 = store.read('players', {}); + const wl = w.toLowerCase(), eid = sso.emailId(em), mid = mid0 > 0 ? mid0 : eid, acc0 = store.read('accounts', {}), pls0 = store.read('players', {}); if (!acc0[String(mid)] && !pls0[String(mid)] && !acc0[String(eid)] && !pls0[String(eid)]) return json(res, 404, { error: 'unknown player' }); const had = (acc0[String(mid)] && acc0[String(mid)].wallet) || null, mask = em.replace(/^(..).*(@.*)$/, '$1***$2'); if (had && had.toLowerCase() !== wl) { console.log(new Date().toISOString(), 'iap wallet push REFUSED (a different wallet is set)', mask, mid, had, wl); return json(res, 409, { error: 'a different wallet is already set', wallet: had }); } - let adopted = false; if (pls0[String(eid)]) adopted = !!game.adopt(eid, mid).moved; - store.update('accounts', {}, all => { const x = all[String(mid)]; if (x && !x.wallet) { x.wallet = wl; x.username = x.username || uname || null; x.email = x.email || em; } return all; }); - if (store.read('players', {})[String(mid)]) game.updPlayer(mid, x => { x.email = x.email || em; x.username = uname || x.username || null; if (!x.wallet) x.wallet = wl; }); + let adopted = false; if (mid !== eid && pls0[String(eid)]) adopted = !!game.adopt(eid, mid).moved; + // fill an empty wallet only; a player with no account row yet (nothing earned so far) gets one holding the wallet, so the + // POL they earn next is paid by the sweep even when their game session never saw the wallet + const hasPlayer = !!store.read('players', {})[String(mid)]; + store.update('accounts', {}, all => { let x = all[String(mid)]; if (!x && hasPlayer) x = all[String(mid)] = { memberId: mid, unpaid: 0, paidTotal: 0, spentTotal: 0, earnedTotal: 0 }; if (x && !x.wallet) { x.wallet = wl; x.username = x.username || uname || null; x.email = x.email || em; } return all; }); + if (hasPlayer) game.updPlayer(mid, x => { x.email = x.email || em; x.username = uname || x.username || null; if (!x.wallet) x.wallet = wl; }); const acc = store.read('accounts', {})[String(mid)] || {}, unpaid = Number(Number(acc.unpaid || 0).toFixed(4)), changed = !had && !!acc.wallet; - if (changed || adopted) store.update('iapwallets', [], l => { l.unshift({ at: Date.now(), email: em, memberId: mid, wallet: wl, adopted, unpaid }); return l.slice(0, 300); }); + if (changed || adopted) store.update('iapwallets', [], l => { l.unshift({ at: Date.now(), email: em, memberId: mid0, local: mid, wallet: wl, adopted, unpaid }); return l.slice(0, 300); }); console.log(new Date().toISOString(), 'iap wallet push', changed ? 'FILLED' : had ? 'already set' : 'no account', mask, mid, wl, adopted ? 'adopted ' + eid : '', 'unpaid', unpaid); return json(res, 200, { ok: true, changed, adopted, wallet: acc.wallet || null, unpaid }); } catch (e) { console.error('iap wallet push', e.message); return json(res, 500, { error: 'failed' }); } @@ -245,6 +250,9 @@ const server = http.createServer(async (req, res) => { 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(); }); + // the hand-off wallet is the member's signature-linked wallet (on chain or not, 2026-10-27): it fills an EMPTY account wallet + // so POL already earned pays on the next sweep; an account that already has a wallet keeps it + if (r.claims.wallet && /^0x[a-f0-9]{40}$/i.test(String(r.claims.wallet))) store.update('accounts', {}, all => { const x = all[String(r.claims.memberId)]; if (x && !x.wallet) x.wallet = String(r.claims.wallet).toLowerCase(); return all; }); 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; }); starter.grantPerk(r.claims.memberId); // a member (memberId > 0) gets one free hangar upgrade, once per account (2026-10-05) if (r.claims.gamePass != null) ledger.gp.rememberPass(ledger.iapId(r.claims), r.claims.email, r.claims.gamePass); // the Game Pass flag rides on the hand-off as gamePass:{active,until} (GAME-PASS.md 3a item 7) @@ -400,10 +408,11 @@ async function memberApi(req, res, u, p, me) { try { { if (p === '/api/me' && req.method === 'GET') { + // me.hasWallet: the player's own wallet is on file (it can arrive by the IAP push after this session began, 2026-10-27) const pl = ledger.pool(); if (!me.guest && ledger.gp.on()) ledger.gp.fetchPass(ledger.iapId(me), me.email).catch(() => {}); // keep the Game Pass flag fresh (display + the shield perk; grant answers carry the truth) 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()), + return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest, hasWallet: !me.guest && !!(me.wallet || ledger.account(me.memberId).wallet || (game.player(me.memberId) || {}).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()), 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 }, perk: me.guest ? null : starter.takeNotice(me.memberId), // the member perk's one-time message (2026-10-05) gamepass: me.guest ? null : ledger.gp.view(ledger.iapId(me), me.email) }); // Game Pass: active until , or the link to get it diff --git a/test/run.js b/test/run.js index 8045093..3ff61a9 100644 --- a/test/run.js +++ b/test/run.js @@ -138,6 +138,32 @@ const spawnLib = require('../lib/spawn'); 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'); + // ---- 2026-10-27: IAP pushes the signature-linked wallet whether or not it is on chain (memberId 0) ---- + const pushW = b => { const raw = JSON.stringify(b), ts = String(Date.now()); const sig = crypto.createHmac('sha256', SECRET).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex'); return hit('/api/iap/wallet', { method: 'POST', body: raw, headers: { 'X-IAP-Ts': ts, 'X-IAP-Sig': sig } }); }; + const zw = '0x' + '12'.repeat(20); let z = ''; + const az = await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank@example.com', wallet: null, username: 'tanker' })); z = jarAdd(z, az.set); + const zme = (await hit('/api/me', {}, z)).body; const zid = zme.me.memberId; + eq([zid < 0, zme.me.hasWallet], [true, false], 'a holding-tank member plays on the email id with hasWallet false'); + store.update('accounts', {}, all => { all[String(zid)] = { memberId: zid, unpaid: 0.02, paidTotal: 0, spentTotal: 0, earnedTotal: 0.02 }; return all; }); // POL earned before the wallet + const z1 = await pushW({ email: 'tank@example.com', wallet: zw, username: 'tanker', memberId: 0 }); + eq([z1.status, z1.body.changed, z1.body.wallet, z1.body.unpaid], [200, true, zw, 0.02], 'push with memberId 0 fills the email-keyed wallet (200 changed:true)'); + eq([(await pushW({ email: 'tank@example.com', wallet: zw })).body.changed, (await pushW({ email: 'tank@example.com', wallet: '0x' + '34'.repeat(20), memberId: 0 })).status], [false, 409], 'same wallet again (memberId missing) is a no-op; a different wallet is refused 409'); + eq((await pushW({ email: 'nobody@example.com', wallet: zw, memberId: 0 })).status, 404, 'an unknown email is still 404'); + eq((await hit('/api/me', {}, z)).body.me.hasWallet, true, 'the session that never saw the wallet now reports hasWallet'); + await admin('/api/admin/settings', { thresholdPol: 0.005 }); + const dz = ledger.payable().filter(x => x.memberId === zid); eq([dz.length, dz[0] && dz[0].wallet, dz[0] && dz[0].pol], [1, zw, 0.02], 'the payout sweep pays the linked wallet with memberId 0'); + // a hand-off with memberId 0 and a wallet fills an empty account wallet too (POL earned so far pays on the next sweep) + const yw = '0x' + '56'.repeat(20); + await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank2@example.com', wallet: null, username: 'tanker2' })); const yid = sso.emailId('tank2@example.com'); + store.update('accounts', {}, all => { all[String(yid)] = { memberId: yid, unpaid: 0.01, paidTotal: 0, spentTotal: 0, earnedTotal: 0.01 }; return all; }); + await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank2@example.com', wallet: yw, username: 'tanker2' })); + const dy = ledger.payable().filter(x => x.memberId === yid); eq([ledger.account(yid).wallet, dy.length, dy[0] && dy[0].wallet], [yw, 1, yw], '/auth with memberId 0 stores the wallet and the sweep pays it'); + await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank2@example.com', wallet: '0x' + '78'.repeat(20), username: 'tanker2' })); + eq(ledger.account(yid).wallet, yw, 'a later hand-off never replaces the account wallet that pays'); + // the member activates later: the push with the real id moves everything (wallet included) onto it + const z9 = await pushW({ email: 'tank@example.com', wallet: zw, username: 'tanker', memberId: 300 }); + eq([z9.status, ledger.account(300).wallet, !!gameLib.player(zid)], [200, zw, false], 'activation later: the email-keyed history and wallet move 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); });