Mystery Hunt Box + Ad Detective, badge tiers

Finish the day's Code Hunts to unlock one box a day. It opens to an Ad
Detective case on one site with a fixed 0.15 POL reward shown up front:
visit (the embed records the visit after the dwell, no code), then answer
one question, one attempt. Paid inside the house cap, never counted as a
find. 34-question bank seeded from lib/detective-bank.json; a hunter never
repeats a question until they have seen every one for that site. Admin
panel with per-question stats and retire/restore.

New badges (all ledger-derived): Detective, Sleuth, Investigator, Master
Detective; Scout, Guide, Trail Boss; Week Sweep; 7-Day Streak. Badges
already earned on deploy are marked announced without posting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-09-26 16:10:17 -05:00
parent 64ab0b505f
commit 469cbf69a5
25 changed files with 1334 additions and 423 deletions
+2 -1
View File
@@ -9,7 +9,8 @@ const { spawn } = require('child_process');
let PUBLIC_DIR = null, CACHE_DIR = null, FONT;
// per-badge ribbon position (fraction of height); tuned to the artwork
const ART = { first: 0.734, hunter: 0.753, tracker: 0.715, sweep: 0.689, lucky: 0.753, streak: 0.702, top: 0.725, recruiter: 0.834 };
const ART = { first: 0.734, hunter: 0.753, tracker: 0.715, sweep: 0.689, lucky: 0.753, streak: 0.702, top: 0.725, recruiter: 0.834,
/* 2026-09-26 set, measured on the art */ detective: 0.82, sleuth: 0.899, investigator: 0.793, masterdetective: 0.879, scout: 0.744, guide: 0.794, trailboss: 0.809, weeksweep: 0.794, weekstreak: 0.789 };
function init(opts) { PUBLIC_DIR = opts.publicDir; CACHE_DIR = path.join(opts.dataDir, 'badges'); try { fs.mkdirSync(CACHE_DIR, { recursive: true }); } catch (e) {} }
function artFile(id) { return path.join(PUBLIC_DIR, 'badges', 'badge-' + id + '.jpg'); }
+481
View File
@@ -0,0 +1,481 @@
{
"_note": "Seed bank for Ad Detective. options[0] is the correct answer; the server shuffles per hunter and never sends which is right. Merged into the volume by id on boot: edits and retirements made on the volume win.",
"questions": [
{
"id": "iap-ledger-1",
"missionId": "iap-ledger",
"q": "What does every line on the ledger carry?",
"options": [
"A verify link to the block explorer",
"A star rating",
"A download button",
"A comment box"
],
"fact": "Every line carries a verify link straight to the block explorer.",
"active": true,
"added": "2026-09-26"
},
{
"id": "iap-ledger-2",
"missionId": "iap-ledger",
"q": "What does the ledger page say about a payment that is not on it?",
"options": [
"It did not happen",
"It is still pending",
"It was paid by email",
"It gets added next week"
],
"fact": "If it is not here, it did not happen.",
"active": true,
"added": "2026-09-26"
},
{
"id": "iap-ledger-3",
"missionId": "iap-ledger",
"q": "When a member runs ads, how does it show on the ledger?",
"options": [
"As credits spent",
"As POL received",
"As a new wallet",
"It does not show; ads are hidden"
],
"fact": "Rows read 'ran ads: -50 credits'.",
"active": true,
"added": "2026-09-26"
},
{
"id": "iap-ledger-4",
"missionId": "iap-ledger",
"q": "Which network brings you InstantAdPay, per the top of the page?",
"options": [
"The Crypto Team Build Network",
"The Polygon Foundation",
"DripOffers",
"AdRevLinks"
],
"fact": "Brought to you by the Crypto Team Build Network.",
"active": true,
"added": "2026-09-26"
},
{
"id": "rmc-training-1",
"missionId": "rmc-training",
"q": "What should you never share with anyone?",
"options": [
"Your Secret Recovery Phrase",
"Your invite link",
"Your member ID",
"Your wallet address"
],
"fact": "Video 2: Never share your Secret Recovery Phrase with anyone.",
"active": true,
"added": "2026-09-26"
},
{
"id": "rmc-training-2",
"missionId": "rmc-training",
"q": "Which wallet does the training show you how to set up?",
"options": [
"MetaMask",
"PayPal",
"Cash App",
"A bank account"
],
"fact": "Video 2: Create your MetaMask wallet.",
"active": true,
"added": "2026-09-26"
},
{
"id": "rmc-training-3",
"missionId": "rmc-training",
"q": "Which network do you fund your wallet on?",
"options": [
"Polygon Mainnet",
"Bitcoin",
"Solana",
"Dogecoin"
],
"fact": "Video 3: Get POL onto Polygon Mainnet.",
"active": true,
"added": "2026-09-26"
},
{
"id": "rmc-training-4",
"missionId": "rmc-training",
"q": "For someone brand new to crypto, which service does the page name for buying POL with a card?",
"options": [
"MoonPay",
"Venmo",
"Western Union",
"Zelle"
],
"fact": "The simplest path is MoonPay.",
"active": true,
"added": "2026-09-26"
},
{
"id": "rmc-training-5",
"missionId": "rmc-training",
"q": "According to Video 7, what does every level you own do?",
"options": [
"Extends your reach one generation deeper",
"Doubles every payment",
"Removes the need for directs",
"Nothing, levels are cosmetic"
],
"fact": "Every level you own extends your reach exactly one generation deeper.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-programs-1",
"missionId": "ctb-programs",
"q": "Where does CTB Rewards open?",
"options": [
"In Telegram",
"In WhatsApp",
"In Discord",
"In your email"
],
"fact": "Telegram Mini App. Opens in Telegram, no signup form needed.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-programs-2",
"missionId": "ctb-programs",
"q": "How many CTB Coins equal $1?",
"options": [
"10,000",
"100",
"1,000",
"1,000,000"
],
"fact": "10,000 Coins = $1 USD.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-programs-3",
"missionId": "ctb-programs",
"q": "Where do you withdraw your earnings?",
"options": [
"To your TON wallet",
"To PayPal",
"To a bank account",
"To a gift card"
],
"fact": "Withdraw to your TON wallet anytime.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-programs-4",
"missionId": "ctb-programs",
"q": "How often can you claim the free faucet?",
"options": [
"Every hour",
"Once a week",
"Once a month",
"Only on Fridays"
],
"fact": "Claim up to 100 free coins every hour.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-programs-5",
"missionId": "ctb-programs",
"q": "What commission do you earn on your direct referrals' earnings?",
"options": [
"20%",
"5%",
"1%",
"50%"
],
"fact": "Level 1: 20%.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mailsplat-home-1",
"missionId": "mailsplat-home",
"q": "What does this site give you?",
"options": [
"A temporary email address",
"A free website",
"A crypto wallet",
"A phone number"
],
"fact": "Your Temporary Email Address.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mailsplat-home-2",
"missionId": "mailsplat-home",
"q": "Why would someone use it?",
"options": [
"To keep their real inbox free of spam",
"To earn POL for every email",
"To back up their photos",
"To send faxes"
],
"fact": "Keep your real mailbox clean and secure.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mailsplat-home-3",
"missionId": "mailsplat-home",
"q": "Which buttons sit with your temporary address?",
"options": [
"Refresh, Change and Delete",
"Like, Share and Follow",
"Buy, Sell and Swap",
"Print, Scan and Fax"
],
"fact": "Refresh / Change / Delete.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mailsplat-home-4",
"missionId": "mailsplat-home",
"q": "What does the inbox say before any mail arrives?",
"options": [
"Your inbox is empty",
"Upgrade to read mail",
"Account suspended",
"Please verify your phone"
],
"fact": "Your inbox is empty. Waiting for incoming emails.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mylnks-home-1",
"missionId": "mylnks-home",
"q": "What does My Link Shortener turn long URLs into?",
"options": [
"Short links",
"Videos",
"PDF files",
"Emails"
],
"fact": "Transform long, complex URLs into memorable short links.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mylnks-home-2",
"missionId": "mylnks-home",
"q": "Besides short links, what else can you create there?",
"options": [
"QR codes and Bio Pages",
"Crypto tokens",
"Online courses",
"Phone apps"
],
"fact": "Dynamic Links, QR codes and Bio Pages.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mylnks-home-3",
"missionId": "mylnks-home",
"q": "Do you need a credit card to start?",
"options": [
"No, no credit card required",
"Yes, a card is required",
"Only a crypto card",
"Only PayPal"
],
"fact": "Start free, upgrade later. No credit card required.",
"active": true,
"added": "2026-09-26"
},
{
"id": "mylnks-home-4",
"missionId": "mylnks-home",
"q": "What does Smart Deep Linking do?",
"options": [
"Opens the mobile app automatically when it is installed",
"Translates web pages",
"Blocks all ads",
"Speeds up your wifi"
],
"fact": "Automatically opening mobile apps when the app is installed.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-home-1",
"missionId": "ctb-home",
"q": "Since when has Crypto Team Build been online and paying?",
"options": [
"February 2022",
"January 2025",
"Last month",
"2015"
],
"fact": "Online and paying members since February 2022.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-home-2",
"missionId": "ctb-home",
"q": "What is the lowest price of an advertising position?",
"options": [
"$1.25",
"$10",
"$49",
"$100"
],
"fact": "Buy an advertising position from $1.25.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-home-3",
"missionId": "ctb-home",
"q": "How long do referrals you sponsor stay coded to you?",
"options": [
"For life",
"30 days",
"One year",
"Until they buy a position"
],
"fact": "Every referral you sponsor stays coded to you for life.",
"active": true,
"added": "2026-09-26"
},
{
"id": "ctb-home-4",
"missionId": "ctb-home",
"q": "What follows up with your leads without any outside service?",
"options": [
"The built-in autoresponder",
"A paid call center",
"Your sponsor, by phone",
"Nothing, you do it by hand"
],
"fact": "Built-in autoresponder. Multi-list follow-up, no outside service needed.",
"active": true,
"added": "2026-09-26"
},
{
"id": "adrevlnks-home-1",
"missionId": "adrevlnks-home",
"q": "What does AdRevLinks pay you for?",
"options": [
"Visits to the short links you post",
"Watching videos",
"Taking surveys",
"Mining crypto"
],
"fact": "Create a link and post it. For every visit, you earn money.",
"active": true,
"added": "2026-09-26"
},
{
"id": "adrevlnks-home-2",
"missionId": "adrevlnks-home",
"q": "What is the referral bonus?",
"options": [
"20% of friends' earnings for life",
"5% for one month",
"$1 per friend, once",
"There is none"
],
"fact": "Refer friends and receive 20% of their earnings for life.",
"active": true,
"added": "2026-09-26"
},
{
"id": "adrevlnks-home-3",
"missionId": "adrevlnks-home",
"q": "How much must you earn before you are paid?",
"options": [
"$5",
"$50",
"$100",
"$1,000"
],
"fact": "You are required to earn only $5 before you will be paid.",
"active": true,
"added": "2026-09-26"
},
{
"id": "adrevlnks-home-4",
"missionId": "adrevlnks-home",
"q": "In the three steps to start, what is step 2?",
"options": [
"Shorten your link",
"Buy a package",
"Verify your ID",
"Watch a video"
],
"fact": "1 Create an account, 2 Shorten your link, 3 Earn money.",
"active": true,
"added": "2026-09-26"
},
{
"id": "dripoffers-home-1",
"missionId": "dripoffers-home",
"q": "What does DripOffers give website owners to earn money?",
"options": [
"An offerwall",
"Web hosting",
"A domain name",
"An email list"
],
"fact": "Monetize your website with our simple offerwall.",
"active": true,
"added": "2026-09-26"
},
{
"id": "dripoffers-home-2",
"missionId": "dripoffers-home",
"q": "How cheaply can you start advertising there?",
"options": [
"Less than a dollar",
"$100 minimum",
"$1,000 minimum",
"Advertising is invite-only"
],
"fact": "You can advertise your website, product or services with less than a dollar.",
"active": true,
"added": "2026-09-26"
},
{
"id": "dripoffers-home-3",
"missionId": "dripoffers-home",
"q": "How fast can a site owner get the offerwall running?",
"options": [
"Less than 5 minutes",
"About a week",
"One month",
"Only after a sales call"
],
"fact": "Monetize your website with our Offerwall in less than 5 minutes.",
"active": true,
"added": "2026-09-26"
},
{
"id": "dripoffers-home-4",
"missionId": "dripoffers-home",
"q": "How do publishers add the offerwall to their site?",
"options": [
"An HTML5 iframe or the API",
"A printed form",
"A phone call",
"A browser extension"
],
"fact": "We provide an HTML5 iframe, API Based Integration.",
"active": true,
"added": "2026-09-26"
}
]
}
+176
View File
@@ -0,0 +1,176 @@
// Mystery Hunt Box + Ad Detective (Phase 1, Marty 2026-09-26).
//
// The box: finish the day's Code Hunts (missionsPerDay, normally 3) and one Mystery Hunt Box
// unlocks, once per member per Central day. Opening it reveals a mission, never an amount: an Ad
// Detective case on one of the network's sites, with its FIXED reward shown before the hunter
// starts (settings.detectivePol, default 0.15 POL). The only chance element is which site you get;
// every case pays the same disclosed rate, so this is a task, not a prize draw.
//
// The case: Begin issues a normal mission token (kind 'detective'). The hunter visits the site; the
// embed's origin-locked call after the dwell records the visit on the box (no code is shown). Only
// then does the board show the question. One answer. Correct pays the fixed reward through the
// same faucet, inside the same daily house cap (over the cap it queues, like a find). Wrong pays
// nothing today. Every answer is logged (answers.json) for per-question stats.
//
// Detective payouts are NOT finds: they never count toward the daily limit, the leaderboard, the
// weekly prizes, referral matches or the find badges. They have their own badge family.
//
// Variety (Marty's ask, 2026-09-26): a hunter is never asked the same question twice until they
// have answered every active question for that site, and the box leans toward the site with the
// most questions they have not seen yet. The options are shuffled per hunter per case. The bank
// grows from the admin (POST /api/admin/detective/question); per-question stats show which are
// worn and should be retired or replaced.
'use strict';
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const store = require('./store');
const missions = require('./missions');
const rewards = require('./rewards');
const SECRET = String(process.env.HUNT_CODE_SECRET || process.env.HUNT_SSO_SECRET || 'dev').trim();
const h = s => crypto.createHmac('sha256', SECRET).update('det:' + s).digest().readUInt32BE(0);
const ctDay = missions.ctDay;
const settings = () => { const s = rewards.settings(); return { on: s.detectiveOn == null ? true : !!Number(s.detectiveOn), pol: Number(s.detectivePol) > 0 ? Number(s.detectivePol) : 0.15, base: Math.max(1, Number(s.missionsPerDay) || 3) }; };
// ---- the bank -------------------------------------------------------------------------------
// seed from the repo, merged by id: questions already on the volume (edited or retired) win
function init() {
let seed = [];
try { seed = JSON.parse(fs.readFileSync(path.join(__dirname, 'detective-bank.json'), 'utf8')).questions || []; } catch (e) { console.error('detective seed', e.message); }
store.update('detective-bank', [], all => { const have = new Set(all.map(q => q.id)); for (const q of seed) if (!have.has(q.id)) all.push(q); return all; });
missions.onVisit = visited; // the embed tells us when a detective token has done its dwell on the right origin
}
function bank() { return store.read('detective-bank', []); }
function saveQuestion(q) {
const opts = (Array.isArray(q.options) ? q.options : []).map(o => String(o || '').trim().slice(0, 140)).filter(Boolean);
if (!q.missionId || !missions.get(String(q.missionId))) return { error: 'missionId must be an existing mission' };
if (!String(q.q || '').trim()) return { error: 'question text required' };
if (opts.length < 3 || opts.length > 5 || new Set(opts.map(o => o.toLowerCase())).size !== opts.length) return { error: 'three to five distinct options, the correct one first' };
let saved;
store.update('detective-bank', [], all => {
const id = q.id ? String(q.id).replace(/[^a-z0-9-]/gi, '').slice(0, 60) : String(q.missionId) + '-' + Date.now().toString(36);
const i = all.findIndex(x => x.id === id);
saved = Object.assign(i >= 0 ? all[i] : { id, added: ctDay() }, { missionId: String(q.missionId), q: String(q.q).trim().slice(0, 240), options: opts, fact: String(q.fact || '').slice(0, 300), active: q.active !== false });
if (i < 0) all.push(saved);
return all;
});
return { ok: true, question: saved };
}
function setActive(id, active) { let hit = false; store.update('detective-bank', [], all => { const q = all.find(x => x.id === id); if (q) { q.active = !!active; hit = true; } return all; }); return hit; }
const answers = () => store.read('answers', []);
function seenBy(memberId) { const m = new Map(); for (const a of answers()) if (a.memberId === Number(memberId)) m.set(a.qid, (m.get(a.qid) || 0) + 1); return m; }
// sites a case can be on: active house missions (not advertiser-paid) with at least one active question
function caseSites() {
const live = new Set(missions.list().filter(m => m.active && !m.paid).map(m => m.id));
const by = new Map(); for (const q of bank()) if (q.active !== false && live.has(q.missionId)) { if (!by.has(q.missionId)) by.set(q.missionId, []); by.get(q.missionId).push(q); }
return by;
}
// the site with the most questions this hunter has not answered; ties broken per hunter per day
function pickCase(memberId, day) {
const by = caseSites(); if (!by.size) return null;
const seen = seenBy(memberId);
const rows = [...by.entries()].map(([mid, qs]) => ({ mid, qs, fresh: qs.filter(q => !seen.get(q.id)).length, k: h(day + ':' + memberId + ':' + mid) }));
rows.sort((a, b) => b.fresh - a.fresh || a.k - b.k);
const pick = rows[0];
// within the site: the least-asked question for this hunter, ties broken the same way
const qs = pick.qs.map(q => ({ q, n: seen.get(q.id) || 0, k: h(day + ':' + memberId + ':' + q.id) })).sort((a, b) => a.n - b.n || a.k - b.k);
return { missionId: pick.mid, qid: qs[0].q.id };
}
// the options in this case's own order; the server alone knows which one is right (index 0 in the bank)
function order(box, q) { return q.options.map((o, i) => ({ i, k: h(box.id + ':' + q.id + ':' + i) })).sort((a, b) => a.k - b.k).map(x => x.i); }
// ---- the box ----------------------------------------------------------------------------------
const boxId = (memberId, day) => Number(memberId) + ':' + day;
function getBox(memberId, day) { return store.read('boxes', {})[boxId(memberId, day || ctDay())] || null; }
function putBox(b) { store.update('boxes', {}, all => { all[b.id] = b; return all; }); return b; }
function patchBox(id, patch) { let out = null; store.update('boxes', {}, all => { if (all[id]) { Object.assign(all[id], patch); out = all[id]; } return all; }); return out; }
function earned(me) { const s = settings(); return s.on && rewards.findsToday(me.memberId, ctDay()) >= s.base; }
// what the board shows
function view(me) {
const s = settings(); if (!s.on) return { on: false };
const day = ctDay(); const b = getBox(me.memberId, day);
const done = rewards.findsToday(me.memberId, day);
if (!b) return { on: true, status: done >= s.base ? 'ready' : 'locked', need: s.base, done: Math.min(done, s.base), pol: s.pol };
const m = missions.get(b.missionId) || {}; const q = bank().find(x => x.id === b.qid);
const out = { on: true, status: b.status, pol: b.pol, site: m.site || b.missionId, name: m.name || '', dwell: m.dwell || 30, url: b.url || null, expires: b.exp || null };
if (b.status === 'visited' && q) {
if (!b.shownAt) patchBox(b.id, { shownAt: Date.now() });
out.question = q.q; out.options = order(b, q).map(i => q.options[i]);
}
if (b.status === 'won' || b.status === 'missed') { out.question = q ? q.q : null; out.correct = b.status === 'won'; out.answer = q ? q.options[0] : null; }
return out;
}
function open(me) {
if (!earned(me)) return { error: 'Finish today’s Code Hunts first. The box unlocks when your last one is found.' };
const day = ctDay(); const cur = getBox(me.memberId, day); if (cur) return { ok: true, box: cur };
const c = pickCase(me.memberId, day); if (!c) return { error: 'No cases are open right now. Check back tomorrow.' };
let made = null;
// idempotent per member per day: a double tap or two tabs can never mint a second box
store.update('boxes', {}, all => { const id = boxId(me.memberId, day); if (!all[id]) all[id] = { id, memberId: Number(me.memberId), day, missionId: c.missionId, qid: c.qid, pol: settings().pol, status: 'open', openedAt: Date.now() }; made = all[id]; return all; });
return { ok: true, box: made };
}
function start(me) {
const b = getBox(me.memberId, ctDay()); if (!b) return { error: 'Open your Mystery Hunt Box first.' };
if (b.status === 'visited') return { error: 'You have been to the site. Your question is waiting on your board.' };
if (b.status === 'won' || b.status === 'missed') return { error: 'Today’s case is closed. A new box unlocks tomorrow.' };
const m = missions.get(b.missionId); if (!m || !m.active) return { error: 'That site is not open right now. Try again later.' };
// a live token is reused, so a second tap does not restart the dwell
const live = b.token && missions.token(b.token);
const t = live || missions.issue(me.memberId, m.id, { kind: 'detective', boxId: b.id });
const url = m.url.includes('{token}') ? m.url.replace('{token}', t.t) : m.url + '#ph=' + t.t;
patchBox(b.id, { status: 'started', token: t.t, url, exp: t.exp, startedAt: b.startedAt || Date.now() });
return { ok: true, url, dwell: m.dwell || 30, expires: t.exp };
}
// called by missions.codeForEmbed once a detective token has passed the origin and dwell locks
function visited(rec) {
if (!rec || rec.kind !== 'detective' || !rec.boxId) return;
store.update('boxes', {}, all => { const b = all[rec.boxId]; if (b && b.status === 'started' && b.token === rec.t) { b.status = 'visited'; b.visitedAt = Date.now(); } return all; });
}
function answer(me, choice) {
const b = getBox(me.memberId, ctDay()); if (!b) return { error: 'No case open today.' };
if (b.status === 'won' || b.status === 'missed') return { error: 'You already answered today’s case.' };
if (b.status !== 'visited') return { error: 'Visit the site first. The question unlocks once your visit is recorded.' };
const q = bank().find(x => x.id === b.qid); if (!q) return { error: 'That question was withdrawn. Tell support and we will make it right.' };
const ord = order(b, q); const n = Number(choice);
if (!Number.isInteger(n) || n < 0 || n >= ord.length) return { error: 'Pick one of the answers.' };
// claim the answer before anything else, so two taps or two tabs can only ever answer once
let claimed = false;
store.update('boxes', {}, all => { const x = all[b.id]; if (x && x.status === 'visited') { x.status = 'answering'; claimed = true; } return all; });
if (!claimed) return { error: 'You already answered today’s case.' };
const correct = ord[n] === 0; const at = Date.now();
store.update('answers', [], all => { all.push({ memberId: Number(me.memberId), boxId: b.id, missionId: b.missionId, qid: q.id, correct, picked: q.options[ord[n]], at, ms: b.shownAt ? at - b.shownAt : null }); return all; });
let g = null;
try {
if (correct) {
const m = missions.get(b.missionId) || { id: b.missionId, site: b.missionId };
g = rewards.grantFixed(me, { missionId: 'detective:' + m.id, site: m.site, pol: b.pol, detective: { boxId: b.id, qid: q.id } });
}
} finally {
// the answer is final either way; a grant that failed shows in the admin as a won box with no payout
patchBox(b.id, { status: correct ? 'won' : 'missed', answeredAt: at, payoutId: g && g.rec ? g.rec.id : null });
}
return { ok: true, correct, pol: correct ? b.pol : 0, queued: !!(g && g.queued), rec: g && g.rec, answer: q.options[0] };
}
// ---- stats for the admin -------------------------------------------------------------------------
function stats() {
const all = answers(); const by = new Map();
for (const a of all) { const r = by.get(a.qid) || { asked: 0, correct: 0 }; r.asked++; if (a.correct) r.correct++; by.set(a.qid, r); }
const boxes = Object.values(store.read('boxes', {})); const today = ctDay();
return {
settings: settings(),
questions: bank().map(q => Object.assign({}, q, by.get(q.id) || { asked: 0, correct: 0 })),
today: { boxes: boxes.filter(b => b.day === today).length, won: boxes.filter(b => b.day === today && b.status === 'won').length, missed: boxes.filter(b => b.day === today && b.status === 'missed').length },
recent: all.slice(-50).reverse(),
};
}
module.exports = { init, bank, saveQuestion, setActive, view, open, start, answer, visited, stats, pickCase, earned };
+7 -3
View File
@@ -41,9 +41,10 @@ function forMember(memberId) {
}
// ---- tokens ------------------------------------------------------------------------------
function issue(memberId, missionId) {
// extra: { kind: 'detective', boxId } for an Ad Detective case (lib/detective.js); a Code Hunt token has no kind
function issue(memberId, missionId, extra) {
const t = crypto.randomBytes(16).toString('hex');
const rec = { t, memberId: Number(memberId), missionId, iat: Date.now(), exp: Date.now() + TOKEN_TTL };
const rec = Object.assign({ t, memberId: Number(memberId), missionId, iat: Date.now(), exp: Date.now() + TOKEN_TTL }, extra || {});
store.update('tokens', {}, all => { for (const k of Object.keys(all)) if (all[k].exp < Date.now() - 3600000) delete all[k]; all[t] = rec; return all; });
return rec;
}
@@ -64,6 +65,8 @@ function codeForEmbed(t, origin) {
if (!allowed.includes(host)) return { error: 'origin' };
const waited = (Date.now() - rec.iat) / 1000;
if (waited < (m.dwell || 30)) return { wait: Math.ceil((m.dwell || 30) - waited) };
// an Ad Detective case shows no code: the visit itself is the receipt, and the question waits on the board
if (rec.kind === 'detective') { try { if (module.exports.onVisit) module.exports.onVisit(rec); } catch (e) { console.error('detective visit', e.message); } return { visited: true, slot: slotFor(rec, m.slots || 1) }; }
return { code: codeFor(rec), slot: slotFor(rec, m.slots || 1) };
}
@@ -71,6 +74,7 @@ function codeForEmbed(t, origin) {
function check(t, memberId, typed) {
const rec = token(t); if (!rec) return { error: 'That mission timed out. Start it again from your board.' };
if (rec.memberId !== Number(memberId)) return { error: 'That mission belongs to a different account.' };
if (rec.kind) return { error: 'That is an Ad Detective case. Answer its question on your board.' };
const want = codeFor(rec);
const got = String(typed || '').trim().toUpperCase();
if (got.length !== 6) return { error: 'Codes are 6 characters and you typed ' + got.length + '. Look at the site again: the code sits in six boxes, and a tap on it copies all six.' };
@@ -78,4 +82,4 @@ function check(t, memberId, typed) {
return { ok: true, rec };
}
module.exports = { list, get, save, remove, forMember, issue, token, codeForEmbed, check, ctDay };
module.exports = { list, get, save, remove, forMember, issue, token, codeForEmbed, check, ctDay, onVisit: null };
+154 -154
View File
@@ -1,154 +1,154 @@
// Advertiser-funded missions (Marty, 2026-09-24).
//
// A member buys a mission: they pay POL into the faucet wallet, and hunters who complete it are
// dripped out of what they paid. Two rules follow from that, and everything here exists to hold
// them:
//
// 1. A paid completion is NOT house spend. It does not count against dailyCapPol, and it does
// not use up one of the hunter's missionsPerDay. Each live paid mission raises that hunter's
// allowance by one, because the company is not funding it. ("Each additional mission paid by
// an advertiser should allow +1 above the cap.")
//
// 2. THE SOLVENCY RULE. The faucet is one wallet holding house float AND every advertiser's
// unspent reserve. If reserves ever exceed the balance we have sold delivery we cannot pay
// for, and a hunter completes a mission only to watch the drip fail. So:
//
// faucet balance >= house float + sum(outstanding reserves)
//
// checked before a sale is accepted, never after.
//
// Money in is split at purchase: the hunter payout is reserved, the rest is company margin the
// P&L can recognise. The advertiser sets the hunter payout themselves (base 0.30, they may pay
// more to get completed sooner), so the reserve is exact rather than estimated. No draw, no
// variance, no guessing.
'use strict';
const store = require('./store');
const DEFAULTS = {
paidEnabled: 1,
paidBaseHunterPol: 0.30, // the floor an advertiser may set as the hunter's payout
// The company's share, on the SAME BASIS as InstantAdPay's platform 20%: a percentage of what
// the advertiser pays, not a mark-up on the reserve. So at 20 the hunters get 80% of the
// purchase and the house keeps 20, which is the number members already understand.
paidMarginPct: 20,
paidMinBlock: 100, // completions per block
paidMaxConcurrent: 0, // 0 = no limit; supply is elastic now that paid missions add capacity
// Every drip is its own transaction and the faucet pays the gas. Measured at 0.0060 POL across
// recent payouts (21,000 gas, the plain-transfer floor); held at 0.01 so a busy chain cannot
// turn a sold mission into a shortfall. Without this the gas came quietly out of house money.
paidGasPol: 0.01,
// Marty, 2026-09-24: happy to hold more back than the arithmetic demands. Applied to drips and
// gas together, so a failed-and-retried send or a price spike is already covered.
paidReserveBufferPct: 10,
paidHouseFloatPol: 50, // POL kept back for house missions, never counted as sellable
// Priced in dollars because that is what a buyer judges; converted at the InstantAdPay
// contract's own rate at purchase (Marty, 2026-09-24).
paidBlockCents: 3000, // $30 a block
paidListingCents: 1000, // $10, once per mission, charged AT APPROVAL after the review is done
paidListingFreeBlocks: 4, // a first order this size or larger gets the listing free
};
function cfg() { return Object.assign({}, DEFAULTS, store.read('settings', {})); }
const r4 = n => Math.round(Number(n) * 10000) / 10000;
// ---- what a block costs -----------------------------------------------------------------
// hunterPol is what each completing hunter receives; the advertiser pays that plus the margin.
function quote(hunterPol, completions) {
const c = cfg();
const hp = r4(Math.max(Number(c.paidBaseHunterPol), Number(hunterPol) || 0));
const n = Math.max(Number(c.paidMinBlock), Math.round(Number(completions) || 0));
// What must actually be held: the drips, the gas to send them, and the safety buffer.
const drips = r4(hp * n);
const gas = r4(Number(c.paidGasPol) * n);
const buf = Math.max(0, Number(c.paidReserveBufferPct) || 0);
const reserve = r4((drips + gas) * (1 + buf / 100));
// Margin is a share of what the advertiser pays, the same basis as InstantAdPay's platform 20%.
const pct = Math.min(90, Math.max(0, Number(c.paidMarginPct) || 0));
const total = r4(reserve / (1 - pct / 100));
return { hunterPol: hp, completions: n, drips, gas, bufferPct: buf, reserve,
margin: r4(total - reserve), total, marginPct: pct };
}
// How many completions a block buys. The inverse of quote(): the advertiser fixes the spend and
// the payout they want hunters to get, and the completion count falls out.
//
// NOTE, because it is easy to get backwards: with a fixed-price block the house margin is the
// same whatever the payout. Raising the payout trades completions for SPEED at the same price,
// it does not earn the house more. Margin only moves with the number of blocks sold. So the
// upsell is "more blocks", and a higher payout is the reason a buyer needs more of them.
function blockFor(hunterPol, totalPol) {
const c = cfg();
const hp = r4(Math.max(Number(c.paidBaseHunterPol), Number(hunterPol) || 0));
const gas = Number(c.paidGasPol) || 0;
const buf = 1 + (Math.max(0, Number(c.paidReserveBufferPct) || 0) / 100);
const pct = Math.min(90, Math.max(0, Number(c.paidMarginPct) || 0));
const reserve = Number(totalPol) * (1 - pct / 100);
const n = Math.floor(reserve / ((hp + gas) * buf));
return Object.assign(quote(hp, n), { requestedPol: r4(Number(totalPol)) });
}
// What this order costs all in. The listing fee is charged ONCE per mission, at approval, because
// it pays for the review that has already happened by then. It is never charged again on that
// mission, and a first order of paidListingFreeBlocks or more waives it: a serious first buyer
// should not be taxed for the privilege.
function orderTotal(blocks, alreadyListed) {
const c = cfg();
const n = Math.max(1, Math.round(Number(blocks) || 1));
const blockCents = Number(c.paidBlockCents) * n;
const waived = alreadyListed || n >= Number(c.paidListingFreeBlocks);
const listingCents = waived ? 0 : Number(c.paidListingCents);
return { blocks: n, blockCents, listingCents, totalCents: blockCents + listingCents,
listingWaived: waived, listingReason: alreadyListed ? 'already listed' : (waived ? 'waived, ' + n + ' blocks' : 'first order') };
}
// ---- reserves ---------------------------------------------------------------------------
const paidMissions = () => store.read('missions', []).filter(m => m.paid);
// completions already granted against a mission (failed ones do not count, they never paid)
function usedOf(missionId) {
return store.read('payouts', []).filter(p => p.missionId === missionId && p.status !== 'failed' && !p.prize && !p.ref).length;
}
// what every live paid mission still owes its hunters
function outstanding() {
let pol = 0, left = 0;
const c = cfg();
const gas = Number(c.paidGasPol) || 0;
const buf = 1 + (Math.max(0, Number(c.paidReserveBufferPct) || 0) / 100);
for (const m of paidMissions()) {
const remaining = Math.max(0, Number(m.budget || 0) - usedOf(m.id));
left += remaining;
// reserved on the same basis it was sold on: drip + gas + buffer, per completion still owed
pol += remaining * (Number(m.hunterPol || 0) + gas) * buf;
}
return { reservePol: r4(pol), completionsLeft: left, missions: paidMissions().length };
}
// THE guard. Given the faucet's real balance, can we take this sale?
function canSell(balancePol, addReservePol) {
const c = cfg();
const o = outstanding();
const float = Number(c.paidHouseFloatPol) || 0;
const committed = r4(o.reservePol + float + Number(addReservePol || 0));
const bal = r4(Number(balancePol) || 0);
return {
ok: bal >= committed,
balance: bal, committed, houseFloat: float,
alreadyReserved: o.reservePol, adding: r4(Number(addReservePol) || 0),
shortBy: bal >= committed ? 0 : r4(committed - bal),
};
}
// ---- the hunter's allowance ---------------------------------------------------------------
// Base allowance is the company-funded missionsPerDay. Every live paid mission the hunter has
// not yet done adds one, because that completion costs the company nothing.
function extraAllowance(doneIds) {
const done = doneIds instanceof Set ? doneIds : new Set(doneIds || []);
return paidMissions().filter(m => m.active && !done.has(m.id) && Math.max(0, Number(m.budget || 0) - usedOf(m.id)) > 0).length;
}
function isPaid(missionId) {
const m = store.read('missions', []).find(x => x.id === missionId);
return !!(m && m.paid);
}
module.exports = { cfg, quote, blockFor, orderTotal, outstanding, canSell, extraAllowance, isPaid, usedOf, paidMissions };
// Advertiser-funded missions (Marty, 2026-09-24).
//
// A member buys a mission: they pay POL into the faucet wallet, and hunters who complete it are
// dripped out of what they paid. Two rules follow from that, and everything here exists to hold
// them:
//
// 1. A paid completion is NOT house spend. It does not count against dailyCapPol, and it does
// not use up one of the hunter's missionsPerDay. Each live paid mission raises that hunter's
// allowance by one, because the company is not funding it. ("Each additional mission paid by
// an advertiser should allow +1 above the cap.")
//
// 2. THE SOLVENCY RULE. The faucet is one wallet holding house float AND every advertiser's
// unspent reserve. If reserves ever exceed the balance we have sold delivery we cannot pay
// for, and a hunter completes a mission only to watch the drip fail. So:
//
// faucet balance >= house float + sum(outstanding reserves)
//
// checked before a sale is accepted, never after.
//
// Money in is split at purchase: the hunter payout is reserved, the rest is company margin the
// P&L can recognise. The advertiser sets the hunter payout themselves (base 0.30, they may pay
// more to get completed sooner), so the reserve is exact rather than estimated. No draw, no
// variance, no guessing.
'use strict';
const store = require('./store');
const DEFAULTS = {
paidEnabled: 1,
paidBaseHunterPol: 0.30, // the floor an advertiser may set as the hunter's payout
// The company's share, on the SAME BASIS as InstantAdPay's platform 20%: a percentage of what
// the advertiser pays, not a mark-up on the reserve. So at 20 the hunters get 80% of the
// purchase and the house keeps 20, which is the number members already understand.
paidMarginPct: 20,
paidMinBlock: 100, // completions per block
paidMaxConcurrent: 0, // 0 = no limit; supply is elastic now that paid missions add capacity
// Every drip is its own transaction and the faucet pays the gas. Measured at 0.0060 POL across
// recent payouts (21,000 gas, the plain-transfer floor); held at 0.01 so a busy chain cannot
// turn a sold mission into a shortfall. Without this the gas came quietly out of house money.
paidGasPol: 0.01,
// Marty, 2026-09-24: happy to hold more back than the arithmetic demands. Applied to drips and
// gas together, so a failed-and-retried send or a price spike is already covered.
paidReserveBufferPct: 10,
paidHouseFloatPol: 50, // POL kept back for house missions, never counted as sellable
// Priced in dollars because that is what a buyer judges; converted at the InstantAdPay
// contract's own rate at purchase (Marty, 2026-09-24).
paidBlockCents: 3000, // $30 a block
paidListingCents: 1000, // $10, once per mission, charged AT APPROVAL after the review is done
paidListingFreeBlocks: 4, // a first order this size or larger gets the listing free
};
function cfg() { return Object.assign({}, DEFAULTS, store.read('settings', {})); }
const r4 = n => Math.round(Number(n) * 10000) / 10000;
// ---- what a block costs -----------------------------------------------------------------
// hunterPol is what each completing hunter receives; the advertiser pays that plus the margin.
function quote(hunterPol, completions) {
const c = cfg();
const hp = r4(Math.max(Number(c.paidBaseHunterPol), Number(hunterPol) || 0));
const n = Math.max(Number(c.paidMinBlock), Math.round(Number(completions) || 0));
// What must actually be held: the drips, the gas to send them, and the safety buffer.
const drips = r4(hp * n);
const gas = r4(Number(c.paidGasPol) * n);
const buf = Math.max(0, Number(c.paidReserveBufferPct) || 0);
const reserve = r4((drips + gas) * (1 + buf / 100));
// Margin is a share of what the advertiser pays, the same basis as InstantAdPay's platform 20%.
const pct = Math.min(90, Math.max(0, Number(c.paidMarginPct) || 0));
const total = r4(reserve / (1 - pct / 100));
return { hunterPol: hp, completions: n, drips, gas, bufferPct: buf, reserve,
margin: r4(total - reserve), total, marginPct: pct };
}
// How many completions a block buys. The inverse of quote(): the advertiser fixes the spend and
// the payout they want hunters to get, and the completion count falls out.
//
// NOTE, because it is easy to get backwards: with a fixed-price block the house margin is the
// same whatever the payout. Raising the payout trades completions for SPEED at the same price,
// it does not earn the house more. Margin only moves with the number of blocks sold. So the
// upsell is "more blocks", and a higher payout is the reason a buyer needs more of them.
function blockFor(hunterPol, totalPol) {
const c = cfg();
const hp = r4(Math.max(Number(c.paidBaseHunterPol), Number(hunterPol) || 0));
const gas = Number(c.paidGasPol) || 0;
const buf = 1 + (Math.max(0, Number(c.paidReserveBufferPct) || 0) / 100);
const pct = Math.min(90, Math.max(0, Number(c.paidMarginPct) || 0));
const reserve = Number(totalPol) * (1 - pct / 100);
const n = Math.floor(reserve / ((hp + gas) * buf));
return Object.assign(quote(hp, n), { requestedPol: r4(Number(totalPol)) });
}
// What this order costs all in. The listing fee is charged ONCE per mission, at approval, because
// it pays for the review that has already happened by then. It is never charged again on that
// mission, and a first order of paidListingFreeBlocks or more waives it: a serious first buyer
// should not be taxed for the privilege.
function orderTotal(blocks, alreadyListed) {
const c = cfg();
const n = Math.max(1, Math.round(Number(blocks) || 1));
const blockCents = Number(c.paidBlockCents) * n;
const waived = alreadyListed || n >= Number(c.paidListingFreeBlocks);
const listingCents = waived ? 0 : Number(c.paidListingCents);
return { blocks: n, blockCents, listingCents, totalCents: blockCents + listingCents,
listingWaived: waived, listingReason: alreadyListed ? 'already listed' : (waived ? 'waived, ' + n + ' blocks' : 'first order') };
}
// ---- reserves ---------------------------------------------------------------------------
const paidMissions = () => store.read('missions', []).filter(m => m.paid);
// completions already granted against a mission (failed ones do not count, they never paid)
function usedOf(missionId) {
return store.read('payouts', []).filter(p => p.missionId === missionId && p.status !== 'failed' && !p.prize && !p.ref && !p.detective).length;
}
// what every live paid mission still owes its hunters
function outstanding() {
let pol = 0, left = 0;
const c = cfg();
const gas = Number(c.paidGasPol) || 0;
const buf = 1 + (Math.max(0, Number(c.paidReserveBufferPct) || 0) / 100);
for (const m of paidMissions()) {
const remaining = Math.max(0, Number(m.budget || 0) - usedOf(m.id));
left += remaining;
// reserved on the same basis it was sold on: drip + gas + buffer, per completion still owed
pol += remaining * (Number(m.hunterPol || 0) + gas) * buf;
}
return { reservePol: r4(pol), completionsLeft: left, missions: paidMissions().length };
}
// THE guard. Given the faucet's real balance, can we take this sale?
function canSell(balancePol, addReservePol) {
const c = cfg();
const o = outstanding();
const float = Number(c.paidHouseFloatPol) || 0;
const committed = r4(o.reservePol + float + Number(addReservePol || 0));
const bal = r4(Number(balancePol) || 0);
return {
ok: bal >= committed,
balance: bal, committed, houseFloat: float,
alreadyReserved: o.reservePol, adding: r4(Number(addReservePol) || 0),
shortBy: bal >= committed ? 0 : r4(committed - bal),
};
}
// ---- the hunter's allowance ---------------------------------------------------------------
// Base allowance is the company-funded missionsPerDay. Every live paid mission the hunter has
// not yet done adds one, because that completion costs the company nothing.
function extraAllowance(doneIds) {
const done = doneIds instanceof Set ? doneIds : new Set(doneIds || []);
return paidMissions().filter(m => m.active && !done.has(m.id) && Math.max(0, Number(m.budget || 0) - usedOf(m.id)) > 0).length;
}
function isPaid(missionId) {
const m = store.read('missions', []).find(x => x.id === missionId);
return !!(m && m.paid);
}
module.exports = { cfg, quote, blockFor, orderTotal, outstanding, canSell, extraAllowance, isPaid, usedOf, paidMissions };
+248 -248
View File
@@ -1,248 +1,248 @@
// Referral rewards (Marty, 2026-09-23).
//
// PolHunter retains well and recruits badly: on 2026-09-22 it had its best day ever, 105 finds
// from 37 hunters, and had sent three people to InstantAdPay in its whole life, all three on one
// member's link. Earning and sharing were separate actions and only one of them paid. This makes
// bringing someone the best-paid thing on the board.
//
// Two payments, both to the REFERRER, both out of a pool of their own so a good referral day can
// never starve the finds:
// bounty a flat drip the first time someone they brought completes a find, paid once per person
// match a slice of every find that person makes while they are still new
//
// Who counts as "brought by me" is not a cookie PolHunter guessed at. It is the sponsor the member
// actually joined InstantAdPay under, handed over in the sign-in payload as sponsorRef, so the
// bounty and the InstantAdPay commission always land on the same person.
'use strict';
const store = require('./store');
const rewards = require('./rewards');
const { ctDay } = require('./missions');
const DEFAULTS = {
refEnabled: 1,
refBountyPol: 3, // flat, not a draw: a referral is work someone did, not a lottery
refMatchPct: 20, // paid ON TOP of the newcomer's find, never taken out of it
refMatchDays: 30, // how long the match runs, from the newcomer's InstantAdPay join date
// THE gate, and it has to be an absolute date, not a rolling window. It was refNewDays: 30 on a
// site whose oldest account is 19 days old, so it excluded nobody and 8.67 POL went to sponsors
// for existing members hunting — zero acquisitions (Marty, 2026-09-23: "I need people that never
// existed before. That's why we're doing it."). Anyone whose account predates this moment was
// already a member, by definition, and can never earn their sponsor a bounty or a match.
refNewAfter: '2026-09-23T10:00:00Z',
refRequireOrigin: 1, // only pay for members PolHunter actually sent (joinedRef)
// Member ids forgiven the origin check, comma separated. For people whose match had ALREADY
// started paying before the rule existed: stopping it mid-stream would be taking back something
// they were told they had earned (Marty, 2026-09-24, on skycash and toplinzy). It forgives ONLY
// the origin test. The new-member floor still applies, and bountyPaidFor still stops a second
// bounty, so an exemption can pay the running match and nothing else.
refOriginExempt: '',
refNewDays: 30, // secondary: a newcomer only earns their sponsor a bounty in their first
// month, so a dormant signup cannot trigger one a year later
refCapPol: 20, // referral pool per Central day, separate from the find pool
refMatchMinPol: 0.005,// do not write a transaction for dust
// Marty's launch bonus (2026-09-23): an extra drip to the FIRST hunter whose referral gets all
// the way through. Once ever, never again. Set to 0 to retire it.
refFirstBonusPol: 5,
};
function cfg() { return Object.assign({}, DEFAULTS, store.read('settings', {})); }
const round4 = n => Math.round(Number(n) * 10000) / 10000;
const norm = s => String(s || '').trim().toLowerCase();
// forgiven the origin check by name, because their match was already running when the rule landed
function exempt(c, memberId) {
return String(c.refOriginExempt || '').split(/[,\s]+/).map(Number).filter(n => n > 0).includes(Number(memberId));
}
// ---- the hunter directory -------------------------------------------------------------------
// Every sign-in upserts the member here, so the referral graph survives session expiry and we
// always have a wallet to pay the referrer at.
function seen(claims) {
const id = Number(claims.memberId);
if (!id) return null;
const all = store.update('hunters', {}, h => {
const cur = h[id] || { memberId: id, firstSeen: Date.now() };
if (claims.email) cur.email = norm(claims.email);
if (claims.username) cur.username = String(claims.username);
if (claims.wallet) cur.wallet = norm(claims.wallet);
if (claims.sponsorRef) cur.sponsorRef = norm(claims.sponsorRef);
if (claims.joinedAt) cur.joinedAt = Number(claims.joinedAt);
if (claims.joinedRef) cur.joinedRef = String(claims.joinedRef).toLowerCase();
cur.lastSeen = Date.now();
h[id] = cur;
return h;
});
return all[id];
}
function hunter(memberId) { return store.read('hunters', {})[Number(memberId)] || null; }
function keysOf(h) { return [norm(h.username), String(h.memberId)].filter(Boolean); }
// the referrer has to be a hunter themselves: we pay into a wallet we have seen, and nobody
// earns from a board they have never opened
function referrerOf(memberId) {
const me = hunter(memberId);
if (!me || !me.sponsorRef) return null;
const all = store.read('hunters', {});
for (const k of Object.keys(all)) {
const x = all[k];
if (Number(x.memberId) === Number(memberId)) continue;
if (keysOf(x).includes(me.sponsorRef)) return x;
}
return null;
}
function broughtBy(memberId) {
const me = hunter(memberId);
if (!me) return [];
const keys = keysOf(me);
return Object.values(store.read('hunters', {}))
.filter(x => Number(x.memberId) !== Number(memberId) && x.sponsorRef && keys.includes(x.sponsorRef))
.sort((a, b) => (a.firstSeen || 0) - (b.firstSeen || 0));
}
// ---- the pool -------------------------------------------------------------------------------
const refRows = () => store.read('payouts', []).filter(p => p.ref && p.status !== 'failed');
function paidRefToday(day) { return refRows().filter(p => p.day === (day || ctDay())).reduce((n, p) => n + p.pol, 0); }
function refPool() {
const c = cfg();
const cap = Number(c.refCapPol), today = round4(paidRefToday());
return { capPol: cap, todayPol: today, left: round4(Math.max(0, cap - today)), resetsAt: rewards.nextResetAt() };
}
function write(referrer, pol, ref) {
const rec = {
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 8),
memberId: Number(referrer.memberId), email: referrer.email || null, wallet: referrer.wallet, username: referrer.username || null,
missionId: 'ref:' + ref.kind,
site: ref.kind === 'bounty' ? 'Referral bounty' : ref.kind === 'first-bonus' ? 'First referral bonus' : 'Referral match',
pol: round4(pol), day: ctDay(), at: Date.now(),
status: 'due', tx: null, paidAt: null, error: null, ref,
};
store.update('payouts', [], all => { all.push(rec); return all; });
return rec;
}
const bountyPaidFor = id => refRows().some(p => p.ref.kind === 'bounty' && Number(p.ref.forMemberId) === Number(id));
// ---- the hook: called right after a find is recorded ------------------------------------------
// Returns the drips it created, so the caller can post the bounty to Telegram.
function onFind(member, find) {
const c = cfg();
if (String(c.refEnabled) !== '1') return [];
const id = Number(member.memberId);
const me = hunter(id) || {};
const referrer = referrerOf(id);
if (!referrer || !referrer.wallet || Number(referrer.memberId) === id) return [];
const out = [];
let room = Number(c.refCapPol) - paidRefToday();
const ageDays = me.joinedAt ? (Date.now() - Number(me.joinedAt)) / 86400000 : 0;
// the floor: did this person exist before the mission did?
// This gate FAILS CLOSED and must stay that way. No floor configured, a blank or mistyped
// date, or a member with no InstantAdPay join date on file: nobody gets paid. The last version
// of this line paid out whenever the setting did not exclude anyone, which is how 8.67 POL went
// to sponsors of members who already existed. A referral only counts if the person did not
// exist in InstantAdPay before the mission did.
const floor = Date.parse(String(c.refNewAfter || ''));
if (!Number.isFinite(floor) || floor <= 0) return [];
if (!me.joinedAt || Number(me.joinedAt) < floor) return [];
// AND PolHunter has to have actually sent them. The account being new is not enough: somebody who
// joined InstantAdPay off an email, a banner or another site and only later wandered over here was
// never a PolHunter acquisition, and paying a bounty for them defeats the point (Marty,
// 2026-09-24). The proof is InstantAdPay's first-touch source, handed over signed in the sign-in
// payload; a share link stamps it polhunter.com from the URL itself, so a stripped referrer does
// not lose a genuine referral. Fails closed: no origin on file pays nobody.
// only an explicit '0' turns this off: a typo or a stray value must leave the gate standing,
// the same way the floor does
const viaHunt = /polhunter/i.test(String(me.joinedRef || ''));
const forgiven = !viaHunt && exempt(c, id); // origin forgiven, but MATCH ONLY, see below
if (String(c.refRequireOrigin) !== '0' && !viaHunt && !forgiven) return [];
const who = { forMemberId: id, forName: me.username || ('#' + id) };
// the bounty, once, on their first find, and only while they are genuinely a new member
const finds = store.read('payouts', []).filter(p => Number(p.memberId) === id && !p.ref && !p.prize && p.status !== 'failed');
// `forgiven` covers a match that was already running when the origin rule landed. It must NEVER
// open a new bounty, or an exemption becomes the same hole again wearing a config field.
if (!forgiven && finds.length <= 1 && ageDays <= Number(c.refNewDays) && !bountyPaidFor(id)) {
const pol = Number(c.refBountyPol);
if (pol <= room) {
const firstEver = !refRows().some(p => p.ref.kind === 'bounty');
out.push(write(referrer, pol, Object.assign({ kind: 'bounty' }, who))); room -= pol;
// the launch bonus rides along with the very first bounty anyone earns, once ever. It is
// deliberately outside the daily referral ceiling: it is a single payment, not a rate.
const bonus = Number(c.refFirstBonusPol) || 0;
if (firstEver && bonus > 0 && !refRows().some(p => p.ref.kind === 'first-bonus')) {
out.push(write(referrer, bonus, Object.assign({ kind: 'first-bonus' }, who)));
}
}
}
// the match, on every find inside the window, paid on top and never deducted from the newcomer
if (ageDays <= Number(c.refMatchDays)) {
const pol = round4(Number(find.pol) * Number(c.refMatchPct) / 100);
if (pol >= Number(c.refMatchMinPol) && pol <= room) out.push(write(referrer, pol, Object.assign({ kind: 'match', findId: find.id, findPol: find.pol }, who)));
}
return out;
}
// ---- what the board shows ---------------------------------------------------------------------
function state(member) {
const c = cfg();
const id = Number(member.memberId);
const me = hunter(id) || { memberId: id };
const rows = refRows().filter(p => Number(p.memberId) === id);
const today = ctDay();
// the same floor onFind pays by, so the card can never promise an earning it will not make
const floor = Date.parse(String(c.refNewAfter || ''));
const gateOk = Number.isFinite(floor) && floor > 0;
const needOrigin = String(c.refRequireOrigin) !== '0';
const mine = broughtBy(id).map(x => {
const theirFinds = store.read('payouts', []).filter(p => Number(p.memberId) === Number(x.memberId) && !p.ref && !p.prize && p.status !== 'failed');
const paid = bountyPaidFor(x.memberId);
const viaHunt = /polhunter/i.test(String(x.joinedRef || '')) || exempt(c, x.memberId);
// qualifying means BOTH: new to InstantAdPay, and sent here by PolHunter
const isNew = !!(gateOk && x.joinedAt && Number(x.joinedAt) >= floor && (!needOrigin || viaHunt));
return {
name: x.username || ('#' + x.memberId),
// when they actually joined InstantAdPay, not when this directory first noticed them:
// the backfill stamped firstSeen at seeding time and made everyone look brought-in today
joinedAt: x.joinedAt || x.firstSeen || null,
finds: theirFinds.length,
// an account that predates the mission was already a member: say so plainly rather than
// show them as 'hunting' next to a bounty that will never arrive
isNew, viaHunt,
// say exactly which condition they miss, so nobody waits on a bounty that will not come
state: !isNew
? (gateOk && x.joinedAt && Number(x.joinedAt) < floor
? 'already a member before the mission, earns nothing'
: 'joined InstantAdPay some other way, not through your link')
: paid ? 'earning' : theirFinds.length ? 'hunting' : 'signed up, no find yet',
stillNew: isNew && (Date.now() - Number(x.joinedAt)) / 86400000 <= Number(c.refMatchDays),
};
});
return {
on: String(c.refEnabled) === '1',
bountyPol: Number(c.refBountyPol),
firstBonusPol: refRows().some(p => p.ref.kind === 'first-bonus') ? 0 : Number(c.refFirstBonusPol) || 0,
matchPct: Number(c.refMatchPct),
matchDays: Number(c.refMatchDays),
brought: mine.length,
broughtNew: mine.filter(x => x.isNew).length, // the only ones that can ever pay
broughtToday: mine.filter(x => x.joinedAt && ctDay(x.joinedAt) === today).length,
earnedPol: round4(rows.reduce((n, p) => n + p.pol, 0)),
earnedTodayPol: round4(rows.filter(p => p.day === today).reduce((n, p) => n + p.pol, 0)),
people: mine.slice(0, 25),
pool: refPool(),
};
}
function totals() {
const rows = refRows();
const paid = rows.filter(p => p.status === 'paid');
return {
bounties: rows.filter(p => p.ref.kind === 'bounty').length,
matches: rows.filter(p => p.ref.kind === 'match').length,
firstBonus: (() => { const b = rows.find(p => p.ref.kind === 'first-bonus'); return b ? { who: b.username || ('#' + b.memberId), pol: b.pol, at: b.at, status: b.status } : null; })(),
pol: round4(rows.reduce((n, p) => n + p.pol, 0)),
paidPol: round4(paid.reduce((n, p) => n + p.pol, 0)),
referrers: new Set(rows.map(p => p.memberId)).size,
};
}
module.exports = { seen, hunter, referrerOf, broughtBy, onFind, state, totals, refPool, cfg, paidRefToday };
// Referral rewards (Marty, 2026-09-23).
//
// PolHunter retains well and recruits badly: on 2026-09-22 it had its best day ever, 105 finds
// from 37 hunters, and had sent three people to InstantAdPay in its whole life, all three on one
// member's link. Earning and sharing were separate actions and only one of them paid. This makes
// bringing someone the best-paid thing on the board.
//
// Two payments, both to the REFERRER, both out of a pool of their own so a good referral day can
// never starve the finds:
// bounty a flat drip the first time someone they brought completes a find, paid once per person
// match a slice of every find that person makes while they are still new
//
// Who counts as "brought by me" is not a cookie PolHunter guessed at. It is the sponsor the member
// actually joined InstantAdPay under, handed over in the sign-in payload as sponsorRef, so the
// bounty and the InstantAdPay commission always land on the same person.
'use strict';
const store = require('./store');
const rewards = require('./rewards');
const { ctDay } = require('./missions');
const DEFAULTS = {
refEnabled: 1,
refBountyPol: 3, // flat, not a draw: a referral is work someone did, not a lottery
refMatchPct: 20, // paid ON TOP of the newcomer's find, never taken out of it
refMatchDays: 30, // how long the match runs, from the newcomer's InstantAdPay join date
// THE gate, and it has to be an absolute date, not a rolling window. It was refNewDays: 30 on a
// site whose oldest account is 19 days old, so it excluded nobody and 8.67 POL went to sponsors
// for existing members hunting — zero acquisitions (Marty, 2026-09-23: "I need people that never
// existed before. That's why we're doing it."). Anyone whose account predates this moment was
// already a member, by definition, and can never earn their sponsor a bounty or a match.
refNewAfter: '2026-09-23T10:00:00Z',
refRequireOrigin: 1, // only pay for members PolHunter actually sent (joinedRef)
// Member ids forgiven the origin check, comma separated. For people whose match had ALREADY
// started paying before the rule existed: stopping it mid-stream would be taking back something
// they were told they had earned (Marty, 2026-09-24, on skycash and toplinzy). It forgives ONLY
// the origin test. The new-member floor still applies, and bountyPaidFor still stops a second
// bounty, so an exemption can pay the running match and nothing else.
refOriginExempt: '',
refNewDays: 30, // secondary: a newcomer only earns their sponsor a bounty in their first
// month, so a dormant signup cannot trigger one a year later
refCapPol: 20, // referral pool per Central day, separate from the find pool
refMatchMinPol: 0.005,// do not write a transaction for dust
// Marty's launch bonus (2026-09-23): an extra drip to the FIRST hunter whose referral gets all
// the way through. Once ever, never again. Set to 0 to retire it.
refFirstBonusPol: 5,
};
function cfg() { return Object.assign({}, DEFAULTS, store.read('settings', {})); }
const round4 = n => Math.round(Number(n) * 10000) / 10000;
const norm = s => String(s || '').trim().toLowerCase();
// forgiven the origin check by name, because their match was already running when the rule landed
function exempt(c, memberId) {
return String(c.refOriginExempt || '').split(/[,\s]+/).map(Number).filter(n => n > 0).includes(Number(memberId));
}
// ---- the hunter directory -------------------------------------------------------------------
// Every sign-in upserts the member here, so the referral graph survives session expiry and we
// always have a wallet to pay the referrer at.
function seen(claims) {
const id = Number(claims.memberId);
if (!id) return null;
const all = store.update('hunters', {}, h => {
const cur = h[id] || { memberId: id, firstSeen: Date.now() };
if (claims.email) cur.email = norm(claims.email);
if (claims.username) cur.username = String(claims.username);
if (claims.wallet) cur.wallet = norm(claims.wallet);
if (claims.sponsorRef) cur.sponsorRef = norm(claims.sponsorRef);
if (claims.joinedAt) cur.joinedAt = Number(claims.joinedAt);
if (claims.joinedRef) cur.joinedRef = String(claims.joinedRef).toLowerCase();
cur.lastSeen = Date.now();
h[id] = cur;
return h;
});
return all[id];
}
function hunter(memberId) { return store.read('hunters', {})[Number(memberId)] || null; }
function keysOf(h) { return [norm(h.username), String(h.memberId)].filter(Boolean); }
// the referrer has to be a hunter themselves: we pay into a wallet we have seen, and nobody
// earns from a board they have never opened
function referrerOf(memberId) {
const me = hunter(memberId);
if (!me || !me.sponsorRef) return null;
const all = store.read('hunters', {});
for (const k of Object.keys(all)) {
const x = all[k];
if (Number(x.memberId) === Number(memberId)) continue;
if (keysOf(x).includes(me.sponsorRef)) return x;
}
return null;
}
function broughtBy(memberId) {
const me = hunter(memberId);
if (!me) return [];
const keys = keysOf(me);
return Object.values(store.read('hunters', {}))
.filter(x => Number(x.memberId) !== Number(memberId) && x.sponsorRef && keys.includes(x.sponsorRef))
.sort((a, b) => (a.firstSeen || 0) - (b.firstSeen || 0));
}
// ---- the pool -------------------------------------------------------------------------------
const refRows = () => store.read('payouts', []).filter(p => p.ref && p.status !== 'failed');
function paidRefToday(day) { return refRows().filter(p => p.day === (day || ctDay())).reduce((n, p) => n + p.pol, 0); }
function refPool() {
const c = cfg();
const cap = Number(c.refCapPol), today = round4(paidRefToday());
return { capPol: cap, todayPol: today, left: round4(Math.max(0, cap - today)), resetsAt: rewards.nextResetAt() };
}
function write(referrer, pol, ref) {
const rec = {
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 8),
memberId: Number(referrer.memberId), email: referrer.email || null, wallet: referrer.wallet, username: referrer.username || null,
missionId: 'ref:' + ref.kind,
site: ref.kind === 'bounty' ? 'Referral bounty' : ref.kind === 'first-bonus' ? 'First referral bonus' : 'Referral match',
pol: round4(pol), day: ctDay(), at: Date.now(),
status: 'due', tx: null, paidAt: null, error: null, ref,
};
store.update('payouts', [], all => { all.push(rec); return all; });
return rec;
}
const bountyPaidFor = id => refRows().some(p => p.ref.kind === 'bounty' && Number(p.ref.forMemberId) === Number(id));
// ---- the hook: called right after a find is recorded ------------------------------------------
// Returns the drips it created, so the caller can post the bounty to Telegram.
function onFind(member, find) {
const c = cfg();
if (String(c.refEnabled) !== '1') return [];
const id = Number(member.memberId);
const me = hunter(id) || {};
const referrer = referrerOf(id);
if (!referrer || !referrer.wallet || Number(referrer.memberId) === id) return [];
const out = [];
let room = Number(c.refCapPol) - paidRefToday();
const ageDays = me.joinedAt ? (Date.now() - Number(me.joinedAt)) / 86400000 : 0;
// the floor: did this person exist before the mission did?
// This gate FAILS CLOSED and must stay that way. No floor configured, a blank or mistyped
// date, or a member with no InstantAdPay join date on file: nobody gets paid. The last version
// of this line paid out whenever the setting did not exclude anyone, which is how 8.67 POL went
// to sponsors of members who already existed. A referral only counts if the person did not
// exist in InstantAdPay before the mission did.
const floor = Date.parse(String(c.refNewAfter || ''));
if (!Number.isFinite(floor) || floor <= 0) return [];
if (!me.joinedAt || Number(me.joinedAt) < floor) return [];
// AND PolHunter has to have actually sent them. The account being new is not enough: somebody who
// joined InstantAdPay off an email, a banner or another site and only later wandered over here was
// never a PolHunter acquisition, and paying a bounty for them defeats the point (Marty,
// 2026-09-24). The proof is InstantAdPay's first-touch source, handed over signed in the sign-in
// payload; a share link stamps it polhunter.com from the URL itself, so a stripped referrer does
// not lose a genuine referral. Fails closed: no origin on file pays nobody.
// only an explicit '0' turns this off: a typo or a stray value must leave the gate standing,
// the same way the floor does
const viaHunt = /polhunter/i.test(String(me.joinedRef || ''));
const forgiven = !viaHunt && exempt(c, id); // origin forgiven, but MATCH ONLY, see below
if (String(c.refRequireOrigin) !== '0' && !viaHunt && !forgiven) return [];
const who = { forMemberId: id, forName: me.username || ('#' + id) };
// the bounty, once, on their first find, and only while they are genuinely a new member
const finds = store.read('payouts', []).filter(p => Number(p.memberId) === id && !p.ref && !p.prize && !p.detective && p.status !== 'failed');
// `forgiven` covers a match that was already running when the origin rule landed. It must NEVER
// open a new bounty, or an exemption becomes the same hole again wearing a config field.
if (!forgiven && finds.length <= 1 && ageDays <= Number(c.refNewDays) && !bountyPaidFor(id)) {
const pol = Number(c.refBountyPol);
if (pol <= room) {
const firstEver = !refRows().some(p => p.ref.kind === 'bounty');
out.push(write(referrer, pol, Object.assign({ kind: 'bounty' }, who))); room -= pol;
// the launch bonus rides along with the very first bounty anyone earns, once ever. It is
// deliberately outside the daily referral ceiling: it is a single payment, not a rate.
const bonus = Number(c.refFirstBonusPol) || 0;
if (firstEver && bonus > 0 && !refRows().some(p => p.ref.kind === 'first-bonus')) {
out.push(write(referrer, bonus, Object.assign({ kind: 'first-bonus' }, who)));
}
}
}
// the match, on every find inside the window, paid on top and never deducted from the newcomer
if (ageDays <= Number(c.refMatchDays)) {
const pol = round4(Number(find.pol) * Number(c.refMatchPct) / 100);
if (pol >= Number(c.refMatchMinPol) && pol <= room) out.push(write(referrer, pol, Object.assign({ kind: 'match', findId: find.id, findPol: find.pol }, who)));
}
return out;
}
// ---- what the board shows ---------------------------------------------------------------------
function state(member) {
const c = cfg();
const id = Number(member.memberId);
const me = hunter(id) || { memberId: id };
const rows = refRows().filter(p => Number(p.memberId) === id);
const today = ctDay();
// the same floor onFind pays by, so the card can never promise an earning it will not make
const floor = Date.parse(String(c.refNewAfter || ''));
const gateOk = Number.isFinite(floor) && floor > 0;
const needOrigin = String(c.refRequireOrigin) !== '0';
const mine = broughtBy(id).map(x => {
const theirFinds = store.read('payouts', []).filter(p => Number(p.memberId) === Number(x.memberId) && !p.ref && !p.prize && !p.detective && p.status !== 'failed');
const paid = bountyPaidFor(x.memberId);
const viaHunt = /polhunter/i.test(String(x.joinedRef || '')) || exempt(c, x.memberId);
// qualifying means BOTH: new to InstantAdPay, and sent here by PolHunter
const isNew = !!(gateOk && x.joinedAt && Number(x.joinedAt) >= floor && (!needOrigin || viaHunt));
return {
name: x.username || ('#' + x.memberId),
// when they actually joined InstantAdPay, not when this directory first noticed them:
// the backfill stamped firstSeen at seeding time and made everyone look brought-in today
joinedAt: x.joinedAt || x.firstSeen || null,
finds: theirFinds.length,
// an account that predates the mission was already a member: say so plainly rather than
// show them as 'hunting' next to a bounty that will never arrive
isNew, viaHunt,
// say exactly which condition they miss, so nobody waits on a bounty that will not come
state: !isNew
? (gateOk && x.joinedAt && Number(x.joinedAt) < floor
? 'already a member before the mission, earns nothing'
: 'joined InstantAdPay some other way, not through your link')
: paid ? 'earning' : theirFinds.length ? 'hunting' : 'signed up, no find yet',
stillNew: isNew && (Date.now() - Number(x.joinedAt)) / 86400000 <= Number(c.refMatchDays),
};
});
return {
on: String(c.refEnabled) === '1',
bountyPol: Number(c.refBountyPol),
firstBonusPol: refRows().some(p => p.ref.kind === 'first-bonus') ? 0 : Number(c.refFirstBonusPol) || 0,
matchPct: Number(c.refMatchPct),
matchDays: Number(c.refMatchDays),
brought: mine.length,
broughtNew: mine.filter(x => x.isNew).length, // the only ones that can ever pay
broughtToday: mine.filter(x => x.joinedAt && ctDay(x.joinedAt) === today).length,
earnedPol: round4(rows.reduce((n, p) => n + p.pol, 0)),
earnedTodayPol: round4(rows.filter(p => p.day === today).reduce((n, p) => n + p.pol, 0)),
people: mine.slice(0, 25),
pool: refPool(),
};
}
function totals() {
const rows = refRows();
const paid = rows.filter(p => p.status === 'paid');
return {
bounties: rows.filter(p => p.ref.kind === 'bounty').length,
matches: rows.filter(p => p.ref.kind === 'match').length,
firstBonus: (() => { const b = rows.find(p => p.ref.kind === 'first-bonus'); return b ? { who: b.username || ('#' + b.memberId), pol: b.pol, at: b.at, status: b.status } : null; })(),
pol: round4(rows.reduce((n, p) => n + p.pol, 0)),
paidPol: round4(paid.reduce((n, p) => n + p.pol, 0)),
referrers: new Set(rows.map(p => p.memberId)).size,
};
}
module.exports = { seen, hunter, referrerOf, broughtBy, onFind, state, totals, refPool, cfg, paidRefToday };
+21 -4
View File
@@ -34,7 +34,7 @@ function draw(min, max, skew) {
// a hunter's finds today (Central), prizes excluded
// day defaults to today: called without it the comparison was against undefined and silently
// returned 0 for everyone, which would read as "no finds yet" to any new caller
function findsToday(memberId, day) { const d = day || ctDay(); return store.read('payouts', []).filter(p => p.memberId === Number(memberId) && p.day === d && p.status !== 'failed' && !p.prize && !p.ref).length; }
function findsToday(memberId, day) { const d = day || ctDay(); return store.read('payouts', []).filter(p => p.memberId === Number(memberId) && p.day === d && p.status !== 'failed' && !p.prize && !p.ref && !p.detective).length; }
function daily(memberId, doneIds, bonus) { const s = settings(); const base = Math.max(1, Number(s.missionsPerDay) || 3);
// every live paid mission this hunter has not done yet adds one, because the company is not
// funding that completion
@@ -54,12 +54,12 @@ function paidToday(day) {
// two accounts sharing a wallet get one drip per mission per day between them.
function completed(memberId, missionId, wallet) {
const w = wallet ? String(wallet).toLowerCase() : null; const day = ctDay();
return store.read('payouts', []).some(p => p.missionId === missionId && p.day === day && p.status !== 'failed' && !p.prize && !p.ref && (p.memberId === Number(memberId) || (w && p.wallet && String(p.wallet).toLowerCase() === w)));
return store.read('payouts', []).some(p => p.missionId === missionId && p.day === day && p.status !== 'failed' && !p.prize && !p.ref && !p.detective && (p.memberId === Number(memberId) || (w && p.wallet && String(p.wallet).toLowerCase() === w)));
}
// the mission ids this member (or wallet) has done today
function doneToday(memberId, wallet) {
const w = wallet ? String(wallet).toLowerCase() : null; const day = ctDay();
return new Set(store.read('payouts', []).filter(p => p.day === day && p.status !== 'failed' && !p.prize && !p.ref && (p.memberId === Number(memberId) || (w && p.wallet && String(p.wallet).toLowerCase() === w))).map(p => p.missionId));
return new Set(store.read('payouts', []).filter(p => p.day === day && p.status !== 'failed' && !p.prize && !p.ref && !p.detective && (p.memberId === Number(memberId) || (w && p.wallet && String(p.wallet).toLowerCase() === w))).map(p => p.missionId));
}
// record a completion; decide paid-today vs queued
@@ -86,6 +86,23 @@ function grant(member, mission) {
return { ok: true, rec, queued: overCap };
}
// A fixed, disclosed amount for a non-find task (an Ad Detective case). House money, so it sits inside
// the same daily cap as finds and queues past it; it is never a find (the detective flag keeps it out
// of the daily limit, the leaderboard, prizes, referral matches and the find badges).
function grantFixed(member, t) {
const s = settings(); const day = ctDay(); const pol = Math.round(Number(t.pol) * 10000) / 10000;
if (!(pol > 0)) return { error: 'no reward set' };
const overCap = paidToday(day) + pol > Number(s.dailyCapPol);
const rec = {
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 8),
memberId: Number(member.memberId), email: member.email, wallet: member.wallet, username: member.username || null,
missionId: t.missionId, site: t.site, pol, day, at: Date.now(), detective: t.detective || true,
status: overCap ? 'queued' : 'due', tx: null, paidAt: null, error: null,
};
store.update('payouts', [], all => { all.push(rec); return all; });
return { ok: true, rec, queued: overCap };
}
// what the faucet should pay now: due entries, then queued ones as long as today's cap allows
function payable() {
const s = settings(); const day = ctDay();
@@ -124,4 +141,4 @@ function totals() {
return { paid: paid.length, pol: Math.round(paid.reduce((n, p) => n + p.pol, 0) * 10000) / 10000, queued: all.filter(p => p.status === 'queued').length, today: paidToday(ctDay()), hunters: new Set(paid.map(p => p.memberId)).size };
}
module.exports = { settings, setSettings, draw, grant, completed, doneToday, payable, mark, ledger, mine, totals, paidToday, pool, nextResetAt, daily, findsToday, unposted };
module.exports = { settings, setSettings, draw, grant, grantFixed, completed, doneToday, payable, mark, ledger, mine, totals, paidToday, pool, nextResetAt, daily, findsToday, unposted };
+21 -3
View File
@@ -20,12 +20,23 @@ const BADGES = [
{ id: 'streak', name: 'On a Streak', icon: '\u{1F525}', why: 'finds on three days in a row' },
{ id: 'top', name: 'Top Hunter', icon: '\u{1F3C6}', why: 'won a weekly prize as #1' },
{ id: 'recruiter', name: 'Recruiter', icon: '\u{1F91D}', why: 'brought a hunter who found their first code' },
// 2026-09-26: tiers on top of the originals, all derived from the ledger, so they count work already done
{ id: 'weekstreak', name: '7-Day Streak', icon: '⚡', why: 'finds on seven days in a row' },
{ id: 'weeksweep', name: 'Week Sweep', icon: '\u{1F5D3}\uFE0F', why: 'a find on every site inside one week' },
{ id: 'scout', name: 'Scout', icon: '\u{1F6A9}', why: 'brought three hunters who found their first code' },
{ id: 'guide', name: 'Guide', icon: '\u{1F3EE}', why: 'brought ten hunters who found their first code' },
{ id: 'trailboss', name: 'Trail Boss', icon: '\u{1F3D4}\uFE0F', why: 'brought twenty-five hunters who found their first code' },
// Ad Detective (Mystery Hunt Box): correct answers, never finds
{ id: 'detective', name: 'Detective', icon: '\u{1F50E}', why: 'solved your first Ad Detective case' },
{ id: 'sleuth', name: 'Sleuth', icon: '\u{1F463}', why: 'solved five Ad Detective cases' },
{ id: 'investigator', name: 'Investigator', icon: '\u{1F4CC}', why: 'solved fifteen Ad Detective cases' },
{ id: 'masterdetective', name: 'Master Detective', icon: '\u{1F5DD}\uFE0F', why: 'solved thirty Ad Detective cases' },
];
const PRIZE_DEFAULTS = { weeklyPrizes: [3, 2, 1], weeklyMinFinds: 10 };
function prizeRules() { const s = rewards.settings(); return { pol: Array.isArray(s.weeklyPrizes) && s.weeklyPrizes.length ? s.weeklyPrizes.map(Number) : PRIZE_DEFAULTS.weeklyPrizes, minFinds: Number(s.weeklyMinFinds) > 0 ? Number(s.weeklyMinFinds) : PRIZE_DEFAULTS.weeklyMinFinds }; }
function excluded() { const s = rewards.settings(); const list = Array.isArray(s.leaderboardExclude) ? s.leaderboardExclude : [1]; return new Set(list.map(Number)); }
function finds() { return store.read('payouts', []).filter(p => p.status !== 'failed' && !p.prize && !p.ref); } // prize drips are not finds
function finds() { return store.read('payouts', []).filter(p => p.status !== 'failed' && !p.prize && !p.ref && !p.detective); } // prize, referral and Ad Detective drips are not finds
// Central day arithmetic on 'YYYY-MM-DD' keys
function dayMinus(dayKey, n) { const [y, m, d] = dayKey.split('-').map(Number); const t = Date.UTC(y, m - 1, d) - n * 86400000; return new Date(t).toISOString().slice(0, 10); }
@@ -39,8 +50,12 @@ function inPeriod(p, period, today) {
function badgesFor(memberId, list) {
const mine = (list || finds()).filter(p => p.memberId === Number(memberId));
if (!mine.length) return [];
const out = new Set();
// Ad Detective cases solved: their own family, earned even by someone with no finds counted yet
const all = store.read('payouts', []);
const solved = all.filter(p => p.memberId === Number(memberId) && p.detective && p.status !== 'failed').length;
if (solved >= 1) out.add('detective'); if (solved >= 5) out.add('sleuth'); if (solved >= 15) out.add('investigator'); if (solved >= 30) out.add('masterdetective');
if (!mine.length) return BADGES.filter(b => out.has(b.id));
out.add('first');
if (mine.length >= 5) out.add('hunter');
if (mine.length >= 20) out.add('tracker');
@@ -49,9 +64,12 @@ function badgesFor(memberId, list) {
if (mine.some(p => p.pol >= 0.4)) out.add('lucky');
const days = new Set(mine.map(p => p.day));
for (const d of days) { if (days.has(dayMinus(d, 1)) && days.has(dayMinus(d, 2))) { out.add('streak'); break; } }
for (const d of days) { let run = true; for (let i = 1; i < 7; i++) if (!days.has(dayMinus(d, i))) { run = false; break; } if (run) { out.add('weekstreak'); break; } }
if (sites.size) { const wk = new Map(); for (const p of mine) { const w = weekOf(p.day); if (!wk.has(w)) wk.set(w, new Set()); wk.get(w).add(p.site); } for (const s of wk.values()) if ([...sites].every(x => s.has(x))) { out.add('weeksweep'); break; } }
if (store.read('payouts', []).some(p => p.memberId === Number(memberId) && p.prize && p.prize.rank === 1 && p.status !== 'failed')) out.add('top');
// earned by a bounty, not a match: someone they brought turned up and found their first code
if (store.read('payouts', []).some(p => p.memberId === Number(memberId) && p.ref && p.ref.kind === 'bounty' && p.status !== 'failed')) out.add('recruiter');
const brought = all.filter(p => p.memberId === Number(memberId) && p.ref && p.ref.kind === 'bounty' && p.status !== 'failed').length;
if (brought >= 1) out.add('recruiter'); if (brought >= 3) out.add('scout'); if (brought >= 10) out.add('guide'); if (brought >= 25) out.add('trailboss');
return BADGES.filter(b => out.has(b.id));
}