Wallet push: game balances waiting on a wallet the member already linked (on-chain member address, the same one the hand-off token carries) are pushed to the game's signed POST /api/iap/wallet instead of nudged, so the game's own sweep pays them (solanaclick 1.5 POL in Gem Kingdom, 2026-10-25); PolyBreak, SpellWheel, PolyWarriors join the hourly check push-only (no new nudge mail); admin view counts and lists pushes and refusals

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-25 05:12:15 -05:00
parent 962cdf08b5
commit a4642341aa
2 changed files with 57 additions and 8 deletions
+1 -1
View File
@@ -640,7 +640,7 @@ async function boot() {
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
walletnudge.init({ dataDir: DATA_DIR, accounts, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com',
walletnudge.init({ dataDir: DATA_DIR, accounts, chain, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com',
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); } });
setTimeout(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 3 * 60 * 1000); // past the deploy overlap window
setInterval(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 60 * 60 * 1000);
+56 -7
View File
@@ -4,6 +4,12 @@
// 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.
// nudge: false = push only (PolyBreak, SpellWheel, PolyWarriors joined 2026-10-25; their members never got nudge mail before).
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');
@@ -11,6 +17,7 @@ const blank = () => ({ v: 1, people: {}, stats: { sent: 0, converted: 0, runs: 0
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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[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 || '.'; }
@@ -21,9 +28,32 @@ function games() {
{ 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: '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, nudge: false },
{ key: 'spellwheel', name: 'SpellWheel', url: process.env.SW_URL || 'https://spellwheel.com', secret: process.env.SW_SSO_SECRET, nudge: false },
{ key: 'polywarriors', name: 'PolyWarriors', url: process.env.PW_URL || 'https://polywarriors.com', secret: process.env.PW_SSO_SECRET, nudge: false }
].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 linked address, only when that address is an on-chain member -> { wallet, memberId } | null
async function activatedWallet(a) {
if (!a || !a.address || !/^0x[a-f0-9]{40}$/i.test(a.address) || !R.chain || !R.chain.memberIdByAccount) return null;
const id = await R.chain.memberIdByAccount(a.address); // throws on an RPC failure: the caller skips this row until next hour
return Number(id) > 0 ? { wallet: a.address, memberId: Number(id) } : null;
}
function fetchRows(g) {
return new Promise(resolve => {
const ts = String(Date.now());
@@ -49,14 +79,32 @@ function copy(games, stage, link) {
}
async function tick() {
const S = load(); S.stats.runs++; S.lastRun = Date.now();
const byEmail = new Map(), snapshot = {};
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();
if (!email && r.memberId && R.accounts.byMemberId) { const a = await R.accounts.byMemberId(Number(r.memberId)); email = a ? a.email : ''; }
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 cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid: Math.max(0, Number(r.unpaid) || 0) }); byEmail.set(email, cur);
const unpaid = Math.max(0, Number(r.unpaid) || 0);
// the IAP account already has an activated wallet: hand it to the game instead of asking the member for it
if (!acct) acct = await R.accounts.byEmail(email);
let act = null; try { act = await activatedWallet(acct); } catch (e) { console.warn('walletnudge chain read', e.message); continue; }
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;
@@ -82,7 +130,7 @@ async function tick() {
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 };
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) {
@@ -94,6 +142,7 @@ 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) };
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 };