diff --git a/milestone.js b/milestone.js new file mode 100644 index 0000000..042207b --- /dev/null +++ b/milestone.js @@ -0,0 +1,184 @@ +// 1,000-member milestone drop (Marty, 2026-10-10): when the account count reaches the target, every member whose wallet is +// ACTIVATED on chain (payouts switched on: the account's address maps to an on-chain member record with the activated +// flag, and that member id is not on the no-payout list) receives `milestonePol` POL from a dedicated hot wallet, and is +// told. Everyone else is told they missed it and how to be in the next one: link a wallet (no wallet yet) or switch on +// payouts (wallet linked, not activated). +// +// Snapshot first, then pay: eligibility is frozen the moment the count crosses the target, so nothing linked afterwards +// counts. Payments go one at a time from IAP_MILESTONE_KEY over the site's own RPC list (chain.getConfig().rpcs), each +// row carrying its tx hash; a row is never sent twice (status due -> sent -> paid | failed). Notices are in-app +// (kind 'notice') plus email: the paid email is transactional (everyone paid gets it), the missed-it email respects the +// newsletter opt-in like every other nudge. One Telegram proof post at the start and one at the end (mirrored to Discord +// by telegramSend), never one per payment. The total lands in the P&L as a rewards cost against Receiver A. +// +// Modes (site config milestoneMode): off | dry | armed. dry = snapshot and show, send nothing. State: DATA_DIR/milestone-1000.json. +'use strict'; +const fs = require('fs'), path = require('path'); +let R = {}, DATA_DIR = '.', ethers = null, paying = false; +const FILE = () => path.join(DATA_DIR, 'milestone-1000.json'); +const blank = () => ({ v: 1, status: 'idle', target: 1000, pol: 1, snapshotAt: 0, countAt: 0, rows: [], others: { noWallet: [], notActivated: [], suspended: 0 }, notified: { paidStart: 0, paidEnd: 0, missed: 0 }, log: [] }); +const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } }; +const save = s => { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(s)); fs.renameSync(f + '.tmp', f); }; +const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); +const logLine = (S, t) => { S.log.push({ at: Date.now(), t: String(t).slice(0, 300) }); if (S.log.length > 400) S.log = S.log.slice(-400); }; +const r4 = n => Math.round(Number(n) * 1e4) / 1e4; + +function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; } +const cfg = () => { const sc = (R.siteConfig && R.siteConfig()) || {}; return { mode: ['off', 'dry', 'armed'].includes(sc.milestoneMode) ? sc.milestoneMode : 'off', target: Number(sc.milestoneTarget) || 1000, pol: Number(sc.milestonePol) > 0 ? Number(sc.milestonePol) : 1 }; }; +const keyOk = () => /^0x[0-9a-fA-F]{64}$/.test(String(process.env.IAP_MILESTONE_KEY || '').trim()); +function wallet() { + if (!keyOk()) return null; if (!ethers) ethers = require('ethers'); + const c = R.chain.getConfig(); const rpcs = (c.rpcs || []).filter(Boolean); if (!rpcs.length) return null; + const provider = new ethers.JsonRpcProvider(rpcs[0], Number(c.chainId) || 137); + return { w: new ethers.Wallet(String(process.env.IAP_MILESTONE_KEY).trim(), provider), provider, explorer: c.explorer || 'https://polygonscan.com', chainId: Number(c.chainId) || 137 }; +} +async function balance() { const W = wallet(); if (!W) return null; try { return Number(ethers.formatEther(await W.provider.getBalance(W.w.address))); } catch (e) { return null; } } +const address = () => { const W = wallet(); return W ? W.w.address : null; }; + +// how many accounts exist right now (the number Marty watches on the admin Overview) +async function accountCount() { const all = await R.accounts.listAll(100000); return all.length; } + +// freeze the eligibility list: activated on chain, not on the no-payout list, not suspended +async function snapshot(force) { + const S = load(); const C = cfg(); + if (S.status !== 'idle' && !force) return S; + const all = await R.accounts.listAll(100000); const bad = R.noPayoutSet ? R.noPayoutSet() : new Set(); + const rows = [], noWallet = [], notActivated = []; let suspended = 0; const seenAddr = new Set(); + for (const a of all) { + if (a.suspended) { suspended++; continue; } + const addr = String(a.address || '').toLowerCase(); + if (!/^0x[0-9a-f]{40}$/.test(addr)) { noWallet.push(a.email); continue; } + if (seenAddr.has(addr)) { notActivated.push(a.email); continue; } // the same wallet on a second account never pays twice + let id = 0, activated = false, err = null; + for (let t = 0; t < 3 && !err; t++) { try { id = await R.chain.memberIdByAccount(addr); if (id) { const m = await R.chain.member(id); activated = !!(m && m.activated); } break; } catch (e) { if (t === 2) err = String(e.message || e).slice(0, 120); } } + if (err) { rows.push({ email: a.email, username: a.username || null, address: addr, memberId: 0, status: 'check', error: err, pol: C.pol }); continue; } + if (!id || !activated || bad.has(Number(id))) { notActivated.push(a.email); continue; } + seenAddr.add(addr); + rows.push({ email: a.email, username: a.username || null, address: addr, memberId: id, flags: Array.isArray(a.flags) && a.flags.length ? a.flags : undefined, status: 'due', pol: C.pol, tx: null }); + } + Object.assign(S, { status: 'snapshot', target: C.target, pol: C.pol, snapshotAt: Date.now(), countAt: all.length, rows, others: { noWallet, notActivated, suspended } }); + logLine(S, 'snapshot: ' + all.length + ' accounts, ' + rows.filter(r => r.status === 'due').length + ' eligible, ' + rows.filter(r => r.status === 'check').length + ' unchecked (rpc), ' + notActivated.length + ' wallet not activated, ' + noWallet.length + ' no wallet'); + save(S); return S; +} +// re-check rows the snapshot could not read from the chain (rpc trouble); they join as due or move to the missed list +async function recheck() { + const S = load(); const bad = R.noPayoutSet ? R.noPayoutSet() : new Set(); let fixed = 0; + for (const r of S.rows.filter(x => x.status === 'check')) { + try { const id = await R.chain.memberIdByAccount(r.address); const m = id ? await R.chain.member(id) : null; + if (id && m && m.activated && !bad.has(Number(id))) { r.memberId = id; r.status = 'due'; delete r.error; } else { r.status = 'skip'; S.others.notActivated.push(r.email); } fixed++; } catch (e) { r.error = String(e.message || e).slice(0, 120); } + } + if (fixed) logLine(S, 'recheck: ' + fixed + ' rows resolved'); save(S); return S; +} + +const link = () => (R.site || 'https://instantadpay.com') + '/my#wallet'; +function paidCopy(r, S, W) { + const subject = '1,000 members. We just sent you ' + S.pol + ' POL.'; + const tx = W.explorer + '/tx/' + r.tx; + const p1 = 'InstantAdPay passed 1,000 members today. To mark it, every member whose wallet was activated with payouts on at that moment received ' + S.pol + ' POL, sent straight to the wallet on your account.'; + const p2 = 'Yours is on chain: ' + tx; + const p3 = 'Thank you for building with us. The next milestone will do the same, so keep that wallet on your account.'; + return { subject, text: [p1, '', p2, '', p3].join('\n'), html: '
' + esc(p1) + '
' + esc(p3) + '
' }; +} +function missedCopy(kind, S) { + const subject = 'You missed the 1,000-member POL drop. Here is how to be in the next one.'; + const p1 = 'InstantAdPay passed 1,000 members today, and every member whose wallet was activated with payouts on received ' + S.pol + ' POL on the spot.'; + const p2 = kind === 'noWallet' ? 'Your account had no wallet linked, so there was nowhere to send yours.' : 'Your account had a wallet linked, but payouts were not switched on, so the drop could not reach you.'; + const p3 = kind === 'noWallet' ? 'Link a wallet on your Wallet tab (one free signature, it cannot move funds), then switch on payouts. The next milestone pays everyone who has done both.' : 'Switch on payouts from your Wallet tab. It is one small transaction that activates your position, and from then on every payout, sponsor commission and milestone reaches you automatically.'; + return { subject, text: [p1, '', p2, '', p3, '', link()].join('\n'), html: '' + esc(p1) + '
' + esc(p2) + '
' + esc(p3) + '
' }; +} + +// pay every due row, one at a time; safe to call again (rows already sent or paid are never resent) +async function pay() { + if (paying) return { error: 'already paying' }; paying = true; + try { + const S = load(); const C = cfg(); if (!['snapshot', 'paying'].includes(S.status)) return { error: 'nothing to pay (status ' + S.status + ')' }; + if (C.mode !== 'armed') return { error: 'mode is ' + C.mode + ', not armed' }; + const W = wallet(); if (!W) return { error: 'no milestone wallet key (IAP_MILESTONE_KEY)' }; + const due = S.rows.filter(r => r.status === 'due'); if (!due.length) { return finish(S, W); } + if (S.status === 'snapshot') { + const need = r4(due.length * S.pol) + 0.05, have = await balance(); // the snapshot is frozen; the announcement waits for the funding + if (have == null || have < need) { if (!S.waitLogged || Date.now() - S.waitLogged > 1800000) { logLine(S, 'waiting for funds: wallet holds ' + have + ' POL, needs ' + need); S.waitLogged = Date.now(); save(S); } return { waiting: 'funds', have, need }; } + S.status = 'paying'; S.payStart = Date.now(); save(S); + await post('\u{1F389} InstantAdPay just passed ' + S.target.toLocaleString() + ' members.\nTo mark it, ' + due.length + ' members whose wallets are activated with payouts on are each receiving ' + S.pol + ' POL right now, straight to the wallet on their account. Not activated yet? Switch on payouts on your Wallet tab and you are in the next one.\n' + (R.site || 'https://instantadpay.com') + '/my#wallet'); + S.notified.paidStart = Date.now(); save(S); } + let bal = await balance(); if (bal == null) return { error: 'could not read the wallet balance' }; + for (const r of S.rows) { + if (r.status !== 'due') continue; + if (bal < Number(r.pol) + 0.01) { logLine(S, 'paused: balance ' + bal + ' POL below the next payment'); save(S); return { paused: 'low balance', balance: bal }; } + try { + const tx = await W.w.sendTransaction({ to: r.address, value: ethers.parseEther(String(r.pol)) }); + r.status = 'sent'; r.tx = tx.hash; r.sentAt = Date.now(); save(S); + let rc = null; try { rc = await tx.wait(1, 120000); } catch (e) { if (!(e && e.code === 'TIMEOUT')) throw e; } + if (rc && rc.status === 1) { r.status = 'paid'; r.paidAt = Date.now(); bal -= Number(r.pol); save(S); notifyPaid(r, S, W).catch(() => {}); } + else if (rc) { r.status = 'failed'; r.error = 'reverted'; save(S); } + // a timeout leaves the row 'sent' with its hash; settle() picks it up on the next tick + } catch (e) { + const msg = String(e && (e.shortMessage || e.message) || e); + if (/insufficient funds/i.test(msg)) { r.status = 'due'; logLine(S, 'paused: insufficient funds'); save(S); return { paused: 'insufficient funds' }; } + r.status = 'due'; r.error = msg.slice(0, 160); logLine(S, 'send error for ' + r.email + ': ' + msg.slice(0, 120)); save(S); + return { paused: 'rpc', error: msg.slice(0, 160) }; // leave the rest for the next tick rather than hammer a failing node + } + } + return finish(S, W); + } finally { paying = false; } +} +// rows left 'sent' by a receipt timeout: read the receipt now +async function settle() { + const S = load(); const W = wallet(); if (!W) return; let n = 0; + for (const r of S.rows.filter(x => x.status === 'sent' && x.tx)) { + try { const rc = await W.provider.getTransactionReceipt(r.tx); if (!rc) continue; if (rc.status === 1) { r.status = 'paid'; r.paidAt = Date.now(); notifyPaid(r, S, W).catch(() => {}); } else { r.status = 'failed'; r.error = 'reverted'; } n++; } catch (e) {} + } + if (n) save(S); return n; +} +async function finish(S, W) { + S = load(); if (S.rows.some(r => r.status === 'due' || r.status === 'sent')) return { pending: true }; + if (S.status === 'done') return { done: true }; + const paid = S.rows.filter(r => r.status === 'paid'), failed = S.rows.filter(r => r.status === 'failed'); const total = r4(paid.reduce((n, r) => n + Number(r.pol), 0)); + S.status = 'done'; S.doneAt = Date.now(); logLine(S, 'done: ' + paid.length + ' paid (' + total + ' POL), ' + failed.length + ' failed'); save(S); + await post('✅ ' + S.target.toLocaleString() + '-member drop complete. ' + paid.length + ' activated members received ' + S.pol + ' POL each, ' + total + ' POL in all, every payment on chain from ' + W.explorer + '/address/' + W.w.address + '. Missed it? Switch on payouts on your Wallet tab: the next milestone pays everyone who has.'); + S = load(); S.notified.paidEnd = Date.now(); save(S); + if (R.ledger && total > 0) { try { R.ledger.put({ dir: 'out', amount: total, note: S.target.toLocaleString() + '-member milestone: ' + S.pol + ' POL to ' + paid.length + ' activated members', kind: 'cost', category: 'rewards', wallet: 'feeA', asset: 'POL' }); } catch (e) {} } + notifyMissed().catch(e => console.error('milestone missed-notify', e.message)); + return { done: true, paid: paid.length, total }; +} +async function post(html) { try { if (R.telegram) await R.telegram(html); } catch (e) {} } +async function notifyPaid(r, S, W) { + if (r.notified) return; const c = paidCopy(r, S, W); + try { if (R.message) await R.message(r.email, c.subject, c.html); } catch (e) {} + try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) await R.mailer.send(r.email, c.subject, c.text, c.html); } catch (e) {} + const S2 = load(); const row = S2.rows.find(x => x.email === r.email); if (row) { row.notified = Date.now(); save(S2); } +} +// the missed-it nudge for everyone not paid: in-app notice always, email only with the newsletter opt-in (like every nudge) +async function notifyMissed() { + const S = load(); if (S.notified.missed) return { done: true }; let n = 0; + for (const kind of ['noWallet', 'notActivated']) { + const c = missedCopy(kind, S); + for (const email of S.others[kind] || []) { + try { if (R.message) await R.message(email, c.subject, c.html); n++; } catch (e) {} + try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey() && R.optedIn && await R.optedIn(email)) await R.mailer.send(email, c.subject, c.text, c.html); } catch (e) {} + } + } + const S2 = load(); S2.notified.missed = Date.now(); logLine(S2, 'missed-it notices: ' + n); save(S2); return { sent: n }; +} + +// every 2 minutes: watch the count while armed or dry, and keep paying/settling once a snapshot exists +async function tick() { + const C = cfg(); if (C.mode === 'off') return; + let S = load(); + if (S.status === 'idle') { const n = await accountCount(); if (n < C.target) return { waiting: n }; S = await snapshot(); if (C.mode === 'dry') return { dry: true, eligible: S.rows.filter(r => r.status === 'due').length }; } + if (S.rows.some(r => r.status === 'check')) await recheck(); + if (C.mode !== 'armed') return { dry: true }; + await settle(); + return pay(); +} +async function view() { + const S = load(); const C = cfg(); const W = wallet(); + const by = s => S.rows.filter(r => r.status === s).length; + return { mode: C.mode, target: C.target, pol: C.pol, status: S.status, snapshotAt: S.snapshotAt, countAt: S.countAt, countNow: await accountCount().catch(() => null), + wallet: W ? W.w.address : null, balance: await balance(), keyPresent: keyOk(), + eligible: S.rows.filter(r => ['due', 'sent', 'paid', 'failed'].includes(r.status)).length, due: by('due'), sent: by('sent'), paid: by('paid'), failed: by('failed'), unchecked: by('check'), + needPol: r4(S.rows.filter(r => r.status === 'due').length * S.pol), missed: { noWallet: (S.others.noWallet || []).length, notActivated: (S.others.notActivated || []).length, suspended: S.others.suspended || 0 }, + notified: S.notified, rows: S.rows.map(r => ({ email: r.email, username: r.username, memberId: r.memberId, status: r.status, tx: r.tx || null, error: r.error || null, flags: r.flags || null })), log: S.log.slice(-40) }; +} +function reset() { const S = blank(); save(S); return S; } // only while nothing was paid: the admin route checks +module.exports = { init, tick, snapshot, recheck, pay, settle, notifyMissed, view, reset, address, balance, cfg }; diff --git a/server.js b/server.js index 0a311b0..738de8d 100644 --- a/server.js +++ b/server.js @@ -27,7 +27,8 @@ const chatbot = require('./chatbot'); const fraud = require('./fraud'); const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats const tank = require('./tank'); -const walletnudge = require('./walletnudge'); // players with POL waiting in the games and no wallet (2026-10-07) // holding tank: unsponsored free members, adoptions, pay-it-forward +const walletnudge = require('./walletnudge'); +const milestone = require('./milestone'); // players with POL waiting in the games and no wallet (2026-10-07) // holding tank: unsponsored free members, adoptions, pay-it-forward const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab) const promos = require('./promos'); @@ -551,6 +552,12 @@ async function boot() { 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); + // 1,000-member POL drop (Marty 2026-10-10): watches the account count every 2 minutes while milestoneMode is dry or armed + milestone.init({ dataDir: DATA_DIR, accounts, chain, mailer, ledger, optedIn: updates.optedIn, site: 'https://instantadpay.com', siteConfig, noPayoutSet, + message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); }, + telegram: async html => { const sc = siteConfig(); if (sc.telegramChatId) await telegramSend(sc.telegramChatId, html, sc.telegramTopicId); if (sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, html, sc.telegramEchoTopicId); } }); + setTimeout(() => milestone.tick().catch(e => console.error('milestone', e.message)), 4 * 60 * 1000); + setInterval(() => milestone.tick().catch(e => console.error('milestone', e.message)), 2 * 60 * 1000); await fraud.init({ dataDir: DATA_DIR }); { // a suspended account is signed out everywhere: every member route sees no session const realFrom = auth.fromRequest.bind(auth); @@ -4399,6 +4406,20 @@ const server = http.createServer(async (req, res) => { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r); } + // -- 1,000-member drop: view, mode (off|dry|armed via site config), snapshot now, pay now, resend the missed-it notices, reset (only before any payment) + if (p === '/api/admin/milestone') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + if (req.method === 'GET') return json(res, 200, await milestone.view()); + const b = await readBody(req); const act = String(b.action || ''); + if (act === 'mode') { const m = ['off', 'dry', 'armed'].includes(b.mode) ? b.mode : 'off'; const cur = siteConfig(); fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, { milestoneMode: m }, b.target ? { milestoneTarget: Number(b.target) } : {}, b.pol ? { milestonePol: Number(b.pol) } : {}), null, 2)); return json(res, 200, await milestone.view()); } + if (act === 'snapshot') { await milestone.snapshot(!!b.force); return json(res, 200, await milestone.view()); } + if (act === 'recheck') { await milestone.recheck(); return json(res, 200, await milestone.view()); } + if (act === 'pay') { const r = await milestone.pay(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); } + if (act === 'settle') { await milestone.settle(); return json(res, 200, await milestone.view()); } + if (act === 'notify-missed') { const r = await milestone.notifyMissed(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); } + if (act === 'reset') { const v = await milestone.view(); if (v.paid || v.sent) return json(res, 400, { error: 'Payments exist; the record stays.' }); milestone.reset(); return json(res, 200, await milestone.view()); } + return json(res, 400, { error: 'Unknown action.' }); + } if (p === '/api/admin/site' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, { site: siteConfig() });