Launch week: Founder badge + launch week contest (Marty approved 2026-11-05, PLAN.md options B and C)

Founder badge (cosmetic only: no credits, no POL, no perks, never posted to Telegram)
- Criterion: the account's earliest signed-in visit is before the launch moment (launchAt, default
  2026-11-15T06:00:00-06:00). Field: accounts.firstSeen, else lastSeen. Both are written only by
  accounts.touchSeen() on signed-in requests (dashboard, ping, chat); touchSeen now keeps firstSeen =
  the previous lastSeen on the next visit, so a pre-launch member who signs in again after launch still
  qualifies. Carried-over shells that never signed in have neither field and never qualify.
- Stored flag accounts.founder (JSON + MySQL column). Grant: launchweek.tick every 10 minutes from the
  launch moment, idempotent, one run per 10-minute slot across app copies (marks.claim); founderGrant '0'
  turns it off. Admin preview + "Grant Founder badges now" (refused before launch).
- Shown in the badge strip (on the way before launch, Share works, no Telegram post), wall (wall-founder.js),
  Team rows (my.js + team.js), the Team activity chip, and next to names on /leaderboard. Art:
  /badges/badge-founder.jpg, drawn in code in the existing card layout.

Launch week contest
- Window [launchContestStart or launchAt, launchContestEnd) = Sun Nov 15 6:00 AM to the end of Sat Nov 21,
  Central (end stored exclusive, 2026-11-22T00:00:00-06:00). Count = the weekly board's tier-1 TierPaid
  sales. Never counted: own positions, buys by linked positions (Qualified Start), the admin account and
  overrideHouseIds (as contestants or buyers), launchContestExcludeEmails/Ids. launchContestMinSales 2.
  Ties: sales, dollars, who got there first. Prizes launchContestPrizesPol '10,6,4'.
- Payout only by Admin > Launch week > Pay launch contest: the ranking is frozen on the first press, the
  admin's confirmed list must match it, balance + gas checked first, each place claimed once (marks.claim)
  and written as sending before award(memberId) from the Level 4 override payer wallet
  (override.payerHandle). Records tx hashes; resolve paid-with-tx or retry for blocked/failed/review.
  The prize email + feed line say "Launch week contest prize".
- /leaderboard panel from the launch moment until the prizes are paid; /launch copy states both rules.
- chatbot: CANNED founder-badge + launch-contest, FACTS lines (no amounts quoted before launch).
- qa/launchweek.test.cjs (16 checks: Central window bounds, exclusions, minimum, two-copy payout once,
  frozen result, Founder criterion + grant, touchSeen backfill); run.sh launchweek and in all.
- Versions: my.js?v=20261105fd, team.js?v=20261105fd, wall-founder.js?v=20261105fd,
  admin-launchweek.js?v=20261105lw (wall.js unchanged: the shared policy test pins it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-05 08:14:28 -06:00
parent 4b8b31abe7
commit f41d1ef384
19 changed files with 666 additions and 36 deletions
+8 -3
View File
@@ -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)),
+9 -1
View File
@@ -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:
+2
View File
@@ -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,
+264
View File
@@ -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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[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 = '<section class="lwc" id="launch-contest"><p class="eyebrow" style="margin:0 0 4px">Launch week contest</p>'
+ '<h2>' + (open ? 'Who is bringing in the most buyers' : 'Final standings') + '</h2>'
+ '<p class="muted small" style="margin:0 0 10px">' + 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.</p>'
+ '<div class="prize"><b>Prizes:</b> ' + esc(prizeLine) + '. Prizes are paid in POL to the wallet on file after the week closes and the results are checked.</div>'
+ '<table class="lb"><tr><th>#</th><th>Member</th><th>Packages</th><th>Sales</th></tr>'
+ (rows.length ? rows.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b>' + (r.founder ? ' <span class="fdr" title="Founder badge">Founder</span>' : '') + (r.qualifies ? '' : ' <span class="muted small">(needs ' + c.minSales + ' to place)</span>') + '</td><td>' + r.sales + '</td><td>$' + Number(r.usd).toLocaleString() + '</td></tr>').join('')
: '<tr><td colspan="4" class="muted">No packages sold yet in the contest window. The first sales take the top spots.</td></tr>') + '</table>'
+ '<p class="muted small" style="margin:0">' + (open ? 'Standings update live from the chain.' : 'The window is closed. Winners are paid after the results are checked.') + ' No income is guaranteed.</p></section>';
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 });
+17 -12
View File
@@ -38,14 +38,15 @@ function periodBounds(period, ts) {
let idMap = { at: 0, map: {}, names: {} };
async function memberMap() {
if (Date.now() - idMap.at < 60000) return idMap;
const map = {}, names = {};
const list = await R.accounts.listAll(5000);
const map = {}, names = {}, founders = new Set(), positionIds = new Set(), mainId = {};
const list = await R.accounts.listAll(50000);
for (const a of list) {
if (a.memberId) { map[a.memberId] = a.email; names[a.email] = a.username ? '@' + a.username : 'member #' + a.memberId; }
if (a.memberId) { map[a.memberId] = a.email; mainId[a.email] = a.memberId; names[a.email] = a.username ? '@' + a.username : 'member #' + a.memberId; }
else names[a.email] = a.username ? '@' + a.username : a.email.replace(/@.*/, '') + '@';
try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) map[p.memberId] = a.email; } catch (e) {}
if (a.founder) founders.add(a.email); // Founder badge (2026-11-05): shown next to the name on the board
try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) { map[p.memberId] = a.email; positionIds.add(p.memberId); } } catch (e) {} // linked positions (Qualified Start)
}
idMap = { at: Date.now(), map, names }; return idMap;
idMap = { at: Date.now(), map, names, founders, positionIds, mainId }; return idMap;
}
const computeCache = {};
@@ -55,7 +56,7 @@ async function compute(period) {
}
async function computeRaw(period) {
const { start, end, label } = periodBounds(period);
const { map, names } = await memberMap();
const { map, names, founders } = await memberMap();
const price = {}; // tx -> cents
for (const e of R.chain.recentEvents(1e9)) if (e.type === 'Purchase') price[e.tx + ':' + e.buyerId] = Number(e.priceCents || 0);
const rows = {};
@@ -77,7 +78,7 @@ async function computeRaw(period) {
for (const [em, n] of Object.entries(joins)) { const r = rows[em] = rows[em] || { email: em, name: names[em] || em, sales: 0, cents: 0, pol: 0n, buyers: new Set() }; r.joins = n; }
// the admin's own account (company placements, tank arrivals) is not a contestant
if (R.adminEmail && rows[R.adminEmail]) delete rows[R.adminEmail];
const out = Object.values(rows).map(r => ({ email: r.email, name: r.name, sales: r.sales, usd: r.cents / 100, pol: Number(r.pol / 10n ** 14n) / 10000, buyers: r.buyers.size, joins: r.joins || 0 }))
const out = Object.values(rows).map(r => ({ email: r.email, name: r.name, founder: founders.has(r.email), sales: r.sales, usd: r.cents / 100, pol: Number(r.pol / 10n ** 14n) / 10000, buyers: r.buyers.size, joins: r.joins || 0 }))
.sort((a, b) => b.usd - a.usd || b.sales - a.sales || b.joins - a.joins);
out.forEach((r, i) => { r.rank = i + 1; });
return { period, label, start, end, rows: out };
@@ -91,7 +92,7 @@ async function view(period, meEmail) {
return { period: r.period, label: r.label, start: r.start, end: r.end, prize: prize || '', top: r.rows.slice(0, 10).map(pub), me: me ? pub(me) : null, count: r.rows.length,
winners: winners().slice(0, 6) };
}
const pub = r => ({ rank: r.rank, name: r.name, sales: r.sales, usd: r.usd, buyers: r.buyers, joins: r.joins });
const pub = r => ({ rank: r.rank, name: r.name, founder: !!r.founder, sales: r.sales, usd: r.usd, buyers: r.buyers, joins: r.joins });
// "1000,500,250" -> [1000, 500, 250]: credits for 1st, 2nd, 3rd... (Marty: award the top X positions, 2026-09-14)
const ladder = v => String(v || '').split(',').map(x => Math.round(Number(x)) || 0).filter(n => n > 0);
const ORD = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th'];
@@ -125,24 +126,28 @@ async function rolloverTick() {
}
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
// the Founder badge next to a name (cosmetic, 2026-11-05)
const fdr = r => r && r.founder ? ' <span class="fdr" title="Founder badge: signed in before LinkSpin launched">Founder</span>' : '';
async function renderPage() {
const week = await view('week'), month = await view('month'), all = await view('all');
const sc = R.siteConfig();
const table = v => '<table class="lb"><tr><th>#</th><th>Member</th><th>Packages</th><th>Sales</th><th>Buyers</th><th>New members</th></tr>'
+ (v.top.length ? v.top.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b></td><td>' + r.sales + '</td><td>$' + r.usd.toLocaleString() + '</td><td>' + r.buyers + '</td><td>' + r.joins + '</td></tr>').join('') : '<tr><td colspan="6" class="muted">No sales yet in this period.</td></tr>') + '</table>';
+ (v.top.length ? v.top.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b>' + fdr(r) + '</td><td>' + r.sales + '</td><td>$' + r.usd.toLocaleString() + '</td><td>' + r.buyers + '</td><td>' + r.joins + '</td></tr>').join('') : '<tr><td colspan="6" class="muted">No sales yet in this period.</td></tr>') + '</table>';
const fmtD = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' });
const desc = 'Who is selling the most ad packages on LinkSpin this week and this month. Weekly and monthly referral contest standings, read from the chain.';
let h = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leaderboard | LinkSpin</title><meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="' + SITE_URL + '/leaderboard"><meta property="og:title" content="LinkSpin leaderboard"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="' + SITE_URL + '/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=ls20261101t">'
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:#ffd15c;font-weight:800}.prize{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}</style></head><body><div class="wrap lbw">'
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:#ffd15c;font-weight:800}.prize{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}.fdr{display:inline-block;margin-left:6px;padding:1px 7px;border-radius:999px;font-size:11px;font-weight:700;letter-spacing:.04em;color:#7a5600;background:#ffc94d;vertical-align:1px}.lwc{border:1px solid #ffc94d;border-radius:14px;padding:16px 18px;margin:0 0 28px;background:rgba(255,201,77,.07)}.lwc h2{margin:0 0 4px;font-size:24px}.lwc .lb{margin-bottom:8px}</style></head><body><div class="wrap lbw">'
+ '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">Referral contest</p><h1>Leaderboard: <em>who is selling</em>.</h1><p class="lead">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.</p></section>';
if (R.launchPanel) { try { h += await R.launchPanel(); } catch (e) { console.error('launch panel', e.message); } } // launch week contest (launchweek.js), date-driven
h += '<h2 style="font-size:24px;margin:0 0 4px">' + week.label + ' <span class="muted small">' + fmtD(week.start) + ' to Sunday</span></h2>' + (week.prize ? '<div class="prize"><b>Weekly prizes:</b> ' + esc(week.prize) + '</div>' : '') + table(week);
h += '<h2 style="font-size:24px;margin:0 0 4px">' + month.label + '</h2>' + (month.prize ? '<div class="prize"><b>Monthly prizes:</b> ' + esc(month.prize) + '</div>' : '') + table(month);
h += '<h2 style="font-size:24px;margin:0 0 4px">All time</h2>' + table(all);
const w = winners();
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
h += '<p class="muted small" style="margin-top:30px">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.</p>';
h += '</div><script src="/assets/common.js?v=20261101t"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
return h;
}
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
function setLaunchPanel(fn) { if (R) R.launchPanel = fn; }
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds, memberMap, setLaunchPanel, ctParts };
+5 -1
View File
@@ -344,7 +344,11 @@ function create() {
+ (top || 'Nobody qualified this week.') + '\nNo money moved' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
}
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg };
// the same payer wallet + award(memberId) path for other admin-approved POL awards (launch contest, 2026-11-05):
// null when no key is configured. Independent of overrideMode: the caller is an admin button, not the weekly scheduler.
const payerHandle = () => (payerOverride || keyHex()) ? payer() : null;
const polygonTx = h => txLink(h);
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg, payerHandle, polygonTx };
}
const main = create();
+9 -1
View File
@@ -485,6 +485,14 @@
<p><select id="ovWeek"></select> <button class="btn small sec" type="button" id="ovShow">Show week</button> <button class="btn small" type="button" id="ovPay" hidden>Pay this week now</button></p>
<div id="ovOut" class="small"></div>
</div>
<div class="card" id="lwCard">
<div class="card-head"><h3>Launch week</h3><span class="sub">Founder badge (cosmetic) and the launch week contest (POL prizes, paid only from this button)</span></div>
<p class="small" id="lwFounder">…</p>
<p class="small" id="lwWindow"></p>
<div id="lwStand" class="small"></div>
<div id="lwPayouts" class="small"></div>
<p><button class="btn small sec" type="button" id="lwRefresh">Refresh</button> <button class="btn small sec" type="button" id="lwGrant" hidden>Grant Founder badges now</button> <button class="btn small" type="button" id="lwPay" hidden>Pay launch contest</button></p>
</div>
</div>
<div class="pane" id="pane-settings" hidden>
<div class="card" id="kitCard">
@@ -542,6 +550,6 @@
<script src="/assets/common.js?v=20261105po"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261101t"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script>
<script src="/assets/admin.js?v=20261101t"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script><script src="/assets/admin-launchweek.js?v=20261105lw"></script>
</body>
</html>
+44
View File
@@ -0,0 +1,44 @@
// Admin > Launch week (2026-11-05): Founder badge preview + grant, launch contest standings and the "Pay launch contest" button.
// The pay button sends real POL from the Level 4 override payer wallet. It shows the frozen ranking and amounts first and
// sends exactly that list; the server refuses if anything changed, and every place is paid at most once.
(function () {
const $ = IAP.$;
if (!$('lwCard')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function api(path, body) {
const r = await (await fetch(path, body === undefined ? { cache: 'no-store' } : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
return r;
}
let last = null;
async function load() {
let r; try { r = await api('/api/admin/launch-week'); } catch (e) { $('lwFounder').textContent = 'Could not read launch week: ' + e.message; return; }
last = r;
const f = r.founder || {};
$('lwFounder').innerHTML = '<b>Founder badge</b> (cosmetic): accounts whose earliest signed-in visit (' + esc(f.field) + ') is before ' + esc(f.launchAtCT) + ' Central. '
+ '<b>' + (f.qualify || 0) + '</b> qualify today of ' + (f.accounts || 0) + ' accounts (' + (f.neverSignedIn || 0) + ' never signed in). Granted: ' + (f.granted || 0) + ', still to grant: ' + (f.missing || 0) + '. '
+ (f.launched ? 'Launch has passed; the automatic grant runs every 10 minutes' : 'The automatic grant starts at the launch moment') + (f.autoGrant ? '.' : ' (switched OFF: founderGrant = 0).');
$('lwGrant').hidden = !f.launched;
const w = r.window || {};
$('lwWindow').innerHTML = '<b>Launch week contest</b>: ' + esc(w.startCT) + ' to ' + esc(w.endCT) + ' Central · ' + (w.open ? (w.started ? 'OPEN' : 'not started') : 'CLOSED')
+ ' · minimum ' + r.minSales + ' sales to place · prizes ' + (r.prizes || []).map((p, i) => (i + 1) + ': ' + p + ' POL').join(', ')
+ ' · excluded: ' + esc((r.excluded.emails || []).join(', ')) + ' and member #' + esc((r.excluded.ids || []).join(', #'))
+ ' · payer ' + (r.payer.keyPresent ? esc(r.payer.address) + ' holds ' + esc(r.payer.balancePol || '?') + ' POL' : 'NOT configured');
$('lwStand').innerHTML = (r.standings || []).length ? '<table><tr><th>#</th><th>Member</th><th>Pays to</th><th>Sales</th><th>$</th><th>Places?</th></tr>' + r.standings.map(x => '<tr><td>' + x.rank + '</td><td>' + esc(x.name) + ' <span class="muted">' + esc(x.email) + '</span></td><td>#' + x.memberId + '</td><td>' + x.sales + '</td><td>$' + x.usd + '</td><td>' + (x.qualifies ? 'yes' : 'no') + '</td></tr>').join('') + '</table>' : '<p class="muted">No counted sales in the window yet.</p>';
$('lwPayouts').innerHTML = (r.payouts || []).length ? '<p><b>Payout records</b> (frozen ' + new Date(r.frozen.at).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT)</p><table><tr><th>Place</th><th>Member</th><th>POL</th><th>State</th><th>Tx</th></tr>' + r.payouts.map(x => '<tr><td>' + x.place + '</td><td>' + esc(x.name) + ' #' + x.memberId + '</td><td>' + esc(x.pol) + '</td><td>' + esc(x.state) + (x.note ? ' <span class="muted">' + esc(x.note) + '</span>' : '') + '</td><td>' + (x.tx ? '<a href="' + esc(x.tx) + '" target="_blank" rel="noopener">tx</a>' : '') + '</td></tr>').join('') + '</table>' : '';
$('lwPay').hidden = !r.canPay || !(r.wouldPay || []).length || (r.payouts || []).length && r.payouts.every(x => x.state === 'paid');
}
$('lwRefresh').addEventListener('click', load);
$('lwGrant').addEventListener('click', async () => {
try { const r = await api('/api/admin/launch-week/founders', {}); IAP.status('Founder badge: granted to ' + (r.granted || 0) + ' accounts' + (r.skipped ? ' (' + r.skipped + ')' : '') + '.', 'ok'); load(); } catch (e) { IAP.status(e.message, 'bad'); }
});
$('lwPay').addEventListener('click', async () => {
await load(); if (!last) return;
const list = last.wouldPay || []; if (!list.length) { IAP.status('Nobody placed: nothing to pay.', 'bad'); return; }
const total = list.reduce((n, x) => n + Number(x.pol), 0);
const text = list.map(x => 'Place ' + x.place + ': ' + x.name + ' (member #' + x.memberId + ', ' + x.sales + ' sales) gets ' + x.pol + ' POL').join('\n') + '\n\nTotal ' + total + ' POL plus gas, sent from the payer wallet with award(memberId). Each place is paid once.';
if (!await IAP.confirmBox(text, { title: 'Pay the launch week contest?', ok: 'Pay ' + total + ' POL', cancel: 'Cancel' })) return;
try { const r = await api('/api/admin/launch-week/pay', { confirm: true, places: list.map(x => ({ place: x.place, memberId: x.memberId, pol: x.pol })) }); IAP.status('Launch contest: ' + (r.paidNow || 0) + ' paid now.', 'ok'); load(); } catch (e) { IAP.status(e.message, 'bad'); load(); }
});
load();
})();
+10 -6
View File
@@ -83,7 +83,9 @@
{ key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.873 },
{ key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.873 },
{ key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.873 },
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.873 }
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.873 },
// Founder (2026-11-05): cosmetic, stored on the account, granted at the launch moment to everyone who signed in before it
{ key: 'founder', label: 'Founder', sub: 'in before launch', img: '/badges/badge-founder.jpg?v=1', ribbonY: 0.873, extra: true }
];
let lastMilestones = [];
function renderBadges(d) {
@@ -92,12 +94,14 @@
const strip = $('badgeStrip');
if (!strip) return;
$('badgeCard').hidden = false;
strip.innerHTML = BADGES.map(b => {
const got = reached.includes(b.key);
const held = reached.concat(d.founder ? ['founder'] : []);
strip.innerHTML = BADGES.filter(b => !b.extra || d.founder || d.founderPending).map(b => {
const got = held.includes(b.key);
return '<div class="badge-a' + (got ? '' : ' locked') + '">'
+ '<img class="badge-img" src="' + b.img + '" alt="' + b.label + ' badge" loading="lazy">'
+ '<div class="bl">' + b.label + '</div><div class="bs">' + b.sub + '</div>'
+ (got ? '<button class="share" data-badge="' + b.key + '">Share</button> <button class="share" data-badgepost="' + b.key + '" hidden>Post to Telegram</button>' : '<div class="bs">🔒 locked</div>') + '</div>';
+ (got ? '<button class="share" data-badge="' + b.key + '">Share</button>' + (b.extra ? '' : ' <button class="share" data-badgepost="' + b.key + '" hidden>Post to Telegram</button>')
: b.key === 'founder' ? '<div class="bs">arrives at launch, Sunday Nov 15</div>' : '<div class="bs">🔒 locked</div>') + '</div>';
}).join('');
strip.querySelectorAll('[data-badge]').forEach(btn =>
btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d)));
@@ -1547,7 +1551,7 @@
}
el.innerHTML = r.levels.map(L => !L.members.length ? '' :
'<div class="lin-lvl"><div class="cap">Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '</div>'
+ L.members.map(m => '<div class="lin-row' + (m.own ? ' own' : '') + '"><span class="nm">' + esc(m.name) + (m.own ? ' <span class="badge">yours</span>' : '') + '</span>'
+ L.members.map(m => '<div class="lin-row' + (m.own ? ' own' : '') + '"><span class="nm">' + esc(m.name) + (m.own ? ' <span class="badge">yours</span>' : '') + (m.founder ? ' <span class="badge" title="Founder badge: signed in before LinkSpin launched" style="background:#ffc94d;border-color:#ffc94d;color:#5a3f00">Founder</span>' : '') + '</span>'
+ '<span class="em">' + (m.email ? esc(m.email) : (m.memberId ? '<span class="id">#' + m.memberId + '</span>' : '')) + (m.sponsor ? '<span class="sp">sponsored by ' + esc(m.sponsor) + '</span>' : '') + (m.own ? '' : '<span class="sp">' + (m.bought ? '$25+ buy ✓' : 'no $25+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '</span>') + '</span>'
+ '<span class="earn' + (m.earnedWei && m.earnedWei !== '0' ? ' on' : '') + '" title="POL this person has paid you so far">'
+ (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '</span>'
@@ -1584,7 +1588,7 @@
+ chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '')
+ chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '')
+ chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn')
+ (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '')
+ (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus', founder: 'Founder' }[b] || b)).join(' · ')) : '')
+ '<span class="lin-verdict' + (working ? ' on' : '') + '">' + (working ? 'Working' : 'Quiet') + '</span>';
}
async function loadUplineMessages() {
+1 -1
View File
@@ -21,7 +21,7 @@
const ms = rows(); const L = (LINE && LINE.levels || []).find(x => x.level === LEVEL); const total = L ? L.members.length : 0;
$('rows').innerHTML = ms.length ? ms.map(m => { const today = (m.lastSeen || 0) >= dayStart();
const sg = stageOf(m), q = quiet(m);
return '<div class="rw st-row' + (q ? ' stalled' : '') + '" data-st="' + sg + '"><div><b>' + esc(m.name) + (m.own ? ' <span class="tag dim">YOURS</span>' : '') + '</b><br><span class="mono muted" style="font-size:11px">' + (m.memberId ? '#' + m.memberId + ' · ' : '') + 'joined ' + new Date(m.joined).toLocaleDateString() + (m.bought ? ' · $25+ buy' : '') + (m.buyers ? ' · ' + m.buyers + ' qualifying' : '') + '</span></div>'
return '<div class="rw st-row' + (q ? ' stalled' : '') + '" data-st="' + sg + '"><div><b>' + esc(m.name) + (m.own ? ' <span class="tag dim">YOURS</span>' : '') + (m.founder ? ' <span class="tag" title="Founder badge: signed in before LinkSpin launched" style="background:#ffc94d;color:#5a3f00">FOUNDER</span>' : '') + '</b><br><span class="mono muted" style="font-size:11px">' + (m.memberId ? '#' + m.memberId + ' · ' : '') + 'joined ' + new Date(m.joined).toLocaleDateString() + (m.bought ? ' · $25+ buy' : '') + (m.buyers ? ' · ' + m.buyers + ' qualifying' : '') + '</span></div>'
+ '<span class="mono ' + (today ? 'ok' : (m.lastSeen && Date.now() - m.lastSeen > 3 * 86400e3 ? 'warn' : '')) + '" style="font-size:12px">' + (today ? 'today' : ago(m.lastSeen)) + '</span>'
+ '<span><span class="stg" data-st="' + sg + '">' + STAGE[sg] + '</span>' + (q ? '<br><span class="stg quiet">' + (m.lastSeen ? 'quiet ' + Math.floor((Date.now() - m.lastSeen) / 86400e3) + 'd' : 'never signed in') + '</span>' : '') + '</span>'
+ '<span class="r num">' + (m.earnedWei && m.earnedWei !== '0' ? '+' + pol(m.earnedWei) + ' POL' : '<span class="muted">0</span>') + '</span>'
+9
View File
@@ -0,0 +1,9 @@
// The Founder badge on a member's wall (2026-11-05, cosmetic). Kept apart from wall.js, which a shared policy test pins by version.
(async function () {
const img = document.getElementById('bioFounder'); if (!img) return;
const name = location.pathname.split('/').pop();
try {
const w = await (await fetch('/api/wall/' + encodeURIComponent(name))).json();
if (w && w.founder && w.founder.img) { img.src = w.founder.img; img.title = 'Founder badge: signed in before LinkSpin launched'; img.hidden = false; }
} catch (e) {}
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

+1 -1
View File
@@ -55,7 +55,7 @@
<p class="eyebrow">Launch week · Sunday, November 15, 6 AM Central</p>
<h1>Eight things before <em>Sunday</em>.</h1>
<p class="lead">LinkSpin is open for pre-launch now and opens to the world on Sunday, November 15 at 6 AM Central. Get these done before then, in this order, so your line is set up when everyone else arrives. Everything here reads from your live account.</p>
<div class="lw-rule" style="margin-top:18px"><b>New for launch week</b>Members who are in before launch get a Founder badge on their profile (the exact rule is posted before Sunday). And from Sunday, November 15 through Saturday, November 21, the leaderboard runs a launch week contest with POL prizes for the top sponsors. Prize details are announced on launch day.</div>
<div class="lw-rule" style="margin-top:18px"><b>New for launch week</b>Founder badge: every account that signs in at least once before Sunday, November 15 at 6 AM Central gets the Founder badge on launch morning. It shows on your badges, your wall, your sponsor's Team list and the leaderboard. It is a badge only, nothing else comes with it. Launch week contest: from Sunday, November 15 at 6 AM through Saturday, November 21 at 11:59 PM Central, the <a href="/leaderboard">leaderboard</a> ranks members by packages bought by the people they sponsor directly (at least 2 to place). The top 3 win POL, paid to the wallet on file after the week closes. Prize details are on the leaderboard from launch morning.</div>
</section>
<div class="card" id="gate"><h3>Members only</h3><p class="muted small">Sign in to your member area to open the checklist. <a href="/links">Sign in</a></p></div>
+1 -1
View File
@@ -1020,7 +1020,7 @@
<script src="/assets/tools.js?v=20261011a"></script>
<script src="/assets/wallet.js?v=20261021a"></script>
<script src="/assets/promo.js?v=20261020bs3"></script>
<script src="/assets/my.js?v=20261105lw"></script>
<script src="/assets/my.js?v=20261105fd"></script>
<script src="/assets/chat.js?v=20261016a"></script>
</body>
</html>
+1 -1
View File
@@ -39,6 +39,6 @@
</div>
</div>
<script src="/assets/cr-shell.js?v=20261102a"></script>
<script src="/assets/team.js?v=20261020s"></script>
<script src="/assets/team.js?v=20261105fd"></script>
</body>
</html>
+2
View File
@@ -21,6 +21,7 @@
<div class="bio-head" id="bioHead" hidden>
<img id="bioAvatar" class="bio-avatar" alt="" hidden>
<img id="bioBadge" class="bio-badge" alt="achievement badge" hidden>
<img id="bioFounder" class="bio-badge" alt="Founder badge" hidden>
<div class="bio-meta">
<p class="eyebrow">Your sponsor on LinkSpin</p>
<h2 id="wallTitle" style="margin:.1em 0">Loading…</h2>
@@ -50,5 +51,6 @@
</section>
<script src="/assets/common.js?v=20261105po"></script>
<script src="/assets/wall.js?v=20261030pp"></script>
<script src="/assets/wall-founder.js?v=20261105fd"></script>
</body>
</html>
+233
View File
@@ -0,0 +1,233 @@
// Launch week tests (2026-11-05): contest window in Central time, exclusions, minimum sales, payout idempotency (two app
// copies), Founder criterion + grant, touchSeen firstSeen backfill. Throwaway DATA_DIR, FAKE chain, FAKE signer: nothing
// here touches Polygon, the production volume or a real member. Run: node qa/launchweek.test.cjs
'use strict';
const fs = require('fs'), os = require('os'), path = require('path'), assert = require('assert');
const ROOT = path.join(__dirname, '..');
const LW = require(path.join(ROOT, 'launchweek.js'));
const E = 10n ** 18n;
let pass = 0, fail = 0;
async function test(name, fn) { try { await fn(); pass++; console.log(' ok ' + name); } catch (e) { fail++; console.log(' FAIL ' + name + '\n ' + (e && e.stack || e).toString().split('\n').slice(0, 4).join('\n ')); } }
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'lwtest-'));
const tickAsync = () => new Promise(r => setImmediate(r));
const T = iso => Date.parse(iso);
const LAUNCH = T('2026-11-15T06:00:00-06:00'), END = T('2026-11-22T00:00:00-06:00');
// ---- fakes ----
function fakeAccounts(list, positions) {
const by = {}; for (const a of list) by[a.email] = Object.assign({ memberId: 0, created: 1 }, a);
return { by,
listAll: async () => Object.values(by).map(a => Object.assign({}, a)),
positions: async e => (positions[e] || []).map(id => ({ memberId: id })),
byEmail: async e => by[e] ? Object.assign({}, by[e]) : null,
setFounder: async (e, ts) => { await tickAsync(); const a = by[e]; if (!a) return { error: 'no' }; if (a.founder) return { ok: true, already: true }; a.founder = ts; return { ok: true }; } };
}
// sales: [sponsorId (TierPaid recipient), buyerId, ts, cents]
function fakeChain(sales, extra) {
const ev = []; sales.forEach(([rec, buyer, ts, cents], i) => {
ev.push({ type: 'Purchase', tx: '0xp' + i, buyerId: buyer, priceCents: cents || 2500, ts });
ev.push({ type: 'TierPaid', tx: '0xp' + i, tier: 1, recipientId: rec, buyerId: buyer, amountWei: '1', ts });
});
return { events: ev.concat(extra || []), recentEvents() { return this.events; } };
}
function sharedMarks() { const set = new Set(); return { set, claim: async k => { await tickAsync(); if (set.has(k)) return false; set.add(k); return true; } }; }
function fakePayer(balanceWei, opts) {
const o = opts || {}; let n = 0;
const p = { address: '0x00000000000000000000000000000000000000aa', bal: BigInt(balanceWei), sends: [],
balance: async () => { await tickAsync(); return p.bal; },
fees: async () => ({ maxFeePerGas: 100n * 10n ** 9n, maxPriorityFeePerGas: 30n * 10n ** 9n }),
preflight: async id => { await tickAsync(); if ((o.reject || []).includes(id)) throw Object.assign(new Error('execution reverted'), { reason: 'Send failed' }); },
send: async (id, wei) => { await tickAsync(); await tickAsync(); p.sends.push({ id, wei: BigInt(wei) }); p.bal -= BigInt(wei); const hash = '0x' + (++n).toString(16).padStart(64, '0'); return { hash, wait: async () => { await tickAsync(); return { status: 1 }; } }; } };
return p;
}
function freshLeaderboard(accounts) {
delete require.cache[require.resolve(path.join(ROOT, 'leaderboard.js'))];
const lb = require(path.join(ROOT, 'leaderboard.js'));
lb.init({ accounts, chain: { recentEvents: () => [] }, ads: {}, dataDir: tmp(), siteConfig: () => ({}), adminEmail: 'admin@x.test' });
return lb;
}
function instance(o) {
const lw = LW.create();
lw.init({ accounts: o.accounts, chain: o.chain, marks: o.marks || sharedMarks(), leaderboard: o.lb || freshLeaderboard(o.accounts), siteConfig: () => o.site || {}, dataDir: o.dir || tmp(), adminEmail: 'admin@x.test', payer: () => o.payer || null, txLink: h => 'https://polygonscan.example/tx/' + h, now: () => o.clock.t });
return lw;
}
// a world: admin #1 (house), alice #10 (+ linked position #11), bob #20, carol #30, dave #40, buyers #100+
const ACCTS = [
{ email: 'admin@x.test', memberId: 1, username: 'martbost' },
{ email: 'alice@x.test', memberId: 10, username: 'alice' },
{ email: 'bob@x.test', memberId: 20, username: 'bob' },
{ email: 'carol@x.test', memberId: 30, username: 'carol' },
{ email: 'dave@x.test', memberId: 40, username: 'dave' },
{ email: 'erin@x.test', memberId: 50, username: 'erin' },
...[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110].map(id => ({ email: 'b' + id + '@x.test', memberId: id }))
];
const POS = { 'alice@x.test': [11], 'carol@x.test': [31] };
(async () => {
console.log('launchweek.test: window (Central time)');
await test('defaults: launch Sun 2026-11-15 06:00 CST = 12:00 UTC; window ends at Sun 2026-11-22 00:00 CST (exclusive)', async () => {
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain([]), clock: { t: LAUNCH } });
const c = lw.cfg();
assert.strictEqual(new Date(c.launchAt).toISOString(), '2026-11-15T12:00:00.000Z');
assert.strictEqual(c.start, c.launchAt);
assert.strictEqual(new Date(c.end).toISOString(), '2026-11-22T06:00:00.000Z');
assert.deepStrictEqual(c.prizes, ['10', '6', '4']); assert.strictEqual(c.minSales, 2);
});
await test('bounds: 05:59:59.999 CT Sunday out, 06:00 in, Sat 23:59:59 CT in, Sun 00:00 CT out', async () => {
const sales = [[20, 100, LAUNCH - 1], [20, 101, LAUNCH], [20, 102, T('2026-11-21T23:59:59-06:00')], [20, 103, END]];
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(sales), clock: { t: END + 3600000 } });
const s = await lw.standings();
assert.strictEqual(s.rows.length, 1); assert.strictEqual(s.rows[0].email, 'bob@x.test'); assert.strictEqual(s.rows[0].sales, 2);
assert.strictEqual(s.open, false);
});
await test('settings move the window without a deploy (launchAt and launchContestEnd)', async () => {
const site = { launchAt: '2026-11-16T09:00:00-06:00', launchContestEnd: '2026-11-17T00:00:00-06:00' };
const sales = [[20, 100, T('2026-11-16T08:59:00-06:00')], [20, 101, T('2026-11-16T09:00:00-06:00')], [20, 102, T('2026-11-16T23:00:00-06:00')], [20, 103, T('2026-11-17T00:00:00-06:00')]];
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(sales), site, clock: { t: T('2026-11-18T00:00:00Z') } });
const s = await lw.standings(); assert.strictEqual(s.rows[0].sales, 2);
});
console.log('launchweek.test: exclusions + minimum');
const D = h => LAUNCH + h * 3600000;
const WORLD = [
[10, 100, D(1)], [10, 101, D(2)], [10, 102, D(3)], // alice: 3 real sales
[10, 11, D(4)], // alice's own linked position bought under her: own, never counts
[20, 31, D(5)], // bob sold to carol's linked position: linked positions never count
[20, 103, D(6)], [20, 104, D(7)], // bob: 2 real sales
[1, 105, D(8)], [1, 106, D(9)], [1, 107, D(10)], // admin/company #1: never a contestant
[30, 1, D(11)], [30, 108, D(12)], // carol: one sale is a company placement (buyer = admin #1), one real
[40, 109, D(13)], [40, 110, D(14)], // dave: 2 real sales (excluded by setting in one test)
[50, 100, D(2)] // erin: one sale (under the minimum)
];
await test('own positions, linked positions, admin and house sponsors, company buys never count', async () => {
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock: { t: END + 1 } });
const s = await lw.standings(); const by = Object.fromEntries(s.rows.map(r => [r.email, r]));
assert.strictEqual(by['alice@x.test'].sales, 3);
assert.strictEqual(by['bob@x.test'].sales, 2);
assert.strictEqual(by['carol@x.test'].sales, 1);
assert.ok(!by['admin@x.test']);
});
await test('minimum 2 to place; ties broken by dollars then who got there first; prizes 10/6/4', async () => {
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock: { t: END + 1 } });
const s = await lw.standings();
assert.deepStrictEqual(s.winners.map(w => [w.place, w.email, w.pol, w.memberId]), [[1, 'alice@x.test', '10', 10], [2, 'bob@x.test', '6', 20], [3, 'dave@x.test', '4', 40]]);
assert.ok(s.rows.find(r => r.email === 'erin@x.test' && !r.qualifies));
});
await test('launchContestExcludeEmails / ExcludeIds and a higher minimum', async () => {
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), site: { launchContestExcludeEmails: 'dave@x.test', launchContestMinSales: 3 }, clock: { t: END + 1 } });
const s = await lw.standings();
assert.deepStrictEqual(s.winners.map(w => w.email), ['alice@x.test']);
const lw2 = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), site: { launchContestExcludeIds: '10' }, clock: { t: END + 1 } });
assert.ok(!(await lw2.standings()).rows.find(r => r.email === 'alice@x.test'));
});
console.log('launchweek.test: payout (fake signer)');
const expectOf = async lw => (await lw.standings(END)).winners.map(w => ({ place: w.place, memberId: w.memberId, pol: w.pol }));
await test('refused while the window is open; refused without a payer', async () => {
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), payer: fakePayer(100n * E), clock: { t: END - 1 } });
assert.ok((await lw.pay([])).error.includes('still open'));
const lw2 = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock: { t: END + 1 } });
assert.ok((await lw2.pay([])).error.includes('payer'));
});
await test('a list that differs from the frozen result is refused, nothing sent', async () => {
const payer = fakePayer(100n * E);
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), payer, clock: { t: END + 1 } });
const ex = await expectOf(lw); ex[0].pol = '20';
const r = await lw.pay(ex); assert.ok(r.error && r.error.includes('does not match')); assert.strictEqual(payer.sends.length, 0);
});
await test('not enough POL in the payer: refused before any send', async () => {
const payer = fakePayer(19n * E);
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), payer, clock: { t: END + 1 } });
const r = await lw.pay(await expectOf(lw)); assert.ok(r.error && r.error.includes('Nothing was sent')); assert.strictEqual(payer.sends.length, 0);
});
await test('two app copies press Pay at once: each place paid exactly once; a third press pays nothing', async () => {
const dir = tmp(), marks = sharedMarks(), payer = fakePayer(100n * E), clock = { t: END + 3600000 };
const accounts = fakeAccounts(ACCTS, POS), chain = fakeChain(WORLD);
const a = instance({ accounts, chain, payer, marks, dir, clock }), b = instance({ accounts, chain, payer, marks, dir, clock });
const ex = await expectOf(a);
const [ra, rb] = await Promise.all([a.pay(ex), b.pay(ex)]);
assert.ok(!ra.error && !rb.error, JSON.stringify([ra.error, rb.error]));
assert.deepStrictEqual(payer.sends.map(s => [s.id, s.wei]).sort((x, y) => x[0] - y[0]), [[10, 10n * E], [20, 6n * E], [40, 4n * E]]);
const r3 = await a.pay(ex); assert.strictEqual(r3.paidNow, 0); assert.strictEqual(payer.sends.length, 3);
const v = await a.adminView(); assert.ok(v.payouts.every(x => x.state === 'paid' && /^0x/.test(x.txHash)));
assert.strictEqual(await a.panelHtml(), ''); // panel gone after the payout
assert.ok(a.txInfo(v.payouts[0].txHash));
});
await test('frozen result does not move when late sales index after the first press', async () => {
const dir = tmp(), payer = fakePayer(100n * E, { reject: [40] }), clock = { t: END + 1 }, chain = fakeChain(WORLD), accounts = fakeAccounts(ACCTS, POS);
const lw = instance({ accounts, chain, payer, dir, clock });
const ex = await expectOf(lw); const r = await lw.pay(ex);
assert.strictEqual(r.paidNow, 2); assert.strictEqual(r.payouts.find(x => x.place === 3).state, 'blocked');
chain.events.push({ type: 'TierPaid', tier: 1, recipientId: 50, buyerId: 101, ts: D(20), tx: '0xlate' }, { type: 'TierPaid', tier: 1, recipientId: 50, buyerId: 102, ts: D(21), tx: '0xlate2' });
const v = await lw.adminView(); assert.deepStrictEqual(v.wouldPay.map(w => w.email), ['alice@x.test', 'bob@x.test', 'dave@x.test']);
// the blocked place: admin checked, releases it once; the next press pays it, and only it
payer.sends.length = 0; const rr = await lw.resolve(3, 'retry'); assert.ok(rr.ok);
// still rejected by the wallet: stays blocked, nothing sent
await lw.pay(ex); assert.strictEqual(payer.sends.length, 0);
assert.ok((await lw.resolve(1, 'retry')).error); // a paid place can never be released
});
console.log('launchweek.test: Founder');
const FA = [
{ email: 'early@x.test', lastSeen: LAUNCH - 86400000 }, // signed in before, never since
{ email: 'both@x.test', firstSeen: LAUNCH - 3 * 86400000, lastSeen: LAUNCH + 3600000 }, // before and after
{ email: 'late@x.test', firstSeen: LAUNCH + 60000, lastSeen: LAUNCH + 3600000 }, // first visit after launch
{ email: 'edge@x.test', firstSeen: LAUNCH, lastSeen: LAUNCH }, // exactly at the launch moment: not before
{ email: 'shell@x.test', joinedVia: 'carried' }, // carried over, never signed in
{ email: 'oldlast@x.test', lastSeen: LAUNCH + 5000 } // no firstSeen, only a post-launch lastSeen
];
await test('criterion: earliest signed-in visit strictly before the launch moment', async () => {
const lw = instance({ accounts: fakeAccounts(FA, {}), chain: fakeChain([]), clock: { t: LAUNCH - 1000 } });
const q = FA.filter(a => lw.qualifiesFounder(a, LAUNCH)).map(a => a.email);
assert.deepStrictEqual(q, ['early@x.test', 'both@x.test']);
const p = await lw.founderPreview(); assert.strictEqual(p.qualify, 2); assert.strictEqual(p.neverSignedIn, 1); assert.strictEqual(p.launched, false);
});
await test('grant refused before launch; automatic tick grants from launch; idempotent; two copies grant once each account', async () => {
const accounts = fakeAccounts(FA, {}), clock = { t: LAUNCH - 1000 }, marks = sharedMarks();
const a = instance({ accounts, chain: fakeChain([]), clock, marks }), b = instance({ accounts, chain: fakeChain([]), clock, marks });
assert.ok((await a.grantFounders()).error); await a.tick();
assert.ok(!Object.values(accounts.by).some(x => x.founder));
clock.t = LAUNCH + 60000;
await Promise.all([a.tick(), b.tick()]);
assert.deepStrictEqual(Object.values(accounts.by).filter(x => x.founder).map(x => x.email).sort(), ['both@x.test', 'early@x.test']);
assert.ok(Object.values(accounts.by).filter(x => x.founder).every(x => x.founder === LAUNCH));
clock.t += 600000; const r = await a.grantFounders(); assert.strictEqual(r.granted, 0);
assert.strictEqual(a.founderState(accounts.by['early@x.test']).founder, true);
assert.strictEqual(a.founderState(accounts.by['late@x.test']).founder, false);
});
await test('founderGrant 0 switches the automatic grant off', async () => {
const accounts = fakeAccounts(FA, {});
const lw = instance({ accounts, chain: fakeChain([]), site: { founderGrant: '0' }, clock: { t: LAUNCH + 1 } });
await lw.tick(); assert.ok(!Object.values(accounts.by).some(x => x.founder));
});
await test('accounts.js (JSON): touchSeen keeps the earlier visit as firstSeen; setFounder is once', async () => {
const dir = tmp(); delete process.env.DATABASE_URL;
const accts = require(path.join(ROOT, 'accounts.js')); accts.init({ dataDir: dir });
await accts.ensure('m@x.test', '', 'carried');
let a = await accts.byEmail('m@x.test'); assert.strictEqual(a.firstSeen, 0); assert.strictEqual(a.lastSeen, 0);
await accts.touchSeen('m@x.test'); a = await accts.byEmail('m@x.test'); const first = a.firstSeen; assert.ok(first > 0 && a.lastSeen === first);
await new Promise(r => setTimeout(r, 5)); await accts.touchSeen('m@x.test'); a = await accts.byEmail('m@x.test');
assert.strictEqual(a.firstSeen, first); assert.ok(a.lastSeen > first);
// an account that only has an old lastSeen (signed in before this field existed): its next visit keeps that time
const raw = JSON.parse(fs.readFileSync(path.join(dir, 'accounts.json'), 'utf8')); raw.byEmail['m@x.test'] = Object.assign(raw.byEmail['m@x.test'], { firstSeen: undefined, lastSeen: 12345 });
fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify(raw)); accts.init({ dataDir: dir });
await accts.touchSeen('m@x.test'); a = await accts.byEmail('m@x.test'); assert.strictEqual(a.firstSeen, 12345);
assert.deepStrictEqual(await accts.setFounder('m@x.test', LAUNCH), { ok: true }); assert.deepStrictEqual(await accts.setFounder('m@x.test', LAUNCH + 1), { ok: true, already: true });
assert.strictEqual((await accts.byEmail('m@x.test')).founder, LAUNCH);
});
console.log('launchweek.test: public panel');
await test('panel hidden before the launch moment, shown from it, says POL to the wallet on file, no em dashes', async () => {
const clock = { t: LAUNCH - 1 };
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock });
assert.strictEqual(await lw.panelHtml(), '');
clock.t = LAUNCH + 3 * 3600000; const h = await lw.panelHtml();
assert.ok(h.includes('Launch week contest') && h.includes('paid in POL to the wallet on file') && h.includes('at least 2'));
assert.ok(!/—/.test(h));
const pv = await lw.publicView(); assert.strictEqual(pv.contest.live, true); assert.deepStrictEqual(pv.contest.prizes, ['10', '6', '4']);
});
console.log('\nlaunchweek.test: ' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
})();
+4
View File
@@ -11,6 +11,7 @@
# bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed
# bash qa/run.sh nas # Network Ad Space billing: stop snapshot, active-only reconcile, restart without phantom delivery, the 1/N network + partner-zone rate (stubbed NAS, throwaway data)
# bash qa/run.sh loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy
# bash qa/run.sh launchweek # launch week: contest window in Central time, exclusions, minimum sales, payout once across two copies, Founder criterion + grant (fake chain + signer)
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data)
# bash qa/run.sh policy # profile policy + link-farm scan: prohibited list, bio links, quarantine, 06:30 claim, walls of free/paying members, 404 walls (unit + local copy; also runs in member)
# bash qa/run.sh fuel # Fuel Your Offers: refill notices, refuel streak, Refuel Kit, Engine Room (unit + two-copy tests, throwaway data)
@@ -60,6 +61,8 @@ elif [ "$MODE" = "theme" ]; then
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/theme-contrast.mjs || status=1; }; stop_local 8797
elif [ "$MODE" = "override" ]; then
node qa/override.test.cjs || status=1
elif [ "$MODE" = "launchweek" ]; then
node qa/launchweek.test.cjs || status=1
elif [ "$MODE" = "member" ]; then
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
node qa/profile-policy.test.cjs || status=1
@@ -88,6 +91,7 @@ elif [ "$MODE" = "earn" ]; then
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
else
node qa/walk.mjs public || status=1
node qa/launchweek.test.cjs || status=1
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
fi
+46 -8
View File
@@ -90,6 +90,7 @@ const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays',
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
const launchweek = require('./launchweek'); // launch week (2026-11-05): Founder badge grant + the launch contest (admin-approved POL prizes)
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
const PORT = Number(process.env.PORT || 3000);
@@ -769,6 +770,11 @@ async function boot() {
override.init({ dataDir: DATA_DIR, chain, siteConfig, db, brand: 'LinkSpin', siteUrl: SITE_URL,
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) { await telegramSend(sc.telegramAdminChatId, text); return true; } if (ADMIN_EMAIL && mailer.hasKey()) { await mailer.send(ADMIN_EMAIL, 'LinkSpin: level-4 override', text.replace(/<[^>]+>/g, '')); return true; } return false; } });
setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000);
// launch week: Founder grant from the launch moment (idempotent, every 10 minutes) + the /leaderboard contest panel; POL prizes only by the admin button
launchweek.init({ accounts, chain, marks, leaderboard, siteConfig, dataDir: DATA_DIR, adminEmail: ADMIN_EMAIL, payer: () => override.payerHandle(), txLink: h => override.polygonTx(h) });
leaderboard.setLaunchPanel(() => launchweek.panelHtml());
setTimeout(() => launchweek.tick().catch(e => console.error('launchweek', e.message)), 2 * 60 * 1000);
setInterval(() => launchweek.tick().catch(e => console.error('launchweek', e.message)), 10 * 60 * 1000);
if (OUTBOUND_MAIL) { // same for the lead follow-up sequence
setTimeout(() => drip.tick().catch(e => console.error('drip', e.message)), 30 * 1000);
setInterval(() => drip.tick().catch(e => console.error('drip', e.message)), 10 * 60 * 1000);
@@ -802,6 +808,8 @@ function siteConfig() {
telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic
telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL
spamScanAllow: spamscan.DEFAULT_ALLOW.join(', '), // link-farm scan (2026-10-30): emails never listed as candidates; Admin > Members > Link-farm list > Allow adds here
founderGrant: '1', // Founder badge: '0' stops the automatic grant at the launch moment (launchweek.js); the badge is cosmetic
launchContest: '1', launchContestStart: '', launchContestEnd: '2026-11-22T00:00:00-06:00', launchContestPrizesPol: '10,6,4', launchContestMinSales: 2, launchContestMinCents: 0, launchContestExcludeEmails: '', launchContestExcludeIds: '', // launch week contest: start '' = launchAt; end is EXCLUSIVE (all of Sat Nov 21 Central); POL prizes 1st,2nd,3rd paid only by the admin button; admin + overrideHouseIds always excluded
launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark
aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation
carryClaimDays: '3',
@@ -1099,7 +1107,9 @@ async function emailOnEvent(ev) {
}
else if (ev.type === 'AwardPaid') {
const ov = override.txInfo(ev.tx); // a level-4 override payment from the weekly payer
if (ov) await tell(ev.toId, 'Your Level 4 override is paid: ' + weiToPol(ev.amountWei) + ' POL', 'Your Level 4 override for the week of ' + ov.week + ' just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL. That is 3 percent of the purchases made four levels down in your line (or deeper, when the upline between was not yet qualified), paid weekly from the company wallet. You earn it while you have 5 or more qualifying buyers.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
const lw = !ov && launchweek.txInfo(ev.tx); // a launch week contest prize (admin-approved)
if (lw) await tell(ev.toId, 'Your launch week contest prize is paid: ' + weiToPol(ev.amountWei) + ' POL', 'You placed ' + ['1st', '2nd', '3rd', '4th', '5th'][lw.place - 1] + ' in the LinkSpin launch week contest. Your prize just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
else if (ov) await tell(ev.toId, 'Your Level 4 override is paid: ' + weiToPol(ev.amountWei) + ' POL', 'Your Level 4 override for the week of ' + ov.week + ' just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL. That is 3 percent of the purchases made four levels down in your line (or deeper, when the upline between was not yet qualified), paid weekly from the company wallet. You earn it while you have 5 or more qualifying buyers.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
else await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
}
else if (ev.type === 'PassedUp' && ev.reason === 'send-failed') {
@@ -1143,7 +1153,7 @@ async function telegramOnEvent(ev) {
if (ev.type === 'TierPaid') line = '\u{1F4B8} Level ' + ev.tier + ' payout: <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.recipientId);
else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has <b>' + ev.newCount + '</b> qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : '');
else if (ev.type === 'Purchase' && mode !== 'payouts') line = '\u{1F9FE} ' + who(ev.buyerId) + ' bought a $' + Math.round(ev.priceCents / 100) + ' package';
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : 'Award payout') + ': <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : launchweek.txInfo(ev.tx) ? 'Launch week contest prize' : 'Award payout') + ': <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts';
if (!line) return null;
return line + ' \u00b7 <a href="' + tx + '">verify</a>' + (sc.telegramCtaUrl ? '\n<a href="' + sc.telegramCtaUrl + '">Join free</a>' : '');
@@ -1290,8 +1300,10 @@ async function telegramSendPhoto(chatId, jpeg, caption, threadId) {
rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body);
});
}
const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'] };
const BADGE_META = { founder: ['Founder', 'signed in before LinkSpin launched'], payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'] };
const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
// every badge a member holds: the chain milestones plus the stored Founder flag (2026-11-05)
async function badgesHeld(email) { const out = []; try { out.push(...await ads.milestonesOf(email)); } catch (e) {} try { const a = await accounts.byEmail(email); if (a && a.founder) out.push('founder'); } catch (e) {} return out; }
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
// ---- live feed (SSE) ----
@@ -2127,6 +2139,7 @@ const server = http.createServer(async (req, res) => {
if (bc >= 5) reached.push('level3');
try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned
out.milestonesReached = reached;
try { const fs0 = launchweek.founderState(acct || await accounts.byEmail(out.email)); out.founder = fs0.founder; out.founderPending = fs0.pending; } catch (e) {} // Founder badge: cosmetic, never in milestonesReached (no credits)
if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached);
}
// who joined through this member: their invite link uses username when set,
@@ -2348,6 +2361,9 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await toolkit.adminUsage());
}
if (p === '/api/launch-week' && req.method === 'GET') { // public: launch moment + whether the contest panel is live (for /launch)
return json(res, 200, await launchweek.publicView());
}
if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row
const s = await auth.fromRequest(req);
const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week';
@@ -2462,6 +2478,7 @@ const server = http.createServer(async (req, res) => {
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const key = String(u.searchParams.get('key') || '');
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
if (key === 'founder') return json(res, 400, { error: 'The Founder badge is not posted to Telegram.' }); // launch week: no mass badge posts (Marty 2026-11-05)
if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' });
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
@@ -2494,7 +2511,7 @@ const server = http.createServer(async (req, res) => {
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
if (!(await ads.milestonesOf(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
if (!(await badgesHeld(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
const a = await accounts.byEmail(s.email);
if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' });
fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg);
@@ -3177,6 +3194,7 @@ const server = http.createServer(async (req, res) => {
memberId: m.memberId || 0,
sponsor: sponsorOf(m),
name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member',
founder: !!m.founder, // Founder badge (cosmetic)
ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels
email: L.level === 1 ? m.email : null, // directs only
joined: m.created,
@@ -3205,7 +3223,7 @@ const server = http.createServer(async (req, res) => {
try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {}
try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {}
try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; }
try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; }
out.badges = await badgesHeld(a.email); // chain milestones + Founder
try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; }
return json(res, 200, out);
}
@@ -3563,6 +3581,7 @@ const server = http.createServer(async (req, res) => {
let socials = null; if (bought) { try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} }
return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), bought,
avatarUrl: bought ? (a.avatarUrl || null) : null, bio: bought ? (a.bio || null) : null, socials, badge,
founder: a.founder ? { img: '/badges/badge-founder.jpg', label: 'Founder' } : null, // cosmetic Founder badge (2026-11-05)
joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent(SITE_URL + joinPath), ladder: finalLadder, unlocked, buyerCount: bc });
}
// -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch
@@ -4027,6 +4046,25 @@ const server = http.createServer(async (req, res) => {
const r = await override.resolve(String(b.week || ''), Number(b.memberId), String(b.action || ''), String(b.tx || ''));
return json(res, r && r.error ? 400 : 200, r);
}
// -- launch week (2026-11-05): Founder badge preview/grant + launch contest standings and the admin-approved POL payout
if (p === '/api/admin/launch-week' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await launchweek.adminView(), { 'Cache-Control': 'no-store' });
}
if (p === '/api/admin/launch-week/founders' && req.method === 'POST') { // run the Founder grant now (refused before the launch moment)
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await launchweek.grantFounders({ manual: true }); return json(res, r.error ? 400 : 200, Object.assign(r, { preview: await launchweek.founderPreview() }));
}
if (p === '/api/admin/launch-week/pay' && req.method === 'POST') { // pays the frozen places that match the list the admin confirmed; never twice
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); if (!b || b.confirm !== true) return json(res, 400, { error: 'Send confirm: true with the places you saw.' });
const r = await launchweek.pay(b.places); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/launch-week/resolve' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const r = await launchweek.resolve(Number(b.place), String(b.action || ''), String(b.tx || ''));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/site' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { site: siteConfig() });
@@ -4219,14 +4257,14 @@ const server = http.createServer(async (req, res) => {
if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12)
if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); // member guide: how earning works (2026-09-12)
// -- badge share page + image: /b/<username>/<key> (OG preview = the member's composed badge) (Marty, 2026-09-13)
m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p);
m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3|founder)\.jpg$/.exec(p);
if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg'));
m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)$/i.exec(p);
m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3|founder)$/i.exec(p);
if (m) {
const un = m[1].toLowerCase(), key = m[2];
const a = await accounts.byUsername(un);
const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg');
if (!a || !fs.existsSync(file) || !(await ads.milestonesOf(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
if (!a || !fs.existsSync(file) || !(await badgesHeld(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
const [label, sub] = BADGE_META[key];
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const url = SITE_URL + '/b/' + un + '/' + key, img = SITE_URL + '/badge-img/' + un + '/' + key + '.jpg';