diff --git a/accounts.js b/accounts.js
index feee990..418670a 100644
--- a/accounts.js
+++ b/accounts.js
@@ -38,6 +38,8 @@ const pub = a => a ? { email: a.email, sponsorRef: a.sponsorRef || '', code: a.c
avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials: a.socials || null,
profileQuarantined: !!a.profileQuarantined, // 2026-10-30: first profile save of a brand-new free account planted a link; stored, never rendered publicly (spamscan.js)
chatAvailable: a.chatAvailable === false ? false : true, lastSeen: a.lastSeen || 0,
+ firstSeen: a.firstSeen || 0, // 2026-11-05: earliest known signed-in visit (backfilled from lastSeen on the next visit); the Founder badge reads it
+ founder: a.founder || 0, // 2026-11-05: Founder badge granted (ms of the launch moment it was granted for); cosmetic only (launchweek.js)
theme: a.theme || null, // 2026-11-01 appearance: auto | light | dark, follows the member across browsers (cr-shell.js)
address: a.address || null, created: a.created } : null;
const USER_RE = /^[a-zA-Z0-9_]{3,20}$/;
@@ -129,7 +131,8 @@ const J = {
this.save();
return { ok: true, account: pub(acct) };
},
- async touchSeen(e) { const a = this.db.byEmail[e]; if (a) { a.lastSeen = Date.now(); this.save(); } },
+ async touchSeen(e) { const a = this.db.byEmail[e]; if (a) { const now = Date.now(); if (!a.firstSeen) a.firstSeen = a.lastSeen || now; a.lastSeen = now; this.save(); } }, // firstSeen keeps the earliest signed-in visit we know of
+ async setFounder(e, ts) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; if (a.founder) return { ok: true, already: true }; a.founder = Number(ts) || Date.now(); this.save(); return { ok: true }; },
async setTheme(e, t) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.theme = THEMES.has(t) ? t : null; this.save(); return { ok: true, account: pub(a) }; },
async setChatAvailable(e, v) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.chatAvailable = !!v; this.save(); return { ok: true, available: !!v }; },
async getMutes(e) { const a = this.db.byEmail[e]; return (a && Array.isArray(a.chatMutes)) ? a.chatMutes : []; },
@@ -235,7 +238,7 @@ const rowPub = r => r ? pub({ email: r.email, sponsorRef: r.sponsor_ref, code: r
username: r.username, memberId: r.member_id || 0, joinedVia: r.joined_via || null, joinedRef: r.joined_ref || null,
lineBannerUrl: r.line_banner_url, lineTargetUrl: r.line_target_url, wallOffers: r.wall_offers || null,
avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials, profileQuarantined: !!r.profile_quarantined,
- chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), theme: r.theme || null,
+ chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), theme: r.theme || null, firstSeen: Number(r.first_seen || 0), founder: Number(r.founder || 0),
address: r.address, created: Number(r.created) }) : null;
const D = {
async signup(e, password, ref) {
@@ -296,7 +299,8 @@ const D = {
if (quarantined !== undefined) await db.q('UPDATE accounts SET profile_quarantined=? WHERE email=?', [quarantined ? 1 : 0, e]);
return { ok: true, account: await this.byEmail(e) };
},
- async touchSeen(e) { await db.q('UPDATE accounts SET last_seen=? WHERE email=?', [Date.now(), e]); },
+ async touchSeen(e) { const now = Date.now(); await db.q('UPDATE accounts SET first_seen=COALESCE(first_seen, last_seen, ?), last_seen=? WHERE email=?', [now, now, e]); }, // SET runs left to right: first_seen takes the OLD last_seen
+ async setFounder(e, ts) { const r = await db.q('UPDATE accounts SET founder=? WHERE email=? AND (founder IS NULL OR founder=0)', [Number(ts) || Date.now(), e]); return { ok: true, already: !(r && r.affectedRows) }; },
async setTheme(e, t) { await db.q('UPDATE accounts SET theme=? WHERE email=?', [THEMES.has(t) ? t : null, e]); return { ok: true, account: await this.byEmail(e) }; },
async setChatAvailable(e, v) { await db.q('UPDATE accounts SET chat_available=? WHERE email=?', [v ? 1 : 0, e]); return { ok: true, available: !!v }; },
async getMutes(e) {
@@ -497,6 +501,7 @@ module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, by
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
setProfile: (e, a, bio, socials, quarantined) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials, quarantined).then(tap(String(e || '').toLowerCase())),
touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()),
+ setFounder: (e, ts) => impl().setFounder(String(e || '').toLowerCase(), ts), // cosmetic Founder flag (launchweek.js); no onChange tap
setTheme: (e, t) => impl().setTheme(String(e || '').toLowerCase(), t), // appearance only: no onChange tap, InstantAdPay does not mirror it
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null).then(tap(String(e || '').toLowerCase())),
positionByAddress: a => impl().positionByAddress(normAddr(a)),
diff --git a/chatbot.js b/chatbot.js
index ba1e4fa..a83cecd 100644
--- a/chatbot.js
+++ b/chatbot.js
@@ -154,6 +154,12 @@ const CANNED = [
{ id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?'], tags: ['balance', 'credits', 'campaigns'],
re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i,
a: 'One rule: your available balance is what is not committed to a live campaign. When you start a campaign its whole budget is set aside right then, so Available drops once and then sits still while the ad runs; the budget spends down inside that campaign on the Ads screen, where you can see delivered views and what is left. A paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live.' },
+ { id: 'founder-badge', title: 'The Founder badge', q: ['What is the Founder badge?', 'How do I get the Founder badge?', 'Why do I not have the Founder badge?'], tags: ['founder', 'badge', 'launch', 'founding member'],
+ re: /(founder'?s? badge|founding member|founder (status|rank)|(get|got|earn|have|see|missing|where is) (the |my )?founder|founder.*(badge|launch))/i,
+ a: 'The Founder badge is a thank-you for members who were here before LinkSpin opened to the public. Every account that signs in at least once before Sunday, November 15, 2026 at 6 AM Central gets it automatically on launch morning. Accounts that were carried over from InstantAdPay but never signed in here do not get it. It shows with your badges on the dashboard, on your wall, next to your name on your sponsor\'s Team list and on the leaderboard. It is a badge only: no credits, no POL and no extra features come with it, and it is not posted to Telegram. Signed in before launch and do not see it on launch day? Open Help (' + SITE_URL + '/help) and Marty will check.' },
+ { id: 'launch-contest', title: 'The launch week contest', q: ['What is the launch week contest?', 'How do I win the launch contest?', 'When are launch contest prizes paid?'], tags: ['launch week', 'contest', 'leaderboard', 'prizes', 'POL'],
+ re: /(launch[ -]?week (contest|competition|prizes?|leaderboard|race)|launch (contest|competition|prizes?)|contest prizes?|(win|winning|enter|join) the (launch )?contest)/i,
+ a: 'The launch week contest runs from Sunday, November 15 at 6 AM Central to Saturday, November 21 at 11:59 PM Central, with standings on the leaderboard (' + SITE_URL + '/leaderboard). It ranks members by the number of packages bought in that window by the people they sponsor directly, the same count the weekly leaderboard uses. Your own positions, linked positions (Qualified Start) and purchases by the company account do not count, and the company and admin accounts are not contestants. You need at least 2 counted sales to place; a tie goes to more dollars in sales, then to whoever got there first. The top 3 places win POL, and the amounts are shown on the leaderboard from launch morning. Prizes are paid in POL to the wallet on file after the week closes and Marty has checked the results; nothing is paid automatically. No income is guaranteed.' },
{ id: 'safe', title: 'Is it safe? Who holds the money?', q: ['Is this safe?', 'Can you run away with the money?', 'Who holds the funds?'], tags: ['safe', 'contract', 'custody', 'trust'],
re: /(safe|trust (you|this|the site)|rug|run away|disappear|hold(s|ing)? (my|the) (money|funds))/i,
a: 'The money never touches us. A verified, immutable contract on Polygon splits every purchase in the same transaction, holds no balance, and has no pause switch or upgrade path. Credits live on the platform and are advertising, not money. Read the plain-language review and the verified source at ' + SITE_URL + '/contract, and watch every payout land at ' + SITE_URL + '/ledger.' }
@@ -199,7 +205,9 @@ ${refuelFact()}${synFact()}- PRODUCT, all free with an email account: SPIN LINKS
- HOLDING TANK ACTIVATION HOLD (2026-10-27): a member with no sponsor is first matched to their network sponsor (the same email or wallet with a sponsor on InstantAdPay). Nobody known: the free Switch on payouts waits for an adopter and the Credits screen says "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)." with the time left; they show at the top of every holding tank with a green Ready to activate badge and the hours left, and the shared payments topic on Telegram is told. Nobody adopts in 24 hours: the site assigns them to the next eligible adopter in rotation (own $25+ package, fewer than 2 open adoptions, signed in within 7 days; least recently auto-assigned first), and the pickup is posted marked (auto-assigned). The moment they have a sponsor (adopted, assigned or matched), the site switches their payouts on under that sponsor (engine-paid) and sends them the transaction link. A PURCHASE IS NEVER HELD: a tank member can buy at any time; with no sponsor yet that purchase places them under the platform position for good. Someone who arrived through a sponsor link is never held.
${launchFact()}
- SUPPORT (LIVE 2026-10-16): members open Help in the Control Room (${SITE_URL}/help) to send Marty a ticket (pick a category, a subject, the message), see each ticket's status (Open, Waiting on you, Closed), and read and answer his replies; a badge on the Help item shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at ${SITE_URL}/support, gets a private link to follow the ticket without signing in, and can reply there. The chat can also pass a conversation to support ("Send this to support"). Marty answers every ticket himself; there is no support email address, point people to ${SITE_URL}/support instead. Tickets share one desk with the rest of the Crypto Team Build Network.
-- Leaderboard at ${SITE_URL}/leaderboard ranks members by packages sold to direct referrals (weekly, monthly, all time; prizes are credits, never cash). Release notes and roadmap at ${SITE_URL}/whats-new.
+- Leaderboard at ${SITE_URL}/leaderboard ranks members by packages sold to direct referrals (weekly, monthly, all time; weekly and monthly prizes are ad credits, never cash).
+- FOUNDER BADGE (2026-11-05): cosmetic only (no credits, no POL, no perks, never posted to Telegram). Granted automatically from the launch moment (Sun 2026-11-15 6:00 AM Central) to every account whose earliest signed-in visit is before that moment; carried-over accounts that never signed in do not get it. Shown in the member's badge strip, on their wall, on their sponsor's Team list and on the leaderboard.
+- LAUNCH WEEK CONTEST (2026-11-05): Sun 2026-11-15 6:00 AM to Sat 2026-11-21 11:59 PM Central, a panel on ${SITE_URL}/leaderboard from launch morning until the prizes are paid. Ranked by packages bought in the window by the member's direct referrals (tier-1 sales, the weekly board's count). Never counted: own positions, linked positions (Qualified Start), purchases by the company/admin account; the company and admin accounts are not contestants. Minimum 2 counted sales to place; ties: more dollars, then who got there first. Top 3 win POL (amounts shown on the leaderboard from launch morning; do not quote amounts), paid to the wallet on file through the contract's award() after the week closes, only after Marty approves the results. Never promise a win or income. Release notes and roadmap at ${SITE_URL}/whats-new.
- InstantAdPay is the sister property in the same network, not this site: it is the ad marketplace (buy ad packages, earn credits by viewing ads, get paid when your line buys); LinkSpin is the tool side (rotator, page builder, zones), free with an email, whose packages buy ad delivery across the LinkSpin viewer, member zones and the partner network and pay the same sponsor line in the purchase transaction. Username, sponsor and profile (avatar, bio, social links) carry over when the member signs in with the same email, and can be changed here any time. Do not describe InstantAdPay mechanics (holding-tank rescue emails, Five Dollar Friday, Wired Wednesday, games, mint passes, surf earn tab) as LinkSpin features.
RULES:
diff --git a/db.js b/db.js
index 7bd37e2..5793e0f 100644
--- a/db.js
+++ b/db.js
@@ -253,6 +253,8 @@ async function bootstrap() {
// per-account chat settings: availability toggle (default on) + muted-member list (JSON emails)
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_available TINYINT NOT NULL DEFAULT 1');
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_mutes VARCHAR(4000) NULL');
+ await alterSafe('ALTER TABLE accounts ADD COLUMN first_seen BIGINT NULL'); // earliest signed-in visit (Founder badge, 2026-11-05)
+ await alterSafe('ALTER TABLE accounts ADD COLUMN founder BIGINT NULL'); // Founder badge granted at (ms)
await q(`CREATE TABLE IF NOT EXISTS video_seen (
email VARCHAR(190) NOT NULL,
campaign_id INT NOT NULL,
diff --git a/launchweek.js b/launchweek.js
new file mode 100644
index 0000000..af70136
--- /dev/null
+++ b/launchweek.js
@@ -0,0 +1,264 @@
+// 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 ' + 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. ' + (open ? 'Standings update live from the chain.' : 'The window is closed. Winners are paid after the results are checked.') + ' No income is guaranteed.' + (open ? 'Who is bringing in the most buyers' : 'Final standings') + '
'
+ + '
'
+ + ' '
+ + (rows.length ? rows.map(r => '# Member Packages Sales ').join('')
+ : '' + 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.
| # | Member | Packages | Sales | Buyers | New members |
|---|---|---|---|---|---|
| ' + r.rank + ' | ' + esc(r.name) + ' | ' + r.sales + ' | $' + r.usd.toLocaleString() + ' | ' + r.buyers + ' | ' + r.joins + ' |
| No sales yet in this period. | |||||
Referral contest
Ranked by ad packages sold to other people (your own positions never count, and the company account is not a contestant). Read from the chain, updated live. Weeks run Monday to Sunday, Central time.
Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.
'; + h += 'Sales are $ of packages bought by members you directly sponsor. Weekly and monthly prizes are advertising credits or packages, never cash. No income is guaranteed.
'; h += '
…
+ + + ++