// 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. 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 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 } ].filter(g => g.url && g.secret && String(g.secret).trim().length >= 32); } 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)); }); } function copy(games, stage, link) { const total = games.reduce((n, g) => n + g.unpaid, 0); const list = games.map(g => g.unpaid.toFixed(2) + ' POL from ' + g.name).join(', '); const subject = total.toFixed(2) + ' POL is waiting for your wallet'; const p1 = 'You have ' + list + ' sitting in your game balance' + (games.length > 1 ? 's' : '') + '. It cannot be paid out yet because no wallet is linked to your InstantAdPay account.'; const p2 = 'Link a wallet on your Wallet tab. It is one free signature, no transaction, and it cannot move funds. Your POL pays out on the next sweep, and 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) + '

Link your wallet

' + 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 = {}; 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(); if (!email && r.memberId && R.accounts.byMemberId) { const a = await R.accounts.byMemberId(Number(r.memberId)); email = a ? a.email : ''; } if (!email) continue; const cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid: Math.max(0, Number(r.unpaid) || 0) }); 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, 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: S.stats, lastRun: S.lastRun, lastRows: S.lastRows, games: games().map(g => ({ key: g.key, name: g.name, url: g.url })), waiting: people.filter(p => !p.done), done: people.filter(p => p.done).slice(0, 100) }; } module.exports = { init, tick, waitingFor, adminView, games, STAGES };