310992e40f
milestone.js watches the account count (site config milestoneMode off|dry|armed, milestoneTarget 1000, milestonePol 1). At the target it freezes the eligibility list: wallet activated on chain (member record with activated flag), not on the no-payout list, not suspended, one payment per wallet. Payments go one at a time from IAP_MILESTONE_KEY with tx hashes per row and never twice; the Telegram start post waits for the wallet to hold the full amount. Paid members get an in-app notice + email with their Polygonscan link; everyone else gets the missed-it nudge (link a wallet / switch on payouts), email only with the newsletter opt-in. One start and one finish Telegram post (Discord mirrored), the total logged in the P&L as a rewards cost against Receiver A. Admin: /api/admin/milestone (view, mode, snapshot, recheck, pay, settle, notify-missed, reset-before-payment). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
185 lines
16 KiB
JavaScript
185 lines
16 KiB
JavaScript
// 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: '<p>' + esc(p1) + '</p><p><a href="' + esc(tx) + '">Your payment on Polygonscan</a></p><p>' + esc(p3) + '</p>' };
|
|
}
|
|
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: '<p>' + esc(p1) + '</p><p>' + esc(p2) + '</p><p>' + esc(p3) + '</p><p><a href="' + esc(link()) + '"><b>Open your Wallet tab</b></a></p>' };
|
|
}
|
|
|
|
// 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} <b>InstantAdPay just passed ' + S.target.toLocaleString() + ' members.</b>\nTo mark it, ' + due.length + ' members whose wallets are activated with payouts on are each receiving <b>' + S.pol + ' POL</b> 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('✅ <b>' + S.target.toLocaleString() + '-member drop complete.</b> ' + 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 };
|