// Wallet-link nudges (Marty, 2026-10-07): players who earned POL in the games but never linked a wallet get told, // so the first reward actually reaches them. Every hour this asks each game (signed with the shared SSO secret) // for its players with an unpaid balance and no wallet, folds them by InstantAdPay account, and sends at most // three touches per person: at once, at 3 days, at 10 days. In-app notice always (kind 'notice', never a pop-up // broadcast); email only when the member opted in and outbound mail is on. Stops the moment a wallet is linked. // State: DATA_DIR/wallet-nudge.json. The coach card reads waitingFor() to badge a direct. // Wallet push (Marty, 2026-10-25): a game only learns the wallet on the IAP -> game hand-off, so a member who linked a wallet // after that and keeps a remembered game session never got paid (solanaclick, 1.5 POL in Gem Kingdom). Now a row whose IAP // account has a wallet that is an on-chain member (the same a.address the hand-off token carries) is PUSHED to that game's // signed POST /api/iap/wallet instead of nudged; the game's own payout sweep then pays it. Idempotent on the game side (the same // wallet twice is a no-op, a different one is refused), so the deploy overlap's two copies cannot do harm. // Any linked wallet (Marty, 2026-10-27, "build all three"): the push no longer waits for the wallet to be an on-chain member. A // holding-tank member can wait a day or more before switching on payouts, and their game POL sat unpaid with the nudges stopped. // accounts.address is only ever set after a verified wallet signature (auth.verifyChallenge -> accounts.linkWallet), so that is // the wallet every game pays. memberId goes along when the chain knows one, else 0. // nudge: false = push only. PolyBreak, SpellWheel and PolyWarriors joined 2026-10-25 push-only; Marty turned their nudges on the same day. const fs = require('fs'), path = require('path'), crypto = require('crypto'), https = require('https'), http = require('http'); let R = {}, DATA_DIR = '.'; const FILE = () => path.join(DATA_DIR, 'wallet-nudge.json'); const blank = () => ({ v: 1, people: {}, stats: { sent: 0, converted: 0, runs: 0 }, lastRun: 0, lastRows: {} }); const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } }; const save = s => { try { fs.writeFileSync(FILE(), JSON.stringify(s)); } catch (e) {} }; const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); const now0 = () => Date.now(); const STAGES = [0, 3 * 86400000, 10 * 86400000]; // first touch now, reminder at 3 days, last word at 10 days function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; } // the games that pay POL through a balance (PolHunter sends each drip directly and never holds one) function games() { return [ { key: 'spookydoors', name: 'Spooky Doors', url: process.env.SD_URL, secret: process.env.SD_SSO_SECRET }, { key: 'gemkingdom', name: 'Gem Kingdom', url: process.env.GK_URL, secret: process.env.GK_SSO_SECRET }, { key: 'clutterhunt', name: 'ClutterHunt', url: process.env.SEEK_URL, secret: process.env.SEEK_SSO_SECRET }, { key: 'driprunner', name: 'Drip Runner', url: process.env.DR_URL, secret: process.env.DR_SSO_SECRET }, { key: 'roadagent', name: 'Road Agent', url: process.env.RA_URL, secret: process.env.RA_SSO_SECRET }, { key: 'polybreak', name: 'PolyBreak', url: process.env.PB_URL || 'https://polybreak.app', secret: process.env.PB_SSO_SECRET }, { key: 'polminer', name: 'POL Miner', url: process.env.POLMINER_URL || 'https://polminer.com', secret: process.env.POLMINER_SSO_SECRET }, // 2026-10-28: idle until POLMINER_SSO_SECRET is set { key: 'turkeydrop', name: 'Turkey Drop', url: process.env.TD_URL || 'https://turkeydropgame.com', secret: process.env.TD_SSO_SECRET }, // 2026-10-28: idle until TD_SSO_SECRET is set { key: 'spellwheel', name: 'SpellWheel', url: process.env.SW_URL || 'https://spellwheel.com', secret: process.env.SW_SSO_SECRET }, { key: 'polywarriors', name: 'PolyWarriors', url: process.env.PW_URL || 'https://polywarriors.com', secret: process.env.PW_SSO_SECRET } ].filter(g => g.url && g.secret && String(g.secret).trim().length >= 32); } // POST the wallet to the game: X-IAP-Sig = hex HMAC-SHA256(secret, 'wallet\n' + ts + '\n' + hex sha256(body)) -> { status, j } function pushWallet(g, body) { return new Promise(resolve => { const raw = JSON.stringify(body), ts = String(Date.now()); const sig = crypto.createHmac('sha256', String(g.secret).trim()).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex'); let url; try { url = new URL(String(g.url).replace(/\/+$/, '') + '/api/iap/wallet'); } catch (e) { return resolve({ status: 0, j: null }); } const mod = url.protocol === 'https:' ? https : http; const rq = mod.request(url, { method: 'POST', timeout: 8000, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw), 'X-IAP-Ts': ts, 'X-IAP-Sig': sig, 'User-Agent': 'InstantAdPay wallet-push/1.0' } }, r => { let d = ''; r.on('data', c => { if (d.length < 1e5) d += c; }); r.on('end', () => { let j = null; try { j = JSON.parse(d); } catch (e) {} resolve({ status: r.statusCode, j }); }); }); rq.on('timeout', () => { rq.destroy(); resolve({ status: 0, j: null }); }); rq.on('error', () => resolve({ status: 0, j: null })); rq.end(raw); }); } // the wallet to push for an account: its signature-linked address, activated or not -> { wallet, memberId } | null // memberId is the on-chain member id when there is one, else 0; a failed chain read falls back to the account's stored id. async function linkedWallet(a) { if (!a || !a.address || !/^0x[a-f0-9]{40}$/i.test(a.address)) return null; let id = Number(a.memberId) || 0; if (R.chain && R.chain.memberIdByAccount) { try { id = Number(await R.chain.memberIdByAccount(a.address)) || 0; } catch (e) { console.warn('walletnudge chain read', e.message); } } return { wallet: a.address, memberId: id > 0 ? id : 0 }; } function fetchRows(g) { return new Promise(resolve => { const ts = String(Date.now()); const sig = crypto.createHmac('sha256', String(g.secret).trim()).update('unpaid\n' + ts).digest('hex'); let url; try { url = new URL(String(g.url).replace(/\/+$/, '') + '/api/iap/unpaid?ts=' + ts + '&sig=' + sig); } catch (e) { return resolve(null); } const mod = url.protocol === 'https:' ? https : http; const rq = mod.get(url, { timeout: 8000, headers: { 'User-Agent': 'InstantAdPay wallet-nudge/1.0' } }, r => { let d = ''; r.on('data', c => { if (d.length < 2e6) d += c; }); r.on('end', () => { try { const j = JSON.parse(d); resolve(j && j.ok && Array.isArray(j.rows) ? j.rows : null); } catch (e) { resolve(null); } }); }); rq.on('timeout', () => { rq.destroy(); resolve(null); }); rq.on('error', () => resolve(null)); }); } // copy (Marty, 2026-10-27): the ask is the LINK step only (one free signature), never "switch on payouts": a linked wallet is paid function copy(games, stage, link) { const total = games.reduce((n, g) => n + g.unpaid, 0); const parts = games.map(g => g.unpaid.toFixed(2) + ' POL in ' + g.name); const list = parts.length > 1 ? parts.slice(0, -1).join(', ') + ' and ' + parts[parts.length - 1] : parts[0]; const subject = total.toFixed(2) + ' POL is waiting for your wallet'; const p1 = "You've earned " + list + ". Link your wallet (one free signature) and it's sent automatically, including everything you've earned so far."; const p2 = 'It is not a transaction and it cannot move funds. Every game pays that same wallet from then on.'; const p3 = stage >= 2 ? 'This is the last reminder about this balance. It stays yours; it just waits for a wallet.' : 'Not sure which wallet to use? SafePal is the one we recommend; MetaMask and Phantom work too. The Wallet tab has a short guide.'; const text = [p1, '', p2, '', 'Link your wallet: ' + link, '', p3].join('\n'); const html = '
' + esc(p1).replace(esc(list), '' + esc(list) + '') + '
' + esc(p2) + '
' + esc(p3) + '
'; return { subject, text, html, total }; } async function tick() { const S = load(); S.stats.runs++; S.lastRun = Date.now(); const byEmail = new Map(), snapshot = {}; let pushed = 0; S.pushes = S.pushes || {}; S.pushLog = S.pushLog || []; S.stats.pushed = S.stats.pushed || 0; for (const g of games()) { const rows = await fetchRows(g); snapshot[g.key] = rows ? rows.length : null; if (!rows) continue; for (const r of rows) { let email = String(r.email || '').trim().toLowerCase(), acct = null; if (!email && Number(r.memberId) > 0 && R.accounts.byMemberId) { acct = await R.accounts.byMemberId(Number(r.memberId)); email = acct ? acct.email : ''; } if (!email) continue; const unpaid = Math.max(0, Number(r.unpaid) || 0); // the IAP account already has a linked wallet (activated or not): hand it to the game instead of asking the member for it if (!acct) acct = await R.accounts.byEmail(email); const act = await linkedWallet(acct); if (act) { const pk = g.key + ':' + email, prev = S.pushes[pk]; // a refusal (different wallet already in the game, unknown player) is retried once a day, never every hour if (prev && prev.wallet === act.wallet && prev.status !== 'ok' && prev.status !== 'error' && now0() - prev.at < 86400000) continue; const out = await pushWallet(g, { email, wallet: act.wallet, username: (acct && acct.username) || r.username || null, memberId: act.memberId }); const status = out.status === 200 && out.j && out.j.ok ? 'ok' : out.status === 409 ? 'conflict' : out.status === 404 ? 'unknown' : 'error'; const changed = status === 'ok' && !!out.j.changed; S.pushes[pk] = { at: now0(), game: g.key, email, wallet: act.wallet, memberId: act.memberId, unpaid, status, code: out.status, changed }; if (changed) { S.stats.pushed++; pushed++; S.pushLog.unshift({ at: now0(), game: g.key, name: g.name, email, username: (acct && acct.username) || r.username || null, memberId: act.memberId, wallet: act.wallet, unpaid }); S.pushLog = S.pushLog.slice(0, 300); } console.log('walletnudge push', g.key, email.replace(/^(..).*(@.*)$/, '$1***$2'), act.wallet, unpaid, status, out.status, changed ? 'FILLED' : ''); continue; // pushed (or a refusal that a nudge cannot fix: the member already has a wallet) } if (g.nudge === false) continue; const cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid }); byEmail.set(email, cur); } } S.lastRows = snapshot; const now = Date.now(); let sent = 0; // conversions: someone we nudged who now has a wallet. The game's own sweep pays them; we just stop. for (const [email, p] of Object.entries(S.people)) { if (p.done) continue; const a = await R.accounts.byEmail(email); if (a && a.address) { p.done = 'linked'; p.doneAt = now; S.stats.converted++; } else if (!byEmail.has(email) && now - (p.last || p.first) > 14 * 86400000) { p.done = 'gone'; p.doneAt = now; } } for (const [email, gs] of byEmail) { const a = await R.accounts.byEmail(email); if (!a || a.address) continue; const p = S.people[email] || (S.people[email] = { first: now, sent: [], games: {} }); p.last = now; gs.forEach(g => { p.games[g.key] = g.unpaid; }); const stage = p.sent.length; if (stage >= STAGES.length) continue; if (now - p.first < STAGES[stage]) continue; const link = (R.site || 'https://instantadpay.com') + '/my#wallet'; const c = copy(gs, stage, link); let ok = false; try { await R.message(email, c.subject, c.html); ok = true; } catch (e) {} if (R.mailer && R.mailer.hasKey && R.mailer.hasKey() && R.optedIn) { try { if (await R.optedIn(email)) { await R.mailer.send(email, c.subject, c.text, c.html); ok = true; } } catch (e) {} } if (ok) { p.sent.push({ ts: now, stage, total: Number(c.total.toFixed(4)) }); S.stats.sent++; sent++; } } save(S); return { ok: true, sent, pushed, people: byEmail.size, games: snapshot }; } // POL a specific member has waiting across the games (0 when none, or once they linked a wallet) function waitingFor(email) { const p = load().people[String(email || '').trim().toLowerCase()]; if (!p || p.done) return 0; return Number(Object.values(p.games || {}).reduce((n, v) => n + Number(v || 0), 0).toFixed(4)); } function adminView() { const S = load(); const people = Object.entries(S.people).map(([email, p]) => ({ email, first: p.first, last: p.last || p.first, sent: p.sent.length, lastSent: p.sent.length ? p.sent[p.sent.length - 1].ts : 0, done: p.done || null, games: p.games, total: Number(Object.values(p.games || {}).reduce((n, v) => n + Number(v || 0), 0).toFixed(4)) })); people.sort((a, b) => b.total - a.total); return { stats: Object.assign({ pushed: 0 }, S.stats), lastRun: S.lastRun, lastRows: S.lastRows, games: games().map(g => ({ key: g.key, name: g.name, url: g.url, nudge: g.nudge !== false })), pushed: (S.pushLog || []).slice(0, 100), pushRefused: Object.values(S.pushes || {}).filter(x => x.status !== 'ok').sort((a, b) => b.at - a.at).slice(0, 100), waiting: people.filter(p => !p.done), done: people.filter(p => p.done).slice(0, 100) }; } module.exports = { init, tick, waitingFor, adminView, games, STAGES };