// Wallet push + nudge (walletnudge.js) against a MOCK game on localhost, throwaway data. Run: node qa/walletnudge.test.cjs // 2026-10-27 (Marty, "build all three"): a signature-linked wallet is pushed to the game whether or not it is an on-chain // member (memberId 0 when it is not); only players with NO linked wallet are nudged, and the nudge asks for the link step only. 'use strict'; const fs = require('fs'); const os = require('os'); const path = require('path'); const http = require('http'); const crypto = require('crypto'); const assert = require('assert'); const ROOT = path.join(__dirname, '..'); let fails = 0, n = 0; async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.message); } } function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); } const SECRET = 'x'.repeat(40); const W1 = '0x' + '1'.repeat(40), W2 = '0x' + '2'.repeat(40), W3 = '0x' + '3'.repeat(40); // a game with the same contract as the real ones: signed GET /api/iap/unpaid, signed POST /api/iap/wallet (fill empty only) function mockGame(players) { const pushes = []; const srv = http.createServer((req, res) => { const u = new URL(req.url, 'http://x'), send = (c, j) => { res.writeHead(c, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(j)); }; if (u.pathname === '/api/iap/unpaid') { const ts = u.searchParams.get('ts'), want = crypto.createHmac('sha256', SECRET).update('unpaid\n' + ts).digest('hex'); if (u.searchParams.get('sig') !== want) return send(401, { error: 'bad signature' }); return send(200, { ok: true, rows: Object.entries(players).filter(([, p]) => p.unpaid > 0 && !p.wallet).map(([email, p]) => ({ email, memberId: 0, username: null, unpaid: p.unpaid })) }); } if (u.pathname === '/api/iap/wallet' && req.method === 'POST') { let raw = ''; req.on('data', c => raw += c); req.on('end', () => { const ts = String(req.headers['x-iap-ts'] || ''); const want = crypto.createHmac('sha256', SECRET).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex'); if (req.headers['x-iap-sig'] !== want) return send(401, { error: 'bad signature' }); const b = JSON.parse(raw), p = players[b.email]; pushes.push(b); if (!p) return send(404, { error: 'unknown player' }); if (p.wallet && p.wallet.toLowerCase() !== b.wallet.toLowerCase()) return send(409, { error: 'a different wallet is already set' }); const changed = !p.wallet; if (!p.wallet) p.wallet = b.wallet; send(200, { ok: true, changed, wallet: b.wallet, unpaid: p.unpaid }); }); return; } send(404, {}); }); return new Promise(ok => srv.listen(0, '127.0.0.1', () => ok({ srv, pushes, url: 'http://127.0.0.1:' + srv.address().port }))); } (async () => { for (const k of ['SD', 'GK', 'SEEK', 'DR', 'RA', 'PB', 'SW', 'PW']) { delete process.env[k + '_URL']; delete process.env[k + '_SSO_SECRET']; } const players = { 'tank@x.test': { unpaid: 1.5 }, // linked wallet, NOT activated (holding tank): must be pushed, memberId 0 'member@x.test': { unpaid: 0.4 }, // linked + activated: pushed with its member id, as before 'nowallet@x.test': { unpaid: 0.75 }, // no linked wallet: nudged 'other@x.test': { unpaid: 0.2, wallet: null }, // game already holds a different wallet -> refused below 'rpc@x.test': { unpaid: 0.3 } // chain read fails: still pushed (stored member id, here 0) }; const G = await mockGame(players); process.env.GK_URL = G.url; process.env.GK_SSO_SECRET = SECRET; const accts = { 'tank@x.test': { email: 'tank@x.test', username: 'tanky', address: W1, memberId: 0 }, 'member@x.test': { email: 'member@x.test', username: 'mem', address: W2, memberId: 0 }, 'nowallet@x.test': { email: 'nowallet@x.test', username: 'nw', address: null, memberId: 0 }, 'other@x.test': { email: 'other@x.test', username: 'ot', address: W3, memberId: 0 }, 'rpc@x.test': { email: 'rpc@x.test', username: 'rp', address: '0x' + '4'.repeat(40), memberId: 0 } }; const chainIds = { [W2.toLowerCase()]: 77 }; const inbox = [], mail = []; const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-wn-')); const wn = fresh('walletnudge.js'); // the 'other' player's game copy got a different wallet in between (fill-empty-only must refuse a replacement) players['other@x.test'].wallet = '0x' + '5'.repeat(40); players['other@x.test'].unpaid = 0.2; // ...but then the game would not list it as unpaid-without-wallet; force it into the list once to exercise the 409 path const origOther = players['other@x.test']; wn.init({ dataDir: dir, site: 'https://instantadpay.com', accounts: { byEmail: async e => accts[e] || null, byMemberId: async () => null }, chain: { memberIdByAccount: async a => { if (a === accts['rpc@x.test'].address) throw new Error('rpc down'); return chainIds[a.toLowerCase()] || 0; } }, mailer: { hasKey: () => true, send: async (to, subject, text, html) => { mail.push({ to, subject, text, html }); } }, optedIn: async () => true, message: async (to, subject, html) => { inbox.push({ to, subject, html }); } }); let r; await t('tick runs against the mock game', async () => { r = await wn.tick(); assert.ok(r.ok); assert.strictEqual(r.games.gemkingdom, 4); }); await t('non-activated linked wallet is pushed with memberId 0 and filled', async () => { const p = G.pushes.find(x => x.email === 'tank@x.test'); assert.ok(p, 'no push'); assert.strictEqual(p.wallet, W1); assert.strictEqual(p.memberId, 0); assert.strictEqual(players['tank@x.test'].wallet, W1); }); await t('activated wallet still pushed with its member id', async () => { const p = G.pushes.find(x => x.email === 'member@x.test'); assert.ok(p); assert.strictEqual(p.memberId, 77); assert.strictEqual(players['member@x.test'].wallet, W2); }); await t('a failed chain read still pushes the linked wallet (stored member id)', async () => { const p = G.pushes.find(x => x.email === 'rpc@x.test'); assert.ok(p); assert.strictEqual(p.memberId, 0); }); await t('linked players are never nudged; the no-wallet player is', async () => { assert.deepStrictEqual(inbox.map(x => x.to), ['nowallet@x.test']); assert.deepStrictEqual(mail.map(x => x.to), ['nowallet@x.test']); assert.strictEqual(r.pushed, 3); assert.strictEqual(r.sent, 1); }); await t('nudge copy: link step only, the exact approved wording, /my#wallet', async () => { const m = mail[0]; assert.strictEqual(m.subject, '0.75 POL is waiting for your wallet'); assert.ok(m.text.includes("You've earned 0.75 POL in Gem Kingdom. Link your wallet (one free signature) and it's sent automatically, including everything you've earned so far."), m.text); assert.ok(m.text.includes('https://instantadpay.com/my#wallet')); assert.ok(inbox[0].html.includes('https://instantadpay.com/my#wallet')); assert.ok(!/switch on|activate/i.test(m.text + inbox[0].html), 'mentions switching on payouts'); assert.ok(!/—/.test(m.text + inbox[0].html), 'em dash'); }); await t('second tick: nothing re-pushed as a change, no second nudge before 3 days', async () => { const before = G.pushes.length; const r2 = await wn.tick(); assert.strictEqual(r2.pushed, 0); assert.strictEqual(r2.sent, 0); assert.strictEqual(G.pushes.length, before, 'filled players are no longer listed'); }); await t('a different wallet in the game is refused (409), never replaced, and not retried within the day', async () => { // list the "other" player as unpaid with no wallet in the listing, but the game copy holds a different wallet const realWallet = origOther.wallet; const saved = G.srv.listeners('request')[0]; G.srv.removeAllListeners('request'); G.srv.on('request', (req, res) => { if (req.url.startsWith('/api/iap/unpaid')) { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ ok: true, rows: [{ email: 'other@x.test', memberId: 0, unpaid: 0.2 }] })); } return saved(req, res); }); const before = G.pushes.length; await wn.tick(); assert.strictEqual(G.pushes.length, before + 1); assert.strictEqual(players['other@x.test'].wallet, realWallet); const v = wn.adminView(); assert.ok(v.pushRefused.some(x => x.email === 'other@x.test' && x.status === 'conflict')); await wn.tick(); assert.strictEqual(G.pushes.length, before + 1, 'retried within 24 h'); }); G.srv.close(); fs.rmSync(dir, { recursive: true, force: true }); console.log((n - fails) + '/' + n + ' passed'); process.exit(fails ? 1 : 0); })();