diff --git a/docs/detective-questions-draft.json b/docs/detective-questions-draft.json new file mode 100644 index 0000000..c2d477e --- /dev/null +++ b/docs/detective-questions-draft.json @@ -0,0 +1,55 @@ +{ + "_note": "Ad Detective question bank, DRAFT 2026-09-26 for Marty's approval. The first option is the correct one; options are shuffled per hunter at display time. 'fact' is the page text the answer rests on. Only fixed page copy is used: no live counters, no ledger rows, no rotating ads.", + "sites": [ + { "mission": "iap-ledger", "url": "https://instantadpay.com/ledger", "name": "InstantAdPay live ledger", "questions": [ + { "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." }, + { "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." }, + { "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'." }, + { "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." } + ]}, + { "mission": "rmc-training", "url": "https://rmcircle.team/training", "name": "RM Circle training", "questions": [ + { "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." }, + { "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." }, + { "q": "Which network do you fund your wallet on?", "options": ["Polygon Mainnet", "Bitcoin", "Solana", "Dogecoin"], "fact": "Video 3: Get POL onto Polygon Mainnet." }, + { "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." }, + { "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." } + ]}, + { "mission": "ctb-programs", "url": "https://ctbrewards.saasy.top/", "name": "CTB Rewards", "questions": [ + { "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." }, + { "q": "How many CTB Coins equal $1?", "options": ["10,000", "100", "1,000", "1,000,000"], "fact": "10,000 Coins = $1 USD." }, + { "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." }, + { "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." }, + { "q": "What commission do you earn on your direct referrals' earnings?", "options": ["20%", "5%", "1%", "50%"], "fact": "Level 1: 20%." } + ]}, + { "mission": "mailsplat-home", "url": "https://mailsplat.xyz/en", "name": "MailSplat", "questions": [ + { "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." }, + { "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." }, + { "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." }, + { "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." } + ]}, + { "mission": "mylnks-home", "url": "https://mylnks.xyz/", "name": "My Link Shortener", "questions": [ + { "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." }, + { "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." }, + { "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." }, + { "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." } + ]}, + { "mission": "ctb-home", "url": "https://cryptoteambuild.com/", "name": "CryptoTeamBuild.com", "questions": [ + { "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." }, + { "q": "What is the lowest price of an advertising position?", "options": ["$1.25", "$10", "$49", "$100"], "fact": "Buy an advertising position from $1.25." }, + { "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." }, + { "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." } + ]}, + { "mission": "adrevlnks-home", "url": "https://adrevlnks.com/", "name": "AdRevLinks", "questions": [ + { "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." }, + { "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." }, + { "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." }, + { "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." } + ]}, + { "mission": "dripoffers-home", "url": "https://dripoffers.com/", "name": "DripOffers", "questions": [ + { "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." }, + { "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." }, + { "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." }, + { "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." } + ]} + ] +} diff --git a/lib/badge.js b/lib/badge.js index 2d228f6..2f0b7cc 100644 --- a/lib/badge.js +++ b/lib/badge.js @@ -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'); } diff --git a/lib/detective-bank.json b/lib/detective-bank.json new file mode 100644 index 0000000..45ed23b --- /dev/null +++ b/lib/detective-bank.json @@ -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" + } + ] +} \ No newline at end of file diff --git a/lib/detective.js b/lib/detective.js new file mode 100644 index 0000000..3fe46b5 --- /dev/null +++ b/lib/detective.js @@ -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 }; diff --git a/lib/missions.js b/lib/missions.js index 8457b8e..c2e5901 100644 --- a/lib/missions.js +++ b/lib/missions.js @@ -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 }; diff --git a/lib/paid.js b/lib/paid.js index f810118..d8ba346 100644 --- a/lib/paid.js +++ b/lib/paid.js @@ -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 }; diff --git a/lib/referrals.js b/lib/referrals.js index b0df3d2..667b9d4 100644 --- a/lib/referrals.js +++ b/lib/referrals.js @@ -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 }; diff --git a/lib/rewards.js b/lib/rewards.js index 7c5b381..e5f2cb9 100644 --- a/lib/rewards.js +++ b/lib/rewards.js @@ -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 }; diff --git a/lib/social.js b/lib/social.js index 37af20b..4a8cd8d 100644 --- a/lib/social.js +++ b/lib/social.js @@ -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)); } diff --git a/public/admin.html b/public/admin.html index ecf51f2..024d08e 100644 --- a/public/admin.html +++ b/public/admin.html @@ -31,6 +31,10 @@
+

Ad Detective

+
+
+

Recent drips

@@ -51,7 +55,15 @@ document.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { if (!confirm('Delete mission ' + b.dataset.del + '?')) return; await api('/api/admin/mission', { method: 'DELETE', body: JSON.stringify({ id: b.dataset.del }) }); load(); })); document.querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', async () => { const r = await api('/api/admin/embed-test?id=' + encodeURIComponent(b.dataset.test)); if (r.url) { window.open(r.url, '_blank', 'noopener'); alert('Opened with a test token. The code renders after ' + r.dwell + 's.'); } else alert(r.error || 'failed'); })); } - $('go').addEventListener('click', () => { KEY = $('key').value.trim(); load(); }); + // Ad Detective: today's boxes, and per question how often it was asked and answered right. A question + // most people get wrong is unclear; one nearly everyone gets right after many asks may be shared around. + async function loadDetective() { + const d = await api('/api/admin/detective'); if (!d || !d.questions) return; + $('detLine').textContent = 'Reward ' + d.settings.pol + ' POL · ' + (d.settings.on ? 'on' : 'OFF') + ' · today: ' + d.today.boxes + ' boxes, ' + d.today.won + ' solved, ' + d.today.missed + ' missed · ' + d.questions.filter(q => q.active !== false).length + ' active questions'; + $('detQs').innerHTML = 'sitequestionright answeraskedright' + d.questions.map(q => '' + esc(q.missionId) + '' + esc(q.q) + '' + esc(q.options[0]) + '' + q.asked + '' + (q.asked ? Math.round(100 * q.correct / q.asked) + '%' : '—') + '').join(''); + document.querySelectorAll('[data-qa]').forEach(b => b.addEventListener('click', async () => { await api('/api/admin/detective/question', { method: 'POST', body: JSON.stringify({ id: b.dataset.qa, active: b.dataset.on === '1' }) }); loadDetective(); })); + } + $('go').addEventListener('click', () => { KEY = $('key').value.trim(); load(); loadDetective(); }); $('key').addEventListener('keydown', e => { if (e.key === 'Enter') $('go').click(); }); $('saveSettings').addEventListener('click', async () => { const b = {}; for (const k of ['minPol', 'maxPol', 'dailyCapPol', 'lowBalancePol']) b[k] = Number($(k).value); const r = await api('/api/admin/settings', { method: 'POST', body: JSON.stringify(b) }); if (r.error) alert(r.error); load(); }); $('tickFaucet').addEventListener('click', async () => { $('faucetLine').textContent = 'running…'; const r = await api('/api/admin/faucet/tick', { method: 'POST' }); $('faucetLine').textContent = r.error ? r.error : 'paid ' + r.paid + ' · balance ' + (r.balance == null ? '—' : Number(r.balance).toFixed(4) + ' POL'); load(); }); diff --git a/public/app.html b/public/app.html index 7db3959..3924180 100644 --- a/public/app.html +++ b/public/app.html @@ -5,7 +5,7 @@ Your board · PolHunter - +
@@ -19,6 +19,7 @@

Your missions

Each find pays a random drip. Your codes are yours alone.
+

Loading your board…

@@ -48,6 +49,6 @@
- + diff --git a/public/app.js b/public/app.js index 27dccbc..bd26539 100644 --- a/public/app.js +++ b/public/app.js @@ -148,10 +148,12 @@ $('copylink').onclick = () => copy($('mylink'), $('copylink')); $('copytext').onclick = () => copy($('sharetext'), $('copytext')); } watchPaid(); if (seenLedger === null) watchLedger(); - doneNudge(board.daily); + // the Mystery Hunt Box comes first: the nudge back to InstantAdPay waits until today's case is closed + { const bx = board.box; if (!bx || !bx.on || bx.status === 'won' || bx.status === 'missed') doneNudge(board.daily); } fridayCard(board.fridayBank); + boxCard(board.box); const dl = board.daily; if (dl && $('rangeLine')) $('rangeLine').innerHTML = ($('rangeLine').textContent.replace(/\s*·\s*You have.*$/, '')) + ' \u00b7 ' + (dl.left ? 'You have ' + dl.left + ' of ' + dl.limit + ' missions left today.' : 'That is your ' + dl.limit + ' for today. Fresh missions at midnight Central.'); - $('mine').innerHTML = board.drips.length ? board.drips.map(d => '
' + esc(d.site) + '' + ({ paid: 'paid', sent: 'sending', due: 'paying next', queued: 'queued for the next pool', failed: 'held, being looked at' }[d.status] || d.status) + '+' + d.pol + ' POL' + (d.tx ? 'verify ↗' : '') + '
').join('') + $('mine').innerHTML = board.drips.length ? board.drips.map(d => '
' + (String(d.missionId || '').startsWith('detective:') ? '\u{1F50E} ' : '') + esc(d.site) + '' + ({ paid: 'paid', sent: 'sending', due: 'paying next', queued: 'queued for the next pool', failed: 'held, being looked at' }[d.status] || d.status) + '+' + d.pol + ' POL' + (d.tx ? 'verify ↗' : '') + '
').join('') : '
Nothing yet. Your first find goes here.
'; document.querySelectorAll('[data-start]').forEach(b => b.addEventListener('click', () => start(b.dataset.start))); const s = $('submit'); if (s) { s.addEventListener('click', submit); $('code').addEventListener('keydown', e => { if (e.key === 'Enter') submit(); }); tick(); } @@ -202,6 +204,43 @@ + '
' + chips + '
' + line + '
'; el.hidden = false; } + // Mystery Hunt Box + Ad Detective (2026-09-26): unlocked by finishing today's Code Hunts, opens to + // a case on one site with a fixed reward shown up front, one question, one answer. + let boxPoll = null; + // refresh only the box, so a code being typed into an open mission is never wiped + async function boxRefresh() { const b = await api('/api/my/board'); if (b && b.me) { board.box = b.box; boxCard(board.box); } } + function boxCard(bx) { + const el = $('boxSlot'); if (!el) return; + clearTimeout(boxPoll); + if (!bx || !bx.on || !board.me.wallet) { el.hidden = true; return; } + const pol = bx.pol + ' POL'; + const head = t => '
\u{1F381} Mystery Hunt Box

' + t + '

'; + const rule = '

One answer only. Look carefully before answering.

'; + let h = ''; + if (bx.status === 'locked') h = head('Unlocks when today’s hunts are done') + '

Find all ' + bx.need + ' of today’s codes and your box opens: a bonus case worth a fixed ' + pol + '. ' + bx.done + ' of ' + bx.need + ' found.

'; + else if (bx.status === 'ready') h = head('Your box is ready') + '

Open it to see today’s bonus case. It pays a fixed ' + pol + ' and does not use up a mission.

'; + else if (bx.status === 'open') h = head('\u{1F50E} Ad Detective on ' + esc(bx.site)) + '

Reward: ' + pol + ', fixed. Visit the site and look around for at least ' + bx.dwell + ' seconds. Then come back here and answer one question about what the site says.

' + rule + ''; + else if (bx.status === 'started') { h = head('\u{1F50E} On the case: ' + esc(bx.site)) + '

Stay on the site tab for at least ' + bx.dwell + ' seconds and read what it says. A note on the page tells you when your visit is recorded. Your question appears here right after.

Open the site again ↗ · if the note never showed, press Begin again after this attempt times out.

' + (bx.expires && Date.now() > bx.expires ? '' : ''); boxPoll = setTimeout(boxRefresh, 6000); } + else if (bx.status === 'visited') h = head('\u{1F50E} Your question: ' + esc(bx.site)) + '

' + esc(bx.question) + '

' + (bx.options || []).map((o, i) => '').join('') + '
' + rule + ' Look at the site again ↗'; + else if (bx.status === 'won') h = head('✅ Case solved') + '

You got it right: ' + pol + ' is yours. ' + esc(bx.question) + ' ' + esc(bx.answer) + '.

A new box unlocks tomorrow when you finish your hunts.

'; + else if (bx.status === 'missed') h = head('Not this time') + '

' + esc(bx.question) + ' The answer was ' + esc(bx.answer) + '.

A new box unlocks tomorrow when you finish your hunts.

'; + else if (bx.status === 'answering') { h = head('Checking your answer…'); boxPoll = setTimeout(boxRefresh, 3000); } + el.innerHTML = h; el.hidden = !h; + const o = $('boxOpen'); if (o) o.onclick = async () => { o.disabled = true; const r = await api('/api/my/box/open', {}); if (r.error) toast(esc(r.error), 'bad'); await load(); }; + const s = $('boxStart'); if (s) s.onclick = async () => { s.disabled = true; const r = await api('/api/my/box/start', {}); if (r.error) { toast(esc(r.error), 'bad'); s.disabled = false; return; } window.open(r.url, '_blank', 'noopener'); await load(); }; + const a = $('boxAnswer'); + if (a) { + el.querySelectorAll('input[name=boxAns]').forEach(x => x.addEventListener('change', () => { a.disabled = false; })); + a.onclick = async () => { + const pick = el.querySelector('input[name=boxAns]:checked'); if (!pick) return; + a.disabled = true; el.querySelectorAll('input[name=boxAns]').forEach(x => { x.disabled = true; }); + const r = await api('/api/my/box/answer', { choice: Number(pick.value) }); + if (r.error) { toast(esc(r.error), 'bad'); await load(); return; } + toast(r.correct ? '\u{1F50E} Case solved! ' + esc(r.message.replace(/^Case solved\.\s*/, '')) : esc(r.message), r.correct ? 'big' : ''); + if (r.unlocked && r.unlocked.length) { const id = r.unlocked[0]; setTimeout(async () => { await load(); shareBadge(id, true); }, 1200); } else await load(); + }; + } + } let explorer = 'https://polygonscan.com'; async function load() { board = await api('/api/my/board'); render(); } async function start(id) { diff --git a/public/badges/badge-detective.jpg b/public/badges/badge-detective.jpg new file mode 100644 index 0000000..12b84e9 Binary files /dev/null and b/public/badges/badge-detective.jpg differ diff --git a/public/badges/badge-guide.jpg b/public/badges/badge-guide.jpg new file mode 100644 index 0000000..bfbc8ab Binary files /dev/null and b/public/badges/badge-guide.jpg differ diff --git a/public/badges/badge-investigator.jpg b/public/badges/badge-investigator.jpg new file mode 100644 index 0000000..3222028 Binary files /dev/null and b/public/badges/badge-investigator.jpg differ diff --git a/public/badges/badge-masterdetective.jpg b/public/badges/badge-masterdetective.jpg new file mode 100644 index 0000000..b3f6240 Binary files /dev/null and b/public/badges/badge-masterdetective.jpg differ diff --git a/public/badges/badge-scout.jpg b/public/badges/badge-scout.jpg new file mode 100644 index 0000000..6f334ff Binary files /dev/null and b/public/badges/badge-scout.jpg differ diff --git a/public/badges/badge-sleuth.jpg b/public/badges/badge-sleuth.jpg new file mode 100644 index 0000000..91851b6 Binary files /dev/null and b/public/badges/badge-sleuth.jpg differ diff --git a/public/badges/badge-trailboss.jpg b/public/badges/badge-trailboss.jpg new file mode 100644 index 0000000..73e8e9c Binary files /dev/null and b/public/badges/badge-trailboss.jpg differ diff --git a/public/badges/badge-weekstreak.jpg b/public/badges/badge-weekstreak.jpg new file mode 100644 index 0000000..8edf1dd Binary files /dev/null and b/public/badges/badge-weekstreak.jpg differ diff --git a/public/badges/badge-weeksweep.jpg b/public/badges/badge-weeksweep.jpg new file mode 100644 index 0000000..6ca65af Binary files /dev/null and b/public/badges/badge-weeksweep.jpg differ diff --git a/public/embed.js b/public/embed.js index 16ab4bd..a4ce60a 100644 --- a/public/embed.js +++ b/public/embed.js @@ -36,12 +36,21 @@ box.addEventListener('click', function () { var done = function () { var s = box.querySelector('[data-ph-hint]'); if (s) s.textContent = 'copied, paste it on your board'; }; try { navigator.clipboard.writeText(code).then(done, done); } catch (e) { done(); } }); el.appendChild(box); } + function note(slot) { + var el = slotEl(slot); el.innerHTML = ''; + var box = document.createElement('div'); box.setAttribute('role', 'note'); + box.style.cssText = 'display:inline-flex;align-items:center;gap:10px;padding:12px 14px;border-radius:14px;background:linear-gradient(135deg,#1a0f3d,#2b1a63);color:#f1eefb;font:600 13px/1.35 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 8px 30px rgba(130,71,229,.45),0 0 0 1px rgba(255,255,255,.08);max-width:100%'; + box.innerHTML = 'Ad Detective: visit recorded.
Look around this page, then answer your question on your PolHunter board.
'; + el.appendChild(box); + } var tries = 0, pending = null, done = false; // phones freeze a background tab's timers: when the hunter comes back to this tab, ask right away document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible' && !done) { clearTimeout(pending); ask(); } }); function ask() { tries++; if (tries > 80 || done) return; fetch(API + '/api/embed/code?t=' + encodeURIComponent(t), { mode: 'cors', credentials: 'omit' }).then(function (r) { return r.json(); }).then(function (r) { + // an Ad Detective case: no code, just the receipt; the question is waiting on the hunter's board + if (r && r.visited) { done = true; note(Number(r.slot) % slots); try { sessionStorage.removeItem('ph.token'); } catch (e) {} return; } if (r && r.code) { done = true; render(r.code, Number(r.slot) % slots); try { sessionStorage.removeItem('ph.token'); } catch (e) {} return; } if (r && r.wait) { pending = setTimeout(ask, Math.min(r.wait, 5) * 1000); return; } // expired / gone / wrong origin: say nothing diff --git a/public/style.css b/public/style.css index 2f73bb9..a4c4b0b 100644 --- a/public/style.css +++ b/public/style.css @@ -141,3 +141,16 @@ textarea{width:100%;padding:12px 14px;border-radius:12px;border:1px solid var(-- /* the one condition that decides whether a referral ever pays, said plainly on the card itself rather than discovered when the bounty does not arrive (Marty, 2026-09-23) */ .ref-note{margin-top:8px;font-size:12.5px;line-height:1.45;color:var(--dim)} + +/* Mystery Hunt Box + Ad Detective (2026-09-26) */ +.box-card{margin:12px 0 16px;padding:16px 18px;border-radius:16px;border:1px solid rgba(243,190,67,.45);background:linear-gradient(135deg,rgba(243,190,67,.10),rgba(130,71,229,.14))} +.box-card h3{margin:4px 0 8px;font-size:18px} +.box-card p{margin:0 0 10px;line-height:1.5} +.box-hd{font:700 12px var(--font);letter-spacing:.12em;text-transform:uppercase;color:var(--gold)} +.box-dim{color:var(--muted);font-size:13px} +.box-rule{font-weight:700;color:var(--gold);font-size:14px} +.box-q{font-size:17px;font-weight:700} +.box-opts{display:grid;gap:8px;margin:0 0 12px} +.box-opt{display:flex;align-items:flex-start;gap:10px;padding:10px 12px;border-radius:12px;border:1px solid var(--edge);background:rgba(0,0,0,.25);cursor:pointer;line-height:1.4} +.box-opt:has(input:checked){border-color:var(--gold);background:rgba(243,190,67,.12)} +.box-opt input{margin-top:3px;accent-color:#f3be43} diff --git a/server.js b/server.js index dd95553..4cdf9f8 100644 --- a/server.js +++ b/server.js @@ -25,6 +25,7 @@ const social = require('./lib/social'); const badge = require('./lib/badge'); const referrals = require('./lib/referrals'); // pays a hunter for bringing someone who turns up and hunts const faucet = require('./lib/faucet'); +const detective = require('./lib/detective'); // Mystery Hunt Box + Ad Detective (2026-09-26) const PORT = Number(process.env.PORT || 3000); const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data'); @@ -42,6 +43,19 @@ const signupsOpen = () => process.env.SIGNUPS === 'open'; store.init(DATA_DIR); const faucetOn = faucet.init(); +detective.init(); +// Badges added after launch count work already done, so on the day they ship many hunters hold them at once. +// Those are marked as announced without posting, or the badge sweep would flood Telegram with old news. +// Badges earned from here on are announced as usual. Runs once per new badge id. +(function seedNewBadges() { + const ORIGINAL = ['first', 'hunter', 'tracker', 'sweep', 'lucky', 'streak', 'top', 'recruiter']; + const known = new Set(store.read('badges-known', ORIGINAL)); + const fresh = social.BADGES.map(b => b.id).filter(id => !known.has(id)); if (!fresh.length) return; + const members = new Set(store.read('payouts', []).map(p => p.memberId)); let n = 0; + store.update('badges-posted', {}, all => { for (const id of members) { const have = new Set(all[String(id)] || []); for (const b of social.badgesFor(id)) if (fresh.includes(b.id) && !have.has(b.id)) { have.add(b.id); n++; } all[String(id)] = [...have]; } return all; }); + store.write('badges-known', [...known, ...fresh]); + console.log('new badges', fresh.join(','), '- marked', n, 'already-earned as announced (no posts)'); +})(); // ---- Telegram (outward: gated) ------------------------------------------------------------ async function telegram(text) { @@ -70,6 +84,7 @@ async function notify(kind, p) { return notifyOther(kind, p); } async function notifyPaid(p) { + if (p.detective) { const ok = await telegram('\u{1F50E} PolHunter · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' cracked an Ad Detective case on ' + p.site + ' and got ' + fmt(p.pol) + ' POL · verify\nHunt yours'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; } { const ok = await telegram('\u{1F3AF} PolHunter · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' found it on ' + p.site + ' and got ' + fmt(p.pol) + ' POL · verify\nHunt yours'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; } } async function notifyOther(kind, p) { @@ -230,7 +245,7 @@ const server = http.createServer(async (req, res) => { return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet }, missions: missions.forMember(me.memberId).map(m => Object.assign(pubMission(m), { done: done.has(m.id) || wdone.has(m.id) })), drips: rewards.mine(me.memberId).slice(0, 20), faucet: { on: faucetOn }, pool: rewards.pool(), daily: rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fbank.bonus), fridayBank: fbank, badges: social.badgesFor(me.memberId), badgeCards: (() => { const got = new Set(social.badgesFor(me.memberId).map(b => b.id)); const who = social.nameOf(me); return social.BADGES.map(b => ({ id: b.id, name: b.name, icon: b.icon, why: b.why, art: '/badges/badge-' + b.id + '.jpg', earned: got.has(b.id), page: got.has(b.id) ? SITE + '/b/' + who + '/' + b.id : null, image: got.has(b.id) ? SITE + '/badge-img/' + who + '/' + b.id + '.jpg' : null })); })(), rank: { week: social.rankOf(me.memberId, 'week'), month: social.rankOf(me.memberId, 'month'), all: social.rankOf(me.memberId, 'all') }, share: { link: social.shareLink(SITE, me), joinUrl: 'https://instantadpay.com/join/' + encodeURIComponent(String(me.username || me.memberId)) + '?from=polhunter' }, - referral: referrals.state(me) }); + referral: referrals.state(me), box: detective.view(me) }); } if (p === '/api/my/start' && req.method === 'POST') { const b = await readBody(req); const m = missions.get(String(b.missionId || '')); if (!m || !m.active) return json(res, 404, { error: 'That mission is not open.' }); @@ -265,6 +280,23 @@ const server = http.createServer(async (req, res) => { for (const b of unlocked) notify('badge', { me, id: b.id }).catch(() => {}); return json(res, 200, { ok: true, pol: g.rec.pol, queued: g.queued, unlocked: unlocked.map(b => b.id), message: g.queued ? 'Found it. Today’s POL is spoken for, so yours is queued and pays out next.' : 'Found it. ' + fmt(g.rec.pol) + ' POL is on its way to your wallet.' }); } + // ---- Mystery Hunt Box + Ad Detective + if (p === '/api/my/box/open' && req.method === 'POST') { const r = detective.open(me); return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, box: detective.view(me) }); } + if (p === '/api/my/box/start' && req.method === 'POST') { + if (!me.wallet) return json(res, 400, { error: 'Link a wallet on InstantAdPay first so the reward has somewhere to land.' }); + if (limited('boxstart:' + me.memberId, 20, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' }); + const r = detective.start(me); return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/box/answer' && req.method === 'POST') { + const b = await readBody(req); + if (limited('boxans:' + me.memberId, 10, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' }); + const before = new Set(social.badgesFor(me.memberId).map(x => x.id)); + const r = detective.answer(me, b.choice); if (r.error) return json(res, 400, r); + const unlocked = r.correct ? social.badgesFor(me.memberId).filter(x => !before.has(x.id)) : []; + for (const x of unlocked) notify('badge', { me, id: x.id }).catch(() => {}); + const msg = r.correct ? (r.queued ? 'Case solved. Today\u2019s POL is spoken for, so your ' + fmt(r.pol) + ' POL is queued and pays out next.' : 'Case solved. ' + fmt(r.pol) + ' POL is on its way to your wallet.') : 'Not this time. The answer was: ' + r.answer + '. A new box unlocks tomorrow.'; + return json(res, 200, { ok: true, correct: r.correct, pol: r.pol, queued: r.queued, unlocked: unlocked.map(x => x.id), message: msg, box: detective.view(me) }); + } return json(res, 404, { error: 'No such call.' }); } @@ -282,9 +314,12 @@ const server = http.createServer(async (req, res) => { return json(res, 200, { ok: true, missions: missions.list() }); } if (p === '/api/admin/mission' && req.method === 'DELETE') { const b = await readBody(req); missions.remove(String(b.id || '')); return json(res, 200, { ok: true, missions: missions.list() }); } - if (p === '/api/admin/settings' && req.method === 'POST') { const b = await readBody(req); const patch = {}; for (const k of ['minPol', 'maxPol', 'dailyCapPol', 'lowBalancePol', 'weeklyMinFinds', 'drawSkew', 'missionsPerDay', 'refEnabled', 'refBountyPol', 'refMatchPct', 'refMatchDays', 'refNewDays', 'refCapPol', 'refMatchMinPol']) if (b[k] != null && Number(b[k]) >= 0) patch[k] = Number(b[k]); for (const k of ['weeklyPrizes', 'leaderboardExclude']) if (Array.isArray(b[k])) patch[k] = b[k].map(Number).filter(n => n >= 0); return json(res, 200, { ok: true, settings: rewards.setSettings(patch) }); } + if (p === '/api/admin/settings' && req.method === 'POST') { const b = await readBody(req); const patch = {}; for (const k of ['minPol', 'maxPol', 'dailyCapPol', 'lowBalancePol', 'weeklyMinFinds', 'drawSkew', 'missionsPerDay', 'detectiveOn', 'detectivePol', 'refEnabled', 'refBountyPol', 'refMatchPct', 'refMatchDays', 'refNewDays', 'refCapPol', 'refMatchMinPol']) if (b[k] != null && Number(b[k]) >= 0) patch[k] = Number(b[k]); for (const k of ['weeklyPrizes', 'leaderboardExclude']) if (Array.isArray(b[k])) patch[k] = b[k].map(Number).filter(n => n >= 0); return json(res, 200, { ok: true, settings: rewards.setSettings(patch) }); } // award a week by hand (its Monday key); already-awarded weeks are skipped if (p === '/api/admin/prizes/award' && req.method === 'POST') { const b = await readBody(req); const r = social.awardWeek(String(b.week || '')); if (r && r.winners && r.winners.length) notify('prize', r).catch(() => {}); return json(res, r && r.error ? 400 : 200, r); } + // Ad Detective question bank: stats per question, add or edit one, retire or restore one + if (p === '/api/admin/detective') return json(res, 200, detective.stats()); + if (p === '/api/admin/detective/question' && req.method === 'POST') { const b = await readBody(req); if (b.id && b.active != null && !b.q) return json(res, detective.setActive(String(b.id), !!b.active) ? 200 : 404, { ok: true }); const r = detective.saveQuestion(b); return json(res, r.error ? 400 : 200, r); } if (p === '/api/admin/drip/retry' && req.method === 'POST') { const b = await readBody(req); rewards.mark(String(b.id || ''), { status: 'due', error: null }); return json(res, 200, { ok: true }); } if (p === '/api/admin/faucet/tick' && req.method === 'POST') { const r = await faucet.tick(notify); return json(res, 200, Object.assign(r, { balance: await faucet.balance() })); } if (p === '/api/admin/embed-test') { // mint a token for any mission so the embed can be tried without a hunter diff --git a/test/run.js b/test/run.js index c665023..fb59b5a 100644 --- a/test/run.js +++ b/test/run.js @@ -59,7 +59,7 @@ const sleep = ms => new Promise(r => setTimeout(r, ms)); // claim const wrong = await call('/api/my/submit', { method: 'POST', body: JSON.stringify({ token: t, code: 'ZZZZZZ' }) }); eq(wrong.status, 400, 'a wrong code is refused'); const ok = await call('/api/my/submit', { method: 'POST', body: JSON.stringify({ token: t, code: code.code }) }); - eq([ok.status, ok.body.pol >= 0.05 && ok.body.pol <= 1, ok.body.queued, ok.body.unlocked], [200, true, false, ['first', 'sweep']], 'the right code pays a drip in range, not queued, and unlocks First Find (and Full Sweep: the test has one site)'); + eq([ok.status, ok.body.pol >= 0.05 && ok.body.pol <= 1, ok.body.queued, ok.body.unlocked], [200, true, false, ['first', 'sweep', 'weeksweep']], 'the right code pays a drip in range, not queued, and unlocks First Find (and Full Sweep + Week Sweep: the test has one site)'); const twice = await call('/api/my/submit', { method: 'POST', body: JSON.stringify({ token: t, code: code.code }) }); eq(twice.status, 400, 'the same mission cannot be claimed twice'); const b2 = await call('/api/my/board'); eq([b2.body.missions[0].done, b2.body.drips.length, b2.body.drips[0].status], [true, 1, 'due'], 'board: done, one drip due (faucet off, so it waits)'); // missions reset with the Central day: a find dated yesterday no longer blocks the mission today @@ -92,11 +92,11 @@ const sleep = ms => new Promise(r => setTimeout(r, ms)); // social: the find is on the leaderboard with a badge, the board carries rank and a share link, // and a share link visit sets the referral cookie that turns sign-ups into that member's IAP join link const lb = await call('/api/leaders?period=all'); eq([lb.status, lb.body.rows.length >= 1, lb.body.rows[0].memberId, lb.body.rows[0].finds >= 1, lb.body.rows[0].badges.length >= 1], [200, true, 42, true, true], 'leaderboard: hunter 42 leads all time with a badge'); - const bd = await call('/api/badges'); eq([bd.body.badges.length, bd.body.badges[0].art], [7, '/badges/badge-first.jpg'], 'seven badges are defined, each with artwork'); + const bd = await call('/api/badges'); const NB = require('../lib/social').BADGES.length; eq([bd.body.badges.length, bd.body.badges[0].art, bd.body.badges.every(x => fs.existsSync(path.join(__dirname, '..', 'public', x.art)))], [NB, '/badges/badge-first.jpg', true], NB + ' badges are defined, each with artwork on disk'); // badge cards: the board lists every card with lock state and share URLs; the share page and the // stamped image exist only for badges the hunter holds const bc = await call('/api/my/board'); const fc = bc.body.badgeCards.find(x => x.id === 'first'), tc = bc.body.badgeCards.find(x => x.id === 'tracker'); - eq([bc.body.badgeCards.length, fc.earned, fc.page, tc.earned, tc.page], [7, true, B + '/b/hunter42/first', false, null], 'board: badge cards with lock state and share page'); + eq([bc.body.badgeCards.length, fc.earned, fc.page, tc.earned, tc.page], [NB, true, B + '/b/hunter42/first', false, null], 'board: badge cards with lock state and share page'); const sp = await fetch(B + '/b/hunter42/first'); const spb = await sp.text(); eq([sp.status, /og:image" content="[^"]*\/badge-img\/hunter42\/first\.jpg"/.test(spb), /unlocked/.test(spb)], [200, true, true], 'share page serves with the stamped card as its OG image'); const sp404 = await fetch(B + '/b/hunter42/tracker'); eq(sp404.status, 404, 'no share page for a badge not held'); const bi = await fetch(B + '/badge-img/hunter42/first.jpg'); eq([bi.status, bi.headers.get('content-type')], [200, 'image/jpeg'], 'stamped badge image serves as JPEG'); @@ -122,6 +122,56 @@ const sleep = ms => new Promise(r => setTimeout(r, ms)); const badRef = await fetch(B + '/?r=