// Launch week (Marty approved 2026-11-05, campaign-2026-11/PLAN.md "Launch-week hook", options B and C). // // FOUNDER BADGE (cosmetic only: no credits, no POL, no perks) // Criterion: the account signed in at least once before the launch moment (siteConfig().launchAt, default // 2026-11-15T06:00:00-06:00, 6 AM Central). "Signed in" = the account's earliest known signed-in visit: // accounts.firstSeen, or lastSeen when firstSeen is not set yet. Both are written only by accounts.touchSeen(), // which runs on signed-in requests (/api/me dashboard load, the /api/my/ping heartbeat, sponsor chat). Since // 2026-11-05 touchSeen keeps firstSeen = the previous lastSeen on the next visit, so a member who signed in before // launch and again after it still reads as "before". Carried-over shell accounts that never signed in have neither // field and never qualify. The flag is stored on the account (accounts.founder = the launch moment, ms). // Grant: automatic from the launch moment (tick every 10 minutes, founderGrant '0' switches it off), idempotent (an // account already flagged is skipped), one run per 10-minute slot across app copies (marks.claim). Admin preview + run // at /api/admin/launch-week. No Telegram posts, no email. // // LAUNCH WEEK CONTEST (option B) // Window [launchContestStart, launchContestEnd): default Sun 2026-11-15 06:00 CT to the end of Sat 2026-11-21 CT // (end stored exclusive as 2026-11-22T00:00:00-06:00). Ranking reuses the weekly leaderboard's count: tier-1 TierPaid // events (the direct sponsor of each package sold), read from the chain index. Never counted: the sponsor's own // positions, any purchase made by a linked position (Qualified Start), the admin account and the company ids // (overrideHouseIds) as contestants or as buyers, and any email or member id in launchContestExcludeEmails / // launchContestExcludeIds (Marty's other accounts). A member must have launchContestMinSales (default 2) counted // sales to place. Ties: more sales, then more dollars, then whoever reached their total first. // Prizes: launchContestPrizesPol (default "10,6,4" = 1st, 2nd, 3rd). Paid ONLY by the admin button after the window // closes (POST /api/admin/launch-week/pay with the exact list the admin saw), through the same payer wallet and the // contract's award(memberId) that the Level 4 override uses. The ranking is frozen on the first pay call; each place // is claimed once (marks.claim) and written to disk as "sending" BEFORE the send, so nothing is ever paid twice. 'use strict'; const fs = require('fs'); const path = require('path'); const TZ = 'America/Chicago'; const DEFAULT_LAUNCH = '2026-11-15T06:00:00-06:00'; const DEFAULT_END = '2026-11-22T00:00:00-06:00'; // exclusive: the window includes all of Saturday Nov 21, Central const WEI = 10n ** 18n; const GAS_LIMIT = 150000n; // same as the override's award() call const toWei = pol => { const [a, b = ''] = String(pol).trim().split('.'); return BigInt(a || '0') * WEI + BigInt((b + '0'.repeat(18)).slice(0, 18) || '0'); }; const polStr = wei => { const w = BigInt(wei); const s = (w * 10000n / WEI).toString().padStart(5, '0'); return (s.slice(0, -4) + '.' + s.slice(-4)).replace(/\.?0+$/, ''); }; const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); const fmtCT = (ts, withTime) => new Date(ts).toLocaleString('en-US', Object.assign({ timeZone: TZ, weekday: 'long', month: 'short', day: 'numeric' }, withTime ? { hour: 'numeric', minute: '2-digit' } : {})); function create() { let R = null; // { accounts, chain, marks, leaderboard, payer: () => signer|null, txLink, siteConfig, dataDir, adminEmail, now } const lastError = { at: 0, msg: '' }; const now = () => (R && R.now ? R.now() : Date.now()); function init(refs) { R = refs; } // ---- settings (all date-driven: launch morning needs no deploy) ---- function cfg() { const s = R.siteConfig() || {}; const t = (v, d) => { const x = Date.parse(String(v || '').trim() || d); return isFinite(x) ? x : Date.parse(d); }; const launchAt = t(s.launchAt, DEFAULT_LAUNCH); const start = String(s.launchContestStart || '').trim() ? t(s.launchContestStart, DEFAULT_LAUNCH) : launchAt; const end = t(s.launchContestEnd, DEFAULT_END); const prizes = String(s.launchContestPrizesPol == null || s.launchContestPrizesPol === '' ? '10,6,4' : s.launchContestPrizesPol).split(',').map(x => x.trim()).filter(x => /^\d+(\.\d{1,6})?$/.test(x) && Number(x) > 0); const minSales = Math.max(1, Math.floor(Number(s.launchContestMinSales == null || s.launchContestMinSales === '' ? 2 : s.launchContestMinSales) || 2)); const minCents = Math.max(0, Math.floor(Number(s.launchContestMinCents || 0) || 0)); const list = v => String(v || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); const exEmails = new Set(list(s.launchContestExcludeEmails)); if (R.adminEmail) exEmails.add(String(R.adminEmail).toLowerCase()); const exIds = new Set([...list(s.overrideHouseIds || '1'), ...list(s.launchContestExcludeIds)].map(Number).filter(Boolean)); return { launchAt, start, end, prizes, minSales, minCents, exEmails, exIds, founderGrant: String(s.founderGrant == null ? '1' : s.founderGrant) !== '0', contestOn: String(s.launchContest == null ? '1' : s.launchContest) !== '0' }; } // ---- FOUNDER ---- const earliestSignIn = a => Number(a.firstSeen) || Number(a.lastSeen) || 0; const qualifiesFounder = (a, launchAt) => { const t = earliestSignIn(a); return t > 0 && t < launchAt; }; async function founderPreview() { const c = cfg(); const all = await R.accounts.listAll(1e6); const q = all.filter(a => qualifiesFounder(a, c.launchAt)); const granted = all.filter(a => a.founder).length; return { launchAt: c.launchAt, launchAtCT: fmtCT(c.launchAt, true), launched: now() >= c.launchAt, field: 'firstSeen (earliest signed-in visit), else lastSeen', accounts: all.length, qualify: q.length, granted, missing: q.filter(a => !a.founder).length, autoGrant: c.founderGrant, neverSignedIn: all.filter(a => !earliestSignIn(a)).length }; } // grant the flag to every qualifying account that lacks it. Refuses before the launch moment. async function grantFounders(opts) { const o = opts || {}; const c = cfg(); if (now() < c.launchAt) return { error: 'The launch moment (' + fmtCT(c.launchAt, true) + ' Central) has not happened yet. Founder badges are granted from then on.' }; const slot = 'lw:founder:' + c.launchAt + ':' + Math.floor(now() / 600000) + (o.manual ? ':m' : ''); if (!await R.marks.claim(slot)) return { ok: true, skipped: 'another copy of the app is granting in this slot' }; const all = await R.accounts.listAll(1e6); let n = 0; for (const a of all) { if (a.founder || !qualifiesFounder(a, c.launchAt)) continue; try { const r = await R.accounts.setFounder(a.email, c.launchAt); if (r && r.ok && !r.already) n++; } catch (e) { lastError.at = now(); lastError.msg = 'founder ' + a.email + ': ' + e.message; } } if (n) { try { const f = path.join(R.dataDir, 'launchweek', 'founder-grants.json'); fs.mkdirSync(path.dirname(f), { recursive: true }); let log = []; try { log = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {} log.push({ at: now(), launchAt: c.launchAt, granted: n, manual: !!o.manual }); fs.writeFileSync(f, JSON.stringify(log.slice(-50))); } catch (e) {} console.log('founder badge: granted to ' + n + ' accounts'); } return { ok: true, granted: n }; } async function tick() { const c = cfg(); if (c.founderGrant && now() >= c.launchAt) { const all = await R.accounts.listAll(1e6); if (all.some(a => !a.founder && qualifiesFounder(a, c.launchAt))) await grantFounders(); } } // what the member's own badge strip shows: held, or (before launch) on the way function founderState(acct) { const c = cfg(); if (!acct) return { founder: false, pending: false }; if (acct.founder) return { founder: true, pending: false }; // the caller is the member's own signed-in dashboard request (touchSeen runs in it), so before launch they are on the way return { founder: false, pending: now() < c.launchAt, launchAt: c.launchAt }; } // ---- CONTEST: standings ---- async function standings(at) { const c = cfg(); const t = at || now(); const { map, names, founders, positionIds, mainId } = await R.leaderboard.memberMap(); const price = {}; const evs = R.chain.recentEvents(1e9); for (const e of evs) if (e.type === 'Purchase') price[e.tx + ':' + e.buyerId] = Number(e.priceCents || 0); const rows = {}; const until = Math.min(c.end, t); for (const e of evs) { if (e.type !== 'TierPaid' || e.tier !== 1 || e.ts < c.start || e.ts >= until) continue; const sponsor = map[e.recipientId], buyer = map[e.buyerId]; if (!sponsor) continue; if (buyer && buyer === sponsor) continue; // own positions never count if (positionIds.has(e.buyerId)) continue; // linked positions (Qualified Start) never count if (c.exEmails.has(sponsor) || c.exIds.has(e.recipientId) || c.exIds.has(mainId[sponsor])) continue; // admin, company, Marty's accounts: not contestants if ((buyer && c.exEmails.has(buyer)) || c.exIds.has(e.buyerId)) continue; // company placements / Marty's own buys const cents = price[e.tx + ':' + e.buyerId] || 0; if (cents < c.minCents) continue; const r = rows[sponsor] = rows[sponsor] || { email: sponsor, name: names[sponsor] || 'member', founder: founders.has(sponsor), sales: 0, cents: 0, lastTs: 0, ids: {} }; r.sales++; r.cents += cents; r.lastTs = Math.max(r.lastTs, e.ts); r.ids[e.recipientId] = (r.ids[e.recipientId] || 0) + 1; } const list = Object.values(rows).sort((a, b) => b.sales - a.sales || b.cents - a.cents || a.lastTs - b.lastTs || (a.email < b.email ? -1 : 1)); list.forEach((r, i) => { r.rank = i + 1; r.usd = r.cents / 100; r.qualifies = r.sales >= c.minSales; r.payId = mainId[r.email] || Number(Object.entries(r.ids).sort((x, y) => y[1] - x[1])[0][0]); }); const winners = []; let place = 0; for (const r of list) { if (!r.qualifies || place >= c.prizes.length) continue; winners.push({ place: place + 1, email: r.email, name: r.name, memberId: r.payId, sales: r.sales, usd: r.usd, pol: c.prizes[place] }); place++; } return { start: c.start, end: c.end, open: t < c.end, started: t >= c.start, minSales: c.minSales, prizes: c.prizes, rows: list, winners }; } // ---- CONTEST: payout store (one small file per place, single writer per claim) ---- const dir = (...p) => path.join(R.dataDir, 'launchweek', 'contest-' + cfg().start, ...p); const readJ = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { return null; } }; const writeJ = (f, o) => { fs.mkdirSync(path.dirname(f), { recursive: true }); const tmp = f + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(o)); fs.renameSync(tmp, f); }; const frozen = () => readJ(dir('frozen.json')); const getPlace = n => readJ(dir('place-' + n + '.json')); const putPlace = (n, patch) => { const o = Object.assign(getPlace(n) || { place: n }, patch, { updated: now() }); writeJ(dir('place-' + n + '.json'), o); return o; }; const places = () => { const f = frozen(); return f ? f.winners.map(w => Object.assign({}, w, getPlace(w.place) || { state: 'pending' })) : []; }; function txInfo(tx) { // an AwardPaid this contest made: for the email / feed label const h = String(tx || '').toLowerCase(); if (!h || !R) return null; try { for (const p of places()) if (p.txHash && String(p.txHash).toLowerCase() === h) return { place: p.place }; } catch (e) {} return null; } async function freeze() { const f = frozen(); if (f) return f; const c = cfg(); if (now() < c.end) return null; if (!await R.marks.claim('lw:freeze:' + c.start)) { for (let i = 0; i < 20 && !frozen(); i++) await new Promise(r => setTimeout(r, 250)); return frozen(); } const s = await standings(c.end); const o = { at: now(), start: c.start, end: c.end, minSales: c.minSales, prizes: c.prizes, winners: s.winners.map(w => Object.assign({}, w, { wei: toWei(w.pol).toString() })), top: s.rows.slice(0, 10).map(r => ({ rank: r.rank, name: r.name, founder: r.founder, sales: r.sales, usd: r.usd, qualifies: r.qualifies })) }; writeJ(dir('frozen.json'), o); return o; } // admin preview: live standings (or the frozen result), what would be paid, the payer and every payout record async function adminView() { const c = cfg(); const s = await standings(); const f = frozen(); const p = R.payer ? R.payer() : null; const payer = { keyPresent: !!p }; if (p) { payer.address = p.address; try { payer.balancePol = polStr(await p.balance()); } catch (e) { payer.balanceError = e.message; } } return { window: { start: c.start, end: c.end, startCT: fmtCT(c.start, true), endCT: fmtCT(c.end - 1, true), open: s.open, started: s.started }, minSales: c.minSales, minCents: c.minCents, prizes: c.prizes, excluded: { emails: [...c.exEmails], ids: [...c.exIds] }, standings: s.rows.slice(0, 25).map(r => ({ rank: r.rank, name: r.name, email: r.email, memberId: r.payId, sales: r.sales, usd: r.usd, qualifies: r.qualifies })), wouldPay: (f ? f.winners : s.winners).map(w => ({ place: w.place, name: w.name, email: w.email, memberId: w.memberId, sales: w.sales, pol: w.pol })), frozen: f ? { at: f.at } : null, payouts: places().map(x => ({ place: x.place, name: x.name, memberId: x.memberId, pol: x.pol, state: x.state, txHash: x.txHash || '', tx: x.txHash && R.txLink ? R.txLink(x.txHash) : '', note: x.note || '' })), payer, canPay: !s.open && !!p, founder: await founderPreview(), lastError: lastError.msg ? lastError : null }; } // the admin button. `expect` = [{ place, memberId, pol }] exactly as the admin saw it; any difference refuses. async function pay(expect) { const c = cfg(); if (now() < c.end) return { error: 'The contest window is still open until ' + fmtCT(c.end - 1, true) + ' Central.' }; const p = R.payer ? R.payer() : null; if (!p) return { error: 'No payer wallet: the Level 4 override payer key (OVERRIDE_PAYER_KEY) is not configured.' }; const f = await freeze(); if (!f) return { error: 'Could not freeze the results; try again.' }; const want = (Array.isArray(expect) ? expect : []).map(x => x.place + ':' + Number(x.memberId) + ':' + String(x.pol)).sort().join('|'); const have = f.winners.map(w => w.place + ':' + w.memberId + ':' + w.pol).sort().join('|'); if (want !== have) return { error: 'The confirmed list does not match the frozen result. Reload and confirm again.', frozen: f.winners }; const todo = f.winners.filter(w => { const s = (getPlace(w.place) || {}).state; return !s || s === 'pending'; }); if (!todo.length) return { ok: true, paidNow: 0, payouts: places() }; let fees, bal; try { fees = await p.fees(); bal = BigInt(await p.balance()); } catch (e) { return { error: 'Payer read failed: ' + e.message }; } const total = todo.reduce((n, w) => n + BigInt(w.wei), 0n), gas = BigInt(todo.length) * GAS_LIMIT * BigInt(fees.maxFeePerGas); if (bal < total + gas) return { error: 'Payer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL; the prizes need ' + polStr(total) + ' POL plus up to ' + polStr(gas) + ' POL gas. Nothing was sent.' }; let paidNow = 0; for (const w of todo) { const rec = getPlace(w.place) || {}; const attempt = rec.attempt || 0; if (!await R.marks.claim('lw:pay:' + c.start + ':' + w.place + ':' + attempt)) continue; // another copy (or an earlier click) owns it const cur = getPlace(w.place); if (cur && cur.state && cur.state !== 'pending') continue; putPlace(w.place, Object.assign({}, w, { state: 'checking', attempt })); try { await p.preflight(w.memberId, w.wei); } catch (e) { putPlace(w.place, { state: 'blocked', note: 'award() would revert (' + String(e.reason || e.shortMessage || e.message).slice(0, 100) + '); nothing sent' }); continue; } putPlace(w.place, { state: 'sending', sendingAt: now() }); // on disk BEFORE the send let tx; try { tx = await p.send(w.memberId, w.wei, fees); } catch (e) { putPlace(w.place, { state: 'review', note: 'send error, may or may not have gone out: ' + String(e.shortMessage || e.message).slice(0, 140) }); continue; } putPlace(w.place, { state: 'sent', txHash: tx.hash }); console.log('launch contest: place ' + w.place + ' #' + w.memberId + ' ' + w.pol + ' POL tx ' + tx.hash); try { const rc = await tx.wait(); if (rc && Number(rc.status) === 1) { putPlace(w.place, { state: 'paid', paidAt: now() }); paidNow++; } else putPlace(w.place, { state: 'failed', note: 'reverted on chain; needs review' }); } catch (e) { putPlace(w.place, { state: 'review', note: 'sent, receipt not confirmed: ' + String(e.message).slice(0, 120) }); } } return { ok: true, paidNow, payouts: places() }; } // admin decision on a stuck place: 'paid' with a tx that is an AwardPaid from the payer to that member for that amount, // or 'retry' after checking the payer wallet on the explorer shows nothing went out (blocked / failed / review only) async function resolve(place, action, tx) { const r = getPlace(Number(place)); if (!r) return { error: 'no such place' }; if (action === 'paid') { const p = R.payer ? R.payer() : null; const hit = p && R.chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && String(e.tx).toLowerCase() === String(tx || '').toLowerCase()); if (!hit || hit.toId !== r.memberId || String(hit.amountWei) !== String(r.wei) || String(hit.from).toLowerCase() !== String(p.address).toLowerCase()) return { error: 'that tx is not an AwardPaid from the payer wallet to #' + r.memberId + ' for ' + r.pol + ' POL in the chain index' }; putPlace(r.place, { state: 'paid', txHash: hit.tx, note: 'admin: confirmed tx' }); return { ok: true }; } if (action === 'retry') { const staleSend = r.state === 'sending' && now() - (r.sendingAt || 0) > 15 * 60000; // the app stopped mid-send: you checked the explorer if (!['blocked', 'failed', 'review', 'checking'].includes(r.state) && !staleSend) return { error: 'place is ' + r.state + '; only blocked, failed, review, checking or a send stuck for 15 minutes can be retried' }; putPlace(r.place, { state: 'pending', attempt: (r.attempt || 0) + 1, note: 'admin: nothing went out, released for one more try (was ' + r.state + ')' }); return { ok: true }; } return { error: 'action must be paid or retry' }; } // ---- public: the /leaderboard panel (from the launch moment through the payout) ---- async function panelState() { const c = cfg(); const t = now(); if (!c.contestOn || t < c.start) return null; const f = frozen(); const ps = places(); const done = f && (f.winners.length === 0 || ps.every(x => x.state === 'paid')); if (done || t > c.end + 21 * 86400000) return null; // after the payout (or three weeks after the close): gone const s = f ? null : await standings(); return { c, s, f, ps }; } async function panelHtml() { const st = await panelState(); if (!st) return ''; const { c, s, f } = st; const ord = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th']; const prizeLine = c.prizes.map((pol, i) => ord[i] + ' place ' + pol + ' POL').join(' ยท '); const rows = f ? f.top : s.rows.slice(0, 10).map(r => ({ rank: r.rank, name: r.name, founder: r.founder, sales: r.sales, usd: r.usd, qualifies: r.qualifies })); const open = !f && s.open; let h = '

Launch week contest

' + '

' + (open ? 'Who is bringing in the most buyers' : 'Final standings') + '

' + '

' + esc(fmtCT(c.start, true)) + ' to ' + esc(fmtCT(c.end - 1, true)) + ', Central time. Ranked by packages bought by the people you sponsor directly. ' + 'You need at least ' + c.minSales + ' to place. Your own positions, linked positions and the company account do not count.

' + '
Prizes: ' + esc(prizeLine) + '. Prizes are paid in POL to the wallet on file after the week closes and the results are checked.
' + '' + (rows.length ? rows.map(r => '').join('') : '') + '
#MemberPackagesSales
' + r.rank + '' + esc(r.name) + '' + (r.founder ? ' Founder' : '') + (r.qualifies ? '' : ' (needs ' + c.minSales + ' to place)') + '' + r.sales + '$' + Number(r.usd).toLocaleString() + '
No packages sold yet in the contest window. The first sales take the top spots.
' + '

' + (open ? 'Standings update live from the chain.' : 'The window is closed. Winners are paid after the results are checked.') + ' No income is guaranteed.

'; return h; } // public JSON for /launch and the dashboard async function publicView() { const c = cfg(); const st = await panelState(); return { launchAt: c.launchAt, launched: now() >= c.launchAt, contest: { start: c.start, end: c.end, minSales: c.minSales, live: !!st, places: c.prizes.length, prizes: now() >= c.start ? c.prizes : null } }; } return { init, cfg, founderPreview, grantFounders, tick, founderState, qualifiesFounder, standings, freeze, adminView, pay, resolve, panelHtml, publicView, txInfo }; } const main = create(); module.exports = Object.assign(main, { create, DEFAULT_LAUNCH, DEFAULT_END, toWei, polStr });