diff --git a/badge.js b/badge.js index 0c6f16e..9209058 100644 --- a/badge.js +++ b/badge.js @@ -1,42 +1,42 @@ -// Achievement badge image, rendered on the server with ffmpeg (Marty, 2026-09-16). -// The browser used to compose it on a canvas and upload the JPEG; a phone that ran short of canvas -// memory (cryptomonk's Spark post) sent a mostly blank card to the group. Now the server draws the -// member's name onto the badge art itself, the same way the Video Maker draws end cards, so every -// badge looks the same no matter what device unlocked it. The browser upload stays as a fallback. -const fs = require('fs'); -const path = require('path'); -const { spawn } = require('child_process'); - -let PUBLIC_DIR = null; -const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 } }; -let FONT; -function font() { - if (FONT !== undefined) return FONT; - FONT = process.env.BADGE_FONT || null; - if (FONT) return FONT; - const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/DejaVuSans-Bold\.ttf$/i.test(f)) return f; } return null; }; - for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } } - if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf'; - return FONT; -} -const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%'); -function init(opts) { PUBLIC_DIR = opts.publicDir; } -// returns a JPEG buffer, or null when ffmpeg or the font is missing (caller falls back to the upload) -function render(key, who) { - return new Promise(resolve => { - const a = ART[key]; const F = font(); if (!a || !F) return resolve(null); - const src = path.resolve(PUBLIC_DIR, 'badges', a.file); if (!fs.existsSync(src)) return resolve(null); - const name = String(who || '').slice(0, 28); - // a Windows font path carries a drive colon that the filter parser trips on: run from the font's folder instead - const winPath = /:/.test(F); - const fontFile = winPath ? path.basename(F) : F; - // 1080-wide art: 59px bold gold text with a dark outline, centred on the ribbon (matches the old canvas layout) - const vf = name ? 'drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=#ffd15c:fontsize=59:borderw=7:bordercolor=0x04140f@0.9:x=(w-text_w)/2:y=" + a.ribbonY + '*h-text_h/2' : 'null'; - const p = spawn('ffmpeg', ['-v', 'error', '-i', src, '-vf', vf, '-frames:v', '1', '-q:v', '3', '-f', 'image2pipe', '-vcodec', 'mjpeg', 'pipe:1'], { stdio: ['ignore', 'pipe', 'pipe'], cwd: winPath ? path.dirname(F) : undefined }); - const chunks = []; let err = ''; - p.stdout.on('data', c => chunks.push(c)); p.stderr.on('data', c => { err += c; }); - p.on('error', () => resolve(null)); - p.on('close', code => { const buf = Buffer.concat(chunks); if (code === 0 && buf.length > 2000 && buf[0] === 0xff && buf[1] === 0xd8) resolve(buf); else { console.error('badge render failed', code, err.slice(0, 200)); resolve(null); } }); - }); -} -module.exports = { init, render, font, ART }; +// Achievement badge image, rendered on the server with ffmpeg (Marty, 2026-09-16). +// The browser used to compose it on a canvas and upload the JPEG; a phone that ran short of canvas +// memory (cryptomonk's Spark post) sent a mostly blank card to the group. Now the server draws the +// member's name onto the badge art itself, the same way the Video Maker draws end cards, so every +// badge looks the same no matter what device unlocked it. The browser upload stays as a fallback. +const fs = require('fs'); +const path = require('path'); +const { spawn } = require('child_process'); + +let PUBLIC_DIR = null; +const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 } }; +let FONT; +function font() { + if (FONT !== undefined) return FONT; + FONT = process.env.BADGE_FONT || null; + if (FONT) return FONT; + const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/DejaVuSans-Bold\.ttf$/i.test(f)) return f; } return null; }; + for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } } + if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf'; + return FONT; +} +const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%'); +function init(opts) { PUBLIC_DIR = opts.publicDir; } +// returns a JPEG buffer, or null when ffmpeg or the font is missing (caller falls back to the upload) +function render(key, who) { + return new Promise(resolve => { + const a = ART[key]; const F = font(); if (!a || !F) return resolve(null); + const src = path.resolve(PUBLIC_DIR, 'badges', a.file); if (!fs.existsSync(src)) return resolve(null); + const name = String(who || '').slice(0, 28); + // a Windows font path carries a drive colon that the filter parser trips on: run from the font's folder instead + const winPath = /:/.test(F); + const fontFile = winPath ? path.basename(F) : F; + // 1080-wide art: 59px bold gold text with a dark outline, centred on the ribbon (matches the old canvas layout) + const vf = name ? 'drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=#ffd15c:fontsize=59:borderw=7:bordercolor=0x04140f@0.9:x=(w-text_w)/2:y=" + a.ribbonY + '*h-text_h/2' : 'null'; + const p = spawn('ffmpeg', ['-v', 'error', '-i', src, '-vf', vf, '-frames:v', '1', '-q:v', '3', '-f', 'image2pipe', '-vcodec', 'mjpeg', 'pipe:1'], { stdio: ['ignore', 'pipe', 'pipe'], cwd: winPath ? path.dirname(F) : undefined }); + const chunks = []; let err = ''; + p.stdout.on('data', c => chunks.push(c)); p.stderr.on('data', c => { err += c; }); + p.on('error', () => resolve(null)); + p.on('close', code => { const buf = Buffer.concat(chunks); if (code === 0 && buf.length > 2000 && buf[0] === 0xff && buf[1] === 0xd8) resolve(buf); else { console.error('badge render failed', code, err.slice(0, 200)); resolve(null); } }); + }); +} +module.exports = { init, render, font, ART }; diff --git a/chatbot.js b/chatbot.js index cc1ea2b..7f55b08 100644 --- a/chatbot.js +++ b/chatbot.js @@ -1,360 +1,360 @@ -// 24/7 site assistant (RM Circle pattern): canned answers first for the -// questions everyone asks, OpenRouter AI for everything else, hard honesty -// rules baked into the system prompt. -// -// HOUSE RULE: whenever a site feature changes, update BOTH the CANNED -// answers and FACTS below in the same commit. -// -// KNOWLEDGE BASE (2026-10-20, kb.js): CANNED below and kb-seed.js SEED the knowledge base, which is -// the one source the assistant answers from. Each CANNED regex becomes its entry's instant-answer -// pattern (same order, first match wins), and for everything else the best-matching entries go into -// the system prompt. Admin > Knowledge base edits entries; an edited entry is no longer refreshed from -// the code. If the KB store fails, the in-code CANNED list still answers. -const fs = require('fs'); -const path = require('path'); -const https = require('https'); -const http = require('http'); -const kb = require('./kb'); -const kbSeed = require('./kb-seed'); - -let DATA_DIR = null; -let chain = null; -const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'; - -function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); } -function key() { - if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); - try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } -} -function enabled() { return !!key(); } - -// ---- canned answers: instant, free, always in voice ---- -const KNOWLEDGE_DATE = '2026-10-22'; // bump whenever the canned answers / prompt are brought up to date -const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; -const CANNED = [ - { id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'], - re: SUPPORT_RE, handoff: true, - a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' }, - { id: 'game-pass', title: 'Game Pass and daily POL caps', q: ['What is the Game Pass?', 'Why did I hit the daily POL cap in the games?', 'Does a boss reward carry over to the next day?'], tags: ['games', 'game pass', 'daily cap', 'tournament'], - re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i, - a: 'The Game Pass is $5 for 7 days and covers all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the gold Game Pass badge with your name. Per game: PolHunter 5 missions a day instead of 3 plus 2 Ad Detective cases; Gem Kingdom one free continue a day; Spooky Doors one extra door a day; ClutterHunt 2 bonus hints a day; SpellWheel daily streak 0.30 POL instead of 0.15 plus 1 free hint a day; PolyBreak daily gem limit 1.5 POL instead of 0.5 plus an extra paddle every round; PolyWarriors a 4th daily mission and defense pays 25 Circuits instead of 15; Drip Runner a free shield at the start of every run; Road Agent 2 patrols a day and 25% more scrap. The full list is on the Game Pass card. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Buy it in Members > Games > Game Pass: it costs 500 purchased credits (credits from a package you bought; earned credits do not count). If you have none, buy a $5 package and the pass starts the moment it settles, and you keep every credit of the package for your ads. Buying while a pass is active adds 7 days.' }, - { id: 'road-agent', title: 'Road Agent (night-highway shooter)', q: ['What is Road Agent?', 'How do fuel stops work in Road Agent?'], tags: ['games', 'road agent', 'fuel stop'], - re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i, - a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' }, - { id: 'presentation', title: 'The InstantAdPay presentation video', q: ['Where is the presentation video?', 'How do I share the presentation with my link?', 'What is the Build Wide video?'], tags: ['presentation', 'video', 'share', 'captions', 'build wide'], - re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i, - a: 'The InstantAdPay presentation is a narrated video of about six minutes at https://instantadpay.com/presentation, with captions in English, Italian, French, Spanish, German and Portuguese (pick the language under the video). It covers what the platform is, how far your ads reach, how one $20 purchase pays $10, $4 and $2 up three levels in the same transaction, why two and then five qualifying buyers unlock levels 2 and 3, Qualified Start, the Pipeline, LinkSpin and your first week. Members share it from Members > Promo tools > Share the presentation: the link carries your username (instantadpay.com/presentation?ref=), sets you as the sponsor exactly like your invite link, and the page shows you as the person who shared it with a Join button. There is also a short Build Wide video, the first card under Promo tools > Videos, with its own front door ?v=wide on your invite link (the page opens on that video). The examples are illustrations, not promises of income.' }, - { id: 'passivedrip', title: 'PassiveDrip earning site', q: ['What is PassiveDrip?', 'Is there a faucet or paid to click?', 'When do coins turn into POL?'], tags: ['passivedrip', 'faucet', 'ptc', 'coins', 'earn'], - re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i, - a: 'PassiveDrip (https://passivedrip.com) is our earning site, listed under More ways to earn on your Earn tab. Claim the faucet, view paid-to-click ads, complete offers and roll the daily bonus for coins. When your balance reaches 2,000 coins ($1) it is paid out automatically in POL to your wallet on Polygon. Open it from the Earn tab with one tap: it signs you in with your InstantAdPay account, no new password. Add your Polygon wallet there so payouts can reach you. What you earn depends on what you do there; nothing is guaranteed.' }, - { id: 'spellwheel', title: 'SpellWheel word game', q: ['What is SpellWheel?', 'Is there a daily word puzzle?'], tags: ['games', 'spellwheel', 'word game', 'daily puzzle'], - re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i, - a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a free word game: swipe the letters on the wheel to fill the crossword grid, travel through six cozy places, and solve a new daily puzzle that everyone gets at the same time. Sign in with your InstantAdPay account right in the game to save progress: clearing levels, finishing a place and solving the daily puzzle each pay POL, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' }, - { id: 'polybreak', title: 'PolyBreak brick breaker', q: ['What is PolyBreak?', 'How do I get another paddle?'], tags: ['games', 'polybreak', 'brick breaker', 'gem'], - re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i, - a: 'PolyBreak (https://polybreak.app, also in Members > Games) is a free brick breaker in the Amiga arcade style: break a wall of glass jewel bricks with the ball and paddle, catch falling capsules (wider paddle, split ball, lasers, slow ball, catch, a break gate that skips the round, an extra paddle), and catch the purple Polygon gem when it drifts down. Sign in with your InstantAdPay account in one tap. Your first clear of each round pays POL into your PolyBreak game balance, and each gem catch pays a small random amount of POL; the balance is sent to the wallet on your InstantAdPay account automatically at the payout line shown in the game. Out of paddles? A short visit to a member\u2019s page gives you one more paddle on the same round. Share your PolyBreak link from the game: when people you invite play, you earn a share too. Nothing here is a promise of income.' }, - { id: 'polywarriors', title: 'PolyWarriors fighting game and NFT warriors', q: ['What is PolyWarriors?', 'How do I get a mint pass?', 'How does fusing warriors work?'], tags: ['games', 'polywarriors', 'nft', 'mint pass', 'duel'], - re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i, - a: 'PolyWarriors (https://www.polywarriors.com, also in Members > Games) is a free cyberpunk turn-based fighting game, open since Oct 12. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit), and challenge other members to duels that play out while you are away. Your first win over each rival pays POL to the wallet on your InstantAdPay account. Your first warrior mints to your wallet as an NFT on Polygon, free; after that each $5 ad package you buy on InstantAdPay earns a mint pass. Fuse three warriors of the same rarity into one rarer warrior, and trade warriors with other members on the marketplace, settled in POL. Sign in with your InstantAdPay account in one tap. Nothing here is a promise of income.' }, - { id: 'clutterhunt', title: 'ClutterHunt hidden-object game', q: ['What is ClutterHunt?', 'How do hints work in ClutterHunt?'], tags: ['games', 'clutterhunt', 'hidden object', 'hints'], - re: /(clutter ?hunt|hidden.object|haunted manor)/i, - a: 'ClutterHunt (https://clutterhunt.com, also in Members > Games) is a free hidden-object game: search cozy, cluttered rooms for 12 hidden objects plus one sponsored find. This season is the Haunted Manor (six rooms) through Oct 31, then new rooms move in every season, and objects move every time you play. You get 2 free hints a round; after that, a short visit to a member’s page earns another. Sign in with your InstantAdPay account right in the game to save your stars and earn POL: each room pays POL for your first clear and your first 3-star clear every season (Expert rooms pay more), collected in your ClutterHunt balance and sent to the wallet on your InstantAdPay account automatically.' }, - { id: 'spooky-doors', title: 'Spooky Doors Halloween game', q: ['What is Spooky Doors?', 'How does the candy ladder pay?', 'How do I buy a costume?'], tags: ['games', 'spooky doors', 'halloween', 'candy', 'costume'], - re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i, - a: 'Spooky Doors (https://spookydoors.com) is the network\u2019s Halloween game. It opens on Oct 4 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Advertisers can also put a verified-visits pack behind the doors: when you create a verified-visits campaign, pick Everywhere (3 credits a visit), Behind Spooky Doors (4 credits a door) or Golden Spooky Door (6 credits a door, and the player gets a little bonus candy). Door packs show only in Spooky Doors until the season ends, then any doors left run as normal visits. Nothing here is a promise of income.' }, - { id: 'games-tab', title: 'Games tab and Drip Runner', q: ['Which games pay POL?', 'What is Drip Runner?', 'How do refuels work?'], tags: ['games', 'drip runner', 'refuel', 'games tab'], - re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i, - a: 'Members > Games lists the network\u2019s games; one tap signs you in. Drip Runner is a runner game: tap to hop, collect gold drips, dodge the bots, clear chapters. The first clear of each chapter drips a little POL into your game balance, which is sent to your wallet once it reaches the payout line shown in the game. When a run ends you can refuel instead of restarting: a short verified visit to a member\u2019s page (or a member video when you have visited them all), up to 20 refuels a day, separate from your regular Earn visits. Refuels are paid for by advertisers, and a share of that funds the POL pool every drip is paid from, so drips depend on the pool and are small. Share your link from the game lobby: when people on your team refuel, a share of what their refuels add to the pool goes to your game balance. Nothing here is a promise of income. The Games tab also has PolHunter, Gem Kingdom (match-3, POL for first clears of stages and bosses), ClutterHunt (hidden objects), SpellWheel (word puzzle), PolyWarriors (cyberpunk fighting, open Oct 12), PolyBreak (brick breaker, opens Oct 13) and Spooky Doors during Halloween; Road Agent opens Thursday Oct 15. The public list of every game, open now and opening next, is https://instantadpay.com/games (add ?ref=yourusername to keep your referral).' }, - { id: 'gem-kingdom', title: 'Gem Kingdom match-3 and Crowns', q: ['What is Gem Kingdom?', 'How do I buy Crowns?', 'What do the bosses pay?'], tags: ['games', 'gem kingdom', 'crowns', 'match-3'], - re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i, - a: 'Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon\u2019s Peak, the Sunken Reef and the Shadow Citadel, where the Shadow King waits), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for first clears only: a little for each stage the first time you clear it, and more for each chapter boss (the Ember Dragon 5 POL, the Kraken 7.5, the Shadow King 10). Replays pay nothing. Rewards go into your game balance and are sent to the wallet on your InstantAdPay account on Polygon once it reaches 0.25 POL. They come from a reward pool funded by a share of Crown purchases, so they pay while the pool has funds (a clear the pool cannot cover pays nothing). Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game\u2019s Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. After a defeat you can also take a free revive by making a short verified visit to a member’s page. In the shop, Specials has a one-time Hero Bundle ($5: a forge weapon, a building level and 60 Crowns), the Kingdom Pass ($10 for 30 days: 10 Crowns a day, a 25-Crown chest each week and the Royal hero looks, no auto-renew) and Hero looks (Halloween looks for 40 Crowns each through Oct 31, yours to keep). Looks are cosmetic only.' }, - { id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'], - re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i, - a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' }, - { id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'], - re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i, - a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' }, - { id: 'five-dollar-friday', title: 'Five Dollar Friday bonus', q: ['What is Five Dollar Friday?', 'What happens on Friday?'], tags: ['five dollar friday', 'bonus credits', 'promotion'], - re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i, - a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' }, - // 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being - // signed out, and the honest answer reads far better than letting it look like a fault. - { id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'], - re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i, - a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' }, - { id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'], - re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i, - a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' }, - { id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is this a ponzi or a scam?'], tags: ['pyramid', 'scam', 'legit', 'ponzi'], - re: /(pyramid|ponzi|scam|scheme)/i, - a: 'Fair question. A pyramid pays for recruiting with no product; here every payment is for real ad delivery, bought by real advertisers, and the whole money flow is public. Check the code and every payout yourself at https://instantadpay.com/contract and https://instantadpay.com/ledger.' }, - { id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'What is the minimum payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'], - re: /(withdraw|cash ?out|payout request|minimum payout)/i, - a: 'There are no withdrawals here, ever. The contract pays your share straight to your own wallet in the same transaction as the purchase. Nothing to request, nothing to wait on.' }, - // "how much do I earn" used to fall through to the PRICE answer below, because that one - // matches "how much do" and this one only caught "how much earn" (Marty, 2026-09-17). - { id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'], - re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i, - a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' }, - { id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?', 'What does In live campaigns mean?'], tags: ['balance', 'credits', 'campaigns', 'credit activity'], - re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i, - a: 'One rule: your balance is what is NOT committed to a live campaign. When you start a campaign its whole budget is set aside right then (earned credits first, then purchased), so your Available number drops once and then sits still while the ad runs. The budget spends down inside that campaign in Members > Campaigns, where you can see delivered views, network views and what is left. The dashboard shows Purchased available, Earned available and In live campaigns as three separate numbers; a paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live. Purchased credits live on the blockchain; if we ever refund or credit purchased money it shows under Purchased as "credited to you" and spends like a purchase, login ads included. Earned credits fund every format except login ads. Two formats are flat buys paid in full when booked: featured links (sold by the day) and verified-visit packs. Adding credits to a featured link does nothing, so its row offers Extend run instead, which books more days at the daily rate; a visit pack offers Buy more visits. Every credit that comes in or goes out is listed with its reason under Members > Campaigns > Credit activity (also linked from Earn credits): sign-in bonus, daily claim, video watched, verified visit, campaign buys, views delivered per day, grants and refunds. Check it before assuming credits went missing.' }, - { id: 'payment-trace', title: 'Why someone was not paid: trace a payment', q: ['Why did my sponsor not get paid?', 'I missed a payment', 'How do I trace a payment?'], tags: ['payment trace', 'missed payment', 'earnings', 'pass-up'], - re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i, - a: 'Every purchase and every share is on the chain, and you can read it yourself: open Members > Earnings > Trace a payment, enter the member number or username (yourself, anyone up to 3 levels below you, or your own uplines), and each purchase they were part of is laid out level by level: who was paid, who was skipped and why. The three usual answers: the person had not unlocked that level when the purchase settled (level 2 needs 2 qualifying $20+ buyers, level 3 needs 5, and qualification never applies backwards); the buyer used Qualified Start, so the purchase came from a linked wallet whose sponsor is the buyer\'s own main position, which means level 1 went to the buyer themselves; or the person\'s payouts were not switched on. Skipped shares pass up to the next qualified person, never to nobody.' }, - { id: 'walk-up', title: 'Unactivated sponsor: the walk-up rule', q: ['What if my sponsor has not switched on payouts?', 'Why did my purchase go to the company position?'], tags: ['sponsor', 'walk up', 'payouts', 'activation'], - re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i, - a: 'Your purchase never waits on your sponsor. If the person who referred you has not linked a wallet and switched on payouts when you buy, the site walks up your sponsor line to the first person who is activated with payouts on and the purchase goes through under them; if nobody in the line is ready it goes under the company position. You see a one-line note on the Buy tab and carry on. For the sponsor it is permanent: the contract locks a buyer to whoever was paid at the first purchase, so that referral moves to the upline who was paid and they cannot earn from that wallet later. They get a message saying so, and the upline gets one too. Two minutes on the Wallet tab prevents it.' }, - // PIF + the holding tank. Asked together often ("should I pif someone from the tank"), - // and the honest answer is that the order matters: you cannot PIF someone still in the - // tank. Canned so it never depends on the AI provider being up (Marty, 2026-09-17). - // The second alternation catches the same question asked without the word PIF - // ("should I fund their first package", "can I buy it for them"). It needs BOTH a - // paying verb AND an explicit for-someone-else phrase, so ordinary pricing questions - // like "which package should I buy" are not stolen (Marty, 2026-09-17). - { id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'], - re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i, - a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' }, - { id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'unsponsored'], - re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i, - a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances.' }, - { id: 'qualification', title: 'Qualification, levels 2 and 3, credits vs POL', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up', 'qualified start'], - re: /(qualif|unlock level|level 2|level 3|pass.?up)/i, - a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' }, - { id: 'free-member', title: 'What free members earn', q: ['What do free members get?', 'Do I have to buy anything?', 'Credits or POL?'], tags: ['free member', 'credits', 'pol', 'activation'], - re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i, - a: 'Free members earn ad credits: view ads, watch videos, make verified visits, read inbox ads, sign in daily. Credits buy your own ads and are never cashed out. POL, the real crypto, is paid to your wallet by the contract when your referrals buy packages, once you are activated: the $20 starter package (2,000 credits to advertise with) and payouts switched on from the Wallet tab. Your own $20 purchase also makes you count as a qualifying buyer for your sponsor, and two or five such buyers in your own line open levels 2 and 3 for you.' }, - { id: 'join', title: 'How to join; do I need a wallet?', q: ['How do I join?', 'Do I need a wallet?', 'Do I need crypto experience?'], tags: ['join', 'sign up', 'wallet', 'email'], - re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i, - a: 'Join free with just your email at https://instantadpay.com/my, no wallet and no password needed. Your wallet only comes out when you buy a package or switch on payouts, and the site walks you through it.' }, - { id: 'referral-link', title: 'My referral and invite links', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools', 'angles'], - re: /(referral link|invite link|share link|refer)/i, - a: 'You get your share link the moment you sign in, free members included. Open Members > Promo tools: the "Your links" block at the top lists your invite link plus five angle versions (Instant, Ad spend, Free, Ledger, Two), each with a note on who it is for and Copy and Share buttons. They are the same link with a code on the end, so every join and purchase credits you; only the first page the person sees changes. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' }, - { id: 'banner-image', title: 'Banner image link and sizes', q: ['Why was my banner image refused?', 'What banner sizes are there?', 'How do I upload a banner?'], tags: ['banner', 'image', 'sizes', 'campaign'], - re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i, - a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' }, - { id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the email swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners', 'objections'], - re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i, - a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, and an Objection handling bank with the truth plus a ready-to-send reply. Everything is personalized with your invite link.' }, - { id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'], - re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i, - a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' }, - { id: 'wall', title: 'Your banner wall and its three positions', q: ['How does my wall work?', 'How do I own wall positions 2 and 3?'], tags: ['wall', 'banner wall', 'positions'], - re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i, - a: 'Your wall (instantadpay.com/wall/yourname) shows three ads. Position 1 is always your line banner. Positions 2 and 3 show your upline (or InstantAdPay) until you earn them: 2 qualifying buyers ($20 or more) make position 2 yours, 5 make position 3 yours, so a fully qualified member owns the whole page with their own links and offers. Set them in Profile > Your wall; an unlocked slot you leave empty keeps showing your upline until you fill it.' }, - { id: 'solo-ads', title: 'Solo ads and the inbox', q: ['What is a solo ad?', 'How do inbox reads pay?'], tags: ['solo ad', 'inbox', 'campaigns'], - re: /(solo ad|inbox ad|inbox)/i, - a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members: give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' }, - { id: 'sponsor', title: 'Who is my sponsor; wrong sponsor', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Can I change my sponsor?'], tags: ['sponsor', 'invite link', 'last touch'], - re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i, - a: 'The invite link you opened most recently sets your sponsor, and the join page shows it: "Personal invitation from @name". It locks the moment you create your account, so opening someone else\'s link afterwards changes nothing, and your first purchase binds you to that same sponsor on the contract. If you have not joined yet and the page shows the wrong name, open the right person\'s link and it updates. If you already joined under the wrong sponsor by mistake, message support before your first purchase and the admin can move you.' }, - { id: 'sponsor-chat', title: 'Sponsor Chat', q: ['How do I message my sponsor?', 'Can I chat with my team?'], tags: ['chat', 'sponsor', 'messages'], - re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i, - a: 'Yes, Members has a two-way Sponsor Chat. You can message your direct sponsor for help (from Overview or the chat button), and sponsors can message anyone in their line. If they are online you chat live; if not, your message waits in their on-site inbox and they get an email. Sponsors can set themselves unavailable in Profile (you can still leave a note, they just reply later) and mute a member if needed. It is separate from the once-a-day team broadcast.' }, - { id: 'earn-credits', title: 'Earning credits: the daily set, videos, visits', q: ['How do I earn credits?', 'How does the daily ad set work?', 'How much is the daily claim?'], tags: ['earn credits', 'daily set', 'claim streak', 'videos', 'visits'], - re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i, - a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits (5 on day one, 7 on day two, 10 from day three, 25 on every 7th day in a row), then keep going with videos (up to 8 a day), verified visits (up to 20 a day) and inbox reads (up to 5 rewarded a day). A separate sign-in bonus pays 5 credits on your first sign-in each day, rising by one per consecutive day up to 10. Earned credits fund every campaign format except login ads. You never see your own ads, and viewer rewards are credits, never cash.' }, - { id: 'featured', title: 'Featured links', q: ['How do featured links work?', 'How do I extend a featured run?'], tags: ['featured links', 'campaigns', 'extend run'], - re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i, - a: 'Featured links run in the strip at the top of every member\'s Overview. Book one under Campaigns for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead; at most 10 links share any day. It is a flat buy, paid in full when booked, and the row shows days left and "runs through" a date. To keep it going use Extend run on the row, which books more days at the same rate; adding credits does not add days. Views (one per viewer per hour) and clicks are counted on the row.' }, - { id: 'verified-visits', title: 'Verified-visit packs', q: ['How do verified visits work?', 'How do I buy visits?'], tags: ['verified visits', 'visit pack', 'campaigns'], - re: /(verified visit|visit pack|buy visits|visits campaign)/i, - a: 'A verified-visit pack sends real members to your site: each one opens it in a new tab, stays at least 8 seconds and passes a check, and no member counts twice. It costs 3 credits per visit, minimum 20 visits, paid in full when you create it, then it fills over time (each member can do at most 20 visits a day). The row shows "N of M visits delivered" and Buy more visits adds to the pack. Members earn 1 credit per verified visit.' }, - { id: 'overview-video', title: 'What is InstantAdPay? The four-minute overview', q: ['What is InstantAdPay?', 'How does this work?', 'Is there an overview video?'], tags: ['overview', 'video', 'what is'], - re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i, - a: 'The quickest answer is the four-minute overview video: it is the first card on Members > Training and on the home page at https://instantadpay.com/#overview-video. It covers what the platform is, what free members get, the campaign formats, how the contract splits every purchase, wallet and payouts, Qualified Start, the payment trace and the tools for building a line.' }, - { id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'Which package should I buy?', 'What do I get for my money?'], tags: ['packages', 'price', 'credits', 'qualification'], - re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i, - a: 'Seven packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Starter $10 for 1,000, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500, Elite $500 for 70,000. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' }, - { id: 'credits', title: 'What ad credits are', q: ['What is a credit worth?', 'What are ad credits?'], tags: ['credits', 'ad formats', 'impressions'], - re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i, - a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' }, - { id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'], - re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i, - a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' }, - { id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'], - re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i, - a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' }, - { id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'], - re: /(safe|trust|rug|run away|company disappear)/i, - a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' } -]; - -// CANNED + the FAQ seeds, in the shape kb.js stores (order keeps the first-match-wins sequence) -function seeds() { - return CANNED.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re.source, - handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(kbSeed.FAQ); -} - -// ---- facts for the AI fallback ---- -function systemPrompt(kbBlock) { - return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform. - -FACTS: -- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref= link. -- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time. -- PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide. -- WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money. -- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises. -- SESSIONS LAST 4 HOURS. Sign-ins expire after 4 hours and the member signs in again with a fresh 6-digit code. This is intentional and we say so plainly: it keeps resources optimised, and the login sponsor ad shown on the way back in is part of what pays for the free side. Nothing is lost on expiry - credits, line and account are untouched. Never describe it as a bug, an error, or something to report. -- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly. -- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase. -- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two, ?v=wide width-unlocks-depth with the Build Wide video; ?v=play opens the games angle), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle. -- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com. -- INVITE PAGES: a member's link instantadpay.com/join/ opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two|wide|play for an angle-matched headline (?v=wide: 'Width unlocks depth.', opens on the Build Wide video, vertical on phones). New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings). -- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use MetaMask/Phantom/SafePal (no hard block). The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again. -- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads. -- LINE BANNER (free, set in Profile): every member can set a destination URL (must allow framing) plus an optional banner image. It is shown to their next THREE levels of new members during welcome tours (position 1 for directs, 2, 3 below), and on their public BANNER WALL at /wall/ — a shareable page showing their line ladder with their join link. Free viral traffic that compounds as the team grows; no credits spent. -- Ad packages: Micro $5/500 credits, Starter $10/1,000, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500, Elite $500/70,000. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery. -- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Video watching is capped at 8 a day per member and pays 1, 2 or 4 credits for a 10, 30 or 60 second watch. FEATURED LINKS (live): a headline + link in the Featured strip at the top of every member's Overview, booked for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead, at most 10 links sharing any day; flat buy paid when booked; the row shows days left and 'runs through ', counts views (one per viewer per hour) and clicks, and offers Extend run. VERIFIED-VISIT PACKS (live): 3 credits per visit, minimum 20 visits, paid up front; each visit is a distinct member who opens the site in a new tab, stays 8 seconds and passes a check, at most 20 visits per member per day; the row shows 'N of M visits delivered' and Buy more visits adds to the pack; the visitor earns 1 credit. -- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase. -- INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/) right under their bio, above the three-level line and the join button. -- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 2 open adoptions, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members. -- DAILY CLAIM STREAK: finishing the daily ad set and claiming pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th consecutive day; miss a day and it restarts. After the set, verified visits (up to 20 a day, 1 credit each) keep earning, and the credits are meant to be spent on a campaign. -- FOUR-MINUTE OVERVIEW VIDEO (2026-09-16): 'InstantAdPay in four minutes' is the first card on Members > Training (group 'Start here') and embedded on the home page at instantadpay.com/#overview-video (hero button 'Watch the 4-minute overview'). Send it to anyone asking what the platform is; the tab-by-tab walkthrough videos on Training go deeper. It is evergreen: no dates, no launch talk. -- ANTI-FRAUD CHECKS (2026-09-16): at sign-up the site records IP, browser type and a browser cookie id. A second account from a browser that already has one is refused, so is a burst of new accounts from one connection in a day, and so is a sign-up through an invite link whose owner used that same browser. A sign-up from the same IP as the sponsor is allowed but flagged (households are fine). Flagged accounts never count on the leaderboard and cannot adopt from the holding tank; a suspended account cannot sign in. If a member says they were refused at sign-up, or asks how to get a second account to qualify themselves: one account per person, sign in to the existing one, and use QUALIFIED START (Buy packages tab) to link extra wallets of their own as positions under that account; each linked wallet that buys $20+ counts as one of their qualifying buyers, credits pool, and half of each such purchase returns to their main wallet. Levels 2 and 3 open at 2 and 5 qualifying buyers whether those buyers are referrals or the member's own linked positions. Shared computer at work or a library: contact support. Never suggest a second account. -- ONE ACCOUNT PER PERSON (Terms section 3, 2026-09-16): a person may hold exactly one account; second or duplicate accounts under any email, name or wallet, and self-referral through another account, are prohibited. The only sanctioned way to hold more than one position is Qualified Start (extra wallets linked inside the one account). Duplicates may be merged, suspended or closed and credits, prizes and contest rankings earned through them are forfeited; the contract's on-chain payments cannot be reversed. Family members join under the member's link with their own email. -- BLOG (public, instantadpay.com/blog): Marty's coaching and teaching articles on building a line, advertising that pays, and daily habits; each article has its own page and can be shared; RSS at /blog/feed.xml. Members who want to write their own articles: not offered today. -- ACHIEVEMENT BADGES ON TELEGRAM (2026-09-13): when a member unlocks Spark/Surge/Circuit/Nexus, their personalised badge image (username on the ribbon) is posted automatically to the team's Telegram payments topic and the main group, once per badge; members cannot trigger posts themselves (the 'Post to Telegram' button is admin-only); 'Share' opens a picker (X, Facebook, Telegram, WhatsApp, LinkedIn, Massifly (copies the post and opens the feed composer), the phone's own share menu, copy link, save image) that shares the member's public badge page instantadpay.com/b//, which shows the badge and their join link. -- PROMO TOOLKIT BY BADGE + AI COPY ENGINE (2026-09-14): Promo tools > AI Copy Engine shows the ladder: Free (links, posts, swipes, banners, wall, objections, shorts, badge pages), Spark (payouts on: one-tap campaign templates aimed at the member's link, printable handout with their QR at /handout/), Surge (first qualifying buyer; the AI Copy Engine is live: posts, DMs, follow-ups, objection replies, emails, story posts, team broadcasts in the member's name with their link, honesty rules built in; 20 free generations a month), Circuit (60 free; Video Maker renders every promo video and short with the member's own end card and QR, hosted for download; split tester compares join angles by views, joins, buyers), Nexus (150 free; Leader Ops: three-level team triage with stalled flags and one-click nudges, AI-drafted team broadcasts, credit grants from the leader's earned pool to anyone in their line, co-branded join page showing the sponsor's bio, and the member's own partner code: welcome credits funded from the leader's pool at each redemption, plus a partner kit page /partners?ref=&promo=CODE). After the free allowance each generation costs 10 ad credits from the earned pool. Credits are advertising, never money. -- MEMBER UPDATE EMAILS (2026-09-14, admin only): Admin > Releases > Email an update to members: pick release notes, add an intro, choose an audience (newsletter opt-ins, opt-ins active in the last 30 days, or everyone including those who declined), preview, send a test to the admin, then send; plain text from no-reply@instantadpay.com with an opt-out link; the log shows sent/opted out/failed. -- LINKED POSITIONS AND BADGES (2026-09-14): qualifying buyers on a member's linked positions count toward their achievement badges (Spark/Surge/Circuit/Nexus) and light their chip on their sponsor's line, and a badge once earned never regresses. CONTRACT RULE: levels 2 and 3 are paid to the MAIN wallet only when that wallet's own count of qualifying buyers reaches 2 and 5; buyers registered under a linked position count for that position, not the main wallet. Qualified Start positions buy UNDER the main wallet, so those buys raise the main count; a member whose old wallet was swapped out (its buyers stay with the old position) needs new $20+ buyers under the current main wallet before level 2 pays it. The contract still pays levels 2 and 3 to each position based on that position's OWN qualifying buyers, so the Qualifying buyers tile shows the main position's count with the linked positions' count underneath. -- CREDITS VS POL (2026-09-15, Marty's stance): EVERY member earns CREDITS (viewing, videos, visits, inbox, sign-in bonus, badge bonuses); credits are ad delivery, not money. POL is paid by the contract to a member's wallet when referrals buy packages. ALWAYS describe activation as 'the $20 starter package plus payouts switched on' and lead every earning answer with it; do NOT volunteer that level 1 can pay without a purchase. If someone asks point-blank whether a purchase is required for level-1 payouts, answer truthfully in one sentence: the contract pays level 1 to any member whose payouts are switched on, and the $20 package is what makes them a qualifying buyer for their sponsor, funds their own ads, and unlocks badges, tools, the holding tank and wall positions. A $20+ purchase by a referral makes that referral a qualifying buyer for their sponsor; 2 and 5 open levels 2 and 3. Never claim the payout itself is gated by a purchase. -- PIPELINE (live since 2026-09-15): a follow-up board on the dashboard, tab 'Pipeline' between My line and Buy packages, with its own training video on the Training tab. Columns: Talking to, Joined, Wallet linked, Payouts on, Bought, Building, Later. Prospects (from the My line prospect list) and directs are placed automatically from what they have actually done (coaching rung, on-chain buys); nobody drags cards. The sponsor adds a note, a follow-up date and a tag (hot, later, no response, not interested); a 'Follow up today' strip lists due cards; stalled cards (quiet 3+ days) are flagged; each card carries the message for its exact stage with 'Open chat with this message' (member chat) or copy. -- LEADER TOOLS (since 2026-10-16): a 'Leader tools' section on the Training tab with the Leader's Guide (a downloadable PDF: building wide, how width unlocks levels 2 and 3, network reach, Qualified Start, LinkSpin, the wallet as your key, the first week), the narrated presentation to share, and the Build wide video. My line and Pipeline each have a Leader tools card with a direct 'Download the Leader's Guide (PDF)' button and 'Open Leader tools'. -- UNACTIVATED SPONSOR = WALK UP, NEVER HOLD (2026-09-16, Marty): if a buyer's sponsor has not linked a wallet or switched on payouts, the purchase is NOT held. The site walks the sponsor line upward to the first upline who is activated with payouts on and the buy goes through under them (on-chain sponsorship for that buyer is then theirs, permanently); if nobody in the line is activated it goes under the company catch position (#1). The buyer sees a one-line notice and proceeds; once the position exists on the chain the skipped sponsor gets a blunt email + on-site message (they lost this referral for good, how to switch on payouts) and the upline who was paid gets a message that the referral is theirs permanently with a nudge to coach the one who missed it; the referral MOVES to whoever got paid (the account's stored sponsor is re-pointed when the position is created on-chain), so the buyer leaves the skipped sponsor's My line for good; the skipped sponsor can never earn from that wallet. Only a transient chain error ('rpc') still pauses a buy ("try again in a minute"). -- DRILL DOWN FROM THE OVERVIEW (2026-09-15): every name chip in 'Your line at a glance' on the Overview is clickable; it jumps to My line with that person's Activity panel already open and the row highlighted. -- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through ', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends. -- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin. -- PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members. -- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL NINE games (linked positions share it). Paid with 500 PURCHASED-grade credits (ads.gamePurchase purchasedOnly, the PolyWarriors mint rule; earned credits never buy a pass); with no purchased credits the pass waits and a $5 package bought meanwhile starts it automatically (the member keeps the package credits). Buying while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit. PER-GAME PERKS (live 2026-10-22, also listed on the Game Pass card): PolHunter 5 missions/day instead of 3 + 2 Ad Detective cases/day; Gem Kingdom 1 free continue/day; Spooky Doors +1 door/day; ClutterHunt 2 bonus hints/day; SpellWheel streak 0.30 POL instead of 0.15 + 1 free hint/day; PolyBreak gem limit 1.5 POL/day instead of 0.5 + extra paddle every round; PolyWarriors 4th daily mission + defense 25 Circuits instead of 15; Drip Runner free shield every run; Road Agent 2 patrols/day + 25% more scrap. Buying a pass unlocks the gold Game Pass achievement badge (Members > Overview badges, share or post to Telegram). New free caps start 2026-10-29. -- PLATFORM FACTS (2026-10-06): instantadpay.com/facts (footer link 'Platform facts') and instantadpay.com/llms.txt are the verified reference for how InstantAdPay works: contract 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 on Polygon; split 50% L1 / 20% L2 (needs 2 referred $20+ buyers) / 10% L3 (needs 5) / 10% platform wallet A / 10% platform wallet B, unqualified shares pass up (25 steps) then go to wallet A; purchased credits are on-chain (engine burns them in batches), earned credits are in the site database; credits are not transferable or cashable; POL payments are final, platform may return credits when a campaign fails because of a platform problem. When someone asks how the platform, payouts, credits or refunds work, answer from these facts and link /facts. -- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed. -- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility. -- LAUNCH WEEK SWIPES (2026-09-15): the founding-week checklist page (/launch) ends with four promoter emails members send to their OWN lists, one a day toward Monday's opening, with the member's invite link and the FOUNDER code (500 credits for anyone who joins before Mon 2026-09-21 9 AM Central) filled in, each with a Copy button. These are swipes for members, not emails the site sends. -- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 3 member slots run at once because every slot shares the same sign-ins; when all 3 are taken the buy is refused until one ends, and a paused slot can only be resumed while a slot is open. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks. -- AD VIEWER OPEN-IN-TAB (2026-09-19): the earn viewer shows the advertiser's page inside a frame; a link in its bar opens the same site in a new tab for sites that refuse to load framed or where signing up is easier in a full tab. The view still credits from the frame's countdown and check. -- (2026-09-14 hold rule REPLACED on 2026-09-16 by the walk-up rule above: a purchase is never held for an unactivated sponsor; only a transient chain read error pauses a buy.) -- NO-PAYOUT POSITIONS (2026-09-14): admin can list member ids (Settings > No-payout positions) whose wallets must never be paid again (e.g. a compromised key). Those positions stay linked for history and counting only: the buy-from picker disables them, a purchase from them is refused, and invite links that would place a new member under them (or under their upline chain) route to the fallback sponsor instead. The contract itself cannot change a member's wallet. -- LINE AT A GLANCE, ALL LEVELS (2026-09-14): a gold chip on any level means that person made their $20+ buy (a qualifying buyer for their own sponsor); a small number on the chip is how many qualifying buyers of their own they have. My line rows say the same in words. Leaders use it to see who is one buyer short and encourage them. -- MY LINE SPONSOR LINE (2026-09-14): every row on My line, all three levels, shows who sponsored that person ("sponsored by @name", or "you" for directs). -- MY LINE ACTIVITY DROP-DOWN (2026-09-14): every row on My line, all three levels, has an Activity button that opens that person's activity: last seen, joined, stage and next step, ads viewed today and claim streak, campaigns active, link views in 30 days and joins, directs and qualifying buyers, wallet/payouts, badges, and a Working or Quiet verdict. Read-only, phone friendly. -- GETTING STARTED CARD (2026-09-14): the top of every new member's Overview shows four steps (username, link wallet, switch on payouts, first package) with the current one explained and one button that opens the right tab and highlights the control (Wallet tab > Link wallet; then Activate payouts). Encouragement only: it can be hidden, and members who only want to view ads and earn credits are never blocked. It disappears once all four are done. -- LEADERBOARD + REFERRAL CONTEST (2026-09-14): instantadpay.com/leaderboard ranks members by ad packages sold to people they directly sponsor (dollar value, read from the chain; a member's own linked positions and second accounts never count). Periods: this week (Monday to Sunday, Central time), this month, all time. Weekly and monthly winners are recorded automatically at rollover, announced in Telegram, and the credit prizes set by the admin (a ladder: 1st 1,000 / 2nd 500 / 3rd 250 weekly, 5,000 / 2,500 / 1,000 monthly by default) are granted automatically to those positions; the prize text is shown on the page and on the Overview's Leaderboard card, which also shows the member's own rank. Prizes are credits or packages, never cash. -- WHAT'S NEW / ROADMAP (2026-09-14): instantadpay.com/whats-new lists release notes (what shipped, dated, tagged new/improved/fixed) and the roadmap (planned / building, with rough ETAs). The Overview has a "What's new" card with the latest three notes and what is being built; a dot marks notes since the member's last look. Written by the admin in Admin > Releases. -- HOLDING TANK ALERTS: when new members land in the tank, a note at the top of every member's Overview names them (usernames) and a post goes to the team's Telegram payments topic; adopt from My line > Holding tank (your own $20 package required). -- LEGACY WELCOME (former Faucet Wave / Tier One Ads members): they join through instantadpay.com/from/faucetwave or instantadpay.com/from/tieroneads and, if their email is on the legacy list, welcome-back credits are added automatically at signup (former advertisers 500, former earners 150; once per person; credits, not POL). They land in the holding tank like any member who joins without a sponsor. SOCIALPIX GATE (2026-09-20): socialpix.club no longer takes ad posts; its visitors are sent to instantadpay.com/from/socialpix (advertiser copy by default, ?seg=earn for the earner copy). No welcome-back credits for SocialPix arrivals; they join free by email and land in the holding tank. -- PROMO CODES: partner site owners get a reusable code; a member redeems it on a join link (?promo=CODE) or in the Overview box "Have a promo code?" and receives free ad credits (amount set per code by the admin, one use per account; codes can cap uses or expire). Credits, not POL. -- DORMANT-LEAD RESCUE: a FREE referral (no wallet, no purchase) with no message from their sponsor for 10 days triggers a warning email + dashboard flag to the sponsor ("unreached, tank in N days"); at 14 days (warning at least 4 days old) the lead moves to the holding tank and the sponsor is told. Sponsor resets the clock with a chat, a Nudge, or the "Contacted them" button (for phone/text contact). Leads whose sponsor link resolves to nobody go to the tank after a day. Nothing on-chain moves; anyone bound by a purchase never moves. -- PIF (pay it forward) button: on a free direct or an adopted member who has linked a wallet, the sponsor taps PIF, enters an amount (suggested: the $20 package plus fees), and their OWN wallet app opens with the member's address prefilled; the POL goes wallet to wallet. The site never touches the funds; it only logs the transaction and tells the recipient with a Polygonscan link. The gift is theirs; nothing forces a purchase. Before every PIF the member confirms a plain warning: the funds go wallet to wallet in good faith, InstantAdPay never holds or moves them and cannot reverse or recover them, and the member should only send what they are willing to give. You cannot PIF someone still in the holding tank: adopt them first, they link a wallet, then the button appears. -- PIF RISK (Marty, 2026-09-17, say this EVERY time PIF comes up, never sell PIF as a tactic): tell the member to make contact and get an explicit commitment BEFORE sending anything. The transfer is wallet to wallet and irreversible, there is no refund or chargeback and support cannot claw it back. The recipient may go quiet, spend it on something else or never sign in again, and none of that breaks any rule. A tank member joined with nobody working with them and may never have engaged, so an unanswered PIF is the easiest money on the site to lose. Honest arithmetic: if they buy $20 the sponsor gets 50 percent back so a gift that works costs about half, and a gift to someone who never answers costs all of it. Never gift money they need, never borrow to do it. If a member asks "should I PIF someone from the tank", the answer starts with talk to them first, not with the mechanics. -- FOUNDING WEEK / PRE-LAUNCH (Training > Founding week checklist, /launch, members only): eight items read live from the account: username, wallet linked, payouts on, level 2 qualified (2 buyers of $20+, or Qualified Start with 2 linked positions), the leader play = level 3 (5 qualifying buyers, up to 5 linked positions; then buy from the main wallet), line banner, links + play chosen (self-marked), first two placed. Reason: unqualified levels pass up, so leaders qualify BEFORE their teams' teams buy. Countdown shows when admin sets launchAt. Never call the site 'pre-launch' publicly: it is live and paying. -- COUNTRY TARGETING (2026-09-11): New campaign form has "Show to" tier checkboxes (Tier 1 = US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE by default; Tier 2 = rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO, etc.; Tier 3 = everyone else; lists editable in Admin > Settings geoTier1/geoTier2). Country comes from the viewer's IP (DB-IP lite). Applies to on-site delivery of every format; a narrowed banner/text ad is NOT sent to the partner network (which is worldwide). Unknown country never matches a narrowed campaign. Campaign rows show 'tier 1+2' chips and top viewer countries. -- SCHEDULING (2026-09-11): any campaign except featured can take an optional start and end time (local time) in the New campaign form; solo ads label it "Send from" (inbox deliveries begin then). A scheduled campaign shows "scheduled" until it starts; at the end it shows "ended" and the unspent budget returns to Available. Banner/text scheduled campaigns join the partner network at their start time. There is NO dayparting (hours-of-day targeting) by design; the daily cap paces budgets. Each campaign row shows a small views-by-hour chart (on-site views, viewer's local time, last 7 days). -- BALANCE RULE (members ask this a lot): a balance is what is NOT committed to a live campaign. Starting a campaign sets aside its whole budget at once (earned pool first, then purchased), so Available drops once and stays still while ads serve; the budget spends down inside Members > Campaigns. Dashboard shows Purchased available, Earned available, In live campaigns. A paused campaign keeps its unspent budget set aside so it can resume. A low balance with a live campaign is not lost credits. Refunds/comps of purchased money are credited off-chain as purchased-grade credits: shown under Purchased as "credited to you", fund anything incl. login ads. Viewing-earned credits never fund login ads. -- Members EARN credits by attention: in the Earn credits section of Members, each ad in the daily set opens FULL SCREEN in its own tab, showing the advertiser's real website. A countdown runs while you watch (it pauses if you leave the tab), then a quick human check (click the named icon) must be passed before the view counts. Finish the daily set, claim a small daily credit batch. Earned credits fund every campaign format except login ads; attention earns advertising, referrals earn money, and viewer rewards are never cash. DAILY SIGN-IN BONUS: separate from the claim, the first sign-in of each day pays 5 credits, rising by one per consecutive day up to 10; a missed day resets it. REPORT AN AD: every served ad carries a 'report' link (broken, inappropriate, spam, scam, other, plus a note) that emails the admin; the Shorts page uses reason buttons. Advertisers get real, verified visits to their site. -- Onsite SOLO ADS are live: a solo ad is a full message (subject + up to 2000 characters of formatted text + your link) delivered into members' on-site Inbox (Members > Inbox). The composer in Campaigns > Solo ad has a rich-text editor (bold, headings, lists, links), lets you ATTACH one image (PNG/JPG/WebP/GIF, up to 3MB) or one video (MP4/WebM, up to 25MB), and adds a call-to-action button with a custom label that opens the target URL. Cost 5 credits per guaranteed delivery, minimum 10 deliveries (50 credits). Each member receives a given solo at most once, and never the sender's own. Readers earn 2 credits per real read (10-second dwell on the open message, up to 5 rewarded reads/day) — claimed right from the message. Compose one in Campaigns > Solo ad. -- Campaign target URLs are checked the moment they are submitted: the page must be reachable and must ALLOW framing (no X-Frame-Options deny/sameorigin, no blocking CSP frame-ancestors), because surf views show the real site full screen. Frame-blocking or dead URLs are rejected with the exact reason; the fix is a landing page that allows framing. Login-ad targets skip the frame check (they are click-through only). -- SPONSOR CHAT (Members): a two-way, one-to-one chat. A member can start a conversation with their DIRECT sponsor; a sponsor can message anyone in their downline. Presence-aware — when both are online it is live, otherwise a message waits in the recipient's on-site inbox and sends an email. Each member has an availability toggle in Profile (default on; turning it off stops live chats but people can still leave a note) and can mute a specific person. This is separate from the once-a-day sponsor BROADCAST to the whole downline. -- PASSIVEDRIP (LIVE on the Earn tab for every member since 2026-10-03): https://passivedrip.com, an EARNING SITE (never call it a game): faucet claims, paid-to-click ad views, offers (offer walls) and a daily bonus roll earn coins; at 2,000 coins ($1) the balance is paid out AUTOMATICALLY in POL on Polygon to the wallet saved on PassiveDrip. The Earn tab card (More ways to earn: PassiveDrip) opens it with ONE TAP using the InstantAdPay account (no new password; it offers the member's InstantAdPay wallet to save). No income is promised. -- POLYBREAK (opens 2026-10-13, https://polybreak.app, in Members > Games): a free Arkanoid-style brick breaker. Eight hand-built rounds that then repeat with tougher silver bricks; colored bricks break in one hit, silver takes more hits each round, gold never breaks. Capsules: S slow, C catch, L laser, E enlarge, D disrupt (three balls), B break (a gate in the right wall skips the round), P extra paddle. One-tap sign-in with the InstantAdPay account; guests can play and their first clears are paid once they sign in. PAYS POL: the first clear of each round (replays pay nothing) and catches of the purple Polygon gem (a small random amount each time, the gem appears every so often during play), into the PolyBreak game balance, sent automatically to the wallet on the member's InstantAdPay account at the payout line shown in the game; rewards are paid from the game's pool, funded by a share of the one-more-paddle visits. ONE MORE PADDLE: when the last paddle is lost, a verified visit to a member's page (or a member video) continues the round with one paddle; it uses the daily refuel allowance shared with the other games. REFERRALS: each player's share link polybreak.app/r/; a sponsor earns a share of the pool income from the paddle visits of players they invited. Never state a maximum or total a player can earn and never promise income. -- POLYWARRIORS (LIVE 2026-10-12, https://www.polywarriors.com, in Members > Games): a free cyberpunk turn-based fighting game. Recruit warriors that are each born with their own traits and rarity (Common, Rare, Epic, Legendary); fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit); challenge other members to async duels that play out while they are away. The FIRST win over each rival pays POL to the wallet on the member's InstantAdPay account (replays pay nothing). The first warrior mints to the member's wallet as an NFT on Polygon for free; after that every $5 ad package bought on InstantAdPay earns a mint pass. Fusion: three warriors of the same rarity fuse into one rarer warrior (the three are consumed). Marketplace: warriors trade between members, settled in POL. One-tap sign-in with the InstantAdPay account; guests can try fights but earn nothing until they sign in. A 40-second trailer and a promo kit are in Promo tools > Games > PolyWarriors. Never state a maximum or total a player can earn and never promise income. -- SPELLWHEEL (LIVE 2026-10-10, https://spellwheel.com, in Members > Games): a free letter-wheel word game: swipe letters on the wheel to fill the crossword grid, travel through six cozy places (chapters), and solve a new daily puzzle shared by everyone. Pays POL for clearing levels, finishing a place and solving the daily puzzle, collected in the SpellWheel balance and sent automatically to the wallet on the member's InstantAdPay account. One-tap sign-in with the InstantAdPay account. Never state totals or promise income. -- CLUTTERHUNT (LIVE 2026-10-03, https://clutterhunt.com, in Members > Games): a free hidden-object game. Search cozy, cluttered rooms for 12 hidden objects plus one sponsored find (a sealed letter with a sponsor's name; tapping it shows their ad). Rooms change with the seasons: the Haunted Manor (Attic, Library, Witch's Kitchen, Wizard's Study, Moonlit Greenhouse, Wine Cellar) through Oct 31, then new seasonal rooms. Objects move every round. Stars: finish under 3 minutes, use at most 1 hint, at most 6 wrong taps. 2 free hints a round; after that a short verified visit to a member's page earns a hint (shares the daily refuel allowance). Sign in with the InstantAdPay account right inside the game to save stars. PAYS POL since 2026-10-04: fixed rewards per room each season for the first clear and the first 3-star clear (more for Expert rooms, which unlock after all six rooms), collected in the ClutterHunt balance and sent automatically to the wallet on the member's InstantAdPay account once it reaches the payout amount. Players who cleared rooms before 10-04 can replay each room once to collect. NEVER state a maximum or total a player can earn (Marty's rule) and never promise earnings. -- SPOOKY DOORS (Halloween season game, 2026-10-02): https://spookydoors.com, open 2026-10-04 through Halloween night (closes at midnight Central at the end of Oct 31); its Games tab card shows only during the season, with a "Limited time, ends Oct 31" ribbon. Members sign in with one tap from Members > Games. Walk the street, collect candy, avoid black cats and bats, knock on doors. Each door is a verified visit to a member's page or ad (a member video once every page has been visited), the advertiser is charged as for any visit, the player gets candy not credits; 15 doors per Central day, separate from the 20 Earn-tab visits and the 20 Drip Runner refuels. A treat is 10 candy; about 1 door in 5 is a trick (a ghost or skeleton you tap 5 times quickly; beat it for a 3 candy bonus, miss it for half the treat). If no paid ad is left for that player, the door shows a house ad for one of our own programs: a smaller treat (5 candy), and it still counts toward the 15 doors. CANDY LADDER pays POL once per rung: 100 candy 0.1 POL, 250 0.25, 500 0.5, 1,000 1, 2,000 2 (Halloween 2026 badge at 500), paid from a season pool funded by a share of door ad spend and costume sales, only while the pool covers it; the game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. COSTUMES bought with ad credits like Gem Kingdom Crowns: witch free, vampire 300 credits (longer trick timer), bedsheet ghost 300 (black cats ignore you), Lucky caramel apple 500 (+2 candy per treat); no cash value. Top 20 by candy on the season leaderboard. DOOR PACKS: creating a verified-visits campaign, the advertiser picks Everywhere (3 credits per visit, as before), Behind Spooky Doors (4 credits per door) or Golden Spooky Door (6 credits per door; the player gets +2 bonus candy). Paid up front like any visit pack. Door packs are served first on doors (Golden Doors before door packs), each player sees a pack at most once per Central day, they never run on the Earn tab or refuels during the season, and from Nov 1 any doors left run as normal visits; the campaign shows doors opened and unique players. Never promise earnings or call it income. -- GEM KINGDOM (LIVE in the Games tab since 2026-10-02): Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon's Peak, the Sunken Reef, the Shadow Citadel), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for FIRST clears only (stages 0.02 to 0.15 POL rising by chapter; bosses 0.25, 0.5, 2, 5, 7.5 and 10 POL for the Goblin King, Ice Queen, Bog Witch, Ember Dragon, Kraken and Shadow King); replays pay nothing. The game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. Rewards come from a pool funded by a share of Crown purchases and pay only while the pool has funds; never promise earnings or call it income. No referral bonus on game clears. Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game's Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. Never promise an amount beyond the posted rewards. (2026-10-03) FREE REVIVE: after a defeat, a short verified visit to a member's page (InstantAdPay verified-visit flow inside the game, shares the 20-a-day refuel allowance with Drip Runner) revives the party once per battle; a revived win earns at most 2 stars. SPECIALS in the Crown shop: Hero Bundle (one time, $5 = 500 credits: a tier-1 forge weapon, one building level, 60 Crowns), Kingdom Pass ($10 = 1,000 credits for 30 days: 10 Crowns a day credited on the first visit each Central day, a 25-Crown chest every 7 days, the three Royal hero looks; no auto-renew, buying again adds 30 days), Hero looks (cosmetic only: Halloween looks Pumpkin Knight, Moon Witch, Scarecrow Ranger for 40 Crowns each, sold through Oct 31 and kept forever; Royal looks with the Pass). Only the purchased-credit part of a purchase funds the POL reward pool. -- GAMES TAB (2026-10-01): Members > Games (/my#games) shows one card per network game (as of 2026-10-15: PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Road Agent, Spooky Doors during Halloween; all pay POL to the member's InstantAdPay wallet), with their own progress and a Play button that signs them in with one tap; new games appear there as they launch (PolHunter is one card). DRIP RUNNER (https://driprunner.app, LIVE for every member since 2026-10-01): tap-to-hop runner; gold drips, magenta bots, orange firewalls from chapter 2; each chapter has a drip goal for one run; the FIRST clear of a chapter pays a small POL drip (amount set by the admin, shown in the game) into the game balance, replays pay nothing; the balance is sent on Polygon to the member's InstantAdPay wallet once it reaches the payout line shown in the game. REFUELS: a run that ends can be refuelled with a verified visit to a member's page (a member video once every page has been visited), up to 20 a day, separate from the 20 Earn-tab visits; the advertiser is charged as for any visit, the player gets fuel not credits. The POL pool is funded ONLY by a share of refuel ad spend plus POL spent in the hangar, so drips depend on refuels and can be zero when the pool is empty; say so honestly. HANGAR: Drip Magnet and Courier Mk II cost drips (game currency); Shield Core and Slow Field cost POL from the game balance, which returns to the pool. GUESTS can try a run without signing in; their clears pay once they sign in. REFERRALS: each player's share link /r/; when members whose InstantAdPay sponsor is that player refuel, a share (10 percent by default) of each refuel's pool income goes to the sponsor's game balance. Telegram posts achievement badges (chapters, unlocks, refuel milestones, payouts). Never promise amounts or income. The public list of every game, open now and opening next, is https://instantadpay.com/games (shareable; add ?ref= to keep the referral). -- Every purchase is split by an immutable smart contract in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. No withdrawals exist; money lands in members' own wallets instantly. -- Qualification: level 1 open to all; 2 buyers of $20+ unlock level 2; 5 unlock level 3. Unqualified shares pass up the sponsor line, checking up to 25 positions, else the platform receives them. Qualification cannot be bought and never expires. -- Every member gets a share link immediately (site code, /join/); the contract locks a buyer to their sponsor at the buyer's FIRST purchase, so members should switch on payouts before their referrals buy. -- Transparency: live ledger at /ledger streams every chain event, and EVERY transaction row carries a clickable "verify" link — to the public block explorer when the chain has one, or to the built-in transaction viewer at /tx/ (block, time, from/to, value, gas, decoded events, read live from the node). Plain-language contract review at /contract; the verified source is public. -- The contract cannot be paused, upgraded, or drained. The operator can only manage the ad catalog ($1-$500 bounds, 24h price timelock) and rotate keys. - -PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile, /my#help (Help: support tickets). Public: /support (contact form for anyone signed out or locked out; support@instantadpay.com also works), /join/ (invite page, ?v=angle), /wall/, /b//, /handout/, /ledger, /tx/, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix. - -RULES: -- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above. -- Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor. -- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes. -- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen. -- No em dashes. If you do not know, say so and point to /contract or the ledger. -- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : ''); -} - -// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai -function endpoint() { - try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); } -} -function askAI(message, historyText, kbBlock) { - return new Promise((resolve, reject) => { - const body = JSON.stringify({ - model: MODEL, - reasoning: { enabled: false }, // 2026-10-16: deepseek-v4-flash now thinks by default and spent the whole max_tokens on it (empty answers) - max_tokens: 300, - messages: [ - { role: 'system', content: systemPrompt(kbBlock) }, - ...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []), - { role: 'user', content: String(message).slice(0, 600) } - ] - }); - const ep = endpoint(); - const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST', - headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(body) }, timeout: 30000 }, - res => { - let d = ''; - res.on('data', c => d += c); - res.on('end', () => { - // OpenRouter pads a slow upstream with keepalive lines before the JSON, and when the - // provider gives up it can close having sent ONLY that padding: HTTP 200, no body. - // JSON.parse then threw and every question died on "I hit a snag" (Marty, 2026-09-17). - // Find the actual JSON object, and treat an empty answer as a failure worth retrying. - const i = d.indexOf('{'); - if (i < 0) return reject(new Error('openrouter ' + res.statusCode + ': empty body (' + d.length + ' bytes of keepalive)')); - let txt = ''; - try { txt = String(JSON.parse(d.slice(i)).choices[0].message.content || '').trim(); } - catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(i, i + 150))); } - if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content')); - resolve(txt); - }); - }); - req.on('error', reject); - req.on('timeout', () => req.destroy(new Error('openrouter timeout'))); - req.end(body); - }); -} - -const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) not (see|check|look)|contact support|reach support|support (ticket|desk)|\/support\b|my#help)/i; -// every reply leaves without em dashes (Marty's voice rule; the model slips one in now and then, 2026-10-20) -async function answer(message, historyText) { const r = await answerRaw(message, historyText); if (r && typeof r.reply === 'string') r.reply = r.reply.replace(/\s*\u2014\s*/g, ', '); return r; } -async function answerRaw(message, historyText) { - const msg = String(message || '').trim(); - if (!msg) return { error: 'Say something first.' }; - // fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down - let hit = null, kbOk = true; - try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); } - if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {}); - if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); - // retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far) - let kbBlock = '', kbIds = []; - try { - const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg; - const hits = await kb.context(query, 5); - kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id); - } catch (e) { console.error('kb search', e.message); } - if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true }; - // One retry: the usual failure is a single provider dropping the request, and asking - // again almost always lands. Only after both fail do we admit defeat. - for (let attempt = 0; attempt < 2; attempt++) { - // handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16) - try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); } - catch (e) { - console.error('chat AI failed (attempt ' + (attempt + 1) + ')', e.message); - if (attempt === 0) await new Promise(r => setTimeout(r, 700)); - } - } - // Never a dead end: say plainly that it was us, and offer a person. - return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true }; -} - -module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt }; +// 24/7 site assistant (RM Circle pattern): canned answers first for the +// questions everyone asks, OpenRouter AI for everything else, hard honesty +// rules baked into the system prompt. +// +// HOUSE RULE: whenever a site feature changes, update BOTH the CANNED +// answers and FACTS below in the same commit. +// +// KNOWLEDGE BASE (2026-10-20, kb.js): CANNED below and kb-seed.js SEED the knowledge base, which is +// the one source the assistant answers from. Each CANNED regex becomes its entry's instant-answer +// pattern (same order, first match wins), and for everything else the best-matching entries go into +// the system prompt. Admin > Knowledge base edits entries; an edited entry is no longer refreshed from +// the code. If the KB store fails, the in-code CANNED list still answers. +const fs = require('fs'); +const path = require('path'); +const https = require('https'); +const http = require('http'); +const kb = require('./kb'); +const kbSeed = require('./kb-seed'); + +let DATA_DIR = null; +let chain = null; +const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'; + +function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); } +function key() { + if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); + try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } +} +function enabled() { return !!key(); } + +// ---- canned answers: instant, free, always in voice ---- +const KNOWLEDGE_DATE = '2026-10-22'; // bump whenever the canned answers / prompt are brought up to date +const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; +const CANNED = [ + { id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'], + re: SUPPORT_RE, handoff: true, + a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' }, + { id: 'game-pass', title: 'Game Pass and daily POL caps', q: ['What is the Game Pass?', 'Why did I hit the daily POL cap in the games?', 'Does a boss reward carry over to the next day?'], tags: ['games', 'game pass', 'daily cap', 'tournament'], + re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i, + a: 'The Game Pass is $5 for 7 days and covers all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the gold Game Pass badge with your name. Per game: PolHunter 5 missions a day instead of 3 plus 2 Ad Detective cases; Gem Kingdom one free continue a day; Spooky Doors one extra door a day; ClutterHunt 2 bonus hints a day; SpellWheel daily streak 0.30 POL instead of 0.15 plus 1 free hint a day; PolyBreak daily gem limit 1.5 POL instead of 0.5 plus an extra paddle every round; PolyWarriors a 4th daily mission and defense pays 25 Circuits instead of 15; Drip Runner a free shield at the start of every run; Road Agent 2 patrols a day and 25% more scrap. The full list is on the Game Pass card. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Buy it in Members > Games > Game Pass: it costs 500 purchased credits (credits from a package you bought; earned credits do not count). If you have none, buy a $5 package and the pass starts the moment it settles, and you keep every credit of the package for your ads. Buying while a pass is active adds 7 days.' }, + { id: 'road-agent', title: 'Road Agent (night-highway shooter)', q: ['What is Road Agent?', 'How do fuel stops work in Road Agent?'], tags: ['games', 'road agent', 'fuel stop'], + re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i, + a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' }, + { id: 'presentation', title: 'The InstantAdPay presentation video', q: ['Where is the presentation video?', 'How do I share the presentation with my link?', 'What is the Build Wide video?'], tags: ['presentation', 'video', 'share', 'captions', 'build wide'], + re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i, + a: 'The InstantAdPay presentation is a narrated video of about six minutes at https://instantadpay.com/presentation, with captions in English, Italian, French, Spanish, German and Portuguese (pick the language under the video). It covers what the platform is, how far your ads reach, how one $20 purchase pays $10, $4 and $2 up three levels in the same transaction, why two and then five qualifying buyers unlock levels 2 and 3, Qualified Start, the Pipeline, LinkSpin and your first week. Members share it from Members > Promo tools > Share the presentation: the link carries your username (instantadpay.com/presentation?ref=), sets you as the sponsor exactly like your invite link, and the page shows you as the person who shared it with a Join button. There is also a short Build Wide video, the first card under Promo tools > Videos, with its own front door ?v=wide on your invite link (the page opens on that video). The examples are illustrations, not promises of income.' }, + { id: 'passivedrip', title: 'PassiveDrip earning site', q: ['What is PassiveDrip?', 'Is there a faucet or paid to click?', 'When do coins turn into POL?'], tags: ['passivedrip', 'faucet', 'ptc', 'coins', 'earn'], + re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i, + a: 'PassiveDrip (https://passivedrip.com) is our earning site, listed under More ways to earn on your Earn tab. Claim the faucet, view paid-to-click ads, complete offers and roll the daily bonus for coins. When your balance reaches 2,000 coins ($1) it is paid out automatically in POL to your wallet on Polygon. Open it from the Earn tab with one tap: it signs you in with your InstantAdPay account, no new password. Add your Polygon wallet there so payouts can reach you. What you earn depends on what you do there; nothing is guaranteed.' }, + { id: 'spellwheel', title: 'SpellWheel word game', q: ['What is SpellWheel?', 'Is there a daily word puzzle?'], tags: ['games', 'spellwheel', 'word game', 'daily puzzle'], + re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i, + a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a free word game: swipe the letters on the wheel to fill the crossword grid, travel through six cozy places, and solve a new daily puzzle that everyone gets at the same time. Sign in with your InstantAdPay account right in the game to save progress: clearing levels, finishing a place and solving the daily puzzle each pay POL, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' }, + { id: 'polybreak', title: 'PolyBreak brick breaker', q: ['What is PolyBreak?', 'How do I get another paddle?'], tags: ['games', 'polybreak', 'brick breaker', 'gem'], + re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i, + a: 'PolyBreak (https://polybreak.app, also in Members > Games) is a free brick breaker in the Amiga arcade style: break a wall of glass jewel bricks with the ball and paddle, catch falling capsules (wider paddle, split ball, lasers, slow ball, catch, a break gate that skips the round, an extra paddle), and catch the purple Polygon gem when it drifts down. Sign in with your InstantAdPay account in one tap. Your first clear of each round pays POL into your PolyBreak game balance, and each gem catch pays a small random amount of POL; the balance is sent to the wallet on your InstantAdPay account automatically at the payout line shown in the game. Out of paddles? A short visit to a member\u2019s page gives you one more paddle on the same round. Share your PolyBreak link from the game: when people you invite play, you earn a share too. Nothing here is a promise of income.' }, + { id: 'polywarriors', title: 'PolyWarriors fighting game and NFT warriors', q: ['What is PolyWarriors?', 'How do I get a mint pass?', 'How does fusing warriors work?'], tags: ['games', 'polywarriors', 'nft', 'mint pass', 'duel'], + re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i, + a: 'PolyWarriors (https://www.polywarriors.com, also in Members > Games) is a free cyberpunk turn-based fighting game, open since Oct 12. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit), and challenge other members to duels that play out while you are away. Your first win over each rival pays POL to the wallet on your InstantAdPay account. Your first warrior mints to your wallet as an NFT on Polygon, free; after that each $5 ad package you buy on InstantAdPay earns a mint pass. Fuse three warriors of the same rarity into one rarer warrior, and trade warriors with other members on the marketplace, settled in POL. Sign in with your InstantAdPay account in one tap. Nothing here is a promise of income.' }, + { id: 'clutterhunt', title: 'ClutterHunt hidden-object game', q: ['What is ClutterHunt?', 'How do hints work in ClutterHunt?'], tags: ['games', 'clutterhunt', 'hidden object', 'hints'], + re: /(clutter ?hunt|hidden.object|haunted manor)/i, + a: 'ClutterHunt (https://clutterhunt.com, also in Members > Games) is a free hidden-object game: search cozy, cluttered rooms for 12 hidden objects plus one sponsored find. This season is the Haunted Manor (six rooms) through Oct 31, then new rooms move in every season, and objects move every time you play. You get 2 free hints a round; after that, a short visit to a member’s page earns another. Sign in with your InstantAdPay account right in the game to save your stars and earn POL: each room pays POL for your first clear and your first 3-star clear every season (Expert rooms pay more), collected in your ClutterHunt balance and sent to the wallet on your InstantAdPay account automatically.' }, + { id: 'spooky-doors', title: 'Spooky Doors Halloween game', q: ['What is Spooky Doors?', 'How does the candy ladder pay?', 'How do I buy a costume?'], tags: ['games', 'spooky doors', 'halloween', 'candy', 'costume'], + re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i, + a: 'Spooky Doors (https://spookydoors.com) is the network\u2019s Halloween game. It opens on Oct 4 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Advertisers can also put a verified-visits pack behind the doors: when you create a verified-visits campaign, pick Everywhere (3 credits a visit), Behind Spooky Doors (4 credits a door) or Golden Spooky Door (6 credits a door, and the player gets a little bonus candy). Door packs show only in Spooky Doors until the season ends, then any doors left run as normal visits. Nothing here is a promise of income.' }, + { id: 'games-tab', title: 'Games tab and Drip Runner', q: ['Which games pay POL?', 'What is Drip Runner?', 'How do refuels work?'], tags: ['games', 'drip runner', 'refuel', 'games tab'], + re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i, + a: 'Members > Games lists the network\u2019s games; one tap signs you in. Drip Runner is a runner game: tap to hop, collect gold drips, dodge the bots, clear chapters. The first clear of each chapter drips a little POL into your game balance, which is sent to your wallet once it reaches the payout line shown in the game. When a run ends you can refuel instead of restarting: a short verified visit to a member\u2019s page (or a member video when you have visited them all), up to 20 refuels a day, separate from your regular Earn visits. Refuels are paid for by advertisers, and a share of that funds the POL pool every drip is paid from, so drips depend on the pool and are small. Share your link from the game lobby: when people on your team refuel, a share of what their refuels add to the pool goes to your game balance. Nothing here is a promise of income. The Games tab also has PolHunter, Gem Kingdom (match-3, POL for first clears of stages and bosses), ClutterHunt (hidden objects), SpellWheel (word puzzle), PolyWarriors (cyberpunk fighting, open Oct 12), PolyBreak (brick breaker, opens Oct 13) and Spooky Doors during Halloween; Road Agent opens Thursday Oct 15. The public list of every game, open now and opening next, is https://instantadpay.com/games (add ?ref=yourusername to keep your referral).' }, + { id: 'gem-kingdom', title: 'Gem Kingdom match-3 and Crowns', q: ['What is Gem Kingdom?', 'How do I buy Crowns?', 'What do the bosses pay?'], tags: ['games', 'gem kingdom', 'crowns', 'match-3'], + re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i, + a: 'Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon\u2019s Peak, the Sunken Reef and the Shadow Citadel, where the Shadow King waits), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for first clears only: a little for each stage the first time you clear it, and more for each chapter boss (the Ember Dragon 5 POL, the Kraken 7.5, the Shadow King 10). Replays pay nothing. Rewards go into your game balance and are sent to the wallet on your InstantAdPay account on Polygon once it reaches 0.25 POL. They come from a reward pool funded by a share of Crown purchases, so they pay while the pool has funds (a clear the pool cannot cover pays nothing). Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game\u2019s Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. After a defeat you can also take a free revive by making a short verified visit to a member’s page. In the shop, Specials has a one-time Hero Bundle ($5: a forge weapon, a building level and 60 Crowns), the Kingdom Pass ($10 for 30 days: 10 Crowns a day, a 25-Crown chest each week and the Royal hero looks, no auto-renew) and Hero looks (Halloween looks for 40 Crowns each through Oct 31, yours to keep). Looks are cosmetic only.' }, + { id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'], + re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i, + a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' }, + { id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'], + re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i, + a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' }, + { id: 'five-dollar-friday', title: 'Five Dollar Friday bonus', q: ['What is Five Dollar Friday?', 'What happens on Friday?'], tags: ['five dollar friday', 'bonus credits', 'promotion'], + re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i, + a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' }, + // 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being + // signed out, and the honest answer reads far better than letting it look like a fault. + { id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'], + re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i, + a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' }, + { id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'], + re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i, + a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' }, + { id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is this a ponzi or a scam?'], tags: ['pyramid', 'scam', 'legit', 'ponzi'], + re: /(pyramid|ponzi|scam|scheme)/i, + a: 'Fair question. A pyramid pays for recruiting with no product; here every payment is for real ad delivery, bought by real advertisers, and the whole money flow is public. Check the code and every payout yourself at https://instantadpay.com/contract and https://instantadpay.com/ledger.' }, + { id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'What is the minimum payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'], + re: /(withdraw|cash ?out|payout request|minimum payout)/i, + a: 'There are no withdrawals here, ever. The contract pays your share straight to your own wallet in the same transaction as the purchase. Nothing to request, nothing to wait on.' }, + // "how much do I earn" used to fall through to the PRICE answer below, because that one + // matches "how much do" and this one only caught "how much earn" (Marty, 2026-09-17). + { id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'], + re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i, + a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' }, + { id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?', 'What does In live campaigns mean?'], tags: ['balance', 'credits', 'campaigns', 'credit activity'], + re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i, + a: 'One rule: your balance is what is NOT committed to a live campaign. When you start a campaign its whole budget is set aside right then (earned credits first, then purchased), so your Available number drops once and then sits still while the ad runs. The budget spends down inside that campaign in Members > Campaigns, where you can see delivered views, network views and what is left. The dashboard shows Purchased available, Earned available and In live campaigns as three separate numbers; a paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live. Purchased credits live on the blockchain; if we ever refund or credit purchased money it shows under Purchased as "credited to you" and spends like a purchase, login ads included. Earned credits fund every format except login ads. Two formats are flat buys paid in full when booked: featured links (sold by the day) and verified-visit packs. Adding credits to a featured link does nothing, so its row offers Extend run instead, which books more days at the daily rate; a visit pack offers Buy more visits. Every credit that comes in or goes out is listed with its reason under Members > Campaigns > Credit activity (also linked from Earn credits): sign-in bonus, daily claim, video watched, verified visit, campaign buys, views delivered per day, grants and refunds. Check it before assuming credits went missing.' }, + { id: 'payment-trace', title: 'Why someone was not paid: trace a payment', q: ['Why did my sponsor not get paid?', 'I missed a payment', 'How do I trace a payment?'], tags: ['payment trace', 'missed payment', 'earnings', 'pass-up'], + re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i, + a: 'Every purchase and every share is on the chain, and you can read it yourself: open Members > Earnings > Trace a payment, enter the member number or username (yourself, anyone up to 3 levels below you, or your own uplines), and each purchase they were part of is laid out level by level: who was paid, who was skipped and why. The three usual answers: the person had not unlocked that level when the purchase settled (level 2 needs 2 qualifying $20+ buyers, level 3 needs 5, and qualification never applies backwards); the buyer used Qualified Start, so the purchase came from a linked wallet whose sponsor is the buyer\'s own main position, which means level 1 went to the buyer themselves; or the person\'s payouts were not switched on. Skipped shares pass up to the next qualified person, never to nobody.' }, + { id: 'walk-up', title: 'Unactivated sponsor: the walk-up rule', q: ['What if my sponsor has not switched on payouts?', 'Why did my purchase go to the company position?'], tags: ['sponsor', 'walk up', 'payouts', 'activation'], + re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i, + a: 'Your purchase never waits on your sponsor. If the person who referred you has not linked a wallet and switched on payouts when you buy, the site walks up your sponsor line to the first person who is activated with payouts on and the purchase goes through under them; if nobody in the line is ready it goes under the company position. You see a one-line note on the Buy tab and carry on. For the sponsor it is permanent: the contract locks a buyer to whoever was paid at the first purchase, so that referral moves to the upline who was paid and they cannot earn from that wallet later. They get a message saying so, and the upline gets one too. Two minutes on the Wallet tab prevents it.' }, + // PIF + the holding tank. Asked together often ("should I pif someone from the tank"), + // and the honest answer is that the order matters: you cannot PIF someone still in the + // tank. Canned so it never depends on the AI provider being up (Marty, 2026-09-17). + // The second alternation catches the same question asked without the word PIF + // ("should I fund their first package", "can I buy it for them"). It needs BOTH a + // paying verb AND an explicit for-someone-else phrase, so ordinary pricing questions + // like "which package should I buy" are not stolen (Marty, 2026-09-17). + { id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'], + re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i, + a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' }, + { id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'unsponsored'], + re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i, + a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances.' }, + { id: 'qualification', title: 'Qualification, levels 2 and 3, credits vs POL', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up', 'qualified start'], + re: /(qualif|unlock level|level 2|level 3|pass.?up)/i, + a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' }, + { id: 'free-member', title: 'What free members earn', q: ['What do free members get?', 'Do I have to buy anything?', 'Credits or POL?'], tags: ['free member', 'credits', 'pol', 'activation'], + re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i, + a: 'Free members earn ad credits: view ads, watch videos, make verified visits, read inbox ads, sign in daily. Credits buy your own ads and are never cashed out. POL, the real crypto, is paid to your wallet by the contract when your referrals buy packages, once you are activated: the $20 starter package (2,000 credits to advertise with) and payouts switched on from the Wallet tab. Your own $20 purchase also makes you count as a qualifying buyer for your sponsor, and two or five such buyers in your own line open levels 2 and 3 for you.' }, + { id: 'join', title: 'How to join; do I need a wallet?', q: ['How do I join?', 'Do I need a wallet?', 'Do I need crypto experience?'], tags: ['join', 'sign up', 'wallet', 'email'], + re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i, + a: 'Join free with just your email at https://instantadpay.com/my, no wallet and no password needed. Your wallet only comes out when you buy a package or switch on payouts, and the site walks you through it.' }, + { id: 'referral-link', title: 'My referral and invite links', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools', 'angles'], + re: /(referral link|invite link|share link|refer)/i, + a: 'You get your share link the moment you sign in, free members included. Open Members > Promo tools: the "Your links" block at the top lists your invite link plus five angle versions (Instant, Ad spend, Free, Ledger, Two), each with a note on who it is for and Copy and Share buttons. They are the same link with a code on the end, so every join and purchase credits you; only the first page the person sees changes. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' }, + { id: 'banner-image', title: 'Banner image link and sizes', q: ['Why was my banner image refused?', 'What banner sizes are there?', 'How do I upload a banner?'], tags: ['banner', 'image', 'sizes', 'campaign'], + re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i, + a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' }, + { id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the email swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners', 'objections'], + re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i, + a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, and an Objection handling bank with the truth plus a ready-to-send reply. Everything is personalized with your invite link.' }, + { id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'], + re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i, + a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' }, + { id: 'wall', title: 'Your banner wall and its three positions', q: ['How does my wall work?', 'How do I own wall positions 2 and 3?'], tags: ['wall', 'banner wall', 'positions'], + re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i, + a: 'Your wall (instantadpay.com/wall/yourname) shows three ads. Position 1 is always your line banner. Positions 2 and 3 show your upline (or InstantAdPay) until you earn them: 2 qualifying buyers ($20 or more) make position 2 yours, 5 make position 3 yours, so a fully qualified member owns the whole page with their own links and offers. Set them in Profile > Your wall; an unlocked slot you leave empty keeps showing your upline until you fill it.' }, + { id: 'solo-ads', title: 'Solo ads and the inbox', q: ['What is a solo ad?', 'How do inbox reads pay?'], tags: ['solo ad', 'inbox', 'campaigns'], + re: /(solo ad|inbox ad|inbox)/i, + a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members: give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' }, + { id: 'sponsor', title: 'Who is my sponsor; wrong sponsor', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Can I change my sponsor?'], tags: ['sponsor', 'invite link', 'last touch'], + re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i, + a: 'The invite link you opened most recently sets your sponsor, and the join page shows it: "Personal invitation from @name". It locks the moment you create your account, so opening someone else\'s link afterwards changes nothing, and your first purchase binds you to that same sponsor on the contract. If you have not joined yet and the page shows the wrong name, open the right person\'s link and it updates. If you already joined under the wrong sponsor by mistake, message support before your first purchase and the admin can move you.' }, + { id: 'sponsor-chat', title: 'Sponsor Chat', q: ['How do I message my sponsor?', 'Can I chat with my team?'], tags: ['chat', 'sponsor', 'messages'], + re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i, + a: 'Yes, Members has a two-way Sponsor Chat. You can message your direct sponsor for help (from Overview or the chat button), and sponsors can message anyone in their line. If they are online you chat live; if not, your message waits in their on-site inbox and they get an email. Sponsors can set themselves unavailable in Profile (you can still leave a note, they just reply later) and mute a member if needed. It is separate from the once-a-day team broadcast.' }, + { id: 'earn-credits', title: 'Earning credits: the daily set, videos, visits', q: ['How do I earn credits?', 'How does the daily ad set work?', 'How much is the daily claim?'], tags: ['earn credits', 'daily set', 'claim streak', 'videos', 'visits'], + re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i, + a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits (5 on day one, 7 on day two, 10 from day three, 25 on every 7th day in a row), then keep going with videos (up to 8 a day), verified visits (up to 20 a day) and inbox reads (up to 5 rewarded a day). A separate sign-in bonus pays 5 credits on your first sign-in each day, rising by one per consecutive day up to 10. Earned credits fund every campaign format except login ads. You never see your own ads, and viewer rewards are credits, never cash.' }, + { id: 'featured', title: 'Featured links', q: ['How do featured links work?', 'How do I extend a featured run?'], tags: ['featured links', 'campaigns', 'extend run'], + re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i, + a: 'Featured links run in the strip at the top of every member\'s Overview. Book one under Campaigns for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead; at most 10 links share any day. It is a flat buy, paid in full when booked, and the row shows days left and "runs through" a date. To keep it going use Extend run on the row, which books more days at the same rate; adding credits does not add days. Views (one per viewer per hour) and clicks are counted on the row.' }, + { id: 'verified-visits', title: 'Verified-visit packs', q: ['How do verified visits work?', 'How do I buy visits?'], tags: ['verified visits', 'visit pack', 'campaigns'], + re: /(verified visit|visit pack|buy visits|visits campaign)/i, + a: 'A verified-visit pack sends real members to your site: each one opens it in a new tab, stays at least 8 seconds and passes a check, and no member counts twice. It costs 3 credits per visit, minimum 20 visits, paid in full when you create it, then it fills over time (each member can do at most 20 visits a day). The row shows "N of M visits delivered" and Buy more visits adds to the pack. Members earn 1 credit per verified visit.' }, + { id: 'overview-video', title: 'What is InstantAdPay? The four-minute overview', q: ['What is InstantAdPay?', 'How does this work?', 'Is there an overview video?'], tags: ['overview', 'video', 'what is'], + re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i, + a: 'The quickest answer is the four-minute overview video: it is the first card on Members > Training and on the home page at https://instantadpay.com/#overview-video. It covers what the platform is, what free members get, the campaign formats, how the contract splits every purchase, wallet and payouts, Qualified Start, the payment trace and the tools for building a line.' }, + { id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'Which package should I buy?', 'What do I get for my money?'], tags: ['packages', 'price', 'credits', 'qualification'], + re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i, + a: 'Seven packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Starter $10 for 1,000, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500, Elite $500 for 70,000. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' }, + { id: 'credits', title: 'What ad credits are', q: ['What is a credit worth?', 'What are ad credits?'], tags: ['credits', 'ad formats', 'impressions'], + re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i, + a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' }, + { id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'], + re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i, + a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' }, + { id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'], + re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i, + a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' }, + { id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'], + re: /(safe|trust|rug|run away|company disappear)/i, + a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' } +]; + +// CANNED + the FAQ seeds, in the shape kb.js stores (order keeps the first-match-wins sequence) +function seeds() { + return CANNED.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re.source, + handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(kbSeed.FAQ); +} + +// ---- facts for the AI fallback ---- +function systemPrompt(kbBlock) { + return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform. + +FACTS: +- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref= link. +- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time. +- PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide. +- WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money. +- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises. +- SESSIONS LAST 4 HOURS. Sign-ins expire after 4 hours and the member signs in again with a fresh 6-digit code. This is intentional and we say so plainly: it keeps resources optimised, and the login sponsor ad shown on the way back in is part of what pays for the free side. Nothing is lost on expiry - credits, line and account are untouched. Never describe it as a bug, an error, or something to report. +- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly. +- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase. +- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two, ?v=wide width-unlocks-depth with the Build Wide video; ?v=play opens the games angle), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle. +- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com. +- INVITE PAGES: a member's link instantadpay.com/join/ opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two|wide|play for an angle-matched headline (?v=wide: 'Width unlocks depth.', opens on the Build Wide video, vertical on phones). New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings). +- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use MetaMask/Phantom/SafePal (no hard block). The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again. +- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads. +- LINE BANNER (free, set in Profile): every member can set a destination URL (must allow framing) plus an optional banner image. It is shown to their next THREE levels of new members during welcome tours (position 1 for directs, 2, 3 below), and on their public BANNER WALL at /wall/ — a shareable page showing their line ladder with their join link. Free viral traffic that compounds as the team grows; no credits spent. +- Ad packages: Micro $5/500 credits, Starter $10/1,000, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500, Elite $500/70,000. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery. +- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Video watching is capped at 8 a day per member and pays 1, 2 or 4 credits for a 10, 30 or 60 second watch. FEATURED LINKS (live): a headline + link in the Featured strip at the top of every member's Overview, booked for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead, at most 10 links sharing any day; flat buy paid when booked; the row shows days left and 'runs through ', counts views (one per viewer per hour) and clicks, and offers Extend run. VERIFIED-VISIT PACKS (live): 3 credits per visit, minimum 20 visits, paid up front; each visit is a distinct member who opens the site in a new tab, stays 8 seconds and passes a check, at most 20 visits per member per day; the row shows 'N of M visits delivered' and Buy more visits adds to the pack; the visitor earns 1 credit. +- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase. +- INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/) right under their bio, above the three-level line and the join button. +- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 2 open adoptions, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members. +- DAILY CLAIM STREAK: finishing the daily ad set and claiming pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th consecutive day; miss a day and it restarts. After the set, verified visits (up to 20 a day, 1 credit each) keep earning, and the credits are meant to be spent on a campaign. +- FOUR-MINUTE OVERVIEW VIDEO (2026-09-16): 'InstantAdPay in four minutes' is the first card on Members > Training (group 'Start here') and embedded on the home page at instantadpay.com/#overview-video (hero button 'Watch the 4-minute overview'). Send it to anyone asking what the platform is; the tab-by-tab walkthrough videos on Training go deeper. It is evergreen: no dates, no launch talk. +- ANTI-FRAUD CHECKS (2026-09-16): at sign-up the site records IP, browser type and a browser cookie id. A second account from a browser that already has one is refused, so is a burst of new accounts from one connection in a day, and so is a sign-up through an invite link whose owner used that same browser. A sign-up from the same IP as the sponsor is allowed but flagged (households are fine). Flagged accounts never count on the leaderboard and cannot adopt from the holding tank; a suspended account cannot sign in. If a member says they were refused at sign-up, or asks how to get a second account to qualify themselves: one account per person, sign in to the existing one, and use QUALIFIED START (Buy packages tab) to link extra wallets of their own as positions under that account; each linked wallet that buys $20+ counts as one of their qualifying buyers, credits pool, and half of each such purchase returns to their main wallet. Levels 2 and 3 open at 2 and 5 qualifying buyers whether those buyers are referrals or the member's own linked positions. Shared computer at work or a library: contact support. Never suggest a second account. +- ONE ACCOUNT PER PERSON (Terms section 3, 2026-09-16): a person may hold exactly one account; second or duplicate accounts under any email, name or wallet, and self-referral through another account, are prohibited. The only sanctioned way to hold more than one position is Qualified Start (extra wallets linked inside the one account). Duplicates may be merged, suspended or closed and credits, prizes and contest rankings earned through them are forfeited; the contract's on-chain payments cannot be reversed. Family members join under the member's link with their own email. +- BLOG (public, instantadpay.com/blog): Marty's coaching and teaching articles on building a line, advertising that pays, and daily habits; each article has its own page and can be shared; RSS at /blog/feed.xml. Members who want to write their own articles: not offered today. +- ACHIEVEMENT BADGES ON TELEGRAM (2026-09-13): when a member unlocks Spark/Surge/Circuit/Nexus, their personalised badge image (username on the ribbon) is posted automatically to the team's Telegram payments topic and the main group, once per badge; members cannot trigger posts themselves (the 'Post to Telegram' button is admin-only); 'Share' opens a picker (X, Facebook, Telegram, WhatsApp, LinkedIn, Massifly (copies the post and opens the feed composer), the phone's own share menu, copy link, save image) that shares the member's public badge page instantadpay.com/b//, which shows the badge and their join link. +- PROMO TOOLKIT BY BADGE + AI COPY ENGINE (2026-09-14): Promo tools > AI Copy Engine shows the ladder: Free (links, posts, swipes, banners, wall, objections, shorts, badge pages), Spark (payouts on: one-tap campaign templates aimed at the member's link, printable handout with their QR at /handout/), Surge (first qualifying buyer; the AI Copy Engine is live: posts, DMs, follow-ups, objection replies, emails, story posts, team broadcasts in the member's name with their link, honesty rules built in; 20 free generations a month), Circuit (60 free; Video Maker renders every promo video and short with the member's own end card and QR, hosted for download; split tester compares join angles by views, joins, buyers), Nexus (150 free; Leader Ops: three-level team triage with stalled flags and one-click nudges, AI-drafted team broadcasts, credit grants from the leader's earned pool to anyone in their line, co-branded join page showing the sponsor's bio, and the member's own partner code: welcome credits funded from the leader's pool at each redemption, plus a partner kit page /partners?ref=&promo=CODE). After the free allowance each generation costs 10 ad credits from the earned pool. Credits are advertising, never money. +- MEMBER UPDATE EMAILS (2026-09-14, admin only): Admin > Releases > Email an update to members: pick release notes, add an intro, choose an audience (newsletter opt-ins, opt-ins active in the last 30 days, or everyone including those who declined), preview, send a test to the admin, then send; plain text from no-reply@instantadpay.com with an opt-out link; the log shows sent/opted out/failed. +- LINKED POSITIONS AND BADGES (2026-09-14): qualifying buyers on a member's linked positions count toward their achievement badges (Spark/Surge/Circuit/Nexus) and light their chip on their sponsor's line, and a badge once earned never regresses. CONTRACT RULE: levels 2 and 3 are paid to the MAIN wallet only when that wallet's own count of qualifying buyers reaches 2 and 5; buyers registered under a linked position count for that position, not the main wallet. Qualified Start positions buy UNDER the main wallet, so those buys raise the main count; a member whose old wallet was swapped out (its buyers stay with the old position) needs new $20+ buyers under the current main wallet before level 2 pays it. The contract still pays levels 2 and 3 to each position based on that position's OWN qualifying buyers, so the Qualifying buyers tile shows the main position's count with the linked positions' count underneath. +- CREDITS VS POL (2026-09-15, Marty's stance): EVERY member earns CREDITS (viewing, videos, visits, inbox, sign-in bonus, badge bonuses); credits are ad delivery, not money. POL is paid by the contract to a member's wallet when referrals buy packages. ALWAYS describe activation as 'the $20 starter package plus payouts switched on' and lead every earning answer with it; do NOT volunteer that level 1 can pay without a purchase. If someone asks point-blank whether a purchase is required for level-1 payouts, answer truthfully in one sentence: the contract pays level 1 to any member whose payouts are switched on, and the $20 package is what makes them a qualifying buyer for their sponsor, funds their own ads, and unlocks badges, tools, the holding tank and wall positions. A $20+ purchase by a referral makes that referral a qualifying buyer for their sponsor; 2 and 5 open levels 2 and 3. Never claim the payout itself is gated by a purchase. +- PIPELINE (live since 2026-09-15): a follow-up board on the dashboard, tab 'Pipeline' between My line and Buy packages, with its own training video on the Training tab. Columns: Talking to, Joined, Wallet linked, Payouts on, Bought, Building, Later. Prospects (from the My line prospect list) and directs are placed automatically from what they have actually done (coaching rung, on-chain buys); nobody drags cards. The sponsor adds a note, a follow-up date and a tag (hot, later, no response, not interested); a 'Follow up today' strip lists due cards; stalled cards (quiet 3+ days) are flagged; each card carries the message for its exact stage with 'Open chat with this message' (member chat) or copy. +- LEADER TOOLS (since 2026-10-16): a 'Leader tools' section on the Training tab with the Leader's Guide (a downloadable PDF: building wide, how width unlocks levels 2 and 3, network reach, Qualified Start, LinkSpin, the wallet as your key, the first week), the narrated presentation to share, and the Build wide video. My line and Pipeline each have a Leader tools card with a direct 'Download the Leader's Guide (PDF)' button and 'Open Leader tools'. +- UNACTIVATED SPONSOR = WALK UP, NEVER HOLD (2026-09-16, Marty): if a buyer's sponsor has not linked a wallet or switched on payouts, the purchase is NOT held. The site walks the sponsor line upward to the first upline who is activated with payouts on and the buy goes through under them (on-chain sponsorship for that buyer is then theirs, permanently); if nobody in the line is activated it goes under the company catch position (#1). The buyer sees a one-line notice and proceeds; once the position exists on the chain the skipped sponsor gets a blunt email + on-site message (they lost this referral for good, how to switch on payouts) and the upline who was paid gets a message that the referral is theirs permanently with a nudge to coach the one who missed it; the referral MOVES to whoever got paid (the account's stored sponsor is re-pointed when the position is created on-chain), so the buyer leaves the skipped sponsor's My line for good; the skipped sponsor can never earn from that wallet. Only a transient chain error ('rpc') still pauses a buy ("try again in a minute"). +- DRILL DOWN FROM THE OVERVIEW (2026-09-15): every name chip in 'Your line at a glance' on the Overview is clickable; it jumps to My line with that person's Activity panel already open and the row highlighted. +- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through ', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends. +- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin. +- PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members. +- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL NINE games (linked positions share it). Paid with 500 PURCHASED-grade credits (ads.gamePurchase purchasedOnly, the PolyWarriors mint rule; earned credits never buy a pass); with no purchased credits the pass waits and a $5 package bought meanwhile starts it automatically (the member keeps the package credits). Buying while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit. PER-GAME PERKS (live 2026-10-22, also listed on the Game Pass card): PolHunter 5 missions/day instead of 3 + 2 Ad Detective cases/day; Gem Kingdom 1 free continue/day; Spooky Doors +1 door/day; ClutterHunt 2 bonus hints/day; SpellWheel streak 0.30 POL instead of 0.15 + 1 free hint/day; PolyBreak gem limit 1.5 POL/day instead of 0.5 + extra paddle every round; PolyWarriors 4th daily mission + defense 25 Circuits instead of 15; Drip Runner free shield every run; Road Agent 2 patrols/day + 25% more scrap. Buying a pass unlocks the gold Game Pass achievement badge (Members > Overview badges, share or post to Telegram). New free caps start 2026-10-29. +- PLATFORM FACTS (2026-10-06): instantadpay.com/facts (footer link 'Platform facts') and instantadpay.com/llms.txt are the verified reference for how InstantAdPay works: contract 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 on Polygon; split 50% L1 / 20% L2 (needs 2 referred $20+ buyers) / 10% L3 (needs 5) / 10% platform wallet A / 10% platform wallet B, unqualified shares pass up (25 steps) then go to wallet A; purchased credits are on-chain (engine burns them in batches), earned credits are in the site database; credits are not transferable or cashable; POL payments are final, platform may return credits when a campaign fails because of a platform problem. When someone asks how the platform, payouts, credits or refunds work, answer from these facts and link /facts. +- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed. +- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility. +- LAUNCH WEEK SWIPES (2026-09-15): the founding-week checklist page (/launch) ends with four promoter emails members send to their OWN lists, one a day toward Monday's opening, with the member's invite link and the FOUNDER code (500 credits for anyone who joins before Mon 2026-09-21 9 AM Central) filled in, each with a Copy button. These are swipes for members, not emails the site sends. +- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 3 member slots run at once because every slot shares the same sign-ins; when all 3 are taken the buy is refused until one ends, and a paused slot can only be resumed while a slot is open. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks. +- AD VIEWER OPEN-IN-TAB (2026-09-19): the earn viewer shows the advertiser's page inside a frame; a link in its bar opens the same site in a new tab for sites that refuse to load framed or where signing up is easier in a full tab. The view still credits from the frame's countdown and check. +- (2026-09-14 hold rule REPLACED on 2026-09-16 by the walk-up rule above: a purchase is never held for an unactivated sponsor; only a transient chain read error pauses a buy.) +- NO-PAYOUT POSITIONS (2026-09-14): admin can list member ids (Settings > No-payout positions) whose wallets must never be paid again (e.g. a compromised key). Those positions stay linked for history and counting only: the buy-from picker disables them, a purchase from them is refused, and invite links that would place a new member under them (or under their upline chain) route to the fallback sponsor instead. The contract itself cannot change a member's wallet. +- LINE AT A GLANCE, ALL LEVELS (2026-09-14): a gold chip on any level means that person made their $20+ buy (a qualifying buyer for their own sponsor); a small number on the chip is how many qualifying buyers of their own they have. My line rows say the same in words. Leaders use it to see who is one buyer short and encourage them. +- MY LINE SPONSOR LINE (2026-09-14): every row on My line, all three levels, shows who sponsored that person ("sponsored by @name", or "you" for directs). +- MY LINE ACTIVITY DROP-DOWN (2026-09-14): every row on My line, all three levels, has an Activity button that opens that person's activity: last seen, joined, stage and next step, ads viewed today and claim streak, campaigns active, link views in 30 days and joins, directs and qualifying buyers, wallet/payouts, badges, and a Working or Quiet verdict. Read-only, phone friendly. +- GETTING STARTED CARD (2026-09-14): the top of every new member's Overview shows four steps (username, link wallet, switch on payouts, first package) with the current one explained and one button that opens the right tab and highlights the control (Wallet tab > Link wallet; then Activate payouts). Encouragement only: it can be hidden, and members who only want to view ads and earn credits are never blocked. It disappears once all four are done. +- LEADERBOARD + REFERRAL CONTEST (2026-09-14): instantadpay.com/leaderboard ranks members by ad packages sold to people they directly sponsor (dollar value, read from the chain; a member's own linked positions and second accounts never count). Periods: this week (Monday to Sunday, Central time), this month, all time. Weekly and monthly winners are recorded automatically at rollover, announced in Telegram, and the credit prizes set by the admin (a ladder: 1st 1,000 / 2nd 500 / 3rd 250 weekly, 5,000 / 2,500 / 1,000 monthly by default) are granted automatically to those positions; the prize text is shown on the page and on the Overview's Leaderboard card, which also shows the member's own rank. Prizes are credits or packages, never cash. +- WHAT'S NEW / ROADMAP (2026-09-14): instantadpay.com/whats-new lists release notes (what shipped, dated, tagged new/improved/fixed) and the roadmap (planned / building, with rough ETAs). The Overview has a "What's new" card with the latest three notes and what is being built; a dot marks notes since the member's last look. Written by the admin in Admin > Releases. +- HOLDING TANK ALERTS: when new members land in the tank, a note at the top of every member's Overview names them (usernames) and a post goes to the team's Telegram payments topic; adopt from My line > Holding tank (your own $20 package required). +- LEGACY WELCOME (former Faucet Wave / Tier One Ads members): they join through instantadpay.com/from/faucetwave or instantadpay.com/from/tieroneads and, if their email is on the legacy list, welcome-back credits are added automatically at signup (former advertisers 500, former earners 150; once per person; credits, not POL). They land in the holding tank like any member who joins without a sponsor. SOCIALPIX GATE (2026-09-20): socialpix.club no longer takes ad posts; its visitors are sent to instantadpay.com/from/socialpix (advertiser copy by default, ?seg=earn for the earner copy). No welcome-back credits for SocialPix arrivals; they join free by email and land in the holding tank. +- PROMO CODES: partner site owners get a reusable code; a member redeems it on a join link (?promo=CODE) or in the Overview box "Have a promo code?" and receives free ad credits (amount set per code by the admin, one use per account; codes can cap uses or expire). Credits, not POL. +- DORMANT-LEAD RESCUE: a FREE referral (no wallet, no purchase) with no message from their sponsor for 10 days triggers a warning email + dashboard flag to the sponsor ("unreached, tank in N days"); at 14 days (warning at least 4 days old) the lead moves to the holding tank and the sponsor is told. Sponsor resets the clock with a chat, a Nudge, or the "Contacted them" button (for phone/text contact). Leads whose sponsor link resolves to nobody go to the tank after a day. Nothing on-chain moves; anyone bound by a purchase never moves. +- PIF (pay it forward) button: on a free direct or an adopted member who has linked a wallet, the sponsor taps PIF, enters an amount (suggested: the $20 package plus fees), and their OWN wallet app opens with the member's address prefilled; the POL goes wallet to wallet. The site never touches the funds; it only logs the transaction and tells the recipient with a Polygonscan link. The gift is theirs; nothing forces a purchase. Before every PIF the member confirms a plain warning: the funds go wallet to wallet in good faith, InstantAdPay never holds or moves them and cannot reverse or recover them, and the member should only send what they are willing to give. You cannot PIF someone still in the holding tank: adopt them first, they link a wallet, then the button appears. +- PIF RISK (Marty, 2026-09-17, say this EVERY time PIF comes up, never sell PIF as a tactic): tell the member to make contact and get an explicit commitment BEFORE sending anything. The transfer is wallet to wallet and irreversible, there is no refund or chargeback and support cannot claw it back. The recipient may go quiet, spend it on something else or never sign in again, and none of that breaks any rule. A tank member joined with nobody working with them and may never have engaged, so an unanswered PIF is the easiest money on the site to lose. Honest arithmetic: if they buy $20 the sponsor gets 50 percent back so a gift that works costs about half, and a gift to someone who never answers costs all of it. Never gift money they need, never borrow to do it. If a member asks "should I PIF someone from the tank", the answer starts with talk to them first, not with the mechanics. +- FOUNDING WEEK / PRE-LAUNCH (Training > Founding week checklist, /launch, members only): eight items read live from the account: username, wallet linked, payouts on, level 2 qualified (2 buyers of $20+, or Qualified Start with 2 linked positions), the leader play = level 3 (5 qualifying buyers, up to 5 linked positions; then buy from the main wallet), line banner, links + play chosen (self-marked), first two placed. Reason: unqualified levels pass up, so leaders qualify BEFORE their teams' teams buy. Countdown shows when admin sets launchAt. Never call the site 'pre-launch' publicly: it is live and paying. +- COUNTRY TARGETING (2026-09-11): New campaign form has "Show to" tier checkboxes (Tier 1 = US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE by default; Tier 2 = rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO, etc.; Tier 3 = everyone else; lists editable in Admin > Settings geoTier1/geoTier2). Country comes from the viewer's IP (DB-IP lite). Applies to on-site delivery of every format; a narrowed banner/text ad is NOT sent to the partner network (which is worldwide). Unknown country never matches a narrowed campaign. Campaign rows show 'tier 1+2' chips and top viewer countries. +- SCHEDULING (2026-09-11): any campaign except featured can take an optional start and end time (local time) in the New campaign form; solo ads label it "Send from" (inbox deliveries begin then). A scheduled campaign shows "scheduled" until it starts; at the end it shows "ended" and the unspent budget returns to Available. Banner/text scheduled campaigns join the partner network at their start time. There is NO dayparting (hours-of-day targeting) by design; the daily cap paces budgets. Each campaign row shows a small views-by-hour chart (on-site views, viewer's local time, last 7 days). +- BALANCE RULE (members ask this a lot): a balance is what is NOT committed to a live campaign. Starting a campaign sets aside its whole budget at once (earned pool first, then purchased), so Available drops once and stays still while ads serve; the budget spends down inside Members > Campaigns. Dashboard shows Purchased available, Earned available, In live campaigns. A paused campaign keeps its unspent budget set aside so it can resume. A low balance with a live campaign is not lost credits. Refunds/comps of purchased money are credited off-chain as purchased-grade credits: shown under Purchased as "credited to you", fund anything incl. login ads. Viewing-earned credits never fund login ads. +- Members EARN credits by attention: in the Earn credits section of Members, each ad in the daily set opens FULL SCREEN in its own tab, showing the advertiser's real website. A countdown runs while you watch (it pauses if you leave the tab), then a quick human check (click the named icon) must be passed before the view counts. Finish the daily set, claim a small daily credit batch. Earned credits fund every campaign format except login ads; attention earns advertising, referrals earn money, and viewer rewards are never cash. DAILY SIGN-IN BONUS: separate from the claim, the first sign-in of each day pays 5 credits, rising by one per consecutive day up to 10; a missed day resets it. REPORT AN AD: every served ad carries a 'report' link (broken, inappropriate, spam, scam, other, plus a note) that emails the admin; the Shorts page uses reason buttons. Advertisers get real, verified visits to their site. +- Onsite SOLO ADS are live: a solo ad is a full message (subject + up to 2000 characters of formatted text + your link) delivered into members' on-site Inbox (Members > Inbox). The composer in Campaigns > Solo ad has a rich-text editor (bold, headings, lists, links), lets you ATTACH one image (PNG/JPG/WebP/GIF, up to 3MB) or one video (MP4/WebM, up to 25MB), and adds a call-to-action button with a custom label that opens the target URL. Cost 5 credits per guaranteed delivery, minimum 10 deliveries (50 credits). Each member receives a given solo at most once, and never the sender's own. Readers earn 2 credits per real read (10-second dwell on the open message, up to 5 rewarded reads/day) — claimed right from the message. Compose one in Campaigns > Solo ad. +- Campaign target URLs are checked the moment they are submitted: the page must be reachable and must ALLOW framing (no X-Frame-Options deny/sameorigin, no blocking CSP frame-ancestors), because surf views show the real site full screen. Frame-blocking or dead URLs are rejected with the exact reason; the fix is a landing page that allows framing. Login-ad targets skip the frame check (they are click-through only). +- SPONSOR CHAT (Members): a two-way, one-to-one chat. A member can start a conversation with their DIRECT sponsor; a sponsor can message anyone in their downline. Presence-aware — when both are online it is live, otherwise a message waits in the recipient's on-site inbox and sends an email. Each member has an availability toggle in Profile (default on; turning it off stops live chats but people can still leave a note) and can mute a specific person. This is separate from the once-a-day sponsor BROADCAST to the whole downline. +- PASSIVEDRIP (LIVE on the Earn tab for every member since 2026-10-03): https://passivedrip.com, an EARNING SITE (never call it a game): faucet claims, paid-to-click ad views, offers (offer walls) and a daily bonus roll earn coins; at 2,000 coins ($1) the balance is paid out AUTOMATICALLY in POL on Polygon to the wallet saved on PassiveDrip. The Earn tab card (More ways to earn: PassiveDrip) opens it with ONE TAP using the InstantAdPay account (no new password; it offers the member's InstantAdPay wallet to save). No income is promised. +- POLYBREAK (opens 2026-10-13, https://polybreak.app, in Members > Games): a free Arkanoid-style brick breaker. Eight hand-built rounds that then repeat with tougher silver bricks; colored bricks break in one hit, silver takes more hits each round, gold never breaks. Capsules: S slow, C catch, L laser, E enlarge, D disrupt (three balls), B break (a gate in the right wall skips the round), P extra paddle. One-tap sign-in with the InstantAdPay account; guests can play and their first clears are paid once they sign in. PAYS POL: the first clear of each round (replays pay nothing) and catches of the purple Polygon gem (a small random amount each time, the gem appears every so often during play), into the PolyBreak game balance, sent automatically to the wallet on the member's InstantAdPay account at the payout line shown in the game; rewards are paid from the game's pool, funded by a share of the one-more-paddle visits. ONE MORE PADDLE: when the last paddle is lost, a verified visit to a member's page (or a member video) continues the round with one paddle; it uses the daily refuel allowance shared with the other games. REFERRALS: each player's share link polybreak.app/r/; a sponsor earns a share of the pool income from the paddle visits of players they invited. Never state a maximum or total a player can earn and never promise income. +- POLYWARRIORS (LIVE 2026-10-12, https://www.polywarriors.com, in Members > Games): a free cyberpunk turn-based fighting game. Recruit warriors that are each born with their own traits and rarity (Common, Rare, Epic, Legendary); fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit); challenge other members to async duels that play out while they are away. The FIRST win over each rival pays POL to the wallet on the member's InstantAdPay account (replays pay nothing). The first warrior mints to the member's wallet as an NFT on Polygon for free; after that every $5 ad package bought on InstantAdPay earns a mint pass. Fusion: three warriors of the same rarity fuse into one rarer warrior (the three are consumed). Marketplace: warriors trade between members, settled in POL. One-tap sign-in with the InstantAdPay account; guests can try fights but earn nothing until they sign in. A 40-second trailer and a promo kit are in Promo tools > Games > PolyWarriors. Never state a maximum or total a player can earn and never promise income. +- SPELLWHEEL (LIVE 2026-10-10, https://spellwheel.com, in Members > Games): a free letter-wheel word game: swipe letters on the wheel to fill the crossword grid, travel through six cozy places (chapters), and solve a new daily puzzle shared by everyone. Pays POL for clearing levels, finishing a place and solving the daily puzzle, collected in the SpellWheel balance and sent automatically to the wallet on the member's InstantAdPay account. One-tap sign-in with the InstantAdPay account. Never state totals or promise income. +- CLUTTERHUNT (LIVE 2026-10-03, https://clutterhunt.com, in Members > Games): a free hidden-object game. Search cozy, cluttered rooms for 12 hidden objects plus one sponsored find (a sealed letter with a sponsor's name; tapping it shows their ad). Rooms change with the seasons: the Haunted Manor (Attic, Library, Witch's Kitchen, Wizard's Study, Moonlit Greenhouse, Wine Cellar) through Oct 31, then new seasonal rooms. Objects move every round. Stars: finish under 3 minutes, use at most 1 hint, at most 6 wrong taps. 2 free hints a round; after that a short verified visit to a member's page earns a hint (shares the daily refuel allowance). Sign in with the InstantAdPay account right inside the game to save stars. PAYS POL since 2026-10-04: fixed rewards per room each season for the first clear and the first 3-star clear (more for Expert rooms, which unlock after all six rooms), collected in the ClutterHunt balance and sent automatically to the wallet on the member's InstantAdPay account once it reaches the payout amount. Players who cleared rooms before 10-04 can replay each room once to collect. NEVER state a maximum or total a player can earn (Marty's rule) and never promise earnings. +- SPOOKY DOORS (Halloween season game, 2026-10-02): https://spookydoors.com, open 2026-10-04 through Halloween night (closes at midnight Central at the end of Oct 31); its Games tab card shows only during the season, with a "Limited time, ends Oct 31" ribbon. Members sign in with one tap from Members > Games. Walk the street, collect candy, avoid black cats and bats, knock on doors. Each door is a verified visit to a member's page or ad (a member video once every page has been visited), the advertiser is charged as for any visit, the player gets candy not credits; 15 doors per Central day, separate from the 20 Earn-tab visits and the 20 Drip Runner refuels. A treat is 10 candy; about 1 door in 5 is a trick (a ghost or skeleton you tap 5 times quickly; beat it for a 3 candy bonus, miss it for half the treat). If no paid ad is left for that player, the door shows a house ad for one of our own programs: a smaller treat (5 candy), and it still counts toward the 15 doors. CANDY LADDER pays POL once per rung: 100 candy 0.1 POL, 250 0.25, 500 0.5, 1,000 1, 2,000 2 (Halloween 2026 badge at 500), paid from a season pool funded by a share of door ad spend and costume sales, only while the pool covers it; the game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. COSTUMES bought with ad credits like Gem Kingdom Crowns: witch free, vampire 300 credits (longer trick timer), bedsheet ghost 300 (black cats ignore you), Lucky caramel apple 500 (+2 candy per treat); no cash value. Top 20 by candy on the season leaderboard. DOOR PACKS: creating a verified-visits campaign, the advertiser picks Everywhere (3 credits per visit, as before), Behind Spooky Doors (4 credits per door) or Golden Spooky Door (6 credits per door; the player gets +2 bonus candy). Paid up front like any visit pack. Door packs are served first on doors (Golden Doors before door packs), each player sees a pack at most once per Central day, they never run on the Earn tab or refuels during the season, and from Nov 1 any doors left run as normal visits; the campaign shows doors opened and unique players. Never promise earnings or call it income. +- GEM KINGDOM (LIVE in the Games tab since 2026-10-02): Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon's Peak, the Sunken Reef, the Shadow Citadel), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for FIRST clears only (stages 0.02 to 0.15 POL rising by chapter; bosses 0.25, 0.5, 2, 5, 7.5 and 10 POL for the Goblin King, Ice Queen, Bog Witch, Ember Dragon, Kraken and Shadow King); replays pay nothing. The game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. Rewards come from a pool funded by a share of Crown purchases and pay only while the pool has funds; never promise earnings or call it income. No referral bonus on game clears. Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game's Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. Never promise an amount beyond the posted rewards. (2026-10-03) FREE REVIVE: after a defeat, a short verified visit to a member's page (InstantAdPay verified-visit flow inside the game, shares the 20-a-day refuel allowance with Drip Runner) revives the party once per battle; a revived win earns at most 2 stars. SPECIALS in the Crown shop: Hero Bundle (one time, $5 = 500 credits: a tier-1 forge weapon, one building level, 60 Crowns), Kingdom Pass ($10 = 1,000 credits for 30 days: 10 Crowns a day credited on the first visit each Central day, a 25-Crown chest every 7 days, the three Royal hero looks; no auto-renew, buying again adds 30 days), Hero looks (cosmetic only: Halloween looks Pumpkin Knight, Moon Witch, Scarecrow Ranger for 40 Crowns each, sold through Oct 31 and kept forever; Royal looks with the Pass). Only the purchased-credit part of a purchase funds the POL reward pool. +- GAMES TAB (2026-10-01): Members > Games (/my#games) shows one card per network game (as of 2026-10-15: PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Road Agent, Spooky Doors during Halloween; all pay POL to the member's InstantAdPay wallet), with their own progress and a Play button that signs them in with one tap; new games appear there as they launch (PolHunter is one card). DRIP RUNNER (https://driprunner.app, LIVE for every member since 2026-10-01): tap-to-hop runner; gold drips, magenta bots, orange firewalls from chapter 2; each chapter has a drip goal for one run; the FIRST clear of a chapter pays a small POL drip (amount set by the admin, shown in the game) into the game balance, replays pay nothing; the balance is sent on Polygon to the member's InstantAdPay wallet once it reaches the payout line shown in the game. REFUELS: a run that ends can be refuelled with a verified visit to a member's page (a member video once every page has been visited), up to 20 a day, separate from the 20 Earn-tab visits; the advertiser is charged as for any visit, the player gets fuel not credits. The POL pool is funded ONLY by a share of refuel ad spend plus POL spent in the hangar, so drips depend on refuels and can be zero when the pool is empty; say so honestly. HANGAR: Drip Magnet and Courier Mk II cost drips (game currency); Shield Core and Slow Field cost POL from the game balance, which returns to the pool. GUESTS can try a run without signing in; their clears pay once they sign in. REFERRALS: each player's share link /r/; when members whose InstantAdPay sponsor is that player refuel, a share (10 percent by default) of each refuel's pool income goes to the sponsor's game balance. Telegram posts achievement badges (chapters, unlocks, refuel milestones, payouts). Never promise amounts or income. The public list of every game, open now and opening next, is https://instantadpay.com/games (shareable; add ?ref= to keep the referral). +- Every purchase is split by an immutable smart contract in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. No withdrawals exist; money lands in members' own wallets instantly. +- Qualification: level 1 open to all; 2 buyers of $20+ unlock level 2; 5 unlock level 3. Unqualified shares pass up the sponsor line, checking up to 25 positions, else the platform receives them. Qualification cannot be bought and never expires. +- Every member gets a share link immediately (site code, /join/); the contract locks a buyer to their sponsor at the buyer's FIRST purchase, so members should switch on payouts before their referrals buy. +- Transparency: live ledger at /ledger streams every chain event, and EVERY transaction row carries a clickable "verify" link — to the public block explorer when the chain has one, or to the built-in transaction viewer at /tx/ (block, time, from/to, value, gas, decoded events, read live from the node). Plain-language contract review at /contract; the verified source is public. +- The contract cannot be paused, upgraded, or drained. The operator can only manage the ad catalog ($1-$500 bounds, 24h price timelock) and rotate keys. + +PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile, /my#help (Help: support tickets). Public: /support (contact form for anyone signed out or locked out; support@instantadpay.com also works), /join/ (invite page, ?v=angle), /wall/, /b//, /handout/, /ledger, /tx/, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix. + +RULES: +- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above. +- Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor. +- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes. +- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen. +- No em dashes. If you do not know, say so and point to /contract or the ledger. +- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : ''); +} + +// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai +function endpoint() { + try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); } +} +function askAI(message, historyText, kbBlock) { + return new Promise((resolve, reject) => { + const body = JSON.stringify({ + model: MODEL, + reasoning: { enabled: false }, // 2026-10-16: deepseek-v4-flash now thinks by default and spent the whole max_tokens on it (empty answers) + max_tokens: 300, + messages: [ + { role: 'system', content: systemPrompt(kbBlock) }, + ...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []), + { role: 'user', content: String(message).slice(0, 600) } + ] + }); + const ep = endpoint(); + const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST', + headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(body) }, timeout: 30000 }, + res => { + let d = ''; + res.on('data', c => d += c); + res.on('end', () => { + // OpenRouter pads a slow upstream with keepalive lines before the JSON, and when the + // provider gives up it can close having sent ONLY that padding: HTTP 200, no body. + // JSON.parse then threw and every question died on "I hit a snag" (Marty, 2026-09-17). + // Find the actual JSON object, and treat an empty answer as a failure worth retrying. + const i = d.indexOf('{'); + if (i < 0) return reject(new Error('openrouter ' + res.statusCode + ': empty body (' + d.length + ' bytes of keepalive)')); + let txt = ''; + try { txt = String(JSON.parse(d.slice(i)).choices[0].message.content || '').trim(); } + catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(i, i + 150))); } + if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content')); + resolve(txt); + }); + }); + req.on('error', reject); + req.on('timeout', () => req.destroy(new Error('openrouter timeout'))); + req.end(body); + }); +} + +const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) not (see|check|look)|contact support|reach support|support (ticket|desk)|\/support\b|my#help)/i; +// every reply leaves without em dashes (Marty's voice rule; the model slips one in now and then, 2026-10-20) +async function answer(message, historyText) { const r = await answerRaw(message, historyText); if (r && typeof r.reply === 'string') r.reply = r.reply.replace(/\s*\u2014\s*/g, ', '); return r; } +async function answerRaw(message, historyText) { + const msg = String(message || '').trim(); + if (!msg) return { error: 'Say something first.' }; + // fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down + let hit = null, kbOk = true; + try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); } + if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {}); + if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); + // retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far) + let kbBlock = '', kbIds = []; + try { + const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg; + const hits = await kb.context(query, 5); + kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id); + } catch (e) { console.error('kb search', e.message); } + if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true }; + // One retry: the usual failure is a single provider dropping the request, and asking + // again almost always lands. Only after both fail do we admit defeat. + for (let attempt = 0; attempt < 2; attempt++) { + // handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16) + try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); } + catch (e) { + console.error('chat AI failed (attempt ' + (attempt + 1) + ')', e.message); + if (attempt === 0) await new Promise(r => setTimeout(r, 700)); + } + } + // Never a dead end: say plainly that it was us, and offer a person. + return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true }; +} + +module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt }; diff --git a/public/assets/my.js b/public/assets/my.js index 0e2391b..3d4d32c 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -1,3453 +1,3453 @@ -// member share links go out on the share domain (2026-10-20): https://ctbgo.com/ -> /join/ on InstantAdPay. -// The domain comes from site config (shareDomain); empty falls back to this site's own /join link. -let SHARE_DOMAIN = ''; -const SHARE_READY = fetch('/api/config').then(r => r.json()).then(c => { SHARE_DOMAIN = String((c && c.shareDomain) || '').trim(); }).catch(() => {}); -function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(String(ref)) ? 'https://' + SHARE_DOMAIN + '/' + ref : location.origin + '/join/' + ref; } -// My account: email-first join/login, wallet link at purchase time, -// free payout activation, invite link, on-chain activity. -(async function () { - // back-office shell: no marketing nav here; rehearsal notice lives in the top bar - const $ = IAP.$; - // dwell timers pause when the tab is away; a focused ad frame or a touch device counts as active (phones never report hasFocus reliably) - const tabActive = () => document.visibilityState === 'visible' && (document.hasFocus() || !!(document.activeElement && document.activeElement.tagName === 'IFRAME') || (window.matchMedia && window.matchMedia('(pointer: coarse)').matches)); - try { - const c = await IAP.getConfig(); - if (c.rehearsal && $('boRehearsal')) { - $('boRehearsal').hidden = false; - $('boRehearsal').innerHTML = 'Testnet rehearsal · ' + c.chainName; - } - if (c.rehearsal && $('faucetCard')) $('faucetCard').hidden = false; - } catch (e) {} - // if they arrived through a sponsor's link, show who they're joining under - (async () => { - try { - const sp = await (await fetch('/api/sponsor?intent=view')).json(); // display only: never an alert - if (sp && sp.invited && sp.name && $('sponsorNote')) { $('sponsorNoteName').textContent = sp.name; $('sponsorNote').hidden = false; } - } catch (e) {} - })(); - - async function api(path, body) { - const r = await (await fetch(path, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); - if (r.error) { const e = new Error(r.error); e.data = r; throw e; } // e.data: the full answer (e.g. top-up switch options) - return r; - } - - function nextMove(d) { - if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.'; - if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.'; - if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $20 or more. Every direct pays you 50 percent from their very first package.'; - if (d.buyerCount === 1) return 'One qualifying buyer down, one to go. Your next $20+ buyer unlocks level 2: 20 percent of everything your people’s people buy.'; - if (d.buyerCount < 5) return 'Level 2 is open. ' + (5 - d.buyerCount) + ' more qualifying buyer(s) unlock level 3 and the full three-level flow.'; - return 'Fully qualified. Every level pays you, and you catch the pass-ups that under-qualified positions below you let slip. Keep sharing and keep your campaigns running.'; - } - // featured rotation strip on the overview - let featItems = [], featIdx = 0, featTimer = null; - function renderOneFeatured() { - if (!featItems.length) return; - const i = featItems[featIdx % featItems.length]; - $('featStrip').innerHTML = '' + esc(i.title) + '' - + (i.by ? '' + esc(i.by) + '' : '') + ''; - } - async function loadFeatured() { - try { - const r = await (await fetch('/api/featured')).json(); - const card = $('featuredCard'); if (!card) return; - if (!r.items || !r.items.length) { card.hidden = true; return; } - card.hidden = false; - featItems = r.items; featIdx = Math.floor(Math.random() * featItems.length); - $('featSub').textContent = r.items.length + ' link' + (r.items.length === 1 ? '' : 's') + ' in rotation'; - renderOneFeatured(); // show ONE at a time (true rotation), cycle if more than one - clearInterval(featTimer); - if (featItems.length > 1) featTimer = setInterval(() => { featIdx++; renderOneFeatured(); }, 6000); - // self-sell: today's open slots + a CTA to feature your own link - try { - const st = await (await fetch('/api/featured/stats')).json(); - const today = (st.occupancy || []).find(d => d.offset === 0); - const cta = $('featCta'); - if (cta) { - cta.innerHTML = (today ? '' + today.open + ' of ' + today.cap + ' featured slots open today. ' : '') - + 'Feature your link →'; - const fb = $('featBuy'); - if (fb) fb.addEventListener('click', e => { e.preventDefault(); setPane('campaigns'); const ct = $('cType'); if (ct) { ct.value = 'featured'; ct.dispatchEvent(new Event('change')); } }); - } - } catch (e) {} - } catch (e) {} - } - - // achievement badges: the milestone ladder as unlockable medals + share-to-image - const BADGES = [ // ribbonY = vertical center of each badge's name ribbon (art differs per tier) - { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.728 }, - { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 }, - { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 }, - { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 }, - { key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 }, - { key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 } - ]; - let lastMilestones = []; - function renderBadges(d) { - const reached = d.milestonesReached || []; - lastMilestones = reached; - const strip = $('badgeStrip'); - if (!strip) return; - $('badgeCard').hidden = false; - strip.innerHTML = BADGES.map(b => { - const got = reached.includes(b.key); - return '
' - + '' + b.label + ' badge' - + '
' + b.label + '
' + b.sub + '
' - + (got ? ' ' : '
🔒 locked
') + '
'; - }).join(''); - strip.querySelectorAll('[data-badge]').forEach(btn => - btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d))); - strip.querySelectorAll('[data-badgepost]').forEach(btn => - btn.addEventListener('click', () => postBadge(btn.dataset.badgepost, d, btn, true))); - fetch('/api/my/badge-posted').then(r => r.json()).then(r => { // the manual button is the admin's only (Marty, 2026-09-13) - if (r.canPost) strip.querySelectorAll('[data-badgepost]').forEach(b => { b.hidden = false; }); - (r.posted || []).forEach(k => { const b = strip.querySelector('[data-badgepost="' + k + '"]'); if (b) { b.textContent = 'Posted ✓'; b.disabled = true; } }); - }).catch(() => {}); - // celebrate anything newly granted this load, and post the branded badge to the team channels (Marty, 2026-09-13) - if (d.milestonesGranted && d.milestonesGranted.length) { - const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0); - const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', '); - IAP.status('🏆 Achievement unlocked: ' + names + ' — +' + total + ' bonus credits!', 'ok'); - d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500)); - } - } - // draw the badge with the member's name on the ribbon; cb(canvas) or cb(null) - function composeBadge(key, d, cb) { - const b = BADGES.find(x => x.key === key); if (!b) return cb(null); - const who = d.username ? d.username : d.memberId ? 'member #' + d.memberId : ''; - const img = new Image(); - img.onload = () => { - const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; - const x = c.getContext('2d'); - x.drawImage(img, 0, 0); - if (who) { - x.textAlign = 'center'; x.textBaseline = 'middle'; - x.font = 'bold ' + Math.round(c.width * 0.055) + 'px Sora, "Segoe UI", sans-serif'; - const y = c.height * (b.ribbonY || 0.75); - x.lineJoin = 'round'; x.lineWidth = Math.max(3, Math.round(c.width * 0.008)); - x.strokeStyle = 'rgba(4,20,15,.9)'; x.strokeText(who, c.width / 2, y); - x.fillStyle = '#ffd15c'; x.fillText(who, c.width / 2, y); - } - cb(c); - }; - img.onerror = () => cb(null); - img.src = b.img; - } - async function postBadge(key, d, btn, manual) { - if (btn && btn.disabled) return; - if (btn) { btn.disabled = true; btn.textContent = 'Posting…'; } - composeBadge(key, d, c => { - if (!c) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } return; } - c.toBlob(async bl => { - try { - const r = await (await fetch('/api/my/badge-post?key=' + encodeURIComponent(key) + (manual ? '&manual=1' : ''), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); - if (r.error) throw new Error(r.error); - if (btn) { btn.textContent = 'Posted ✓'; btn.disabled = true; } - if (!r.already) IAP.status('Your badge is posted in the team channels.', 'ok'); - } catch (e) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } IAP.status(e.message || 'Could not post the badge.', 'bad'); } - }, 'image/jpeg', 0.86); - }); - } - // Share: a picker (Marty, 2026-09-13). The composed badge is stored once so a public page at - // /b// carries it as the preview image; every network gets that link. - function shareBadge(key, d) { - const b = BADGES.find(x => x.key === key); if (!b) return; - if (!d.username) { IAP.status('Pick a username first; your share page carries it.', 'bad'); return; } - IAP.status('Preparing your ' + b.label + ' badge…', 'ok'); - composeBadge(key, d, c => { - if (!c) { IAP.status('Could not load the badge art.', 'bad'); return; } - c.toBlob(async bl => { - let page = null; - try { const r = await (await fetch('/api/my/badge-image?key=' + encodeURIComponent(key), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); if (r.error) throw new Error(r.error); page = r.page; } - catch (e) { IAP.status(e.message || 'Could not prepare the share page.', 'bad'); return; } - openShareSheet(b, d, bl, page); - }, 'image/jpeg', 0.9); - }); - } - function openShareSheet(b, d, blob, page) { - const text = 'I just unlocked the ' + b.label + ' badge on InstantAdPay (' + b.sub + '). Advertising that pays you back, on-chain, the same second a package sells.'; - const enc = encodeURIComponent; - const links = [ - ['X', 'https://x.com/intent/tweet?text=' + enc(text) + '&url=' + enc(page)], - ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc(page)], - ['Telegram', 'https://t.me/share/url?url=' + enc(page) + '&text=' + enc(text)], - ['WhatsApp', 'https://wa.me/?text=' + enc(text + ' ' + page)], - ['LinkedIn', 'https://www.linkedin.com/sharing/share-offsite/?url=' + enc(page)] - ]; - const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200'; - back.innerHTML = ''; - document.body.appendChild(back); - const close = () => back.remove(); - back.addEventListener('click', e => { if (e.target === back) close(); }); - back.querySelector('[data-sh="close"]').addEventListener('click', close); - back.querySelector('[data-sh="copy"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(page); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy this: ' + page, 'ok'); } }); - back.querySelector('[data-sh="save"]').addEventListener('click', () => { - const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); - IAP.status('Your ' + b.label + ' badge is saved.', 'ok'); - }); - // Massifly has no share intent: copy the post text + link, then open the feed composer (Marty, 2026-09-13) - back.querySelector('[data-sh="massifly"]').addEventListener('click', async () => { - try { await navigator.clipboard.writeText(text + ' ' + page); IAP.status('Post copied. Paste it into the Massifly composer; the badge preview appears from the link.', 'ok'); } - catch (e) { IAP.status('Copy this into Massifly: ' + text + ' ' + page, 'ok'); } - window.open('https://massifly.com/account', '_blank', 'noopener'); - }); - const nat = back.querySelector('[data-sh="native"]'); - if (nat) nat.addEventListener('click', async () => { - try { - const file = new File([blob], 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg', { type: 'image/jpeg' }); - if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: b.label + ' badge', text: text + ' ' + page }); - else await navigator.share({ title: b.label + ' badge', text, url: page }); - } catch (e) {} - }); - } - - // milestone stepper under "Your next move": lit nodes for what's done, - // amber glow on the current target — the same ladder the contract pays - function renderSteps(d) { - const el = $('ncSteps'); - if (!el) return; - const b = d.buyerCount || 0; - const steps = [ - { label: 'Joined', sub: 'free account', hit: true }, - { label: 'Spark', sub: 'payouts on', hit: !!d.memberId }, - { label: 'Surge', sub: 'first buyer · 50%', hit: b >= 1 }, - { label: 'Circuit', sub: '2 buyers · +20%', hit: b >= 2 }, - { label: 'Nexus', sub: '5 buyers · +10%', hit: b >= 5 } - ]; - const cur = steps.findIndex(s => !s.hit); - el.innerHTML = steps.map((s, i) => - '
' - + '' + (s.hit ? '✓' : i + 1) + '' - + '' + s.label + '' + s.sub + '
').join(''); - } - // ── overview v3 charts: hand-rolled SVG/CSS, real data only ── - const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - - // Paged lists (Marty, 2026-09-19): 25 rows, then a clearly marked next page, on every list - // that grows with the membership. Works on what is already rendered: rows past the page are - // hidden and a control bar goes under the list, so a row's buttons and bindings never change. - // key remembers the page across re-renders of the same list - // host the element the bar is appended to (a wrapper, never a ) - // rowSel the rows, queried inside host - // opts per (default 25); tail: a selector for a drawer that follows its row and pages - // with it; focus: a row predicate, opens on whichever page holds that row - const PAGE_SIZE = 25; - // My line is the longest page on the dashboard: its lists page at 10 (Marty, 2026-09-26) - const LINE_PER = 10; - // Sortable + filterable member lists (Marty, 2026-09-29): the holding tank, "Your line" and the three-level - // downline share one toolbar. Every row carries joined, last seen, surf earnings and wallet/payout state so a - // sponsor can spot "joined days ago, signed in today, earning on their own, wallet linked but payouts off". - const LIST_UI = {}; - const dayStart = () => { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); }; - const activeToday = m => (m.lastSeen || 0) >= dayStart(); - const LIST_SORTS = [ - { k: 'seen', label: 'Last seen', v: m => m.lastSeen || 0 }, - { k: 'joined', label: 'Joined', v: m => m.joined || 0 }, - { k: 'earned', label: 'Surf earnings', v: m => m.earned || 0 }, - { k: 'balance', label: 'Earned balance', v: m => m.balance || 0 }, - { k: 'name', label: 'Name', v: m => String(m.name || '').toLowerCase(), str: true }, - ]; - const LIST_FILTERS = [ - { k: 'today', label: 'Active today', t: m => activeToday(m) }, - { k: 'earning', label: 'Earning', t: m => (m.earned || 0) > 0 }, - { k: 'wallet', label: 'Wallet linked', t: m => !!m.wallet }, - { k: 'nopay', label: 'Wallet, payouts off', t: m => !!m.wallet && !m.activated }, - { k: 'payouts', label: 'Payouts on', t: m => !!m.activated }, - { k: 'nowallet', label: 'No wallet', t: m => !m.wallet }, - ]; - const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set() }); - function listApply(key, rows) { - const st = listState(key); const s = LIST_SORTS.find(x => x.k === st.sort) || LIST_SORTS[0]; - const out = (rows || []).filter(m => m.own || [...st.on].every(k => { const f = LIST_FILTERS.find(x => x.k === k); return !f || f.t(m); })); - out.sort((a, b) => { const x = s.v(a), y = s.v(b); return (s.str ? String(x).localeCompare(String(y)) : x - y) * st.dir; }); - return out; - } - function listBar(key, total, shown, rerender, opts) { - const st = listState(key); const hide = (opts && opts.hide) || []; - const bar = document.createElement('div'); bar.className = 'lst-bar'; - bar.innerHTML = '' - + '' - + '' + LIST_FILTERS.filter(f => !hide.includes(f.k)).map(f => '').join('') + '' - + '' + (shown === total ? total + (total === 1 ? ' person' : ' people') : shown + ' of ' + total) + ''; - bar.querySelector('select').addEventListener('change', e => { st.sort = e.target.value; st.dir = st.sort === 'name' ? 1 : -1; rerender(); }); - bar.querySelector('.lst-dir').addEventListener('click', () => { st.dir = -st.dir; rerender(); }); - bar.querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (st.on.has(k)) st.on.delete(k); else st.on.add(k); rerender(); })); - return bar; - } - const seenAgo = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; const days = Math.floor(d / 86400e3); return days === 1 ? 'yesterday' : days + ' days ago'; }; - const seenChip = m => m.lastSeen ? '' + (activeToday(m) ? 'active today' : 'seen ' + seenAgo(m.lastSeen)) + '' : 'never signed in'; - const earnChip = m => '' + (m.earned || 0).toLocaleString() + ' cr earned'; - const walletChip = m => m.activated ? 'wallet · payouts on' : m.wallet ? 'wallet · payouts off' : 'no wallet'; - const memberChips = m => seenChip(m) + ' ' + earnChip(m) + ' ' + walletChip(m); - // Section pills at the top of My line: one per visible card marked data-jump, the one in view lit up. - // Cards that show or hide themselves (sponsor, upline messages) rebuild the row when they change. - let lineJumpObs = null; - function buildLineJump() { - const nav = document.getElementById('lineJump'); const pane = document.getElementById('pane-line'); if (!nav || !pane) return; - const cards = [...pane.querySelectorAll(':scope > .card[data-jump]')].filter(c => !c.hidden); - nav.innerHTML = cards.map(c => '').join(''); - nav.hidden = cards.length < 2; - const top = document.querySelector('.bo-top'); nav.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); pane.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); - nav.querySelectorAll('[data-jumpto]').forEach(b => b.addEventListener('click', () => { - const c = document.getElementById(b.dataset.jumpto); if (!c) return; - c.scrollIntoView({ behavior: 'smooth', block: 'start' }); - nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x === b)); - })); - if (lineJumpObs) lineJumpObs.disconnect(); - if ('IntersectionObserver' in window) { - const seen = new Map(); - lineJumpObs = new IntersectionObserver(ents => { - for (const e of ents) seen.set(e.target.id, e.isIntersecting ? e.boundingClientRect.top : null); - let best = null; for (const [id, t] of seen) if (t != null && (best == null || t < seen.get(best))) best = id; - if (best) { nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x.dataset.jumpto === best)); const on = nav.querySelector('.chip-t.on'); if (on && nav.scrollWidth > nav.clientWidth) nav.scrollLeft = on.offsetLeft - 16; } - }, { rootMargin: '-120px 0px -55% 0px' }); - cards.forEach(c => lineJumpObs.observe(c)); - } - } - { const pane = document.getElementById('pane-line'); - if (pane && 'MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(pane, { subtree: false, childList: false, attributes: true, attributeFilter: ['hidden'] }); - if (pane) pane.querySelectorAll(':scope > .card[data-jump]').forEach(c => { if ('MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(c, { attributes: true, attributeFilter: ['hidden'] }); }); } - const PAGE_AT = {}; - function pageList(key, host, rowSel, opts) { - if (!host) return; opts = opts || {}; const per = opts.per || PAGE_SIZE; - const rows = [...host.querySelectorAll(rowSel)]; - const old = host.querySelector(':scope > .pgr'); if (old) old.remove(); - if (rows.length <= per) { rows.forEach(r => { r.hidden = false; }); return; } - const pages = Math.ceil(rows.length / per); - let p = PAGE_AT[key] || 1; - if (opts.focus) { const i = rows.findIndex(opts.focus); if (i >= 0) p = Math.floor(i / per) + 1; } - p = Math.min(Math.max(1, p), pages); PAGE_AT[key] = p; - const start = (p - 1) * per; - rows.forEach((r, i) => { - const on = i >= start && i < start + per; r.hidden = !on; - if (opts.tail) { const t = r.nextElementSibling; if (t && t.matches(opts.tail) && !on && !t.hidden) { t.hidden = true; const b = r.querySelector('[aria-expanded]'); if (b) { b.setAttribute('aria-expanded', 'false'); b.textContent = 'Activity \u25BE'; } } } - }); - const bar = document.createElement('div'); bar.className = 'pgr'; - bar.innerHTML = 'Showing ' + (start + 1) + '\u2013' + Math.min(start + per, rows.length) + ' of ' + rows.length + '' - + '' - + 'Page ' + p + ' of ' + pages + '' - + ''; - bar.querySelectorAll('[data-go]').forEach(b => b.addEventListener('click', () => { - PAGE_AT[key] = Number(b.dataset.go); - pageList(key, host, rowSel, Object.assign({}, opts, { focus: null })); - host.scrollIntoView({ behavior: 'smooth', block: 'start' }); - })); - host.appendChild(bar); - } - const CH = { mint: '#43e8c3', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }; - function bars(el, xel, data) { // data: [{v,label,tip,alt}] - if (!el) return; - const max = Math.max(1, ...data.map(d => d.v)); - el.innerHTML = data.length - ? data.map(d => '
').join('') - : '
'.repeat(8); - if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join(''); - } - function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100 - if (!el) return; - const total = segs.reduce((s, x) => s + x.v, 0); - let off = 25, out = ''; - if (total > 0) for (const s of segs) { - const len = s.v / total * 100; - if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; } - out += ''; - off -= len; - } - out += '' + esc(center.big) + '' - + '' + esc(center.small) + ''; - el.innerHTML = out; - } - function legend(el, rows) { - if (el) el.innerHTML = rows.map(r => '
' - + esc(r.label) + ' ' + esc(r.v) + '
').join(''); - } - async function loadCharts(d) { - // credit composition donut + today's viewing ring (live balances) - try { - const st = await (await fetch('/api/my/earn')).json(); - if (!st.error) { - // one rule: a balance is what is NOT committed to a live campaign. Budgets are - // set aside when a campaign starts and spend down inside Campaigns, so these - // numbers only move when a campaign is created, topped up or paused - const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0; - $('dbCredits').textContent = (purchased + earned).toLocaleString(); - // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13) - if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned'; - $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (d.earnedReserved ? ' (+' + d.earnedReserved.toLocaleString() + ' earned and bonus credits working in your live campaigns)' : '') + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : ''); - donut($('chDonut'), - [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }], - { big: (purchased + earned).toLocaleString(), small: 'available' }); - legend($('chDonutLegend'), [ - { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() }, - { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() }, - { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]); - const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done); - donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }], - { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' }); - legend($('chRingLegend'), [ - { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done }, - { color: CH.track, label: 'To go', v: left }, - { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]); - } - } catch (e) {} - // recent on-chain payouts, sized to scale, oldest→newest - try { - let evs = []; - if (d.memberId) { - const a = await (await fetch('/api/my/activity')).json(); - evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12); - } - bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({ - v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6, - label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1), - tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' }))); - if (!evs.length) $('chEarnSub').textContent = d.memberId - ? 'no payouts yet — share your link' : 'activate a package to start earning'; - } catch (e) {} - // campaign delivery: impressions per campaign - try { - const r = await (await fetch('/api/my/campaigns')).json(); - const cs = (r.campaigns || []).slice(0, 8); - bars($('chCampBars'), $('chCampX'), cs.map(c => ({ - v: c.imps || 0, label: String(c.name || c.type).slice(0, 9), - tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks', - alt: c.type === 'text' }))); - if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad'; - } catch (e) {} - } - // ── live updates: subscribe to the chain event stream so the members area - // reacts to on-chain changes (payouts, qualifications) without a refresh ── - let MYID = 0; - // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message. - function playSound(kind) { - try { - const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; - const ctx = window.__iapAC || (window.__iapAC = new AC()); - if (ctx.state === 'suspended') ctx.resume(); - const now = ctx.currentTime; - const tone = (freq, at, dur, type, peak) => { - const o = ctx.createOscillator(), g = ctx.createGain(); - o.type = type || 'sine'; o.frequency.value = freq; - g.gain.setValueAtTime(0.0001, now + at); - g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02); - g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur); - o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02); - }; - if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); } - else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); } - } catch (e) {} - } - function startLiveFeed() { - if (window.__iapFeed || !window.EventSource) return; - try { - const es = new EventSource('/api/feed/live'); - window.__iapFeed = es; - es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); }; - // browser auto-reconnects on error; nothing to do - } catch (e) {} - } - let liveRefreshT = null; - function liveRefresh() { // debounce a burst of events into one refresh - clearTimeout(liveRefreshT); - liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600); - } - // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins, - // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so - // they never replace a personal one. At most one every 4 s; a burst shows the latest. - let liveT = 0, liveQ = null; - function communityToast(msg) { - const now = Date.now(); - if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; } - liveT = now; - let el = document.getElementById('liveToast'); - if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); } - el.textContent = msg; el.hidden = false; el.style.opacity = '1'; - clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000); - } - function handleLiveEvent(ev) { - if (!ev || !ev.type) return; - const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id; - // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications - if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; } - if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; } - if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; } - if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; } - if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; } - const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID); - if (!mine) { - if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package'); - else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL'); - else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's')); - else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts'); - return; - } - if (!MYID) return; - let toast = null, kind = 'ok'; - let sound = null; - if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } - else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } - else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!'; - else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; } - else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.'; - else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!'; - if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); } - } - - // training center: videos + materials (admin-curated via data/training.json) - async function loadTraining() { - try { - const r = await (await fetch('/api/training')).json(); - const el = $('trainingList'); if (!el) return; - const items = r.items || []; - if (!items.length) { el.innerHTML = '

Training materials are being added. Check back soon.

'; return; } - // section pills at the top: one per group, plus All; the active pill filters the list - const groups = [...new Set(items.map(it => it.group).filter(Boolean))]; - const pills = $('trainingPills'); - const want = loadTraining.filter || 'all'; - if (pills) { - pills.hidden = groups.length < 2; - pills.innerHTML = ['all', ...groups].map(g => '').join(''); - pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); })); - } - const shown = want === 'all' ? items : items.filter(it => it.group === want); - let lastGroup = null; - el.innerHTML = shown.map(it => { - // optional section header: entries carry a `group`; a header renders when it changes - let head = ''; - if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '

' + esc(it.group) + '

'; } - const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl); - // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both) - const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : ''); - const media = isVid ? '' : ''; - const links = []; - if (it.videoUrl && !isVid) links.push('Watch'); - if (it.docUrl) links.push('' + esc(it.docLabel || 'Open material') + ''); - return head + '

' + esc(it.title || 'Lesson') + '

' - + (it.desc ? '

' + esc(it.desc) + '

' : '') - + (media ? '

' + media + '

' : '') - + (links.length ? '

' + links.join(' ') + '

' : '') + '
'; - }).join(''); - } catch (e) {} - } - // visual line tree on the Overview: YOU + three levels, qualified directs in gold - function renderRoster(wrap, all) { - const rows = listApply('roster', all); - wrap.querySelectorAll(':scope > .lst-bar, :scope > table, :scope > .pgr, :scope > .lst-none').forEach(n => n.remove()); - wrap.appendChild(listBar('roster', all.length, rows.length, () => renderRoster(wrap, all))); - if (!rows.length) { wrap.insertAdjacentHTML('beforeend', '

Nobody in your line matches those filters.

'); return; } - const t = document.createElement('table'); t.className = 'roster'; - t.innerHTML = rows.map(r => '' - + '' - + '' - + '').join(''); - wrap.appendChild(t); - pageList('roster', wrap, 'table.roster tr', { per: LINE_PER }); - } - async function loadLineTree(buyerCount) { - try { - const r = await (await fetch('/api/my/line')).json(); - const el = $('lineTree'); if (!el) return; - const levels = r.levels || []; - const total = levels.reduce((n, L) => n + L.members.length, 0); - if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow'; - const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + ''; - const rowFor = lvl => { - const L = levels.find(x => x.level === lvl); const members = L ? L.members : []; - // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips") - let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $20+ buy - if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open'; - if (!html) html = '+ open'; - return '
L' + lvl + '
' + html + '
'; - }; - el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3); - // click a chip to drill down: My line opens with that person's Activity panel expanded (Marty, 2026-09-15) - const go = ref => { LINE_FOCUS_REF = ref; setPane('line'); }; - el.querySelectorAll('[data-goref]').forEach(n => { - n.addEventListener('click', () => go(n.dataset.goref)); - n.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(n.dataset.goref); } }); - }); - } catch (e) {} - } - let LINE_FOCUS_REF = null; // set by an Overview chip click; consumed once My line has rendered - // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14) - let newsLoaded = false; - async function loadNews() { - if (newsLoaded || !$('newsCard')) return; newsLoaded = true; - try { - const r = await (await fetch('/api/releases')).json(); - if (!r.notes.length && !r.roadmap.length) return; - let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {} - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const notes = r.notes.slice(0, 3).map(n => '

' + (n.date > seen ? '● ' : '') + '' + esc(n.title) + ' ' + esc(n.date) + '

').join(''); - const rm = r.roadmap.filter(x => x.status === 'building').slice(0, 2).map(x => '

Building: ' + esc(x.title) + (x.eta ? ' (' + esc(x.eta) + ')' : '') + '

').join(''); - $('newsList').innerHTML = notes + rm + '

All release notes and the roadmap →

'; - $('newsCard').hidden = false; - $('newsCard').addEventListener('click', () => { try { localStorage.setItem('iap.news.seen', r.latest || ''); } catch (e) {} $('newsList').querySelectorAll('span[style*="mint"]').forEach(s => { if (s.textContent === '●') s.remove(); }); }, { once: true }); - } catch (e) {} - } - // Leaderboard card: top 5 this week + your own rank + the prize (Marty, 2026-09-14) - async function loadLeaderboard() { - if (!$('lbCard')) return; - try { - const r = await (await fetch('/api/leaderboard?period=week')).json(); - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - let h = r.prize ? '

Prize this week: ' + esc(r.prize) + '

' : ''; - h += r.top.length ? '
' + esc(r.name || r.email || '') + 'joined ' + new Date(r.joined).toLocaleDateString() + '' + memberChips(r) + '' + esc(r.status) + '
' + r.top.slice(0, 5).map(x => '').join('') + '
' + x.rank + '' + esc(x.name) + '' + x.sales + ' sold · $' + x.usd + '
' - : '

No packages sold yet this week. First sale takes the top spot.

'; - h += r.me ? '

You: #' + r.me.rank + ' · ' + r.me.sales + ' sold · $' + r.me.usd + '

' : '

You: no sales yet this week. Sales are $20+ packages bought by people you sponsor.

'; - h += '

Full leaderboard: week, month, all time →

'; - $('lbList').innerHTML = h; $('lbCard').hidden = false; - } catch (e) {} - } - // Getting-started stepper: username -> wallet -> payouts -> first package. The current step gets one big - // button that opens the right tab and pulses the control (Jim: "it wasn't obvious", 2026-09-14) - function renderSteps(d) { - const card = $('gsCard'); if (!card) return; - const hasUser = !!d.username, hasWallet = !!d.address, hasPayouts = !!d.memberId, hasPackage = !!(d.memberId && (d.credits || 0) > 0); - const steps = [ - { k: 'user', t: 'Pick a username', done: hasUser }, - { k: 'wallet', t: 'Link your wallet', done: hasWallet }, - { k: 'payouts', t: 'Switch on payouts', done: hasPayouts }, - { k: 'package', t: 'Your first package', done: hasPackage } - ]; - if (steps.every(x => x.done)) { card.hidden = true; return; } - const cur = steps.find(x => !x.done); - let collapsed = false; try { collapsed = localStorage.getItem('iap.gs.collapsed') === '1'; } catch (e) {} - $('gsSub').innerHTML = steps.filter(x => x.done).length + ' of 4 done · ' + (collapsed ? 'show' : 'hide') + ''; - $('gsToggle').addEventListener('click', e => { e.preventDefault(); try { localStorage.setItem('iap.gs.collapsed', collapsed ? '0' : '1'); } catch (er) {} renderSteps(d); }); - $('gsSteps').hidden = collapsed; $('gsNow').hidden = collapsed; - $('gsSteps').innerHTML = steps.map((x, i) => '
' + (x.done ? '✓' : i + 1) + '' + x.t + '
').join(''); - const copy = { - user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)], - wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')], - payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')], - package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)] - }[cur.k]; - $('gsNow').innerHTML = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; - $('gsGo').addEventListener('click', copy[3]); - card.hidden = false; - } - // member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=#buy. - // We remember the game (through sign-in), tell the server once, and show the offer + the way back to the perk. - try { const fm = /[?&]from=([a-z]{3,20})/.exec(location.search); if (fm) { sessionStorage.setItem('iap.starterFrom', fm[1]); history.replaceState(null, '', '/my' + (location.hash || '')); } } catch (e) {} - async function starterBanner(me) { - let from = null; try { from = sessionStorage.getItem('iap.starterFrom'); } catch (e) {} - let v = null; - if (from) { try { sessionStorage.removeItem('iap.starterFrom'); } catch (e) {} v = await (await fetch('/api/starter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ game: from }) })).json(); } - else v = await (await fetch('/api/starter')).json(); - if (!v || !v.on || !v.game) return; - const pane = document.querySelector('#pane-buy .card'); if (!pane) return; - let box = document.getElementById('starterBox'); if (!box) { box = document.createElement('div'); box.id = 'starterBox'; pane.insertBefore(box, pane.children[1] || null); } - const esc = t => String(t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - box.style.cssText = 'border:1px solid var(--gold, #e2b04a);border-radius:12px;padding:12px 14px;margin:0 0 14px;background:rgba(226,176,74,.08)'; - box.innerHTML = v.eligible - ? 'Welcome from ' + esc(v.game) + '!
Your first package, $5 or more, comes with +' + v.bonus + ' bonus ad credits, and ' + esc(v.perk) + ' waiting for you in ' + esc(v.game) + '.' - : 'You are a member. ' + (v.granted ? 'Your +' + v.bonus + ' welcome credits are in your balance. ' : '') + 'Your ' + esc(v.perk) + ' is waiting in ' + esc(v.game) + '.
Back to ' + esc(v.game) + ' to collect it'; - if (from && !/^#(passes|games)/.test(location.hash)) setPane('buy'); // a game's Buy-a-pass link (#passes) stays on the pass card - } - function jumpTo(pane, id) { - setPane(pane); - setTimeout(() => { const el = id && $(id); if (!el) return; el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.remove('pulse'); void el.offsetWidth; el.classList.add('pulse'); try { el.focus({ preventScroll: true }); } catch (e) {} }, 250); - } - async function loadDashboard() { - try { - loadNews(); loadLeaderboard(); - const d = await (await fetch('/api/my/dashboard')).json(); - if (d.error) return; - chatSync(d); - try { renderSteps(d); } catch (e) {} - MYID = d.memberId || MYID; - startLiveFeed(); - if (!window.__lbChecked) { // daily login bonus, once per session (server guards once/day) - window.__lbChecked = true; - api('/api/my/login-bonus').then(r => { - if (r && r.comeback > 0) { IAP.status('🎉 Welcome back! +' + r.comeback + ' bonus credits for coming back, plus +' + r.granted + ' for signing in today.', 'ok'); playSound('chaching'); setTimeout(loadDashboard, 900); } - else if (r && r.granted > 0) { - IAP.status('🎁 Daily login bonus: +' + r.granted + ' credits' + (r.streak > 1 ? ' · ' + r.streak + '-day streak' : '') + '!', 'ok'); - playSound('chaching'); setTimeout(loadDashboard, 900); - } - }).catch(() => {}); - } - const earnedAv = d.earnedCredits || 0, inCamp = d.inCampaigns || 0; - $('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString(); - $('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : ''); - $('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0'); - usdRate().then(r => { const el = $('dbEarnedUsd'); if (el) el.textContent = r.usd > 0 && d.earnedWei && d.earnedWei !== '0' ? usdOf(d.earnedWei, r) + ' today' : ''; }); - $('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; } - $('dbTeam').textContent = (d.referrals || []).length; - // trend chips: only real, computable facts - const ec = $('dbEarnedChip'); - if (ec && d.earnCount) { ec.hidden = false; ec.textContent = d.earnCount + ' instant payout' + (d.earnCount > 1 ? 's' : ''); } - const bc = $('dbBuyersChip'); - if (bc && d.memberId) { - bc.hidden = false; - bc.textContent = (d.buyerCount || 0) >= 5 ? 'level 3 open' : (d.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'; - } - const tc = $('dbTeamChip'), wk = (d.referrals || []).filter(r => Date.now() - new Date(r.joined) < 6048e5).length; - if (tc && wk) { tc.hidden = false; tc.textContent = '+' + wk + ' this week'; } - setInboxBadge(d.inboxUnread || 0); - if (d.sponsorMsg) showSponsorModal(d.sponsorMsg); - renderBadges(d); - loadFeatured(); - loadLineTree(d.buyerCount || 0); - loadCharts(d); - $('nextMove').textContent = nextMove(d); - renderSteps(d); - const wrap = $('rosterWrap'); - if ((d.referrals || []).length) { - $('rosterEmpty').hidden = true; - renderRoster(wrap, d.referrals); - } - // overview recent-activity widget: chain events + line joins, newest first - try { - const c = await IAP.getConfig(); - const ov = $('ovFeed'); - const rows = []; - if (d.memberId) { - const a = await (await fetch('/api/my/activity')).json(); - for (const ev of [...(a.earnings || []), ...(a.purchases || [])] - .sort((x, y) => y.block - x.block).slice(0, 5)) rows.push(IAP.feedRow(ev, c)); - } - for (const r of (d.referrals || []).slice(0, 3)) { - const div = document.createElement('div'); - div.className = 'row'; - div.innerHTML = '🤝 ' + esc(r.name || r.email || 'A new member') + ' joined your line' - + new Date(r.joined).toLocaleDateString() + ''; - rows.push(div); - } - if (rows.length) { - ov.innerHTML = ''; - rows.slice(0, 6).forEach(r => ov.appendChild(r)); - } - } catch (e) {} - // ready-to-send share message + promo tools, personalized - await SHARE_READY; - const link = shareLink(d.username || d.refCode || d.memberId || ''); - fillPromo(link, d); - // founding-week readiness: shown until every item is done (or the launch moment is a week past) - try { - const cfg = await IAP.getConfig(); const items = IAP.launchChecks(d); const done = items.filter(i => i.done).length; - const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; - const show = done < items.length && !(at && Date.now() > at + 7 * 86400000); - const lm = $('launchMark'); - if (lm) { lm.hidden = !show; lm.innerHTML = show ? 'Launch ready: ' + done + ' of ' + items.length + '. ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + 'Open the founding-week checklist' : ''; } - } catch (e) {} - // people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it - try { - const tw = d.tankWaiting, tn = $('tankNotice'); - if (tn) { - tn.hidden = !(tw && tw.count); - if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 ' - + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line' - + (tw.eligible ? '.' : ' (you need your own $20 package first).'); - } - } catch (e) {} - // Share the presentation (2026-10-15): instantadpay.com/presentation?ref= sets the same sponsor cookie as /join - { const tokP = d.username || d.refCode || d.memberId; const ps = $('promoPresStrip'); - if (ps && tokP) { const pl = 'https://instantadpay.com/presentation?ref=' + encodeURIComponent(tokP); ps.hidden = false; $('promoPresLink').textContent = pl; $('promoPresOpen').href = '/presentation?ref=' + encodeURIComponent(tokP); - $('promoPresCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); IAP.status('Presentation link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; } } - if (d.username) { // wall link rides the username - const wl = location.origin + '/wall/' + d.username; - $('wallLine').textContent = wl; - if ($('promoWallStrip')) { // the same wall link at the top of Promo tools, next to the invite link - $('promoWallStrip').hidden = false; $('promoWallLink').textContent = wl; $('promoWallOpen').href = '/wall/' + d.username; - $('promoWallCopy').onclick = async () => { try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; - } - $('wallCopy').hidden = false; - $('wallOpen').hidden = false; - $('wallOpen').href = '/wall/' + d.username; - $('wallCopy').onclick = async () => { - try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select the link text instead.', 'bad'); } - }; - } - if (d.refCode || d.memberId) { - const pitch = 'I found an advertising site that pays referrals instantly to your own wallet. ' - + 'No withdrawals, no waiting, and every payment is public on a blockchain ledger you can check yourself. ' - + 'Free to join and look around: ' + link; - $('copyPitch').hidden = false; - $('pitchPreview').hidden = false; - $('pitchPreview').textContent = '"' + pitch + '"'; - $('copyPitch').onclick = async () => { - try { await navigator.clipboard.writeText(pitch); IAP.status('Message copied. Paste it anywhere.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select the preview text instead.', 'bad'); } - }; - } - } catch (e) {} - } - - // ── back-office menu: hash-routed panes ─────────────── - const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile']; - const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns', - earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games', - wallet: 'Wallet & account', profile: 'Profile' }; - function setPane(name) { - let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) - if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card - if (!PANES.includes(name)) name = 'overview'; - for (const p of PANES) { - const el = $('pane-' + p); - if (el) el.hidden = p !== name; - } - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => - b.classList.toggle('on', b.dataset.pane === name)); - if ($('boTitle')) $('boTitle').textContent = TITLES[name]; - // member ads: a fresh text ad in the strip under the title, and a banner at the foot of the pane - IAP.adSlot('text', 'adStripTop'); - if ($('adSlotPane-' + name)) IAP.adSlot('banner', 'adSlotPane-' + name); - if (name === 'earn') { setEarnSub(earnSub); loadPdCard(); } // refresh whichever sub-tab is active; PassiveDrip card (2026-10-01) - else if (vidState.token) stopVideo(); - if (name === 'profile') loadLineBanner(); - if (name === 'line') { buildLineJump(); loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); } - if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits - if (name === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); } - if (name === 'pipeline') loadPipeline(); - if (name === 'games') loadGames(paneQ); - if (name === 'help' && window.IAPSupport) IAPSupport.help(paneQ); // help desk tickets (2026-10-16) - document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer - const keepQ = name === 'help' && paneQ ? '?' + paneQ : ''; // Help keeps ?t= so a reload reopens the ticket - if (location.hash !== '#' + name + keepQ) history.replaceState(null, '', '#' + name + keepQ); - } - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => - b.addEventListener('click', () => setPane(b.dataset.pane))); - document.querySelectorAll('.qa [data-goto]').forEach(b => - b.addEventListener('click', () => setPane(b.dataset.goto))); - const qaCopy = document.getElementById('qaCopyInvite'); - if (qaCopy) qaCopy.addEventListener('click', async () => { - const link = document.getElementById('inviteLine').textContent; - if (!link || !link.startsWith('http')) { setPane('line'); return; } - try { await navigator.clipboard.writeText(link); IAP.status('Invite link copied.', 'ok'); } - catch (e) { setPane('line'); } - }); - window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); - if ($('boBurger')) $('boBurger').addEventListener('click', () => - document.getElementById('memberArea').classList.toggle('side-open')); - - async function render() { - // while /api/me answers, show a spinner instead of flashing the sign-in card at a signed-in member - let me = null; - try { me = await IAP.refreshNavWallet(); } catch (e) { me = null; } - if ($('bootSpin')) $('bootSpin').hidden = true; - // one way in: email. A wallet-only session (no account) is sent back to the - // email card with a finish-setup note; verifying the code links that wallet. - const walletOnly = !!(me && me.signedIn && !me.email); - const signedIn = me && me.signedIn && !walletOnly; - $('authArea').hidden = !!signedIn; - $('memberArea').hidden = !signedIn; - if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; - if (!signedIn) return; - if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL - if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews) - // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be - // skipped or dismissed; it resolves only when a username is saved, then the area renders. - if (!me.username) { - if (!render.gating) { render.gating = true; showOnboard(true).then(() => { render.gating = false; render(); }); } - return; - } - // came from a Drip Runner share link: once they have a username, straight back into the game (2026-09-30) - if (me.returnTo === 'driprunner' && !render.toGame) { render.toGame = true; location.href = '/api/my/driprunner'; return; } - if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01) - if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; } - if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02) - if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13) - if (me.returnTo === 'shardsofvalor' && !render.toGame) { render.toGame = true; location.href = '/api/my/shardsofvalor'; return; } // Shards of Valor sent them here to sign in (2026-10-18) - if (me.returnTo === 'pwmint' && !render.toGame) { render.toGame = true; location.href = '/pw/mint/resume'; return; } // PolyWarriors paid mint (2026-10-05) - if (me.pwMint && !me.gkShop && !me.sdShop && !document.getElementById('pwBack')) { const d = document.createElement('a'); d.id = 'pwBack'; document.body.classList.add('hasback'); d.href = '/pw/mint/resume'; d.textContent = 'PolyWarriors mint: buy a package and you go straight back to the game when it settles. Or go back now →'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 44px 14px 16px;border-radius:14px;background:linear-gradient(180deg,#22E5FF,#7A2CFF);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); - // x = not now: clears the bar cookie (the waiting mint order stays and a later package still completes it), Marty 2026-10-11 - const x = document.createElement('button'); x.type = 'button'; x.setAttribute('aria-label', 'Hide'); x.textContent = '×'; x.setAttribute('style', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);width:30px;height:30px;border:0;border-radius:50%;background:rgba(0,0,0,.28);color:#fff;font-size:20px;line-height:30px;cursor:pointer;padding:0'); - x.addEventListener('click', ev => { ev.preventDefault(); ev.stopPropagation(); fetch('/pw/mint/dismiss', { method: 'POST' }).catch(() => {}); d.remove(); document.body.classList.remove('hasback'); if (me) me.pwMint = false; }); d.appendChild(x); } - if (me.returnTo === 'sdshop' && !render.toGame) { render.toGame = true; location.href = '/sd/shop/resume'; return; } - if (me.sdShop && !document.getElementById('sdBack')) { const d = document.createElement('a'); d.id = 'sdBack'; document.body.classList.add('hasback'); d.href = '/sd/shop/resume'; d.textContent = 'Finish your Spooky Doors costume order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:' + (me.gkShop ? '74px' : '14px') + ';z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:#FF8A1F;color:#2a1200;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 5px 0 #C25A06,0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } - if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; document.body.classList.add('hasback'); d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } - if (me.returnTo === 'passivedrip' && !render.toGame) { render.toGame = true; location.href = '/api/my/passivedrip'; return; } // PassiveDrip sent them here to sign in (2026-10-01) - // arrived from an invite page: run the welcome tour and login ad once - if (/[?&]welcome=1/.test(location.search) && !render.welcomed) { - render.welcomed = true; - history.replaceState(null, '', '/my' + (location.hash || '')); - (async () => { - try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {} - await render(); - })(); - } - starterBanner(me).catch(() => {}); - setPane(location.hash.slice(1) || 'overview'); - $('campGate').hidden = !!me.memberId; - $('earnGate').hidden = !!me.memberId; - if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); } - loadDashboard(); - if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket - - const who = []; - if (me.email) who.push(me.email); - // members kept asking whether the wallet was really connected (Marty, 2026-09-12): say it, with a green check - if (me.address) who.push('Wallet connected ' + me.address.slice(0, 8) + '…' + me.address.slice(-6) + ''); - else who.push('No wallet connected yet (link one below)'); - if (me.memberId) who.push('on-chain member #' + me.memberId + '' - + (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : '')); - else if (me.sponsorId) who.push('invited by member #' + me.sponsorId); - $('posLine').innerHTML = who.join('
'); - - $('creditLine').textContent = (me.credits || 0).toLocaleString(); - loadPositions(me); - $('linkCard').hidden = !!me.address; - $('activateCard').hidden = !(me.address && !me.memberId); - $('activityArea').hidden = !me.memberId; - $('campGate').hidden = true; // earned credits fund campaigns for everyone - $('campaignCard').hidden = false; - loadCampaigns(); - - // profile pane state - $('pfCurrent').textContent = me.username ? '@' + me.username + ' is your permanent username. Your invite link, your public page and any banners you shared carry it, so it cannot be changed.' : 'No username yet. Members see you as a number until you pick one. Choose carefully: it is permanent once saved.'; - if (!$('pfUsername').value) $('pfUsername').value = me.username || ''; - $('pfUsername').disabled = !!me.username; $('pfSaveBtn').hidden = !!me.username; - $('pfDetails').innerHTML = 'Email: ' + (me.email || 'none') + '
Wallet: ' - + (me.address ? '' + me.address.slice(0, 10) + '…' + me.address.slice(-6) + '' : 'not linked yet') - + '
On-chain member: ' + (me.memberId ? '#' + me.memberId : 'not yet'); - // the share link works from day one; usernames make it a vanity link - if (me.username || me.refCode || me.memberId) { - await SHARE_READY; - $('inviteLine').textContent = shareLink(me.username || me.refCode || me.memberId); - $('copyInvite').hidden = false; - } else { - $('inviteLine').textContent = 'Sign in with your email to get your link.'; - $('copyInvite').hidden = true; - } - if (me.memberId) { - const bc = me.buyerCount || 0; - $('qualLine').innerHTML = '' + bc + ' qualifying buyer(s) referred
' - + (bc >= 5 ? 'Level 3 unlocked: full three-level earnings' - : bc >= 2 ? 'Level 2 unlocked · ' + (5 - bc) + ' more for level 3' - : (2 - bc) + ' more buyer(s) of $20+ unlock level 2'); - loadActivity(); - } else { - $('qualLine').innerHTML = 'Share your link now. Then switch on payouts (free, above) ' - + 'before your people start buying: the contract locks each buyer to their sponsor at ' - + 'their first purchase, and payments only route to wallets that are switched on.'; - } - } - - // Dollar value at today's POL price (Marty, 2026-10-22): one cached rate from our own server (5 min there, 2 min here), - // shown as "≈ $x.xx" next to POL amounts on the member's own pages. It is today's value, not the value on the payout day. - let USD = null; - async function usdRate() { - if (USD && Date.now() - USD.got < 120000) return USD; - try { const r = await (await fetch('/api/public/polusd')).json(); USD = { usd: Number(r.usd) || 0, at: Number(r.at) || Date.now(), got: Date.now() }; } catch (e) { USD = USD || { usd: 0, at: 0, got: Date.now() }; } - return USD; - } - function usdOf(wei, r) { - let pol = 0; try { pol = Number(BigInt(wei || '0') / 10n ** 12n) / 1e6; } catch (e) {} - const v = pol * ((r && r.usd) || 0); - return '≈ $' + v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); - } - function usdNote(r) { - if (!r || !(r.usd > 0)) return ''; - const mins = Math.max(0, Math.round((Date.now() - r.at) / 60000)); - return '1 POL ≈ $' + r.usd.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 }) + ' at today’s price (updated ' + (mins < 1 ? 'just now' : mins + ' min ago') + '). Dollar amounts are what the POL is worth today, not on the day it was paid.'; - } - async function loadActivity() { - try { - const c = await IAP.getConfig(); - const a = await (await fetch('/api/my/activity')).json(); - const fill = (id, evs, empty) => { - const el = $(id); - el.innerHTML = ''; - if (!evs || !evs.length) { el.innerHTML = '
' + empty + '
'; return; } - for (const ev of evs) el.appendChild(IAP.feedRow(ev, c)); - }; - fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.'); - usdRate().then(r => { - const note = $('earnUsdNote'); if (note) note.textContent = usdNote(r); - if (!(r.usd > 0)) return; - const rows = $('earnFeed').querySelectorAll('.row'); let i = 0; - for (const ev of (a.earnings || [])) { const row = rows[i++]; if (!row || !ev.amountWei) continue; const s = document.createElement('span'); s.className = 'usd muted small'; s.textContent = usdOf(ev.amountWei, r); const tx = row.querySelector('.tx'); row.insertBefore(s, tx || null); } - }); - fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.'); - fill('buyFeed', a.purchases, 'No purchases from your wallet yet.'); - } catch (e) {} - initTrace(); - } - // payment trace (2026-09-16): who was paid, who was skipped and why, per purchase - let traceInit = false; - function initTrace() { - if (traceInit || !$('trGo')) return; traceInit = true; - const run = async () => { - const who = ($('trWho').value || '').trim(); const out = $('trOut'); const msg = $('trMsg'); - msg.textContent = 'Reading the chain…'; out.innerHTML = ''; - try { - const c = await IAP.getConfig(); - const r = await (await fetch('/api/my/trace?who=' + encodeURIComponent(who))).json(); - if (r.error) { msg.textContent = r.error; return; } - msg.textContent = ''; - const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody'; - const pol = w => IAP.fmtPol(w) + ' POL'; - const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - let h = '

' + nm(r.memberId) + ' · ' + (r.activated ? 'activated under ' + nm(r.sponsorId) : 'not activated on the chain yet') + ' · ' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' (level 2 needs 2, level 3 needs 5)

'; - if (!r.purchases.length) { out.innerHTML = h + '

No purchases involving ' + nm(r.memberId) + ' yet.

'; return; } - for (const p of r.purchases) { - const isBuyer = p.buyerId === r.memberId; - h += '
' - + '
' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought a $' + (p.priceCents / 100).toFixed(0) + ' package (' + pol(p.paidWei) + ')' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') - + (c.explorer ? ' · verify ↗' : '') + '
'; - for (const t of p.tiers) { - const me = t.paidTo === r.memberId, skippedMe = t.skipped.some(x => x.id === r.memberId); - let line = 'Level ' + t.tier + ' (' + t.pct + '%): '; - for (const x of t.skipped) line += '' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'not qualified: had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' qualifying buyers then' : esc(x.reason)) + ') → '; - line += t.paidTo ? '' + nm(t.paidTo) + ' paid ' + pol(t.amountWei) + '' : 'no eligible catcher within reach → company'; - h += '
' + line + '
'; - } - h += '
Platform (20%): ' + pol(p.adminWei) + (isBuyer ? '' : '') + '
'; - } - h += '

A skipped level means that person had not unlocked it when the purchase settled. Qualification never applies backwards; the next purchase after they qualify pays them.

'; - out.innerHTML = h; - } catch (e) { msg.textContent = 'Could not read the chain just now. Try again in a minute.'; } - }; - $('trGo').addEventListener('click', run); - $('trWho').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); run(); } }); - } - - // credit activity ledger under the campaign table (2026-09-16): every earn and spend with its reason - // Archived campaigns: everything they did, none of the clutter and none of the reservation. - function renderArchived(el, r) { - const rows = r.archived || []; - if (!rows.length) return; - const box = document.createElement('div'); - box.className = 'card'; - box.style.marginTop = '18px'; - // what each one gave back = budget not delivered (flat packs are charged in full when bought, so theirs is 0) - const leftOf = c => Math.max(0, Number(c.budget || 0) - Number(c.spent || 0) - Number(c.accrued || 0)); - const returned = rows.reduce((n, c) => n + leftOf(c), 0); - box.innerHTML = '

Archived

' + rows.length + ' finished campaign' + (rows.length === 1 ? '' : 's') + ' · ' + returned.toLocaleString() + ' unspent credit' + (returned === 1 ? '' : 's') + ' returned
' - + '
' - + rows.map(c => '' - + '' - + '' - + '' - + '' - + '' - + '').join('') - + '
NameTypeViews hereClicksSpentReturnedRan until
' + esc(c.name || ('#' + c.id)) + '' + esc(c.type) + '' + Number(c.imps || 0).toLocaleString() + '' + Number(c.clicks || 0).toLocaleString() + '' + Number(c.spent || 0).toLocaleString() + '' + leftOf(c).toLocaleString() + '' + (c.created ? new Date(c.created).toLocaleDateString() : '') + '
' - + '

Archived campaigns keep every number they earned. They serve nothing and reserve nothing, so any budget they had not delivered is back in your Available balance (the Returned column). A campaign that delivered its whole budget has nothing left to return, and visit packs, Golden Door, login and featured runs are paid in full when bought. Restore brings one back, paused.

'; - el.appendChild(box); - box.querySelectorAll('[data-unarch]').forEach(b => b.addEventListener('click', async () => { - b.disabled = true; - try { await api('/api/my/campaigns/' + b.dataset.unarch + '/unarchive'); IAP.status('Restored, and paused. Press Resume when you want it running.', 'ok'); await loadCampaigns(); loadDashboard(); } - catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - })); - } - async function loadCreditActivity(el) { - try { - const r = await (await fetch('/api/my/credits/activity')).json(); - if (!r.items || !r.items.length) return; - const box = document.createElement('div'); box.id = 'creditActivity'; box.style.marginTop = '16px'; - const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - box.innerHTML = '

Credit activity

' - + '

Every credit that came in or went out, newest first. Earned credits are spent before purchased ones, so an earn followed by a buy shows as two lines here. Views a campaign delivers roll up into one line per day.

' - + '
' - + r.items.map(i => '').join('') - + '
' + when(i.ts) + '' + (i.delta > 0 ? '+' : '') + i.delta.toLocaleString() + '' + esc(i.note) + '
'; - el.appendChild(box); - pageList('credits', box, 'tbody tr'); - } catch (e) {} - } - async function loadCampaigns() { - try { - const r = await (await fetch('/api/my/campaigns')).json(); - if (r.error) return; - lastRates = r.rates; - if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.'; - // populate the banner-size dropdown once (ids map to NAS width/height) - if (r.bannerSizes && $('cSize') && !$('cSize').options.length) - $('cSize').innerHTML = r.bannerSizes.map(s => '').join(''); - applyType(); // the default type is banner: show its size + image rows now that the sizes exist - soloHint(); - if ($('spendBanner')) { - $('spendBanner').hidden = false; - $('spendBig').textContent = r.availableCredits.toLocaleString(); - $('spendSub').textContent = '= $' + (r.availableCredits / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' of ad delivery · ' + r.purchasedCredits.toLocaleString() + ' purchased' + (r.creditedCredits ? ' (' + r.creditedCredits.toLocaleString() + ' of it credited to you, spends on anything)' : '') + ' + ' + (r.earnedCredits || 0).toLocaleString() + ' earned' + (r.earnedReserved ? ' (' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits are already working inside your live campaigns)' : '') + (r.positionCount > 1 ? ' · pooled across ' + r.positionCount + ' positions (largest single position ' + (r.largestPosition || 0).toLocaleString() + ')' : ''); - if ($('spendNote')) $('spendNote').textContent = r.inCampaigns - ? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.' - : 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.'; - $('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', r.rates.loginCreditsPerDay + ' cr / day'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '' + x[0] + ' ' + x[1] + '').join(''); - } - $('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString() - + ((r.earnedCredits || r.earnedReserved) ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + (r.earnedCredits || 0) + ' earned' + (r.earnedReserved ? ', ' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits already working inside your live campaigns' : '') + ')' : '') - + (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '') - + ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch - + ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch - + ' views, login ' + r.rates.loginCreditsPerDay + 'cr/day, solo ' - + (r.rates.soloCostPerRecipient || 5) + 'cr/delivery'; - const el = $('campList'); - el.innerHTML = ''; - if (!r.campaigns.length) { el.innerHTML = '

No campaigns yet. Launch your first below.

'; loadCreditActivity(el); return; } - const tbl = document.createElement('div'); - tbl.className = 'tablewrap'; - tbl.innerHTML = '' - + '' - + r.campaigns.map(c => '' - + '' - + '' - + '' - + '' - + (c.type === 'visits' ? '' - : c.type === 'featured' ? '' - : '') - + '' - + '').join('') + '
NameTypeViews hereNetwork viewsClicksSpentBudgetStatus
' + c.name + '' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '' + c.type + (c.type === 'banner' && c.width ? ' ' + c.width + '×' + c.height + '' : '') + (c.dailyCap ? ' cap ' + c.dailyCap + '/day' : '') + (c.geo ? ' tier ' + esc(c.geo.replace(/,/g, '+')) + '' : '') + schedChips(c) - + (c.type === 'visits' && (c.placement === 'golden' || c.placement === 'doors') ? ' ' + (c.placement === 'golden' ? 'Golden Door' : 'Spooky Doors') + '' : '') + '' + c.imps.toLocaleString() + '' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : 'n/a') + '' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '
' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '' + esc(k) + ' ' + v + '').join('') + (c.impsNas ? ' · network: see Network views' : '') + '
' : '') + '
paid up front' + c.imps.toLocaleString() + ' of ' + Number(c.body || 0).toLocaleString() + (c.placement === 'golden' || c.placement === 'doors' ? ' doors' : ' visits') - + (((r.doorStats && r.doorStats[c.id]) || c.placement === 'golden' || c.placement === 'doors') ? (ds => '
\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '
')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '
paid up front' + featRun(c) + '' + c.spent + '' + c.budget + '' + (c.status === 'out' ? (c.type === 'visits' ? 'pack delivered' : 'budget spent') : c.status === 'done' ? '' + (c.type === 'featured' ? 'run ended' : 'ended') + '' : c.scheduled ? 'scheduled' : c.status) + '' + (c.status === 'active' ? '' - : c.status === 'paused' ? '' : '') - + (['paused', 'out', 'done'].includes(c.status) ? ' ' : '') - + (c.type === 'featured' ? ' ' - : c.type === 'visits' ? ' ' - : c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up - : ' ') - + '
'; - el.appendChild(tbl); - pageList('camps', tbl, 'tbody tr'); - renderArchived(el, r); - const note = document.createElement('p'); note.className = 'muted small'; - note.textContent = 'Credits you put into a campaign are set aside the moment you start it, so your Available number drops right away and the campaign spends from its own budget. Featured links and verified-visit packs are paid in full up front; a featured run is sold by the day, so use Extend run to keep it going. Whatever a campaign has not spent comes back to Available when it ends.'; - el.appendChild(note); - loadCreditActivity(el); - el.querySelectorAll('button[data-extend]').forEach(b => b.addEventListener('click', async () => { - const rr = r.rates || {}; const durs = rr.featuredDurations || [1, 2, 7]; const per = rr.featuredPerDay || 40; - const d = await IAP.ask({ title: 'Extend featured run', text: 'How many more days? Choose ' + durs.join(', ') + '. ' + per + ' credits a day, charged now. The days are added after the current run, or start today if it has ended.', type: 'number', placeholder: 'e.g. ' + durs[durs.length - 1], ok: 'Extend' }); - if (!d) return; - try { const x = await api('/api/my/campaigns/' + b.dataset.extend + '/extend', { days: Number(d) }); - IAP.status('Extended ' + x.days + ' day' + (x.days === 1 ? '' : 's') + ' for ' + x.cost + ' credits' + (x.resumed ? '. The run is live again.' : '.'), 'ok'); - await loadCampaigns(); loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('button[data-morevisits]').forEach(b => b.addEventListener('click', async () => { - const per = Number(b.dataset.vper) || (r.rates && r.rates.visitCostPerVisit) || 3; const door = b.dataset.vdoor; // door packs top up at their door price - const what = door === 'golden' ? 'Golden Doors' : door ? 'doors' : 'visits'; - const n = await IAP.ask({ title: 'Buy more ' + what, text: door ? 'How many more ' + what + '? ' + per + ' credits each, charged now like the original pack.' : 'How many more verified visits? ' + per + ' credits each, charged now like the original pack.', type: 'number', placeholder: 'e.g. 50', ok: 'Buy ' + what }); - if (!n) return; - try { const x = await api('/api/my/campaigns/' + b.dataset.morevisits + '/topup', { credits: Math.floor(Number(n)) * per }); - IAP.status('Added ' + x.visits + ' ' + what + ' (' + x.added + ' credits)' + (x.reactivated ? '. The pack is open again.' : '.'), 'ok'); - await loadCampaigns(); loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => { - try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('[data-arch]').forEach(b => b.addEventListener('click', async () => { - const left = Number(b.dataset.archleft) || 0; - const ok = await IAP.confirmBox( - 'It stops appearing in this list but keeps every number it earned, in the Archived section below.' - + (left ? ' Its ' + left.toLocaleString() + ' unspent credits go straight back to your Available balance.' : '') - + ' You can restore it at any time.', - { title: 'Archive ' + b.dataset.archname, ok: 'Archive it', cancel: 'Keep it here' }); - if (!ok) return; - b.disabled = true; - try { const x = await api('/api/my/campaigns/' + b.dataset.arch + '/archive'); - IAP.status('Archived.' + (x.freed ? ' ' + Number(x.freed).toLocaleString() + ' credits released.' : ''), 'ok'); - await loadCampaigns(); loadDashboard(); } - catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - })); - el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => { - const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views. They are set aside now and spend as views are delivered; anything unspent comes back when the campaign ends.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' }); - if (!n) return; - const done = r => { IAP.status('Added ' + r.added + ' credits' + (r.paidFrom ? ', paid from position #' + r.paidFrom : '') + (r.reactivated ? '. The campaign is live again.' : '.'), 'ok'); }; - try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) })); await loadCampaigns(); loadDashboard(); } - catch (e) { - // the ad's own position is short but another of yours has the credits: offer to pay from that one - const opt = e.data && e.data.switchOptions && e.data.switchOptions[0]; - if (!opt) { IAP.status(e.message, 'bad'); return; } - const yes = await IAP.confirmBox('This ad pays from your position #' + e.data.fundId + ', which has ' + e.data.free + ' credits free. Your position #' + opt.memberId + ' has ' + opt.free + ' free. Pay for this top-up from #' + opt.memberId + '? From now on this ad spends from #' + opt.memberId + '.', { title: 'Pay from another position?', ok: 'Pay from #' + opt.memberId, cancel: 'Cancel' }); - if (!yes) return; - try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n), switchTo: opt.memberId })); await loadCampaigns(); loadDashboard(); } - catch (e2) { IAP.status(e2.message, 'bad'); } - } - })); - } catch (e) {} - } - let lastRates = null; - function soloHint() { - if (!lastRates || $('cType').value !== 'solo') return; - const cost = lastRates.soloCostPerRecipient || 5; - const n = Math.floor((Number($('cBudget').value) || 0) / cost); - $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery' - + (n ? ' — this budget reaches ' + n + ' members' : '') - + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.'; - } - $('cBudget').addEventListener('input', soloHint); - // rich solo editor: small toolbar over contenteditable (CSP allows no external editor); - // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort - document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn => - btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); })); - document.querySelectorAll('.ed-bar [data-block]').forEach(btn => - btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); })); - $('edLinkBtn').addEventListener('click', async () => { - const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection - const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); - if (!url) return; - $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } - document.execCommand('createLink', false, url); - }); - // inline media: upload, then drop the element at the cursor (BV-style) - let mediaMode = 'image'; - function insertHtmlAtCursor(html) { - const ed = $('cSoloEd'); - ed.focus(); - if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html); - } - $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); }); - $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); }); - $('cSoloFile').addEventListener('change', async () => { - const f = $('cSoloFile').files[0]; - if (!f) return; - $('edMediaInfo').textContent = 'Uploading ' + f.name + '…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; } - insertHtmlAtCursor(r.type === 'video' - ? '


' - : '


'); - $('edMediaInfo').textContent = f.name + ' inserted'; - } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; } - $('cSoloFile').value = ''; - }); - // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back - $('edRawBtn').addEventListener('click', () => { - const ed = $('cSoloEd'), raw = $('cSoloRaw'); - if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; } - else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; } - }); - const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.', - text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.', - login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. Login ads spend purchased credits only.', - solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.', - video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.', - featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.', - visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' }; - const whereHint = () => { const el = $('cWhere'); if (el) el.textContent = WHERE[$('cType').value] || ''; }; - whereHint(); - // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately - function applyType() { // hoisted: loadCampaigns may run before this line is reached - whereHint(); - const t = $('cType').value; - $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL - if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner'; - $('cSizeRow').hidden = t !== 'banner'; - $('cTitleRow').hidden = t !== 'text' && t !== 'solo'; - $('cBodyRow').hidden = t !== 'text'; - $('cSoloRow').hidden = t !== 'solo'; - $('cSoloHint').hidden = t !== 'solo'; - $('cVideoRow').hidden = t !== 'video'; - $('cFeaturedRow').hidden = t !== 'featured'; - $('cVisitsRow').hidden = t !== 'visits'; - if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)'; - $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; } - // fixed-cost types derive their spend (featured = day slots, visits = flat pack), - // so hide the free-form Budget field for them to avoid confusion - $('cBudgetRow').hidden = (t === 'featured' || t === 'visits'); - if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text'); - // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected - if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10; - if (t === 'visits') visitHint(); - $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)'; - soloHint(); - if (t === 'video') videoHint(); - if (t === 'featured') featHint(); - } - $('cType').addEventListener('change', applyType); - let featStartDay = 0; // selected start-day offset (0 = today) - async function featHint() { - if (!lastRates || !lastRates.featuredDurations) return; - if ($('cFeatDays') && !$('cFeatDays').options.length) - $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys => - '').join(''); - let s = null; - try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {} - if (s && s.occupancy) { - const grid = $('cFeatDaysGrid'); - grid.innerHTML = s.occupancy.map(d => { - const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' }); - const full = d.open <= 0; - return '
' - + '
' + label + '
' + d.count + '/' + d.cap + (full ? ' full' : ' left ' + d.open) + '
'; - }).join(''); - grid.querySelectorAll('.feat-day:not(.full)').forEach(el => - el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); })); - } - const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]); - const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days'; - $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel - + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.'; - } - document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); }); - // where a visits pack runs (Spooky Doors, 2026-10-02): everywhere, behind the doors, or a Golden Door, each with its own price - // function declarations (hoisted): loadCampaigns can run before this point is reached - function visitPlace() { const x = document.querySelector('input[name="cVisitPlace"]:checked'); return x ? x.value : 'all'; } - function placeCost(pl, rr) { rr = rr || lastRates || {}; return pl === 'golden' ? (rr.goldenDoorCost || 6) : pl === 'doors' ? (rr.doorPackCost || 4) : (rr.visitCostPerVisit || 3); } - function sdSeasonOpen(rr) { return new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) < String((rr && rr.sdSeasonEnd) || '2026-11-01'); } - function sdLastDay(rr) { const t = new Date(String((rr && rr.sdSeasonEnd) || '2026-11-01') + 'T12:00:00Z'); t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); } - function visitHint() { - if (!lastRates) return; - const open = sdSeasonOpen(lastRates); - document.querySelectorAll('#cVisitPlaceRow .sd-place').forEach(el => { el.hidden = !open; }); - if (!open && visitPlace() !== 'all') { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; } - document.querySelectorAll('[data-vpcost]').forEach(el => { const p = el.dataset.vpcost; el.textContent = '(' + placeCost(p) + ' credits a ' + (p === 'all' ? 'visit' : 'door') + ')'; }); - const pl = visitPlace(), per = placeCost(pl), min = lastRates.visitMinPack || 20; - const n = Number($('cVisitCount').value) || 0; - const unit = pl === 'golden' ? 'Golden Door' : pl === 'doors' ? 'door' : 'verified visit'; - $('cVisitCount').placeholder = pl === 'all' ? 'How many verified visits?' : pl === 'golden' ? 'How many Golden Doors?' : 'How many doors?'; - $('cVisitHint').textContent = per + ' credits per ' + unit - + (n >= min ? ': ' + n + ' = ' + (n * per).toLocaleString() + ' credits, paid up front' : ' (min ' + min + ')') - + (pl === 'all' ? '. Each is a unique member, dwell + human-check verified.' - : '. Each door is a dwell + human-check verified visit by a Spooky Doors player, at most once a day per player' - + (pl === 'golden' ? '; Golden Doors open before every other door and give the player bonus candy' : '; door packs open before ordinary visits') - + '. They run only in Spooky Doors until the season ends on ' + sdLastDay(lastRates) + ', then any doors left run as normal visits.'); - } - $('cVisitCount').addEventListener('input', visitHint); - document.querySelectorAll('input[name="cVisitPlace"]').forEach(x => x.addEventListener('change', visitHint)); - // video composer: tier dropdown + upload + price hint - function videoHint() { - if (!lastRates || !lastRates.videoTiers) return; - if ($('cWatchSecs') && !$('cWatchSecs').options.length) - $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t => - '').join(''); - const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0]; - const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0; - $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view' - + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : ''; - } - document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); }); - $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); }); - $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click()); - $('cVideoUrl').addEventListener('change', async () => { - const url = $('cVideoUrl').value.trim(); - $('cVideoInfo').textContent = url ? 'checking video…' : ''; - cVidDims = url ? await probeVideoDims(url) : null; - if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video'; - else { $('cVideoInfo').textContent = ''; showVidOrient(); } - }); - $('cVideoFile').addEventListener('change', async () => { - const f = $('cVideoFile').files[0]; - if (!f) return; - $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; } - $('cVideoUrl').value = r.url; - $('cVideoInfo').textContent = f.name + ' uploaded'; - $('cVideoPrev').hidden = false; - $('cVideoPrev').innerHTML = ''; - cVidDims = await probeVideoDims(r.url); showVidOrient(); - } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; } - $('cVideoFile').value = ''; - }); - $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => { - // in raw mode the source of truth is the textarea; sync it back first - let soloBody = $('cSoloEd').innerHTML; - if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value; - const t = $('cType').value; - const isVideo = t === 'video', isFeat = t === 'featured'; - if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value); - await api('/api/my/campaigns', { type: t, name: $('cName').value, - targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value, - title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value, - body: t === 'solo' ? soloBody : $('cBody').value, - videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value), - videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null, - days: Number($('cFeatDays').value), startDay: featStartDay, - count: Number($('cVisitCount').value), placement: t === 'visits' ? visitPlace() : undefined, - dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0, - geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','), - startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0, - endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0, - ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value, - budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) }); - const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null; - IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok'); - // clear EVERY field so no target/creative carries into the next campaign - ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel', - 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt'] - .forEach(id => { if ($(id)) $(id).value = ''; }); - document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; }); - { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; if (t === 'visits') visitHint(); } - $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = ''; - $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = ''; - if ($('edMediaInfo')) $('edMediaInfo').textContent = ''; - cVidDims = null; - await loadCampaigns(); - })); - // defers the busy() lookup to click time (busy is declared below) - function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); } - - // ── verified visits: open a member's site (new tab), dwell, human-check, earn ── - const visState = { token: null, id: null, dwell: 8 }; - async function loadVisitStatus() { - try { - const st = await (await fetch('/api/my/visits')).json(); - if (st.error) return; - $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits'; - $('vsStartBtn').hidden = st.status.count >= st.status.cap; - if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.'; - } catch (e) {} - } - async function loadVisit() { - $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = ''; - let r = null; - try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {} - if (!r || !r.ad) { - $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap - ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + ''; - return; - } - visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8; - $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + '
Open the site and stay ' + visState.dwell + 's.'; - const visit = $('vsVisit'); - visit.href = r.ad.url; visit.hidden = false; - $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true; - // opening the site starts the dwell; then we ask the human-check - visit.onclick = () => { - let left = visState.dwell; - $('vsHint').textContent = 'Counting your visit: ' + left + 's'; - const t = setInterval(async () => { - left--; - if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; } - clearInterval(t); - $('vsHint').textContent = 'One quick check to count the visit:'; - let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); - if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); } - if (c.error) { $('vsHint').textContent = c.error; return; } - renderVisitCheck(c); - }, 1000); - }; - $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false; - } - function renderVisitCheck(c) { - $('vsPrompt').textContent = 'Click the ' + c.prompt + ':'; - const w = $('vsOpts'); w.innerHTML = ''; - c.options.forEach((em, i) => { - const b = document.createElement('button'); - b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em; - b.addEventListener('click', () => answerVisit(i)); - w.appendChild(b); - }); - $('vsCheck').hidden = false; - } - async function answerVisit(i) { - const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json(); - if (r.error) { - if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); } - $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return; - } - $('vsCheck').hidden = true; - $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.'; - $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits'; - IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok'); - loadDashboard(); - } - $('vsStartBtn').addEventListener('click', () => loadVisit()); - - // ── watch-to-earn videos: escape-proof player, server-clock reward ── - const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false }; - // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos - let cVidDims = null; - function probeVideoDims(url) { - return new Promise(resolve => { - if (!url) return resolve(null); - const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; - let done = false; const fin = r => { if (!done) { done = true; resolve(r); } }; - v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); - v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url; - }); - } - function showVidOrient() { - const el = $('cVideoInfo'); if (!el) return; - if (!cVidDims) return; - const portrait = cVidDims.h > cVidDims.w; - el.textContent = (el.textContent ? el.textContent + ' · ' : '') - + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab'); - } - async function loadVideoStatus() { - try { - const st = await (await fetch('/api/my/videos?orientation=landscape')).json(); - if (st.error) return; - $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched'; - if (st.status.left <= 0) { - $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.'; - $('vidStartBtn').hidden = true; - return; - } - $('vidStartBtn').hidden = false; - } catch (e) {} - } - // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13) - function stopVideo() { - const p = $('vidPlayer'); if (!p) return; - const was = !!vidState.token && !vidState.done; - try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {} - vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0; vidState.needsTap = false; - if ($('vidWrap')) $('vidWrap').hidden = true; - if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; } - if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; } - } - document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); }); - async function loadVideoAd() { - let r = null; - try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {} - if (!r || !r.ad) { - // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13) - const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched); - // the tab can run dry while Shorts still has clips, and both count toward the same - // daily total, so say so instead of sending them away (Marty, 2026-09-22) - const toShorts = !capHit && r && r.otherFormat === 'shorts'; - $('vidBox').innerHTML = toShorts - ? '
✓That is every video on this tab' - + 'You have watched all ' + r.status.count + ' of today’s landscape videos. The rest are upright clips that play in Shorts, and they count toward the same daily ' + r.status.cap + '. You have ' + r.status.left + ' left.' - + 'Open Shorts
' - : (capHit || allWatched) - ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
' - : 'No member videos are live right now. Check back when a campaign is running.'; - if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched || toShorts; - $('vidBox').hidden = false; - $('vidWrap').hidden = true; - return; - } - const ad = r.ad; - vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false; - $('vidBox').hidden = true; - $('vidWrap').hidden = false; - $('vidCta').hidden = true; - $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : ''; - const p = $('vidPlayer'); - p.src = ad.videoUrl; - p.currentTime = 0; - // escape-proof: no seeking past what's been watched; track max reached - p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; }; - p.ontimeupdate = () => { - if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime; - const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen)); - $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…'; - if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); } - }; - $('vidStartBtn').textContent = 'Playing…'; - $('vidStartBtn').disabled = true; - vidState.needsTap = false; - // a browser that refuses to autoplay leaves the clip loaded and paused; the button then has to - // START it. Wired to loadVideoAd it threw the clip away and fetched another, so on a phone the - // video could never be played at all (Marty, 2026-09-22) - try { await p.play(); } catch (e) { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; } - $('vidCta').href = ad.ctaUrl; - $('vidCta').textContent = ad.ctaLabel || 'Learn more'; - $('vidCta').hidden = false; - } - async function completeVideo(ad) { - if (vidState.credited) return; - vidState.credited = true; - try { - const r = await (await fetch('/api/my/videowatch', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json(); - if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); } - else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); } - else $('vidHint').textContent = 'That video just ran out of budget — load another.'; - if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched'; - } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); } - $('vidStartBtn').disabled = false; - $('vidStartBtn').textContent = 'Next video'; - } - $('vidStartBtn').addEventListener('click', () => { - const p = $('vidPlayer'); - if (vidState.needsTap && p && p.src && !vidState.done) { // a clip is loaded and waiting on a tap: start it, never replace it - vidState.needsTap = false; - $('vidStartBtn').textContent = 'Playing…'; $('vidStartBtn').disabled = true; - p.play().catch(() => { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; }); - return; - } - loadVideoAd(); - }); - // presence enforcement: pause the watch-to-earn video when the tab/window loses focus, - // resume when it comes back — the viewer must stay on the page for the watch to complete - document.addEventListener('visibilitychange', () => { - const p = $('vidPlayer'); if (!p || !p.src) return; - if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {}); - }); - window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); }); - window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); }); - - // ── unmissable sponsor-message modal on sign-in ── - // Only a message a PERSON wrote reaches here; system notices (payouts, purchase - // confirmations) are kind 'notice' and go straight to the inbox. - // - // loadDashboard() runs on far more than sign-in — it refreshes after every ad view, every - // campaign edit, every chat close. So the modal is shown at most once per page load and - // never twice for the same message, otherwise a member earning credits gets interrupted - // after every single view. - const msgModalShown = new Set(); - function showSponsorModal(msg) { - if (!$('msgModal') || !msg || msgModalShown.has(msg.id)) return; - if (!$('msgModal').hidden) return; // one already open - msgModalShown.add(msg.id); - // An alert is generated by the system, so crediting it to a person ("A message from - // @martbost") is both wrong and misleading about what the member is looking at. - $('mmFrom').textContent = msg.kind === 'alert' - ? 'Action needed on your account' - : 'A message from ' + (msg.fromName || 'your sponsor'); - $('mmSubject').textContent = msg.subject || ''; - $('mmBody').innerHTML = msg.body || ''; // server-sanitized - $('msgModal').hidden = false; - $('mmAck').onclick = async () => { - $('msgModal').hidden = true; - try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {} - setInboxBadge(Math.max(0, (Number($('inboxBadge') && $('inboxBadge').textContent) || 1) - 1)); - }; - } - - // ── coaching: every direct's rung, stalled flag, one-click nudge ── - // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ── - async function pif(email, name, address) { - // Marty, 2026-09-27: the member must see the risk before every PIF. The platform holds no funds; this is a - // wallet-to-wallet gift in good faith, and nothing the site does can recover it. - const ok = await IAP.confirmBox('You are about to send POL from your own wallet directly to ' + name + '\'s wallet, in good faith, so they can buy their first package.\n\nInstantAdPay never holds or moves these funds and cannot reverse or recover them. Nothing obliges ' + name + ' to make a purchase. Only send what you are willing to give.', { title: 'Before you pay it forward', ok: 'I understand, continue', cancel: 'Cancel' }); - if (!ok) return; - let suggest = 25; - try { const { products } = await (await fetch('/api/catalog')).json(); const p20 = (products || []).find(p => p.priceCents === 2000); if (p20 && p20.costWei) suggest = Math.ceil(Number(p20.costWei) / 1e18) + 3; } catch (e) {} - const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $20 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' }); - if (amt === null) return; - const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; } - try { - IAP.status('Confirm the transfer in your wallet…', 'ok'); - const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString(); - const hash = await IAPWallet.sendPol(address, wei); - await api('/api/my/gift', { email, tx: hash, pol }); - IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok'); - playSound && playSound('chaching'); - } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); } - } - // ── holding tank: waiting members, adopt, my open adoptions ── - const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; }; - async function loadTank() { - const el = $('tankList'); if (!el) return; - try { - const r = await (await fetch('/api/my/tank')).json(); - if (r.error) { el.innerHTML = ''; return; } - $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays; - $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now'; - const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason); - $('tankMine').innerHTML = r.mine.length ? '

Your open adoptions

' + r.mine.map(m => '
' + esc(m.name) + '' - + '' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '' - + '' + Math.max(0, Math.ceil((m.expires - Date.now()) / 86400000)) + ' days left' - + '' - + (m.address && !m.bought ? ' ' : '') + '
').join('') : ''; - $('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname))); - $('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); - if (!r.waiting.length) { el.innerHTML = '

The tank is empty. Anyone who joins from the public site without a sponsor lands here.

'; return; } - renderTank(el, r); - } catch (e) {} - } - function renderTank(el, r) { - const rows = listApply('tank', r.waiting); - el.innerHTML = ''; - el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on - el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '
' + esc(w.name) + '' - + 'joined ' + ago(w.joined) + '' + memberChips(w) + '' - + 'last sign-in: ' + ago(w.lastSeen) + '' - + (r.eligible ? '' : '') + '
').join('') - : '

Nobody in the tank matches those filters.

'); - pageList('tank', el, ':scope > .lin-row', { per: LINE_PER }); - el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => { - const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the InstantAdPay holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' }); - if (note === null) return; - try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } - // The announcement cards at the top of the Overview are repeated on a timer, so a member who has read - // one can put it away: dismissed for 24 hours on this browser (Marty, 2026-10-03; it used to come back - // at every sign-in and the cards stacked up), then it shows again so it is never gone for good. - const CARD_SNOOZE_MS = 24 * 3600 * 1000; - function cardHidden(key) { try { const t = Number(localStorage.getItem('iap-hide-' + key)); return t > 0 && Date.now() - t < CARD_SNOOZE_MS; } catch (e) { return false; } } - function cardDismiss(card, key) { - if (!card || card.querySelector('.card-x')) return; - const x = document.createElement('button'); - x.type = 'button'; x.className = 'card-x'; x.innerHTML = '×'; - x.title = 'Hide this for 24 hours'; - x.setAttribute('aria-label', 'Hide this message for 24 hours'); - x.addEventListener('click', () => { try { localStorage.setItem('iap-hide-' + key, String(Date.now())); } catch (e) {} card.hidden = true; }); - (card.querySelector('.card-head') || card).appendChild(x); - } - // Five Dollar Friday card on the Overview: the live wave on Fridays, the date the rest of the week - async function loadFridayCard() { - const card = $('fdfCard'); if (!card) return; - if (cardHidden('fdf')) { card.hidden = true; return; } - try { - const f = await (await fetch('/api/friday')).json(); if (!f.on) { card.hidden = true; return; } - card.hidden = false; - if (f.live && f.today) card.innerHTML = '

\u{1F4B5} It\u2019s Five Dollar Friday

+' + f.pct + '% credits on any pack today
' - + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Every $5+ package bought before midnight Central earns +' + f.pct + '% bonus credits the moment it settles. Your pack pays your sponsor line instantly; your line\u2019s packs pay you.

' - + ' Watch the wave'; - else card.innerHTML = '

\u{1F4B5} Five Dollar Friday

every Friday
' - + '

Every Friday (Central time), any ad package from $5 up earns +' + f.pct + '% bonus credits, added the moment it settles. The whole network buys on the same day, so every line gets paid at once. Next one: ' + (f.nextLabel || 'soon') + '.

' - + ''; - const b = $('fdfBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); - cardDismiss(card, 'fdf'); - } catch (e) {} - } - loadFridayCard(); setInterval(loadFridayCard, 120000); - // Wired Wednesday card on the Overview: the live wave on Wednesdays, the date the rest of the week - async function loadWednesdayCard() { - const card = $('wwCard'); if (!card) return; - if (cardHidden('ww')) { card.hidden = true; return; } - try { - const f = await (await fetch('/api/wednesday')).json(); if (!f.on) { card.hidden = true; return; } - card.hidden = false; - if (f.live && f.today) card.innerHTML = '

⚡ It’s Wired Wednesday

+' + f.pct + '% credits on any $' + f.minUsd + '+ pack today
' - + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + Number(f.today.bonusCredits || 0).toLocaleString() + ' bonus credits wired in, ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Buy any $' + f.minUsd + '+ package before midnight Central and +' + f.pct + '% is wired into your balance the moment it settles, good for any format.

' - + ' How it works'; - else card.innerHTML = '

⚡ Wired Wednesday

every Wednesday
' - + '

Every Wednesday (Central time), any ad package from $' + f.minUsd + ' up earns +' + f.pct + '% bonus credits, wired into your balance the second it settles, purchased-grade so they run on any format, login ads included. Next one: ' + (f.nextLabel || 'soon') + '.

' - + ''; - const b = $('wwBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); - cardDismiss(card, 'ww'); - } catch (e) {} - } - loadWednesdayCard(); setInterval(loadWednesdayCard, 120000); - - // ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ---- - const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }); - const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, ''); - // Pass tiers (2026-10-18, Marty approved the safe form): weekly Game Pass, monthly Explorer and Champion side by side. Paid tiers add - // islands and looks in Shards of Valor, never power and never more POL; the main story is free. End dates in Central time. - const gpCT = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)'; - const GP_TIER_PERKS = { - weekly: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and the Weekly look'], - explorer: ['Everything in the Game Pass, in every game', 'Shards of Valor: up to 4 bonus islands you pick (1 swap a month)', 'Explorer outfits and gear styles for your character'], - champion: ['Everything in Explorer', 'Shards of Valor: every bonus island, now and future', 'Champion outfits and gear styles for your character'], - }; - function renderPassTiers(card, gp, highlight) { - const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier); - const state = top ? '' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '' - : 'No pass active'; - const caps = gp.caps || {}; - const capsLine = caps.enforced ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' : ''; - const box = r => { - const btn = r.waiting ? '' - : r.open ? '' - : 'Not on sale right now. Your pass keeps running.'; - return '

' + esc(r.name) + '

' - + '

$' + r.usd + ' for ' + r.days + ' days

' - + '
    ' + (GP_TIER_PERKS[r.tier] || []).map(x => '
  • ' + esc(x) + '
  • ').join('') + '
' - + '

' + (r.active ? 'Active until ' + esc(gpCT(r.until)) + '' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '

' - + btn + '
'; - }; - card.hidden = false; card.classList.toggle('gp-hl', !!highlight); - card.innerHTML = '

\u{1F39F}️ Game Passes

weekly or monthly · every game
' - + (gp.tierPreview ? '

Admin preview. Explorer and Champion are hidden from members until sovTiers is switched on in Settings.

' : '') - + '

' + state + '

' - + '

Free play pays real POL every day, and the main story of Shards of Valor is free for everyone. Every pass gives the same higher POL caps in every game. The monthly passes add islands to explore and looks in Shards of Valor. Paid passes never make you stronger than players who earn their gear, and they never pay more POL.

' - + '
' + rows.map(box).join('') + '
' - + (capsLine ? '

' + capsLine + '

' : '') - + '

Paid with purchased credits from your packages (earned credits never buy a pass). Passes run side by side: a higher pass shows first, and the one underneath keeps its own end date. No auto-renew: buy again any time and that pass extends from its end date. When a pass ends, nothing you earned in a game is taken away.

'; - card.querySelectorAll('[data-gp-tier]').forEach(b => b.addEventListener('click', async () => { - const r = rows.find(x => x.tier === b.dataset.gpTier); if (!r) return; - const yes = await IAP.confirmBox((r.active ? 'Extend your ' + r.name + ' by ' + r.days + ' days' : 'Get ' + r.name + ' for ' + r.days + ' days') + ' for ' + r.price + ' purchased credits ($' + r.usd + ')? It starts at once. Islands and looks only: no extra power, no extra POL.', { title: r.name, ok: r.active ? 'Extend' : 'Get ' + r.name, cancel: 'Not now' }); - if (!yes) return; - b.disabled = true; - try { - const x = await api('/api/my/gamepass/buy', { tier: r.tier }); - if (x.needPay) { IAP.status(x.message || 'Buy a package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; } - IAP.status(r.name + ' active until ' + gpCT(x.until) + '. Have fun out there.', 'ok'); - await loadGamePassCard(true); - } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - })); - card.querySelectorAll('[data-gp-go]').forEach(b => b.addEventListener('click', () => setPane('buy'))); - if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } - } - // What the Pass adds in each game (Marty, 2026-10-22: members must see what they are buying). Keep in step with the games' perks. - const GP_PERKS = [ - ['PolHunter', '5 missions a day instead of 3, plus 2 Ad Detective cases a day'], - ['Gem Kingdom', 'one free continue every day'], - ['Spooky Doors', 'one extra door every day'], - ['ClutterHunt', '2 bonus hints every day'], - ['SpellWheel', 'daily streak pays 0.30 POL instead of 0.15, plus 1 free hint a day'], - ['PolyBreak', 'daily gem limit 1.5 POL instead of 0.5, plus an extra paddle every round'], - ['PolyWarriors', 'a 4th daily mission, and defense pays 25 Circuits instead of 15'], - ['Drip Runner', 'a free shield at the start of every run'], - ['Road Agent', '2 patrols a day and 25% more scrap'] - ]; - function gpPerksHtml() { - return '

What you get

' - + '' - + '' - + '
Every gameDaily POL caps of 1.50 a day on repeatable rewards (free play 0.30) and 5 a day in all (free play 2), counted across all nine games
WeeklyA seat in the Pass Tournament, POL prizes from 5% of pass sales, paid Mondays
BadgeThe gold Game Pass badge with your name, to share or post
' - + '

In each game

' - + GP_PERKS.map(p => '').join('') + '
' + p[0] + '' + p[1] + '
' - + '

The Pass never changes how much a reward pays: it lets you play and collect more each day.

'; - } - async function loadGamePassCard(highlight) { - const card = $('gpCard'); if (!card) return; - let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} - if (!gp || !(gp.enabled || gp.show)) { card.hidden = true; return; } - if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight); // Explorer / Champion on sale (or admin preview, or a holder) - const caps = gp.caps || {}; const price = gp.price || 500; - const state = gp.active ? 'Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '' - : gp.waiting ? 'Waiting for a $' + (gp.usd || 5) + ' package' : 'Not active'; - const capsLine = caps.enforced - ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' - : gp.capsStart ? 'Account-wide caps start on ' + esc(gpDate(Date.parse(gp.capsStart + 'T17:00:00Z'))) + ': free play ' + gpPol(caps.daily) + ' POL a day on repeatable rewards, 2 POL a day in all; with the Pass 1.50 and 5.' - : 'Account-wide caps are not switched on yet; the games\u2019 own caps stand for now.'; - card.hidden = false; card.classList.toggle('gp-hl', !!highlight); - card.innerHTML = '

\u{1F39F}\uFE0F Game Pass

$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 all nine games
' - + '

' + state + '

' - + '

Free play pays real POL every day. The Pass plays more: higher daily POL caps across every game (1.50 a day on repeatable rewards instead of 0.30, 5 a day in all instead of 2), a seat in the weekly Pass Tournament with POL prizes from ' + (gp.tournament && gp.tournament.pct || 5) + '% of pass sales, extra plays and perks in each game, and the Pass badge. One pass covers your whole account, linked positions included.

' - + gpPerksHtml() - + '

' + capsLine + '

' - + (gp.waiting ? '

Your pass is waiting: buy a $' + (gp.usd || 5) + ' package and it starts the moment the purchase settles. You keep every credit of the package for your ads.

' : '') - + '

' - + (gp.waiting ? '' : '') - + 'Paid with purchased credits from your packages (earned credits never buy a pass). Short? A $' + (gp.usd || 5) + ' package starts it the moment it settles.

'; - const b = $('gpBuy'); if (b) b.addEventListener('click', async () => { - const yes = await IAP.confirmBox((gp.active ? 'Extend your Game Pass by ' + (gp.days || 7) + ' days' : 'Get the Game Pass for ' + (gp.days || 7) + ' days') + ' for ' + price + ' purchased credits? Higher daily caps across all nine games, the weekly Pass Tournament and the Pass perks start at once.', { title: 'Game Pass', ok: gp.active ? 'Extend the Pass' : 'Get the Pass', cancel: 'Not now' }); - if (!yes) return; - b.disabled = true; - try { - const r = await api('/api/my/gamepass/buy'); - if (r.needPay) { IAP.status(r.message || 'Buy a $5 package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; } - IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok'); - await loadGamePassCard(true); - } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - }); - const g = $('gpGoBuy'); if (g) g.addEventListener('click', () => setPane('buy')); - if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } - } - // Overview nudge: a game reported this member hit the free cap (polgrant lastCapHit). Shown once a day per browser, never to pass holders. - async function loadGpNudge() { - const card = $('gpNudge'); if (!card) return; - if (cardHidden('gpnudge')) { card.hidden = true; return; } - let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} - if (!gp || !gp.enabled || gp.active || !gp.lastCapHit || gp.lastCapHit.pass) { card.hidden = true; return; } - const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' }; - card.hidden = false; - card.innerHTML = '

\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '

free play keeps paying; the Pass plays more
' - + '

Every member earns real POL in the games up to the daily cap. The Game Pass raises the caps across all nine games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with purchased credits), adds the weekly Pass Tournament and a perk in every game.

' - + ''; - $('gpNudgeGo').addEventListener('click', () => setPane('games?pass=1')); - try { localStorage.setItem('iap-hide-gpnudge', String(Date.now())); } catch (e) {} // once a day - cardDismiss(card, 'gpnudge'); - } - loadGpNudge(); - // launch-day surprise (Marty, 2026-09-20): PolHunter appears at siteConfig.launchAt, not a minute before. - // The card and the menu entry flip on their own if the dashboard is already open. - let phShown = false; - const LAUNCH_CARD_DAYS = 7; - async function launchReveal() { - try { - const nav = $('polhunterNav'); if (nav) nav.hidden = false; // listed in the menu from launch morning (Marty, 2026-09-21); the card below is the announcement and waits for launchAt - const cfg = await IAP.getConfig(); const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; - if (!at || Date.now() < at) return; - // launch cards retire 7 days after launch (Marty, 2026-10-03: old announcements kept stacking up) - if (Date.now() > at + LAUNCH_CARD_DAYS * 86400000) { const c = $('phLaunch'); if (c) c.hidden = true; return; } - const card = $('phLaunch'); if (!card || phShown) return; - if (cardHidden('phLaunch')) { card.hidden = true; return; } - phShown = true; card.hidden = false; - card.innerHTML = '

\u{1F3AF} New today: PolHunter

Launch-day surprise
' - + '

Missions across our sites. Visit the site, find your personal code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in the wallet on this account, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly POL prizes, and badge cards you can share. Your PolHunter share link puts sign-ups on your InstantAdPay line.

' - + 'Open my PolHunter board The teaser'; - const tb = $('phTrain'); if (tb) tb.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="training"]'); if (m) m.click(); }); - cardDismiss(card, 'phLaunch'); - } catch (e) {} - } - launchReveal(); setInterval(launchReveal, 30000); - // came from PolHunter (iap.return cookie): one card at the top of the Overview that sends them back - // Games hub (2026-10-01): one card per game, the player's own progress where the game reports it - // PassiveDrip, our earning site: a card on the Earn tab (not a game, Marty 2026-10-01) - async function loadPdCard() { - const card = $('pdCard'); if (!card) return; - let j = null; try { j = await (await fetch('/api/my/passivedrip/card')).json(); } catch (e) {} - if (!j || !j.show) { card.hidden = true; return; } - card.hidden = false; $('pdPre').hidden = !j.preview; $('pdLine').textContent = j.line || ''; - } - async function loadGames(q) { - const el = $('gamesGrid'); if (!el) return; - loadGamePassCard(/(^|&)pass=1(&|$)/.test(q || '')).catch(() => {}); - let g = null; try { g = await (await fetch('/api/my/games')).json(); } catch (e) {} - const list = (g && g.games) || []; - if (!list.length) { el.innerHTML = '

No games are open yet. Check back soon.

'; return; } - // a seasonal card (x.season, 2026-10-02) wears the pink limited-time ribbon from the Spooky Doors UI kit - el.innerHTML = list.map(x => '
' + (x.soon ? '' : x.season && x.season.ends ? 'Limited time \u00b7 ends ' + esc(x.season.ends) + '' : '') + '
' + esc(x.tag || '') + '

' + esc(x.name) + (x.preview ? '' + esc(x.previewNote || 'preview, not live') + '' : '') + '

' + esc(x.blurb) + '

' + (x.progress && x.progress.line ? '
' + esc(x.progress.line) + '
' : '') + '

Pays: ' + esc(x.pays || 'POL') + '

' + (x.perk ? '

Members get ' + esc(x.perk) + '

' : '') + (x.soon ? '' + esc(x.soon) + '' : '' + esc(x.cta || 'Play') + '') + '
').join(''); - } - async function loadReturnCard() { - const card = $('phReturn'); if (!card) return; - if (cardHidden('phReturn')) { card.hidden = true; return; } - try { - const me = await (await fetch('/api/me')).json(); - if (me.returnTo !== 'polhunter') { card.hidden = true; return; } - card.hidden = false; - card.innerHTML = '

You came from PolHunter

' + (me.address - ? '

Your wallet is linked, so your board is ready.

Back to PolHunter' - : '

One step left: link the wallet your POL drips will be paid to. The moment it is linked you go straight back.

'); - const b = $('phGoWallet'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="wallet"]'); if (m) m.click(); }); - cardDismiss(card, 'phReturn'); - } catch (e) {} - } - async function loadCoach() { - loadReturnCard(); - loadTank(); - try { - const r = await (await fetch('/api/my/coach')).json(); - const el = $('coachList'); if (!el || r.error) return; - const d = r.directs || []; - $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : ''; - if (!d.length) { el.innerHTML = '

No directs yet. When someone joins through your link they show up here with their next step.

'; return; } - el.innerHTML = d.map(x => '
' + esc(x.name) + (x.stalled ? ' quiet ' + x.quietDays + 'd' : '') - + (x.polWaiting ? ' ' + x.polWaiting.toFixed(2) + ' POL waiting · no wallet' : '') - + (x.rescue && x.rescue.unreached ? ' unreached · tank in ' + x.rescue.rescueInDays + 'd' : '') + (x.bound === false ? ' not bound to you on-chain' : '') + '' - + '' + esc(x.label) + ' → ' + esc(x.next) + '' - + 'rung ' + x.rung + '/6' - + '' + (x.buyerCount ? x.buyerCount + ' buyer' + (x.buyerCount === 1 ? '' : 's') : '') + '' - + '' - + (x.address ? ' ' : '') - + (x.free && x.rescue ? ' ' : '') - + (x.free ? ' ' : '') + '
').join(''); - pageList('coach', el, ':scope > .lin-row', { per: LINE_PER }); - el.querySelectorAll('[data-contacted]').forEach(b => b.addEventListener('click', async () => { - try { await api('/api/my/tank/contacted', { email: b.dataset.contacted }); IAP.status('Marked: you have contacted ' + b.dataset.cname + '.', 'ok'); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); - el.querySelectorAll('[data-nudge]').forEach(b => b.addEventListener('click', async () => { - await openConvo(b.dataset.nudge, b.dataset.nname); - const inp = $('chatInput'); if (inp) { inp.value = b.dataset.say.replace(/\{\{name\}\}/g, b.dataset.nname.replace(/^@/, '')); inp.focus(); } - })); - el.querySelectorAll('[data-release]').forEach(b => b.addEventListener('click', async () => { - if (!(await IAP.confirmBox('Release ' + b.dataset.rname + ' to the holding tank? You stop being their sponsor and another member can adopt them.', { title: 'Release to the tank', ok: 'Release' }))) return; - try { await api('/api/my/tank/release', { email: b.dataset.release }); IAP.status(b.dataset.rname + ' is in the holding tank.', 'ok'); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - // schedule chips on the campaign table (local time) + by-hour view bars - const fmtWhen = ms => new Date(ms).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - // featured run column: days left of the booked total (Hugh, 2026-09-16: "says 14 but it's actually 7") - function featRun(c) { - const total = Number(c.body || 0), now = Date.now(); - if (c.status === 'done' || !c.expires || c.expires <= now) return '' + total + ' day' + (total === 1 ? '' : 's') + ' done'; - const left = Math.max(1, Math.ceil((c.expires - now) / 86400000)); - return '' + left + ' of ' + total + ' day' + (total === 1 ? '' : 's') + ' left'; - } - function schedChips(c) { - const now = Date.now(); let s = ''; - if (c.starts && c.starts > now) s += ' starts ' + fmtWhen(c.starts) + ''; - if (c.expires && c.type === 'featured') { const day = new Date(c.expires - 1).toLocaleDateString([], { month: 'short', day: 'numeric' }); s += ' ' + (c.expires > now ? 'runs through ' : 'ran through ') + day + ''; } - else if (c.expires) s += ' ' + (c.expires > now ? 'ends ' : 'ended ') + fmtWhen(c.expires) + ''; - return s; - } - function geoLine(rows) { - if (!rows || !rows.length) return ''; - return '
' + rows.map(r => esc(r.cc) + ' ' + r.n).join(' · ') + '
'; - } - function hourBars(utc) { - if (!utc || !utc.some(n => n)) return ''; - // rotate the 24 UTC buckets into the viewer's local hours - const local = new Array(24).fill(0); - for (let h = 0; h < 24; h++) local[new Date(Date.UTC(2000, 0, 1, h)).getHours()] += utc[h]; - const max = Math.max(...local); - const lab = h => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'); - return '
' + local.map((n, h) => - '').join('') - + '
views by hour · last 7 days · your time
'; - } - // ── link stats: views, joins, buyers per angle ── - async function loadLinkStats() { - try { - const r = await (await fetch('/api/my/linkstats')).json(); - const t = $('linkStatsTable'); if (!t || r.error) return; - const rows = (r.angles || []).filter(a => a.views || a.joins || a.buyers); - if (!rows.length) { t.innerHTML = 'No views yet. Share your link and the numbers start here.'; return; } - t.innerHTML = 'HookViews (30d)Views (all)JoinedQualifying buyers' - + rows.map(a => '' + esc(a.angle === 'plain' ? 'plain link' : a.angle === 'page' ? 'any page (viral link)' : '?v=' + a.angle) + '' + a.views30 + '' + a.views + '' + a.joins + '' + a.buyers + '').join(''); - const st = $('linkSrcTable'); - if (st) { - const src = (r.sources || []).filter(x => x.views || x.joins); - st.innerHTML = src.length ? 'SourceViews (30d)Views (all)JoinedQualifying buyers' - + src.map(x => '' + esc(x.source) + '' + x.views30 + '' + x.views + '' + x.joins + '' + x.buyers + '').join('') - : 'Sources appear as visits arrive.'; - pageList('linksrc', st.parentElement, 'table tr:has(td)', { per: LINE_PER }); - } - pageList('linkangles', t.parentElement, 'table tr:has(td)', { per: LINE_PER }); - } catch (e) {} - } - // ── prospects: the member's own follow-up list ── - let PP_STATUSES = ['new', 'contacted', 'interested', 'joined', 'bought', 'not now']; - // ── Pipeline: the follow-up board (Marty, 2026-09-15). Stages come from the server; cards never move by hand ── - let PIPE = null, PIPE_KEY = null; - const pipeAgo = ts => { const d = Math.floor((Date.now() - ts) / 86400000); return d <= 0 ? 'today' : d === 1 ? 'yesterday' : d < 30 ? d + 'd ago' : new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); }; - const pipeInvite = () => { const t = ($('inviteLine') && $('inviteLine').textContent) || ''; return /^https?:\/\//.test(t) ? t : ''; }; - function pipeCardHtml(c, showStage) { - const today = new Date(); today.setHours(23, 59, 59, 999); - const due = c.followUp && c.followUp <= today.getTime(); - const chips = []; - if (c.stalled) chips.push('stalled ' + c.quietDays + 'd'); - if (due) chips.push('follow up'); - else if (c.followUp) chips.push('' + new Date(c.followUp).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ''); - if (c.tag) chips.push('' + esc(c.tag) + ''); - if (c.kind === 'member' && c.buyers) chips.push('' + c.buyers + ' buyer' + (c.buyers === 1 ? '' : 's') + ''); - const stage = showStage ? (PIPE.stages.find(s => s.key === c.stage) || {}).label || '' : ''; - return '
' - + '
' + esc(c.name) + '' + (c.kind === 'prospect' ? 'prospect' : (c.lastSeen ? 'seen ' + pipeAgo(c.lastSeen) : 'never signed in')) + '
' - + '
' + esc(stage ? stage + ' · ' + c.next : c.next) + '
' - + (c.note ? '
' + esc(c.note) + '
' : '') - + (chips.length ? '
' + chips.join('') + '
' : '') + '
'; - } - async function loadPipeline() { - try { - const r = await (await fetch('/api/my/pipeline')).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - if (!r.live) { - $('pipeSoon').hidden = false; $('pipeLive').hidden = true; - $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.'; - return; - } - PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false; - const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; } - $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length; - $('pipeDue').innerHTML = r.due.length ? '
' + r.due.map(c => pipeCardHtml(c, true)).join('') + '
' : '

Nothing due. Set a follow-up date on any card and it shows up here.

'; - $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.'; - $('pipeBoard').innerHTML = r.columns.map(col => '

' + esc(col.label) + '' + col.cards.length + '

' + esc(col.hint) + '

' + col.cards.map(c => pipeCardHtml(c, false)).join('') + '
').join(''); - $('pipeBoard').querySelectorAll('.pipe-col').forEach((col, i) => pageList('pipe-' + i, col, ':scope > [data-pk]')); - $('pipeLive').querySelectorAll('[data-pk]').forEach(el => { - el.addEventListener('click', () => openPipeCard(el.dataset.pk)); - el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPipeCard(el.dataset.pk); } }); - }); - if (PIPE_KEY) { const c = allPipeCards().find(x => x.key === PIPE_KEY); if (c) fillPipeCard(c); else { PIPE_KEY = null; $('pipeCard').hidden = true; } } - } catch (e) { IAP.status('Could not load your pipeline.', 'bad'); } - } - function allPipeCards() { return PIPE ? PIPE.columns.flatMap(c => c.cards) : []; } - function fillPipeCard(c) { - $('pipeCardName').textContent = c.name; - const stage = (PIPE.stages.find(s => s.key === c.stage) || {}).label || ''; - $('pipeCardMeta').textContent = stage + (c.kind === 'member' ? ' · joined ' + new Date(c.since).toLocaleDateString() + (c.lastSeen ? ' · last seen ' + pipeAgo(c.lastSeen) : ' · never signed in') + (c.bought ? ' · your qualifying buyer' : '') + (c.buyersPositions ? ' · ' + c.buyers + ' buyers: ' + c.buyersMain + ' on the main wallet, ' + c.buyersPositions + ' on linked positions' : '') : ' · prospect' + (c.contact ? ' · ' + c.contact : '')); - $('pipeCardNext').innerHTML = 'Next for them: ' + esc(c.next) + (c.stalled ? ' quiet ' + c.quietDays + ' days' : ''); - const say = (c.say || '').replace('{{link}}', pipeInvite()); - $('pipeSayBlock').hidden = !say; $('pipeSay').textContent = say; - $('pipeSend').hidden = c.kind !== 'member' || !c.email; - $('pipeFollow').value = c.followUp ? new Date(c.followUp).toISOString().slice(0, 10) : ''; - const sel = $('pipeTag'); sel.innerHTML = PIPE.tags.map(t => '').join(''); - $('pipeNote').value = c.note || ''; $('pipeSaved').textContent = ''; - $('pipeCard').hidden = false; - } - function openPipeCard(key) { - const c = allPipeCards().find(x => x.key === key); if (!c) return; - PIPE_KEY = key; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.toggle('on', el.dataset.pk === key)); - fillPipeCard(c); $('pipeCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); - } - if ($('pipeCardClose')) $('pipeCardClose').addEventListener('click', () => { PIPE_KEY = null; $('pipeCard').hidden = true; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.remove('on')); }); - if ($('pipeSave')) $('pipeSave').addEventListener('click', async () => { - if (!PIPE_KEY) return; - try { await api('/api/my/pipeline/note', { key: PIPE_KEY, note: $('pipeNote').value, followUp: $('pipeFollow').value || null, tag: $('pipeTag').value }); $('pipeSaved').textContent = 'Saved.'; loadPipeline(); } - catch (e) { IAP.status(e.message, 'bad'); } - }); - if ($('pipeCopy')) $('pipeCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('pipeSay').textContent); $('pipeCopy').textContent = 'Copied'; setTimeout(() => { $('pipeCopy').textContent = 'Copy message'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); } }); - if ($('pipeSend')) $('pipeSend').addEventListener('click', () => { - const c = allPipeCards().find(x => x.key === PIPE_KEY); if (!c || !c.email) return; - openConvo(c.email, c.name); - const ta = $('chatInput'); if (ta) { ta.value = $('pipeSay').textContent; ta.dispatchEvent(new Event('input')); ta.focus(); } - }); - async function loadProspects() { - try { - const r = await (await fetch('/api/my/prospects')).json(); - if (r.error) return; - PP_STATUSES = r.statuses || PP_STATUSES; - const sel = $('ppStatus'); if (sel && !sel.options.length) sel.innerHTML = PP_STATUSES.map(s => '').join(''); - const list = r.prospects || []; const el = $('prospectList'); if (!el) return; - if (!list.length) { el.innerHTML = '

Nobody on the list yet.

'; return; } - const today = new Date(); today.setHours(0, 0, 0, 0); - el.innerHTML = list.map(p => { const due = p.nextTs && p.nextTs <= today.getTime() + 86399999; return '
' + esc(p.name) + (due ? ' follow up' : '') + '' - + '' + esc(p.contact || '') + (p.note ? ' · ' + esc(p.note) : '') + '' - + '' - + '' - + '
'; }).join(''); - const save = async (id, patch) => { const p = list.find(x => x.id === Number(id)); if (!p) return; try { await api('/api/my/prospects', Object.assign({}, p, patch)); } catch (e) { IAP.status(e.message, 'bad'); } }; - pageList('prospects', el, ':scope > .lin-row', { per: LINE_PER }); - el.querySelectorAll('[data-pstatus]').forEach(s => s.addEventListener('change', () => save(s.dataset.pstatus, { status: s.value }))); - el.querySelectorAll('[data-pnext]').forEach(i => i.addEventListener('change', () => save(i.dataset.pnext, { next: i.value, nextTs: i.value ? Date.parse(i.value + 'T12:00:00') : null }))); - el.querySelectorAll('[data-pdel]').forEach(b => b.addEventListener('click', async () => { try { await api('/api/my/prospects/remove', { id: b.dataset.pdel }); loadProspects(); } catch (e) { IAP.status(e.message, 'bad'); } })); - } catch (e) {} - } - if ($('prospectForm')) $('prospectForm').addEventListener('submit', async e => { - e.preventDefault(); - try { - await api('/api/my/prospects', { name: $('ppName').value, contact: $('ppContact').value, status: $('ppStatus').value, nextTs: $('ppNext').value ? Date.parse($('ppNext').value + 'T12:00:00') : null }); - $('ppName').value = ''; $('ppContact').value = ''; $('ppNext').value = ''; loadProspects(); - } catch (err) { IAP.status(err.message, 'bad'); } - }); - // ── broadcast templates ── - const BC_TEMPLATES = [ - { label: 'Welcome', subject: 'Welcome to my line: your first three moves', html: '

Glad you are in. Three things today, in this order:

  1. Pick your username on the Profile tab (it becomes your link).
  2. Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
  3. Copy your invite link from My line and send it to one person.

Reply here if you get stuck on any of them. That is what I am here for.

' }, - { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '

Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.

The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.

' }, - { label: 'The $5 test', subject: 'See a payout land in real time', html: '

Want to see the whole thing work? Buy the $5 Micro package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.

When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.

' }, - { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '

You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $20 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.

Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.

' }, - { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '

Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.

Do not wait for the perfect moment. Nobody who waited ever built a line.

' } - ]; - (function () { - const w = $('bcTemplates'); if (!w) return; - w.innerHTML = BC_TEMPLATES.map((t, i) => '').join(''); - w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); })); - })(); - // ── Qualified Start calculator ── - (function () { - const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return; - const CR = { 20: 2000, 50: 5500, 100: 12000, 250: 32500, 500: 70000 }; - const calc = () => { - const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 20; - const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0); - const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.'; - out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + '
$' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share)
$' + net + ' net, plus a little POL for gas in each wallet
' - + '
' + credits.toLocaleString() + ' credits pooled for your own ads
' + level + '
The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
'; - }; - n.addEventListener('input', calc); pk.addEventListener('change', calc); calc(); - })(); - - // ── downline lineage + sponsor broadcast + upline messages ── - async function loadLineage() { - try { - const r = await (await fetch('/api/my/line')).json(); - const el = $('lineageWrap'); - if (r.error || !r.levels || !r.levels.every) return; - if (!r.levels.length || !r.levels.some(L => L.members.length)) { - el.innerHTML = '

No one in your downline yet. Share your link and it fills in here.

'; - return; - } - LINE_DATA = r; renderLineage(el); - } catch (e) {} - } - let LINE_DATA = null; - function renderLineage(el) { - const r = LINE_DATA; if (!r) return; - try { - const all = r.levels.reduce((n, L) => n + L.members.length, 0); - const shown = r.levels.map(L => ({ level: L.level, members: listApply('line', L.members) })); - const kept = shown.reduce((n, L) => n + L.members.length, 0); - el.innerHTML = ''; - el.appendChild(listBar('line', all, kept, () => renderLineage(el))); - el.insertAdjacentHTML('beforeend', !kept ? '

Nobody in your downline matches those filters.

' : shown.map(L => !L.members.length ? '' : - '
Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '
' - + L.members.map(m => '
' + esc(m.name) + (m.own ? ' yours' : '') + '' - + '' + (m.email ? esc(m.email) : (m.memberId ? '#' + m.memberId + '' : '')) + (m.sponsor ? 'sponsored by ' + esc(m.sponsor) + '' : '') + (m.own ? '' : '' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '' + memberChips(m) + '') + '' - + '' - + (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '' - + '' + new Date(m.joined).toLocaleDateString() + '' - + (m.email ? '' : '') - + (m.ref && !m.own ? '' : '') - + '
' + (m.ref && !m.own ? '' : '')).join('') - + '
').join('')); - el.querySelectorAll('[data-cemail]').forEach(b => - b.addEventListener('click', () => openConvo(b.dataset.cemail, b.dataset.cname))); - el.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => toggleLineActivity(b))); - const focusRef = LINE_FOCUS_REF ? LINE_FOCUS_REF.replace(/"/g, '') : null; - el.querySelectorAll('.lin-lvl').forEach((lv, i) => pageList('line-' + i, lv, ':scope > .lin-row', { per: LINE_PER, tail: '.lin-act', focus: focusRef ? row => !!row.querySelector('[data-act="' + focusRef + '"]') : null })); - if (LINE_FOCUS_REF) { - const ref = LINE_FOCUS_REF; LINE_FOCUS_REF = null; - const b = el.querySelector('[data-act="' + ref.replace(/"/g, '') + '"]'); - if (b) { const row = b.closest('.lin-row'); if (row) { row.classList.add('lin-focus'); setTimeout(() => row.classList.remove('lin-focus'), 4000); } toggleLineActivity(b); setTimeout(() => (row || b).scrollIntoView({ behavior: 'smooth', block: 'center' }), 150); } - } - } catch (e) {} - } - // who is working: per-member activity drop-down under the row (any of the three levels) - const lineActCache = {}; - async function toggleLineActivity(btn) { - const box = document.querySelector('[data-actbox="' + btn.dataset.act + '"]'); if (!box) return; - const open = box.hidden; box.hidden = !open; btn.setAttribute('aria-expanded', String(open)); btn.textContent = open ? 'Activity ▴' : 'Activity ▾'; - if (!open) return; - if (!lineActCache[btn.dataset.act]) { - box.innerHTML = 'Loading…'; - try { lineActCache[btn.dataset.act] = await (await fetch('/api/my/line/activity?ref=' + encodeURIComponent(btn.dataset.act))).json(); } catch (e) { lineActCache[btn.dataset.act] = { error: 'Could not load.' }; } - } - const a = lineActCache[btn.dataset.act]; - if (a.error) { box.innerHTML = '' + esc(a.error) + ''; return; } - const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; return Math.round(d / 86400e3) + 'd ago'; }; - const chip = (label, val, cls) => '' + esc(label) + '' + esc(val) + ''; - const working = (a.viewsToday || 0) > 0 || (a.campaignsActive || 0) > 0 || (a.linkViews30 || 0) > 0 || (a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3); - box.innerHTML = chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : '')) - + chip('Joined', new Date(a.joined).toLocaleDateString()) - + chip('Stage', (a.rung || 'Joined') + (a.next ? ' · next: ' + a.next : ''), a.stalled ? 'warn' : '') - + chip('Ads today', (a.viewsToday || 0) + '/' + (a.target || 5) + (a.claimedToday ? ' claimed' : '') + (a.streakDay ? ' · streak day ' + a.streakDay : ''), (a.viewsToday || 0) > 0 ? 'on' : '') - + chip('Campaigns', (a.campaignsActive || 0) + ' active of ' + (a.campaigns || 0) + (a.imps ? ' · ' + a.imps.toLocaleString() + ' views' : ''), (a.campaignsActive || 0) > 0 ? 'on' : '') - + chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '') - + chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '') - + chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn') - + (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '') - + '' + (working ? 'Working' : 'Quiet') + ''; - } - async function loadUplineMessages() { - try { - const r = await (await fetch('/api/my/messages')).json(); - if (r.error) return; - const card = $('upMsgCard'), list = $('upList'); - if (!r.items || !r.items.length) { card.hidden = true; return; } - card.hidden = false; - list.innerHTML = r.items.map(i => '
' - + '
' + esc(i.subject) + '' - + '' + esc(i.fromName) + ' · ' + new Date(i.sent).toLocaleDateString() + '
' - + '
' + (i.body || '') + '
').join(''); - pageList('upmsg', list, ':scope > .promo-block', { per: 5 }); - // opening the pane marks them read - for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {}); - } catch (e) {} - } - // broadcast composer editor (its own small rich editor, server sanitizes) - document.querySelectorAll('[data-bc]').forEach(b => - b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); })); - document.querySelectorAll('[data-bcblock]').forEach(b => - b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); })); - if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => { - const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; - const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); - if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } - }); - // broadcast send (2026-10-05, Brian: "clicking send didn't give me anything to feel it was sent"): a pop-up either way, - // and an expired sign-in keeps the draft so nothing typed is lost - const BC_DRAFT = 'iap.bcDraft'; - try { const d = JSON.parse(localStorage.getItem(BC_DRAFT) || 'null'); if (d && $('bcSubject') && !$('bcSubject').value) { $('bcSubject').value = d.subject || ''; $('bcEd').innerHTML = d.body || ''; if ($('bcScope') && d.scope) $('bcScope').value = d.scope; localStorage.removeItem(BC_DRAFT); } } catch (e) {} - if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', async () => { - const btn = $('bcSendBtn'); btn.disabled = true; const label = btn.textContent; btn.textContent = 'Sending…'; - try { - const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML }); - $('bcSubject').value = ''; $('bcEd').innerHTML = ''; - $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.'; - await IAP.confirmBox('Your broadcast was delivered to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + ' in your line. They see it in their Messages, and get a copy by email. You can send your next broadcast in 24 hours.', { title: '✅ Broadcast sent', ok: 'Done', noCancel: true }); - } catch (e) { - const msg = (e && e.message) || String(e); - if (/sign in/i.test(msg)) { - try { localStorage.setItem(BC_DRAFT, JSON.stringify({ subject: $('bcSubject').value, body: $('bcEd').innerHTML, scope: $('bcScope').value })); } catch (x) {} - if (await IAP.confirmBox('Your sign-in expired, so the broadcast was NOT sent. Your message is saved: sign in again and it will be waiting for you here.', { title: 'Not sent yet', ok: 'Sign in again', cancel: 'Close' })) location.href = '/my#line'; - } else { - await IAP.confirmBox(msg + ' Your message is still in the box.', { title: 'Broadcast not sent', ok: 'OK', noCancel: true }); - } - } finally { btn.disabled = false; btn.textContent = label; } - }); - - // ── solo-ads inbox: list, read view, dwell-gated read reward ── - let ibTimer = null; - function setInboxBadge(n) { - for (const id of ['inboxBadge', 'inboxBadge2']) { - const b = $(id); - if (b) { b.hidden = !n; b.textContent = n; } - } - } - // Earn credits sub-tabs: Watch ads | Inbox - let earnSub = 'watch'; - function setEarnSub(which) { - earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch'; - if (earnSub !== 'videos' && vidState.token) stopVideo(); - const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits'); - if (w) w.hidden = earnSub !== 'watch'; - if (i) i.hidden = earnSub !== 'inbox'; - if (v) v.hidden = earnSub !== 'videos'; - if (vs) vs.hidden = earnSub !== 'visits'; - document.querySelectorAll('.subtabs [data-earn]').forEach(b => - b.classList.toggle('on', b.dataset.earn === earnSub)); - if (earnSub === 'inbox') loadInbox(); - else if (earnSub === 'videos') loadVideoStatus(); - else if (earnSub === 'visits') loadVisitStatus(); - else earnRefresh(); - } - document.querySelectorAll('.subtabs [data-earn]').forEach(b => - b.addEventListener('click', () => setEarnSub(b.dataset.earn))); - // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14) - let tkState = null; - async function loadToolkit() { - try { - const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r; - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' }; - $('tkTierLine').textContent = 'you are at ' + names[r.tier]; - $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
    ' + t.items.map(i => '' + esc(i.t) + '').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join(''); - $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked; - if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $20 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; } - $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits'; - $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.'; - if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); } - renderTkTools(r); - $('tkHistory').innerHTML = r.history.length ? '

Recent

' + r.history.map(h => '
' + esc(h.kind) + ' · ' + new Date(h.ts).toLocaleString() + (h.charged ? ' · ' + h.charged + ' credits' : ' · free') + '
' + esc(h.text).replace(/\n/g, '
') + '
').join('') : ''; - } catch (e) { console.error('toolkit', e); } - } - // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops - const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 }; - async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; } - function renderTkTools(r) { - const at = tkRank[r.tier] || 0; - // Spark - const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark; - if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.'; - else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; } - // Circuit - const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ; - if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.'; - else { loadTkVideos(r); loadTkSplit(); } - // Nexus - const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex; - if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.'; - else { loadTkTeam(); renderTkPartner(r); } - } - let tkVidTimer = null; - async function loadTkVideos(r) { - const box = $('tkVideos'); - if (!r.videoMaker) { box.innerHTML = '

The Video Maker is warming up on the server. Check back shortly.

'; return; } - if (!r.username) { box.innerHTML = '

Pick a username first (Profile); it goes on the end card.

'; return; } - try { - const v = await (await fetch('/api/my/toolkit/videos')).json(); if (v.error) return; - box.innerHTML = v.list.map(x => '
' + tkEsc(x.title) + '' + (x.status === 'done' ? 'Download ' : x.status === 'queued' || x.status === 'working' ? '
' + tkEsc(x.stage || 'Starting') + (x.status === 'working' ? ' · ' + (x.pct || 0) + '%' : '') + '' : '') + '
').join(''); - clearTimeout(tkVidTimer); if (v.list.some(x => x.status === 'queued' || x.status === 'working')) tkVidTimer = setTimeout(() => loadTkVideos(r), 2500); - } catch (e) {} - } - async function loadTkSplit() { - try { - const sp = await (await fetch('/api/my/toolkit/split')).json(); if (sp.error) return; - const rows = sp.rows.filter(x => x.views || x.joins); - $('tkSplit').innerHTML = !rows.length ? '

No link views yet. Share two different angle links this week and the winner shows up here.

' - : '
' + rows.map(x => '').join('') + '
AngleViewsLast 30dJoinsBuyersJoin rate
' + tkEsc(x.angle) + (x.angle === sp.best ? ' (winner so far)' : '') + '
' + tkEsc(x.link) + '
' + x.views + '' + x.views30 + '' + x.joins + '' + x.buyers + '' + x.rate + '%

Rate = joins per 100 views. A winner needs at least 10 views. Send more traffic to the winner, keep testing the rest.

'; - } catch (e) {} - } - let tkTeamData = null; - async function loadTkTeam() { - try { - const t = await (await fetch('/api/my/toolkit/team')).json(); if (t.error || !t.unlocked) return; tkTeamData = t; - $('tkTeamSub').textContent = t.total + ' in three levels (' + t.byLevel.join(' / ') + ') · ' + t.recent + ' new this week · ' + t.stalled.length + ' stalled'; - const list = t.stalled.length ? t.stalled : t.members.slice(0, 12); - $('tkTeam').innerHTML = (t.stalled.length ? '

Stalled first: quiet for a while and not yet past the next rung. One click sends them the right message from you.

' : '

Nobody stalled right now. Your newest people:

') - + list.map(m => '
' + tkEsc(m.name) + ' L' + m.level + ' · ' + tkEsc(m.label) + (m.quietDays ? ' · quiet ' + m.quietDays + 'd' : '') + '
Next: ' + tkEsc(m.next) + '
').join(''); - $('tkGrantTo').innerHTML = t.members.map(m => '').join(''); - } catch (e) {} - } - function renderTkPartner(r) { - const pk = r.partner; - $('tkPartner').innerHTML = pk - ? '

Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.

Invite link with the code: ' + tkEsc(pk.link) + '

Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '

' - : '

Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.

'; - } - document.addEventListener('click', async ev => { - const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return; - if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; } - if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; } - if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; } - if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; } - if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; } - if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; } - if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; } - if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; } - }); - $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; }); - async function tkSendBroadcast() { - const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt); - const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim(); - if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return; - const r = await tkPost('/api/my/broadcast', { subject, body: '

' + tkEsc(body).replace(/\n{2,}/g, '

').replace(/\n/g, '
') + '

', scope: 'all' }); - if (r) IAP.status('Sent to ' + (r.sent || r.count || r.recipients || 'your team') + '.', 'ok'); - } - async function tkGenerate() { - const btn = $('tkGo'); if (btn.disabled) return; btn.disabled = true; btn.textContent = 'Writing…'; - try { - const r = await (await fetch('/api/my/toolkit/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind: $('tkKind').value, angle: $('tkAngle').value, brief: $('tkBrief').value }) })).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - $('tkText').value = r.text; $('tkOut').hidden = false; $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; - IAP.status(r.charged ? r.charged + ' credits used.' : 'Written. ' + r.freeLeft + ' free left this month.', 'ok'); - loadToolkit(); loadDashboard(); - } catch (e) { IAP.status('The engine did not answer. Try again.', 'bad'); } - finally { btn.disabled = false; btn.textContent = 'Write it'; } - } - if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); } - // promo tools: pill menu switches between posts / swipes / banners / wall / videos - function setPromoSub(name) { - const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'games']; - if (['polhunter', 'spookydoors', 'gamebanners'].includes(name)) name = 'games'; // those tabs live inside Games now (2026-10-06) - if (name === 'toolkit') loadToolkit(); - const pill = document.querySelector('.promo-pills [data-promo="' + name + '"]'); - if (!ids.includes(name) || !pill || pill.hidden) name = 'posts'; - ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; }); - document.querySelectorAll('.promo-pills [data-promo]').forEach(b => { - b.classList.toggle('on', b.dataset.promo === name); - b.setAttribute('aria-selected', b.dataset.promo === name ? 'true' : 'false'); - }); - try { localStorage.setItem('iap.promoSub', name); } catch (e) {} - } - document.querySelectorAll('.promo-pills [data-promo]').forEach(b => - b.addEventListener('click', () => setPromoSub(b.dataset.promo))); - try { setPromoSub(localStorage.getItem('iap.promoSub') || 'posts'); } catch (e) { setPromoSub('posts'); } - async function loadInbox() { - try { - const r = await (await fetch('/api/my/inbox')).json(); - if (r.error) return; - $('ibRewardNote').textContent = '+' + r.readCredits + ' credits per real read (up to ' - + r.readCap + ' rewarded reads a day)'; - const el = $('ibList'); - $('inboxReadCard').hidden = true; - $('inboxListCard').hidden = false; - setInboxBadge(r.unread); - if (!r.items.length) { - el.innerHTML = '

No solo ads yet. When a member sends one, it lands here — and reading it pays.

'; - return; - } - el.innerHTML = ''; - for (const i of r.items) { - const d = document.createElement('div'); - d.className = 'ib-row' + (i.read ? '' : ' unread'); - d.innerHTML = '' - + (i.rewarded ? 'claimed' : i.read ? '' : 'new') - + '' + new Date(i.delivered).toLocaleDateString() + ''; - d.querySelector('.sub').textContent = i.subject || '(no subject)'; - d.querySelector('.from').textContent = 'from ' + (i.fromName || 'a member'); - d.addEventListener('click', () => openInboxItem(i.id)); - el.appendChild(d); - } - } catch (e) {} - } - async function openInboxItem(id) { - try { - const r = await (await fetch('/api/my/inbox/' + id)).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - $('inboxListCard').hidden = true; - $('inboxReadCard').hidden = false; - $('ibSubject').textContent = r.subject || '(no subject)'; - $('ibMeta').textContent = 'from ' + (r.fromName || 'a member') + ' · ' + new Date(r.delivered).toLocaleString(); - $('ibBody').innerHTML = r.body || ''; // whitelist-sanitized on the server at submit - const mv = $('ibMedia'); - mv.hidden = !r.mediaUrl; - mv.innerHTML = !r.mediaUrl ? '' - : r.mediaType === 'video' - ? '' - : 'attachment'; - // the read reward needs BOTH the dwell AND an actual click-through to the - // advertiser — the visit is what makes the ad worth the sender's credits - const visit = $('ibVisit'); - visit.href = r.url; - visit.textContent = r.ctaLabel || 'Learn more'; - visit.target = '_blank'; - const btn = $('ibClaimBtn'); - clearInterval(ibTimer); - if (r.rewarded) { - btn.hidden = true; - visit.classList.remove('cta-need'); - $('ibHint').textContent = 'Read reward already claimed for this one.'; - return; - } - let dwellDone = false; - let visited = !!r.visited; - btn.hidden = false; - btn.disabled = true; - visit.classList.toggle('cta-need', !visited); - let left = r.dwell; - const refresh = () => { - if (!dwellDone) { btn.textContent = 'Read it — claim in ' + left + 's'; return; } - if (!visited) { btn.textContent = 'Claim +' + r.reward + ' — visit the ad first'; btn.disabled = true; return; } - btn.textContent = 'Claim +' + r.reward + ' credits'; btn.disabled = false; - }; - $('ibHint').textContent = 'Read the message, click through to the advertiser, then claim your credits.'; - refresh(); - // countdown pauses off-tab; the server separately enforces the dwell on its own clock - ibTimer = setInterval(() => { - if (!tabActive()) return; - left -= 1; - if (left > 0) { refresh(); return; } - clearInterval(ibTimer); - dwellDone = true; - refresh(); - }, 1000); - // clicking the CTA records the visit (and counts the advertiser's click) - visit.onclick = async () => { - visited = true; - visit.classList.remove('cta-need'); - try { await fetch('/api/my/inbox/' + id + '/visit', { method: 'POST' }); } catch (e2) {} - refresh(); - }; - btn.onclick = async () => { - try { - const c = await api('/api/my/inbox/' + id + '/claim'); - IAP.status('+' + c.credited + ' credits for reading. They spend like any earned credits.', 'ok'); - btn.hidden = true; - $('ibHint').textContent = 'Claimed. Head back for the next one.'; - loadDashboard(); - } catch (e2) { IAP.status(e2.message, 'bad'); } - }; - } catch (e) {} - } - $('ibBack').addEventListener('click', ev => { ev.preventDefault(); clearInterval(ibTimer); loadInbox(); }); - - // ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ── - function fillPromo(link, me) { - if (window.IAPPromo) IAPPromo.fill(link, me || {}); - // banner kit - const bwrap = $('promoBanners'); - if (bwrap && !bwrap.dataset.filled) { - bwrap.dataset.filled = '1'; - // one collapsed accordion per size / use, so the kit stays scannable as it grows - const GROUPS = [ - { title: 'Stop chasing shiny objects · share the article with your link', bridge: { page: 'blog/stop-chasing-shiny-objects', name: 'shiny-objects article', short: 'article' }, items: [ - { file: 'iap-shiny-objects-wide-1200x630.jpg', size: '1200×630 · the article cover (widescreen art) · Facebook, X, link previews' }, - { file: 'iap-shiny-objects-wide-1600x896.jpg', size: '1600×896 · full widescreen art · YouTube community, LinkedIn, blogs' }, - { file: 'iap-shiny-objects-1200x630.jpg', size: '1200×630 · tight crop of the portrait art' }, - { file: 'iap-shiny-objects-1080x1080.jpg', size: '1080×1080 · square · Instagram, Facebook, Telegram' }, - { file: 'iap-shiny-objects-1080x1349.jpg', size: '1080×1349 · portrait · Instagram feed, Pinterest' } ] }, - { title: 'Wired Wednesday · share with your /wednesday link', bridge: { page: 'wednesday', name: 'Wired Wednesday', short: 'Wednesday' }, items: [ - { file: 'iap-wired-wednesday-1200x630.jpg', size: '1200×630 · Wired Wednesday · social card, link previews, Daily News' }, - { file: 'iap-wired-wednesday-1080x1080.jpg', size: '1080×1080 · Wired Wednesday · Instagram, Facebook, Telegram' }, - { file: 'iap-wired-wednesday-728x90.png', size: '728×90 · Wired Wednesday · leaderboard' }, - { file: 'iap-wired-wednesday-300x250.png', size: '300×250 · Wired Wednesday · rectangle' } ] }, - { title: 'Five Dollar Friday · share with your /friday link', friday: true, items: [ - { file: 'iap-five-dollar-friday-october-1200x630.jpg', size: '1200×630 · Five Dollar Friday · October porch, bright' }, - { file: 'iap-five-dollar-friday-october-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · October porch, square' }, - { file: 'iap-five-dollar-friday-v2-1200x630.jpg', size: '1200×630 · Five Dollar Friday · loft, Central-time window' }, - { file: 'iap-five-dollar-friday-dark-1200x630.jpg', size: '1200×630 · Five Dollar Friday · dark studio' }, - { file: 'iap-five-dollar-friday-v2-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · square for Instagram and feeds' } ] }, - { title: '600×300 · traffic exchanges and splash pages', items: [ - { file: 'iap-advertise-earn-600x300.png', size: '600×300 · advertise and earn · traffic exchanges, splash pages, safelist mailers' } ] }, - { title: '1200×630 · social posts, link previews, Daily News covers', items: [ - { file: 'iap-hero-1200x630.png', size: '1200×630 · hero · advertise and earn' }, - { file: 'iap-advertise-earn-1200x630.jpg', size: '1200×630 · advertise and earn instantly, locked in code' }, - { file: 'iap-team-build-tiers-1200x630.jpg', size: '1200×630 · team build and instant payments · 50 / 20 / 10 tiers' }, - { file: 'iap-team-build-tiers-v2-1200x630.jpg', size: '1200×630 · team build and instant payments · variant 2' }, - { file: 'iap-instant-payments-tiers-1200x630.jpg', size: '1200×630 · instant payments, direct commissions · tiers' }, - { file: 'iap-instant-payments-tiers-v2-1200x630.jpg', size: '1200×630 · instant payments · variant 2' }, - { file: 'iap-multistream-info-1200x630.jpg', size: '1200×630 · multi-stream revenue · "INFO or message me" CTA' }, - { file: 'iap-multistream-info-v2-1200x630.jpg', size: '1200×630 · multi-stream revenue · variant 2' }, - { file: 'iap-success-path-info-1200x630.jpg', size: '1200×630 · success path, training and coaching · "INFO or message me" CTA' }, - { file: 'iap-success-path-link-1200x630.jpg', size: '1200×630 · success path · "link in the description" (feed posts, Daily News)' }, - { file: 'iap-success-path-coaching-1200x630.jpg', size: '1200×630 · success path · quality network traffic' } ] }, - { title: 'Five Dollar Friday · every Friday, +20% credits on any $5+ pack', items: [ - { file: 'iap-five-dollar-friday-1200x630.jpg', size: '1200×630 · social card, Daily News, feed posts' }, - { file: 'iap-five-dollar-friday-1080x1080.jpg', size: '1080×1080 · Instagram, Facebook, Telegram' }, - { file: 'iap-five-dollar-friday-728x90.png', size: '728×90 · leaderboard' }, - { file: 'iap-five-dollar-friday-300x250.png', size: '300×250 · rectangle' } ] }, - { title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [ - { file: 'iap-1080x1080.png', size: '1080×1080 · square' }, - { file: 'iap-1080x1920.png', size: '1080×1920 · story / reel' } ] }, - { title: '1280×720 · Telegram and group posts', items: [ - { file: 'iap-1280x720.png', size: '1280×720 · group post' } ] }, - { title: 'Leaderboards · 728×90, 468×60, 320×50', items: [ - { file: 'iap-728x90.png', size: '728×90 · leaderboard' }, - { file: 'iap-advertise-earn-728x90.png', size: '728×90 · advertise and earn instantly · Join free' }, - { file: 'iap-ledger-728x90.png', size: '728×90 · advertising that pays you on-chain · See the ledger' }, - { file: 'iap-468x60.png', size: '468×60 · banner' }, - { file: 'iap-ledger-468x60.png', size: '468×60 · advertising that pays you on-chain · See the ledger' }, - { file: 'iap-320x50.svg', size: '320×50 · mobile leaderboard' } ] }, - { title: 'Rectangles and buttons · 336×280, 300×250, 125×125', items: [ - { file: 'iap-336x280.png', size: '336×280 · large rectangle' }, - { file: 'iap-advertise-earn-336x280.png', size: '336×280 · advertise and earn instantly' }, - { file: 'iap-advertise-earn-v2-336x280.png', size: '336×280 · advertise and earn · variant 2' }, - { file: 'iap-300x250.png', size: '300×250 · rectangle' }, - { file: 'iap-advertise-earn-300x250.png', size: '300×250 · advertise and earn instantly' }, - { file: 'iap-team-build-link-300x250.jpg', size: '300×250 · team build and instant payments · "link in the description"' }, - { file: 'iap-125x125.png', size: '125×125 · square button' } ] }, - { title: 'Skyscrapers · 160×600, 120×600', items: [ - { file: 'iap-160x600.png', size: '160×600 · wide skyscraper' }, - { file: 'iap-120x600.png', size: '120×600 · skyscraper' } ] } - ]; - bwrap.innerHTML = ''; - for (const g of GROUPS) { - const det = document.createElement('details'); - det.className = 'pb-acc'; - det.innerHTML = '' + esc(g.title) + '' + g.items.length + (g.items.length === 1 ? ' banner' : ' banners') + '
'; - const grid = det.querySelector('.pb-grid'); - const bridge = g.bridge || (g.friday ? { page: 'friday', name: 'Five Dollar Friday', short: 'Friday' } : null); - if (bridge) { - // the bridge page with this member's referral: any public page + ?ref sets the sponsor cookie - const inv = (document.getElementById('inviteLine') || {}).textContent || ''; - const fl = inv.replace(/\/join\/([^/?#]+).*$/, '/' + bridge.page + '?ref=$1'); - const note = document.createElement('div'); - note.className = 'pb-note'; - note.innerHTML = 'Post any of these with your ' + esc(bridge.name) + ' link: '; - note.querySelector('b').textContent = fl; - const cp = document.createElement('button'); cp.className = 'btn small'; cp.textContent = 'Copy my ' + bridge.short + ' link'; - cp.addEventListener('click', async () => { try { await navigator.clipboard.writeText(fl); IAP.status(bridge.short + ' link copied.', 'ok'); } catch (e) { IAP.status('Copy failed.', 'bad'); } }); - note.appendChild(cp); - grid.before(note); - } - for (const b of g.items) { - const url = location.origin + '/banners/' + b.file; - const d = document.createElement('div'); - d.className = 'pb-item'; - d.innerHTML = 'InstantAdPay banner ' + b.size + '' - + '
' + b.size + '
'; - const dl = document.createElement('a'); - dl.className = 'btn small'; dl.textContent = 'Download'; dl.href = '/banners/' + b.file; dl.setAttribute('download', b.file); - d.querySelector('.pb-row').appendChild(dl); - const btn = document.createElement('button'); - btn.className = 'btn small sec'; - btn.textContent = 'Copy image URL'; - btn.addEventListener('click', async () => { - try { await navigator.clipboard.writeText(url); IAP.status('Banner URL copied.', 'ok'); } - catch (e) { IAP.status('Copy failed.', 'bad'); } - }); - d.querySelector('.pb-row').appendChild(btn); - grid.appendChild(d); - } - bwrap.appendChild(det); - } - } - } - - // ── profile ── (busy2 defers the busy lookup past its TDZ) - $('pfSaveBtn').addEventListener('click', busy2($('pfSaveBtn'), async () => { - const r = await api('/api/my/profile', { username: $('pfUsername').value }); - IAP.status('You are @' + r.account.username + ' now.', 'ok'); - await render(); - })); - - // ── in-dashboard package buying ── - const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' }; - // Card on-ramp: buy POL with a card via MoonPay, delivered to the buyer's own - // wallet. Signed + wallet-prefilled once MoonPay keys are set; generic page - // otherwise. The site never touches funds — MoonPay is merchant of record. - async function openMoonpay(pol) { - try { - let addr = ''; - try { const me = await (await fetch('/api/me')).json(); addr = me.address || ''; } catch (e) {} - const q = '/api/moonpay-url?pol=' + encodeURIComponent(pol || '') + (addr ? '&address=' + encodeURIComponent(addr) : ''); - const r = await (await fetch(q)).json(); - if (r && r.url) { - window.open(r.url, '_blank', 'noopener'); - IAP.status(r.signed - ? 'MoonPay opened in a new tab with your wallet address pre-filled. Choose POL on Polygon, finish the purchase, then come back and buy your package.' - : 'MoonPay opened in a new tab. Choose POL on the Polygon network and paste your own wallet address as the destination, then come back.', 'ok'); - } - } catch (e) { IAP.status('Could not open MoonPay: ' + ((e && e.message) || e), 'bad'); } - } - // ── linked positions (Qualified Start) ── - const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : ''; - let noPayoutAddrs = new Set(); // positions the site refuses to buy from (see siteConfig.noPayoutIds) - async function loadPositions(me) { - try { - const r = await (await fetch('/api/my/positions')).json(); - if (r.error) return; - const list = r.positions || []; - const rows = list.map((p, i) => '
Position ' + (i + 2) + ' ' + short(p.address) + '' - + '' + (p.memberId ? '#' + p.memberId : 'not on-chain yet') + '' - + '' + (p.noPayout ? 'linkage only: no purchases from this position (payouts would reach a retired wallet)' : p.counted ? 'counts as a qualifying buyer' : p.memberId ? 'registered, buy $20+ to count' : 'buy a $20+ package to register it') + '' - + '' + (p.credits || 0).toLocaleString() + ' credits' + (p.balanceWei != null ? ' · ' + (Number(BigInt(p.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '' - + (!p.memberId ? '' : '') - + '
').join(''); - const mainRow = r.main && r.main.address ? '
Position 1 · main ' + short(r.main.address) + '' - + '' + (r.main.memberId ? '#' + r.main.memberId : 'payouts not on yet') + '' - + '' + (r.main.buyerCount || 0) + ' qualifying buyer(s)' - + '' + (r.main.credits || 0).toLocaleString() + ' credits' + (r.main.balanceWei != null ? ' · ' + (Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '
' : ''; - const html = mainRow + rows + (list.length ? '

Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.

' : ''); - if ($('qsList')) $('qsList').innerHTML = html; - // Wallet tab: live POL balance of the linked wallet, and which package it covers - const wb = $('walletBal'); - if (wb && r.main && r.main.address && r.main.balanceWei != null) { - const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000; - const usd = r.polUsd ? polN * r.polUsd : 0; - const pkgs = [5, 20, 50, 100, 250]; - const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : []; - wb.hidden = false; - wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '') - + (r.polUsd ? '
' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : ''); - } - if ($('posList')) $('posList').innerHTML = html; - if ($('posCard')) $('posCard').hidden = !list.length; - // "Buy from" picker: main + every position - const sel = $('buyFrom'); - if (sel) { - const keep = sel.value; - sel.innerHTML = '' - + list.map((p, i) => '').join(''); - noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase()); - if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep; - $('buyFromWrap').hidden = !list.length; - } - document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => { - if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return; - try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => { - const me = await (await fetch('/api/me')).json(); - if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.'); - if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.'); - if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return; - IAP.status('Pick the new account in your wallet, then sign once…'); - const r = await IAPWallet.signIn({ asPosition: true, pick: true }); - $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $20 or larger package.'; - IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $20+ package to count it.', 'ok'); - await loadPositions(); - const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase(); - try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {} - })); - async function loadBuyTiles() { - try { - const { products } = await (await fetch('/api/catalog')).json(); - const wrap = $('boTiles'); - wrap.innerHTML = ''; - products.sort((a, b) => a.priceCents - b.priceCents); - for (const p of products) { - const bonus = p.creditAmount - p.priceCents; - const div = document.createElement('div'); - div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : ''); - div.innerHTML = '
' + (PKG[p.id] || 'Package ' + p.id) + '
' - + '
$' + Math.round(p.priceCents / 100) + '
' - + '
' + p.creditAmount.toLocaleString() + ' credits
' - + '
' + (bonus > 0 ? '+' + bonus.toLocaleString() + ' bonus credits' : ' ') + '
' - + '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
' - + ''; - wrap.appendChild(div); - } - wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => { - try { - b.disabled = true; - // the buyer's credits are read by the member id of their LINKED wallet. - // If they only connected a wallet (e.g. for the faucet) but never linked - // it, link it first (one signature) so the purchase's credits show up. - // retry these through transient failures — mobile drops in-flight - // fetches when the page returns from the wallet app-switch - const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; }; - const meNow = await jretry('/api/me'); - // which of the member's wallets is buying: the main wallet (default) or a - // linked position (Qualified Start). A position registers under the main - // member id on its first buy, so its sponsor is always this member. - const fromSel = $('buyFrom'); - const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null; - if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; } - if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; } - if (!fromPos && !meNow.address) { - IAP.status('Link your wallet first — one quick signature…'); - await IAPWallet.signIn(); - } - const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null); - if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member - await IAPWallet.connect(); - let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); - if (cur !== wantAddr) { - IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…'); - cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); - } - if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.'); - } - const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy'); - if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company - if (!fromPos && !meNow.memberId && spNow.sponsorRouted) IAP.status((spNow.sponsorRouted.from || 'Your sponsor') + ' has not switched on payouts, so this purchase credits ' + spNow.sponsorRouted.to + ' instead. You are not held up; carrying on.', 'ok'); - // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any - // transaction that spends most of the balance ("drain your wallet"), so Trust users - // get a heads-up first; other wallets go straight to the confirmation. - try { - const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy() - const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address); - if (bal < need) { - IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad'); - return; - } - const pct = Number(need * 100n / bal); - const isTrust = /trust/i.test(IAPWallet.walletName() || ''); - if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) { - IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok'); - return; - } - } catch (e) { /* balance read failed: let the wallet decide */ } - IAP.status('Confirm the purchase in your wallet…'); - const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost); - if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.'); - // a game sent them here to pay (PolyWarriors mint, Gem Kingdom Crowns, Spooky Doors costume): go straight back once it settles (Marty 2026-10-08) - const back = document.getElementById('pwBack') ? ['/pw/mint/resume', 'PolyWarriors'] : document.getElementById('gkBack') ? ['/gk/shop/resume', 'Gem Kingdom'] : document.getElementById('sdBack') ? ['/sd/shop/resume', 'Spooky Doors'] : null; - if (back) { IAP.status('Purchase settled on-chain. Taking you back to ' + back[1] + '…', 'ok'); setTimeout(() => { location.href = back[0]; }, 1800); return; } - IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok'); - await render(); - loadBuyTiles(); - } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); } - finally { b.disabled = false; } - })); - // brand new to crypto? buy POL with a card, sent straight to the wallet - const builder = products.find(p => p.priceCents === 5000) || products[products.length - 1]; - const needPol = (builder && builder.costWei) ? Math.max(30, Math.ceil(Number(builder.costWei) / 1e18) + 3) : 30; - const cta = document.createElement('div'); - cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center'; - cta.innerHTML = '

New to crypto? Buy POL with a debit or credit card, Apple Pay, or Google Pay. It lands straight in your own wallet, and this site never touches your money.

' - + ' Wallet and MoonPay guide'; - wrap.appendChild(cta); - const mb = $('moonpayBtn'); if (mb) mb.addEventListener('click', () => openMoonpay(needPol)); - } catch (e) {} - } - loadBuyTiles(); - - // ── earn-by-viewing: daily ad set with dwell, then claim ── - const earnState = { types: ['banner', 'text'], i: 0, timer: null }; - async function earnRefresh() { - try { - const st = await (await fetch('/api/my/earn')).json(); - if (st.error) return null; - $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed'; - loadFridayBank(); - $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : ''); - if ($('earnActLink')) $('earnActLink').onclick = e => { e.preventDefault(); jumpTo('campaigns', 'creditActivity'); }; - const done = st.views >= st.target; - $('earnClaimBtn').hidden = !(done && !st.claimed); - if (st.claimed) { - $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.'; - // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign - const box = $('earnAdBox'); - if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.' - + '
' - + (st.visitsLeft ? '' : '') - + ((st.earnedAvailable != null ? st.earnedAvailable : st.earned) > 0 - ? '' - : '') + '
'; - if (box) box.querySelectorAll('[data-earnnext]').forEach(b => b.addEventListener('click', () => { if (b.dataset.earnnext === 'campaigns') setPane('campaigns'); else setEarnSub('visits'); })); - if ($('earnStartBtn')) $('earnStartBtn').hidden = true; - } else { - if ($('earnStartBtn')) $('earnStartBtn').hidden = done; // set done: the claim button takes over - $('earnHint').textContent = done - ? 'Set complete. Claim your ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' - : (st.views ? (st.target - st.views) + ' more to go, then claim ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' : 'View ' + st.target + ' ads to unlock the daily claim of ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.'); - } - return st; - } catch (e) { return null; } - } - async function earnShowAd() { - // each view happens full screen in its own tab: /view/ frames the - // advertiser's site, runs the countdown, then a human check credits it - const type = earnState.types[earnState.i++ % earnState.types.length]; - let r = null; - try { r = await (await fetch('/api/my/earnview?type=' + type)).json(); } catch (e) {} - const box = $('earnAdBox'); - if (!r || !r.ad || !r.viewUrl) { - await earnRefresh(); - box.innerHTML = '' + (r && r.status && r.status.views >= r.status.target - ? 'Set complete for today.' - : 'No member ads are live in rotation right now. Views resume the moment a campaign is running.') + ''; - return; - } - openAdOverlay(r.viewUrl); - box.innerHTML = 'Watch the countdown and pass the quick check. Your view credits itself and this page updates right away.'; - $('earnStartBtn').textContent = 'View next ad'; - } - // In-page ad overlay: no new tab (mobile and in-app wallet browsers handle tabs - // badly), no window.close needed. The /view page runs the dwell + check inside, - // messages back when it credits or when the user is done. - function openAdOverlay(url) { - closeAdOverlay(); - const back = document.createElement('div'); - back.id = 'adOverlay'; - back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050b09;display:flex;flex-direction:column'; - const x = document.createElement('button'); - x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); - x.textContent = '✕'; - x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; - x.addEventListener('click', closeAdOverlay); - const ifr = document.createElement('iframe'); - ifr.src = url; - ifr.style.cssText = 'flex:1;width:100%;border:0;background:#050b09'; - back.appendChild(ifr); back.appendChild(x); - document.body.appendChild(back); - document.body.style.overflow = 'hidden'; - } - function closeAdOverlay() { - const m = $('adOverlay'); if (m) m.remove(); - document.body.style.overflow = ''; - earnRefresh(); loadDashboard(); - } - window.addEventListener('message', e => { - if (e.origin !== location.origin || !e.data) return; - if (e.data.t === 'iap-view-close') closeAdOverlay(); - else if (e.data.t === 'iap-view-done') { earnRefresh(); loadDashboard(); } - }); - $('earnStartBtn').addEventListener('click', () => earnShowAd()); - // the viewer tab pings localStorage when a view credits; refresh instantly - window.addEventListener('storage', e => { - if (e.key === 'iap-view-done') { earnRefresh(); loadDashboard(); } - }); - document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'visible' && $('pane-earn') && !$('pane-earn').hidden) earnRefresh(); - }); - $('earnClaimBtn').addEventListener('click', async () => { - try { - const r = await api('/api/my/claim'); - IAP.status('+' + r.credited + ' credits earned' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Tomorrow\'s claim pays ' + r.nextClaim + '. Spend them in Campaigns.', 'ok'); - await earnRefresh(); - loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - }); - - const busy = (btn, fn) => async () => { - try { btn.disabled = true; await fn(); } - catch (e) { IAP.status((e && e.message) || String(e), 'bad'); } - finally { btn.disabled = false; } - }; - - // passwordless (feature-flagged on config.emailAuth): code replaces passwords - (async () => { - const cfg = await IAP.getConfig(); - if (!cfg.emailAuth) return; - $('passCards').hidden = true; - $('magicCard').hidden = false; - const codeOpts = () => ({ honeypot: $('mcWebsite'), host: $('mcCheck') }); - const start = busy($('mcSendBtn'), async () => { - const r = await IAP.requestCode($('mcEmail').value, codeOpts()); - $('mcCodeRow').hidden = false; - $('mcVerifyBtn').hidden = false; - $('mcSendBtn').hidden = true; - $('mcResend').hidden = false; - if (r.devCode) { $('mcCode').value = r.devCode; IAP.status('Dev mode: code filled in for you.', 'ok'); } - else IAP.status('Code sent. Check your inbox (and spam, the first time).', 'ok'); - $('mcCode').focus(); - }); - $('mcSendBtn').addEventListener('click', start); - $('mcResend').addEventListener('click', busy($('mcResend'), async () => { - const r = await IAP.requestCode($('mcEmail').value, codeOpts()); - if (r.devCode) $('mcCode').value = r.devCode; - IAP.status('Fresh code sent.', 'ok'); - })); - $('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => { - const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); - IAP.status('You are in.', 'ok'); - if (r.next && !r.created) { location.href = r.next; return; } // came from Drip Runner: straight back into the game - if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first - if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad - await render(); - })); - })(); - - // new-member onboarding: choose a username (required), optionally a bio. - // required=true: no skip, no backdrop dismiss, prefilled suggestion, resolves only after a save. - function showOnboard(required) { - return new Promise(resolve => { - const m = $('onboardModal'); if (!m) return resolve(); - m.hidden = false; $('obErr').hidden = true; - $('obSkip').hidden = !!required; - if (required && !$('obUsername').value) { - fetch('/api/my/username-suggest').then(r => r.json()).then(r => { if (r.suggest && !$('obUsername').value) { $('obUsername').value = r.suggest; $('obUsername').select(); } }).catch(() => {}); - } - setTimeout(() => $('obUsername').focus(), 50); - const done = () => { m.hidden = true; resolve(); }; - $('obSkip').onclick = required ? null : done; - $('obUsername').onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); $('obSave').click(); } }; - $('obSave').onclick = async () => { - const u = $('obUsername').value.trim(); - if (required && !u) { $('obErr').hidden = false; $('obErr').textContent = 'Pick a username to continue.'; return; } - try { - if (u) await api('/api/my/profile', { username: u }); - const bio = $('obBio').value.trim(); - if (bio) await api('/api/my/profile-details', { bio }); - done(); - } catch (e) { $('obErr').hidden = false; $('obErr').textContent = e.message || 'Could not save that. Try a different username.'; } - }; - }); - } - - $('signupBtn').addEventListener('click', busy($('signupBtn'), async () => { - const r = await api('/api/signup', { email: $('suEmail').value, password: $('suPass').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); - IAP.status('Welcome aboard. You are in.', 'ok'); - if (!(r.account && r.account.username)) await showOnboard(); - await render(); - })); - $('loginBtn').addEventListener('click', busy($('loginBtn'), async () => { - await api('/api/login', { email: $('liEmail').value, password: $('liPass').value }); - IAP.status('Logged in.', 'ok'); - if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad - await render(); - })); - $('linkBtn').addEventListener('click', busy($('linkBtn'), async () => { - IAP.status('Check your wallet for the free link signature…'); - const lr = await IAPWallet.signIn(); // server binds the wallet to the signed-in email account - if (lr && lr.next) { IAP.status('Wallet linked. Taking you back to PolHunter…', 'ok'); setTimeout(() => { location.href = lr.next; }, 700); return; } // they came from PolHunter: close the loop - IAP.status('Wallet linked. Earnings pay there from now on.', 'ok'); - await render(); - })); - if ($('faucetBtn')) $('faucetBtn').addEventListener('click', busy($('faucetBtn'), async () => { - IAP.status('Connect your wallet first…'); - const addr = await IAPWallet.connect(); - let copied = false; - try { await navigator.clipboard.writeText(addr); copied = true; } catch (e) {} - window.open('https://faucet.polygon.technology/', '_blank', 'noopener'); - $('faucetInfo').innerHTML = 'Your address ' + addr.slice(0, 8) + '…' + addr.slice(-6) + '' - + (copied ? ' is copied' : '') + '. On the faucet, choose Polygon Amoy, paste your address, and request POL. Then come back and buy.'; - IAP.status('Faucet opened in a new tab. Choose Polygon Amoy, paste your address, and request test POL.', 'ok'); - })); - if ($('wcDisconnect')) $('wcDisconnect').addEventListener('click', busy($('wcDisconnect'), async () => { - // fire-and-forget: don't gate the reload on disconnect resolving (it can - // stall). The reload drops all in-memory wallet state and the picker returns. - IAPWallet.disconnect().catch(() => {}); - $('wcDisconnectInfo').textContent = 'Disconnecting — reloading so you can pick a different wallet…'; - IAP.status('Disconnecting — reloading…', 'ok'); - setTimeout(() => location.reload(), 900); - })); - // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) - function sponsorHoldText(sp) { - const who = sp.sponsorName || 'your sponsor'; - if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.'; - if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; - return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; - } - $('activateBtn').addEventListener('click', busy($('activateBtn'), async () => { - const me = await (await fetch('/api/me')).json(); - if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; } - IAP.status('Confirm the free activation in your wallet…'); - const r = await IAPWallet.activate(me.sponsorId || 0); - if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); - IAP.status('Payouts are on. Your invite link is live.', 'ok'); - await render(); - })); - $('copyInvite').addEventListener('click', async () => { - try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); } - }); - $('logoutLink').addEventListener('click', async e => { - e.preventDefault(); - await fetch('/api/auth/logout', { method: 'POST' }); - IAP.status('Logged out.', 'ok'); - await render(); - }); - - // ── welcome tour (viral banner gauntlet): a new member meets their 3-level - // upline's sites, 10 focus-paused seconds each, then unlocks welcome credits. - // Same three levels the contract pays — the tour IS the org chart. - async function showGauntlet() { - try { - const g = await (await fetch('/api/my/gauntlet')).json(); - if (!g.pending || !g.slides || !g.slides.length) return false; - const gate = $('gauntGate'); - gate.hidden = false; - for (let i = 0; i < g.slides.length; i++) { - const s = g.slides[i]; - $('ggWho').textContent = 'Position ' + (i + 1) + ': ' + s.name + (i === 0 ? ' — the person who invited you' : ''); - $('ggProgress').textContent = 'Meeting your line: ' + (i + 1) + ' of ' + g.slides.length; - $('ggFrame').hidden = false; - $('ggFrame').src = s.targetUrl; - let left = g.dwell || 10; - $('ggTimer').textContent = left + 's'; - await new Promise(done => { - const t = setInterval(() => { - if (!tabActive()) return; - left -= 1; - $('ggTimer').textContent = Math.max(0, left) + 's'; - if (left <= 0) { clearInterval(t); done(); } - }, 1000); - }); - } - $('ggFrame').src = 'about:blank'; - $('ggFrame').hidden = true; // avoid a white about:blank panel once the tour is done - $('ggTimer').textContent = '✓'; - $('ggWho').textContent = 'That is your line. When you grow, they earn — and yours starts the day you share.'; - $('ggClaim').hidden = false; - await new Promise(done => { - $('ggClaim').onclick = async () => { - try { - const r = await api('/api/my/gauntlet/complete', { token: g.token }); - IAP.status('+' + r.credited + ' welcome credits unlocked. They spend on real campaigns.', 'ok'); - } catch (e) { IAP.status(e.message, 'bad'); } - done(); - }; - }); - gate.hidden = true; - $('ggClaim').hidden = true; - return true; - } catch (e) { return false; } - } - - // ── line banner (profile): the member's slot on welcome tours + their wall ── - function fillLineBanner(a) { - if (!a) return; - if (a.lineTargetUrl) $('lbTarget').value = a.lineTargetUrl; - if (a.lineBannerUrl) { - $('lbBanner').value = a.lineBannerUrl; - $('lbPreview').hidden = false; - $('lbPreview').innerHTML = 'line banner'; - } - $('lbCurrent').textContent = a.lineTargetUrl - ? 'Live: your next three levels meet ' + a.lineTargetUrl + ' on their welcome tour.' - : 'Not set yet. Until you set one, your tour slot is skipped.'; - } - async function loadLineBanner() { - try { - const a = await (await fetch('/api/me')).json(); - fillLineBanner(a); - fillProfileDetails(a); - // buyerCount + wallUnlocked live on the dashboard payload (chain read), not on /api/me - let d = {}; try { d = await (await fetch('/api/my/dashboard')).json(); } catch (e) {} - fillWallOffers(Object.assign({}, a, { buyerCount: d.buyerCount || 0, wallUnlocked: d.wallUnlocked || 1 })); - } catch (e) {} - } - // ── wall positions 2 & 3: the member's own offers, unlocked by qualifying buyers ── - function fillWallOffers(a) { - if (!a || !$('wallOffersCard')) return; - const unlocked = a.wallUnlocked || 1, bc = a.buyerCount || 0; - const offers = Array.isArray(a.wallOffers) ? a.wallOffers : []; - const NEED = [2, 5]; - for (let i = 0; i < 2; i++) { - const o = offers[i] || {}; - const open = unlocked >= i + 2; - $('woTitle' + i).value = o.title || ''; $('woTarget' + i).value = o.targetUrl || ''; $('woBanner' + i).value = o.bannerUrl || ''; - $('woPrev' + i).hidden = !o.bannerUrl; $('woPrev' + i).innerHTML = o.bannerUrl ? '' : ''; - $('woLock' + i).textContent = open ? 'yours' : 'unlocks at ' + NEED[i] + ' qualifying buyers (' + bc + '/' + NEED[i] + ')'; - $('woSlot' + i).classList.toggle('locked', !open); - } - $('woStatus').textContent = unlocked >= 3 ? 'Fully qualified: all three wall positions are yours.' - : unlocked === 2 ? 'Position 2 is yours. ' + (5 - bc) + ' more qualifying buyer' + (5 - bc === 1 ? '' : 's') + ' and position 3 is too.' - : (2 - bc) + ' more qualifying buyer' + (2 - bc === 1 ? '' : 's') + ' ($20 or more) opens position 2. You can set your links now; they go live the moment a slot unlocks.'; - } - document.querySelectorAll('.wo-upload').forEach(b => b.addEventListener('click', () => { const f = document.querySelector('.wo-file[data-slot="' + b.dataset.slot + '"]'); if (f) f.click(); })); - document.querySelectorAll('.wo-file').forEach(inp => inp.addEventListener('change', async () => { - const i = inp.dataset.slot, f = inp.files[0]; if (!f) return; - $('woInfo' + i).textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('woInfo' + i).textContent = r.error; } - else { $('woBanner' + i).value = r.url; $('woInfo' + i).textContent = 'Uploaded'; $('woPrev' + i).hidden = false; $('woPrev' + i).innerHTML = ''; } - } catch (e) { $('woInfo' + i).textContent = 'Upload failed. Try again.'; } - inp.value = ''; - })); - if ($('woSaveBtn')) $('woSaveBtn').addEventListener('click', busy2($('woSaveBtn'), async () => { - const offers = [0, 1].map(i => ({ title: $('woTitle' + i).value, targetUrl: $('woTarget' + i).value, bannerUrl: $('woBanner' + i).value })); - const r = await api('/api/my/wall-offers', { offers }); - IAP.status('Wall positions saved.', 'ok'); - await loadLineBanner(); - })); - const SOCIALS = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; // video = intro video on the wall, not a social link - function fillProfileDetails(a) { - if (!a) return; - if (a.bio) $('pfBio').value = a.bio; - if (a.avatarUrl) { const p = $('pfAvatarPrev'); p.src = a.avatarUrl; p.hidden = false; } - let soc = {}; try { soc = a.socials ? JSON.parse(a.socials) : {}; } catch (e) {} - for (const p of SOCIALS) if ($('soc-' + p)) $('soc-' + p).value = soc[p] || ''; - if (a.username) { - const link = location.origin + '/wall/' + a.username; - $('pfBioLink').textContent = link; - $('pfViewBio').hidden = false; - $('pfViewBio').href = '/wall/' + a.username; - } - } - let pfAvatar; // pending avatar url - $('pfAvatarBtn').addEventListener('click', () => $('pfAvatarFile').click()); - $('pfAvatarFile').addEventListener('change', async () => { - const f = $('pfAvatarFile').files[0]; - if (!f) return; - $('pfAvatarInfo').textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('pfAvatarInfo').textContent = r.error; $('pfAvatarFile').value = ''; return; } - pfAvatar = r.url; - $('pfAvatarInfo').textContent = 'Uploaded — save to apply.'; - const p = $('pfAvatarPrev'); p.src = r.url; p.hidden = false; - } catch (e) { $('pfAvatarInfo').textContent = 'Upload failed.'; } - $('pfAvatarFile').value = ''; - }); - $('pfDetailsSave').addEventListener('click', busy2($('pfDetailsSave'), async () => { - const body = { bio: $('pfBio').value, socials: {} }; - for (const p of SOCIALS) body.socials[p] = ($('soc-' + p) && $('soc-' + p).value.trim()) || ''; - if (pfAvatar) body.avatarUrl = pfAvatar; - const r = await api('/api/my/profile-details', body); - IAP.status('Profile saved.', 'ok'); - if (r.account) fillProfileDetails(r.account); - })); - $('lbUploadBtn').addEventListener('click', () => $('lbFile').click()); - $('lbFile').addEventListener('change', async () => { - const f = $('lbFile').files[0]; - if (!f) return; - $('lbUpInfo').textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('lbUpInfo').textContent = r.error; $('lbFile').value = ''; return; } - $('lbBanner').value = r.url; - $('lbUpInfo').textContent = 'Uploaded.'; - $('lbPreview').hidden = false; - $('lbPreview').innerHTML = 'line banner'; - } catch (e) { $('lbUpInfo').textContent = 'Upload failed. Try again.'; } - $('lbFile').value = ''; - }); - $('lbSaveBtn').addEventListener('click', busy2($('lbSaveBtn'), async () => { - const r = await api('/api/my/linebanner', { bannerUrl: $('lbBanner').value, targetUrl: $('lbTarget').value }); - IAP.status('Line banner saved. Your next three levels will meet it.', 'ok'); - if (r.account) fillLineBanner(r.account); - })); - - // ── login ad interstitial: after a successful sign-in the sponsor card - // appears; "Open Ad" loads the sponsor's page INSIDE the gate, under our bar - // (countdown, open-in-new-tab, dashboard button), so the timer and the way - // out sit on the ad itself (Brian Holland, 2026-10-09: "no timer, no X"). - // Sites that refuse framing open in a new tab instead, with the bar saying - // so; the timer is not paused, the member is expected to be on the ad. - async function showLoginAd() { - try { - const { ad } = await (await fetch('/api/ads/slot?type=login')).json(); - if (!ad || !ad.targetUrl) return; - const gate = $('loginGate'); - const openBtn = $('lgOpen'); - const goBtn = $('lgContinue'); - const timer = $('lgTimer'); - const frame = $('lgFrame'); - const tab = $('lgOpenTab'); - const body = gate.querySelector('.lgate-body'); - const framed = !!(ad.frameable && frame); - $('lgCreative').innerHTML = ad.imageUrl - ? 'sponsor ad' - : '' + (ad.title ? String(ad.title).replace(/[&<>]/g, '') : 'Visit today\'s sponsor') + ''; - $('lgStatus').textContent = 'Login ad sponsor — click "Open Ad" to begin.'; - const how = $('lgHow'); - if (how) how.textContent = framed - ? 'The sponsor\'s page opens right here under this bar. The timer counts down at the top; when it hits zero, your dashboard button appears beside it.' - : 'This sponsor\'s site does not allow loading inside a frame, so it opens in a new tab. The timer counts down here; come back to this tab when it hits zero for your dashboard button.'; - timer.hidden = true; - goBtn.hidden = true; - if (tab) tab.hidden = true; - if (frame) { frame.hidden = true; frame.src = 'about:blank'; } - if (body) body.hidden = false; - openBtn.disabled = false; - gate.hidden = false; - await new Promise(done => { - openBtn.onclick = () => { - openBtn.disabled = true; - if (framed) { - frame.src = ad.targetUrl; // the click relay counts it, then redirects inside the frame - frame.hidden = false; - if (body) body.hidden = true; - if (tab) { tab.href = ad.siteUrl || ad.targetUrl; tab.hidden = false; } - $('lgStatus').textContent = 'Today\'s sponsor. Have a look; your dashboard button appears when the timer ends.'; - } else { - window.open(ad.targetUrl, '_blank'); // the click relay counts it - $('lgStatus').textContent = 'The sponsor opened in a new tab (that site does not allow framing). View it and come back; the timer runs here.'; - } - let left = ad.dwell || 10; - timer.hidden = false; - timer.textContent = 'Time remaining: ' + left + 's'; - const t = setInterval(() => { - left -= 1; - if (left > 0) { timer.textContent = 'Time remaining: ' + left + 's'; return; } - clearInterval(t); - timer.textContent = 'Time is up'; - timer.classList.add('done'); - $('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.'; - goBtn.hidden = false; - }, 1000); - goBtn.onclick = () => done(); - }; - }); - gate.hidden = true; - if (frame) { frame.src = 'about:blank'; frame.hidden = true; } - if (body) body.hidden = false; - $('lgTimer').classList.remove('done'); - } catch (e) {} - } - - // ── SPONSOR CHAT: two-way threads, presence-aware, with a slide-in drawer ── - let CHAT_ME = null, CHAT_OTHER = null, CHAT_LASTID = 0, CHAT_POLL = null, CHAT_CANMUTE = false, CHAT_IMUTE = false, CHAT_SPONSOR = null, CHAT_LAST_UNREAD = 0; - function chatSync(d) { - CHAT_ME = d.email || CHAT_ME; - CHAT_SPONSOR = (d.sponsor && d.sponsor.email) ? d.sponsor : null; - const link = $('chatMenuBtn'); if (link && link.closest('.bo-links')) link.closest('.bo-links').hidden = !d.email; - setChatBadge(d.chatUnread || 0); - CHAT_LAST_UNREAD = d.chatUnread || 0; - const tog = $('chatAvailToggle'); if (tog) tog.checked = d.chatAvailable !== false; - // Overview quick action + My line card: message-your-sponsor entry points - const qs = $('qaMsgSponsor'); - if (qs) { - if (CHAT_SPONSOR) { qs.hidden = false; qs.dataset.email = CHAT_SPONSOR.email; qs.dataset.name = CHAT_SPONSOR.name || 'your sponsor'; } - else qs.hidden = true; - } - const card = $('sponsorMsgCard'); - if (card) { - card.hidden = !CHAT_SPONSOR; - if (CHAT_SPONSOR && $('sponsorMsgName')) $('sponsorMsgName').textContent = CHAT_SPONSOR.name || 'your sponsor'; - } - } - function setChatBadge(n) { const b = $('chatNavBadge'); if (b) { b.hidden = !n; b.textContent = n > 9 ? '9+' : n; } } - function stopPoll() { if (CHAT_POLL) { clearInterval(CHAT_POLL); CHAT_POLL = null; } } - function startPoll() { stopPoll(); CHAT_POLL = setInterval(() => pullThread(false), 4000); } - // the composer grows with the message up to ~45% of the screen, and keeps any height the member dragged it to (Bradley, 2026-09-13) - function autoGrow(el) { - const cap = Math.max(160, Math.floor(window.innerHeight * 0.45)); - const dragged = Number(el.dataset.dragged || 0); - el.style.height = 'auto'; - el.style.height = Math.min(cap, Math.max(dragged, el.scrollHeight)) + 'px'; - } - function closeDrawer() { stopPoll(); if ($('chatDrawer')) $('chatDrawer').hidden = true; CHAT_OTHER = null; loadDashboard(); } - - async function openThreads() { - const dr = $('chatDrawer'); if (!dr) return; - dr.hidden = false; $('chatConvo').hidden = true; $('chatThreads').hidden = false; - $('chatBack').hidden = true; $('chatMute').hidden = true; $('chatDot').hidden = true; - $('chatTitle').textContent = 'Messages'; $('chatStatus').textContent = ''; - stopPoll(); CHAT_OTHER = null; - $('chatThreads').innerHTML = '

Loading…

'; - try { - const r = await (await fetch('/api/my/chat/threads')).json(); - const list = r.threads || []; - // always offer "message your sponsor" up top when they have one and no thread yet - const hasSponsorThread = CHAT_SPONSOR && list.some(t => t.email === CHAT_SPONSOR.email); - const sponsorRow = (CHAT_SPONSOR && !hasSponsorThread) - ? '
' - + '' - + '
' + esc(CHAT_SPONSOR.name) + '
' - + '
Your sponsor · tap to message
' - : ''; - if (!list.length && !sponsorRow) { $('chatThreads').innerHTML = '
No conversations yet. You can message anyone in your line from “My line”.
'; return; } - $('chatThreads').innerHTML = sponsorRow + list.map(t => - '
' - + '' - + '
' + esc(t.name) + '
' - + '
' + (t.last.fromMe ? 'You: ' : '') + esc((t.last.body || '').slice(0, 64)) + '
' - + (t.unread ? '' + t.unread + '' : '') + '
').join(''); - $('chatThreads').querySelectorAll('.chat-thread').forEach(el => - el.addEventListener('click', () => openConvo(el.dataset.email, el.dataset.name))); - pageList('chat', $('chatThreads'), '.chat-thread'); - } catch (e) { $('chatThreads').innerHTML = '
Could not load messages.
'; } - } - - async function openConvo(email, name) { - if (!email) return; - CHAT_OTHER = email; CHAT_LASTID = 0; - const dr = $('chatDrawer'); if (!dr) return; - dr.hidden = false; $('chatThreads').hidden = true; $('chatConvo').hidden = false; - $('chatBack').hidden = false; $('chatDot').hidden = false; - $('chatTitle').textContent = name || email; $('chatStatus').textContent = '…'; - $('chatMsgs').innerHTML = ''; $('chatBanner').hidden = true; - $('chatInput').disabled = false; $('chatSend').disabled = false; - await pullThread(true); startPoll(); - setTimeout(() => { const i = $('chatInput'); if (i) i.focus(); }, 60); - } - - function renderMsgs(msgs) { - const box = $('chatMsgs'); if (!box) return; - const atBottom = box.scrollTop + box.clientHeight >= box.scrollHeight - 60; - for (const m of msgs) { - if (m.id <= CHAT_LASTID) continue; - CHAT_LASTID = Math.max(CHAT_LASTID, m.id); - const d = document.createElement('div'); - d.className = 'cbub ' + (m.fromMe ? 'me' : 'them'); - d.textContent = m.body; - const t = document.createElement('span'); t.className = 'ct-time'; - t.textContent = new Date(m.sent).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); - d.appendChild(t); box.appendChild(d); - } - if (atBottom) box.scrollTop = box.scrollHeight; - } - - async function pullThread(reset) { - if (!CHAT_OTHER) return; - try { - const r = await (await fetch('/api/my/chat/thread?with=' + encodeURIComponent(CHAT_OTHER) + '&after=' + (reset ? 0 : CHAT_LASTID))).json(); - if (r.error) { $('chatBanner').hidden = false; $('chatBanner').textContent = r.error; return; } - if (reset) { $('chatMsgs').innerHTML = ''; CHAT_LASTID = 0; } - renderMsgs(r.messages || []); - $('chatDot').className = 'pres-dot' + (r.online ? ' on' : ''); - $('chatStatus').textContent = r.online ? 'active now' : (r.available ? 'away · will get your note' : 'not taking live chats · leave a note'); - CHAT_CANMUTE = !!r.canMute; CHAT_IMUTE = !!r.iMute; - const mb = $('chatMute'); mb.hidden = !CHAT_CANMUTE; mb.textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; - const blocked = !!r.blocked; - $('chatInput').disabled = blocked; $('chatSend').disabled = blocked; - if (blocked) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'They are not accepting messages from you right now.'; } - else if (CHAT_IMUTE) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'You muted this member. Unmute to let them message you again.'; } - else $('chatBanner').hidden = true; - } catch (e) {} - } - - async function chatSend() { - const inp = $('chatInput'); if (!inp) return; - const text = inp.value.trim(); if (!text || !CHAT_OTHER) return; - $('chatSend').disabled = true; - try { - const r = await api('/api/my/chat/send', { to: CHAT_OTHER, body: text }); - inp.value = ''; autoGrow(inp); renderMsgs([r.message]); - const box = $('chatMsgs'); box.scrollTop = box.scrollHeight; - } catch (e) { IAP.status(e.message || 'Could not send.', 'bad'); } - finally { $('chatSend').disabled = false; inp.focus(); } - } - - async function toggleMute() { - if (!CHAT_OTHER) return; - try { const r = await api('/api/my/chat/mute', { email: CHAT_OTHER, muted: !CHAT_IMUTE }); CHAT_IMUTE = r.muted; $('chatMute').textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; pullThread(false); } - catch (e) { IAP.status(e.message, 'bad'); } - } - - (function chatInit() { - if (!$('chatDrawer')) return; - const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); }; - on('chatMenuBtn', 'click', e => { if (e && e.preventDefault) e.preventDefault(); openThreads(); }); - on('chatClose', 'click', closeDrawer); - on('chatBack', 'click', openThreads); - on('chatMute', 'click', toggleMute); - on('chatSend', 'click', chatSend); - const inp = $('chatInput'); - if (inp) { - inp.addEventListener('input', () => autoGrow(inp)); - inp.addEventListener('mouseup', () => { const h = inp.getBoundingClientRect().height; inp.dataset.dragged = h > 60 ? String(Math.round(h)) : ''; }); - inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatSend(); } }); - } - on('qaMsgSponsor', 'click', () => { const q = $('qaMsgSponsor'); if (q.dataset.email) openConvo(q.dataset.email, q.dataset.name || 'your sponsor'); }); - on('lineMsgSponsor', 'click', () => { if (CHAT_SPONSOR) openConvo(CHAT_SPONSOR.email, CHAT_SPONSOR.name || 'your sponsor'); }); - on('chatAvailToggle', 'change', async () => { - const t = $('chatAvailToggle'); - try { await api('/api/my/chat/available', { available: t.checked }); IAP.status(t.checked ? 'You are available to chat with your line.' : 'Live chat off. People can still leave you a note.', 'ok'); } - catch (e) { IAP.status(e.message, 'bad'); t.checked = !t.checked; } - }); - // presence heartbeat + new-message notifier: pop + toast when unread rises - setInterval(async () => { - try { - const r = await (await fetch('/api/my/ping')).json(); - const n = r.chatUnread || 0; - if (n > CHAT_LAST_UNREAD) { playSound('pop'); IAP.status('💬 New message from your team.', 'ok'); } - CHAT_LAST_UNREAD = n; setChatBadge(n); - } catch (e) {} - }, 20000); - })(); - - // ad surfaces: a banner greets the sign-in screen; members see live - // banner + text placements inside the back office (they ARE the audience) - IAP.adSlot('banner', 'adSlotLogin'); - IAP.adSlot('banner', 'adSlotOverview'); - IAP.adSlot('banner', 'adSlotSide', { width: 125, height: 125 }); // square button ad in the sidebar - - render(); -})(); - -// ── partner promo codes: typed on the Overview (Marty, 2026-09-12) ── -(function () { - const btn = document.getElementById('promoApply'), inp = document.getElementById('promoCode'), msg = document.getElementById('promoMsg'); - if (!btn || !inp) return; - const say = (t, ok) => { msg.hidden = false; msg.textContent = t; msg.style.color = ok ? 'var(--mint)' : '#ff8a8a'; }; - const go = async () => { - const code = inp.value.trim(); if (!code) { say('Enter a promo code.', false); return; } - btn.disabled = true; - try { - const r = await (await fetch('/api/my/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })).json(); - if (r.error) { say(r.error, false); return; } - say(r.step - ? Number(r.now || 0).toLocaleString() + ' credits added now' + (r.partner ? ' from ' + r.partner : '') + '. The rest of the ' + Number(r.credits).toLocaleString() + ' arrive ' + r.step + ' at a time, one for each day you finish your daily ads, for the next 30 days.' - : 'Added ' + Number(r.credits).toLocaleString() + ' credits' + (r.partner ? ' from ' + r.partner : '') + '. They are in your balance now.', true); - inp.value = ''; if (typeof loadDashboard === 'function') loadDashboard(); - } catch (e) { say('Could not apply that code. Try again.', false); } - finally { btn.disabled = false; } - }; - btn.addEventListener('click', go); inp.addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); -})(); - -// Friday Bonus Hunts card on the Earn tab (2026-09-26). Hoisted so the Earn loader can call it. -async function loadFridayBank() { - const card = document.getElementById('fbankCard'); if (!card) return; - let b; try { const r = await fetch('/api/my/friday-bank', { credentials: 'same-origin' }); if (!r.ok) return; b = await r.json(); } catch (e) { return; } - const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - const wd = d => WD[new Date(d + 'T12:00:00Z').getUTCDay()]; - document.getElementById('fbankCount').textContent = b.banked + ' banked'; - document.getElementById('fbankDays').innerHTML = (b.days || []).map(d => { - const st = d.banked ? ['#43e8c3', '✓'] : d.future ? ['var(--line-strong)', '·'] : d.day === b.today ? ['#ffb238', '○'] : ['var(--line-strong)', '×']; - return '' + st[1] + '' + wd(d.day) + ''; - }).join('') + 'Fri: +' + b.banked + ' hunts'; - const t = (b.days || []).find(d => d.day === b.today); - let msg = ''; - if (b.isFriday) msg = b.banked ? 'It\'s Friday. Your ' + b.banked + ' banked hunt' + (b.banked === 1 ? '' : 's') + ' are live on PolHunter today.' : 'It\'s Friday. Bank hunts Saturday through Thursday for next Friday.'; - else if (t && t.banked) msg = '✓ Today is banked. Come back tomorrow to bank another.'; - else if (t && t.video && t.soloNeeded && !t.solo) msg = '✓ Video watched. Not banked yet: an inbox ad is waiting for you today, and a day only counts once it is opened. Open the inbox ad and today is banked. (On days when nothing is waiting in your inbox, the video alone counts, which is why some days banked without one.)'; - else if (t) msg = 'To bank today: ' + (t.video ? '✓ video watched' : 'watch one video') + (t.soloNeeded ? ' and ' + (t.solo ? '✓ inbox ad opened' : 'open one inbox ad') : ' (no inbox ad waiting, so the video alone counts)') + '.'; - const el = document.getElementById('fbankToday'); el.innerHTML = msg; - el.querySelectorAll('[data-earn-go]').forEach(a => a.addEventListener('click', ev => { ev.preventDefault(); const tab = document.querySelector('[data-earn="' + a.dataset.earnGo + '"]'); if (tab) tab.click(); })); - card.hidden = false; -} +// member share links go out on the share domain (2026-10-20): https://ctbgo.com/ -> /join/ on InstantAdPay. +// The domain comes from site config (shareDomain); empty falls back to this site's own /join link. +let SHARE_DOMAIN = ''; +const SHARE_READY = fetch('/api/config').then(r => r.json()).then(c => { SHARE_DOMAIN = String((c && c.shareDomain) || '').trim(); }).catch(() => {}); +function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(String(ref)) ? 'https://' + SHARE_DOMAIN + '/' + ref : location.origin + '/join/' + ref; } +// My account: email-first join/login, wallet link at purchase time, +// free payout activation, invite link, on-chain activity. +(async function () { + // back-office shell: no marketing nav here; rehearsal notice lives in the top bar + const $ = IAP.$; + // dwell timers pause when the tab is away; a focused ad frame or a touch device counts as active (phones never report hasFocus reliably) + const tabActive = () => document.visibilityState === 'visible' && (document.hasFocus() || !!(document.activeElement && document.activeElement.tagName === 'IFRAME') || (window.matchMedia && window.matchMedia('(pointer: coarse)').matches)); + try { + const c = await IAP.getConfig(); + if (c.rehearsal && $('boRehearsal')) { + $('boRehearsal').hidden = false; + $('boRehearsal').innerHTML = 'Testnet rehearsal · ' + c.chainName; + } + if (c.rehearsal && $('faucetCard')) $('faucetCard').hidden = false; + } catch (e) {} + // if they arrived through a sponsor's link, show who they're joining under + (async () => { + try { + const sp = await (await fetch('/api/sponsor?intent=view')).json(); // display only: never an alert + if (sp && sp.invited && sp.name && $('sponsorNote')) { $('sponsorNoteName').textContent = sp.name; $('sponsorNote').hidden = false; } + } catch (e) {} + })(); + + async function api(path, body) { + const r = await (await fetch(path, { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); + if (r.error) { const e = new Error(r.error); e.data = r; throw e; } // e.data: the full answer (e.g. top-up switch options) + return r; + } + + function nextMove(d) { + if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.'; + if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.'; + if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $20 or more. Every direct pays you 50 percent from their very first package.'; + if (d.buyerCount === 1) return 'One qualifying buyer down, one to go. Your next $20+ buyer unlocks level 2: 20 percent of everything your people’s people buy.'; + if (d.buyerCount < 5) return 'Level 2 is open. ' + (5 - d.buyerCount) + ' more qualifying buyer(s) unlock level 3 and the full three-level flow.'; + return 'Fully qualified. Every level pays you, and you catch the pass-ups that under-qualified positions below you let slip. Keep sharing and keep your campaigns running.'; + } + // featured rotation strip on the overview + let featItems = [], featIdx = 0, featTimer = null; + function renderOneFeatured() { + if (!featItems.length) return; + const i = featItems[featIdx % featItems.length]; + $('featStrip').innerHTML = '' + esc(i.title) + '' + + (i.by ? '' + esc(i.by) + '' : '') + ''; + } + async function loadFeatured() { + try { + const r = await (await fetch('/api/featured')).json(); + const card = $('featuredCard'); if (!card) return; + if (!r.items || !r.items.length) { card.hidden = true; return; } + card.hidden = false; + featItems = r.items; featIdx = Math.floor(Math.random() * featItems.length); + $('featSub').textContent = r.items.length + ' link' + (r.items.length === 1 ? '' : 's') + ' in rotation'; + renderOneFeatured(); // show ONE at a time (true rotation), cycle if more than one + clearInterval(featTimer); + if (featItems.length > 1) featTimer = setInterval(() => { featIdx++; renderOneFeatured(); }, 6000); + // self-sell: today's open slots + a CTA to feature your own link + try { + const st = await (await fetch('/api/featured/stats')).json(); + const today = (st.occupancy || []).find(d => d.offset === 0); + const cta = $('featCta'); + if (cta) { + cta.innerHTML = (today ? '' + today.open + ' of ' + today.cap + ' featured slots open today. ' : '') + + 'Feature your link →'; + const fb = $('featBuy'); + if (fb) fb.addEventListener('click', e => { e.preventDefault(); setPane('campaigns'); const ct = $('cType'); if (ct) { ct.value = 'featured'; ct.dispatchEvent(new Event('change')); } }); + } + } catch (e) {} + } catch (e) {} + } + + // achievement badges: the milestone ladder as unlockable medals + share-to-image + const BADGES = [ // ribbonY = vertical center of each badge's name ribbon (art differs per tier) + { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.728 }, + { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 }, + { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 }, + { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 }, + { key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 }, + { key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 } + ]; + let lastMilestones = []; + function renderBadges(d) { + const reached = d.milestonesReached || []; + lastMilestones = reached; + const strip = $('badgeStrip'); + if (!strip) return; + $('badgeCard').hidden = false; + strip.innerHTML = BADGES.map(b => { + const got = reached.includes(b.key); + return '
' + + '' + b.label + ' badge' + + '
' + b.label + '
' + b.sub + '
' + + (got ? ' ' : '
🔒 locked
') + '
'; + }).join(''); + strip.querySelectorAll('[data-badge]').forEach(btn => + btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d))); + strip.querySelectorAll('[data-badgepost]').forEach(btn => + btn.addEventListener('click', () => postBadge(btn.dataset.badgepost, d, btn, true))); + fetch('/api/my/badge-posted').then(r => r.json()).then(r => { // the manual button is the admin's only (Marty, 2026-09-13) + if (r.canPost) strip.querySelectorAll('[data-badgepost]').forEach(b => { b.hidden = false; }); + (r.posted || []).forEach(k => { const b = strip.querySelector('[data-badgepost="' + k + '"]'); if (b) { b.textContent = 'Posted ✓'; b.disabled = true; } }); + }).catch(() => {}); + // celebrate anything newly granted this load, and post the branded badge to the team channels (Marty, 2026-09-13) + if (d.milestonesGranted && d.milestonesGranted.length) { + const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0); + const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', '); + IAP.status('🏆 Achievement unlocked: ' + names + ' — +' + total + ' bonus credits!', 'ok'); + d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500)); + } + } + // draw the badge with the member's name on the ribbon; cb(canvas) or cb(null) + function composeBadge(key, d, cb) { + const b = BADGES.find(x => x.key === key); if (!b) return cb(null); + const who = d.username ? d.username : d.memberId ? 'member #' + d.memberId : ''; + const img = new Image(); + img.onload = () => { + const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; + const x = c.getContext('2d'); + x.drawImage(img, 0, 0); + if (who) { + x.textAlign = 'center'; x.textBaseline = 'middle'; + x.font = 'bold ' + Math.round(c.width * 0.055) + 'px Sora, "Segoe UI", sans-serif'; + const y = c.height * (b.ribbonY || 0.75); + x.lineJoin = 'round'; x.lineWidth = Math.max(3, Math.round(c.width * 0.008)); + x.strokeStyle = 'rgba(4,20,15,.9)'; x.strokeText(who, c.width / 2, y); + x.fillStyle = '#ffd15c'; x.fillText(who, c.width / 2, y); + } + cb(c); + }; + img.onerror = () => cb(null); + img.src = b.img; + } + async function postBadge(key, d, btn, manual) { + if (btn && btn.disabled) return; + if (btn) { btn.disabled = true; btn.textContent = 'Posting…'; } + composeBadge(key, d, c => { + if (!c) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } return; } + c.toBlob(async bl => { + try { + const r = await (await fetch('/api/my/badge-post?key=' + encodeURIComponent(key) + (manual ? '&manual=1' : ''), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); + if (r.error) throw new Error(r.error); + if (btn) { btn.textContent = 'Posted ✓'; btn.disabled = true; } + if (!r.already) IAP.status('Your badge is posted in the team channels.', 'ok'); + } catch (e) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } IAP.status(e.message || 'Could not post the badge.', 'bad'); } + }, 'image/jpeg', 0.86); + }); + } + // Share: a picker (Marty, 2026-09-13). The composed badge is stored once so a public page at + // /b// carries it as the preview image; every network gets that link. + function shareBadge(key, d) { + const b = BADGES.find(x => x.key === key); if (!b) return; + if (!d.username) { IAP.status('Pick a username first; your share page carries it.', 'bad'); return; } + IAP.status('Preparing your ' + b.label + ' badge…', 'ok'); + composeBadge(key, d, c => { + if (!c) { IAP.status('Could not load the badge art.', 'bad'); return; } + c.toBlob(async bl => { + let page = null; + try { const r = await (await fetch('/api/my/badge-image?key=' + encodeURIComponent(key), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); if (r.error) throw new Error(r.error); page = r.page; } + catch (e) { IAP.status(e.message || 'Could not prepare the share page.', 'bad'); return; } + openShareSheet(b, d, bl, page); + }, 'image/jpeg', 0.9); + }); + } + function openShareSheet(b, d, blob, page) { + const text = 'I just unlocked the ' + b.label + ' badge on InstantAdPay (' + b.sub + '). Advertising that pays you back, on-chain, the same second a package sells.'; + const enc = encodeURIComponent; + const links = [ + ['X', 'https://x.com/intent/tweet?text=' + enc(text) + '&url=' + enc(page)], + ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc(page)], + ['Telegram', 'https://t.me/share/url?url=' + enc(page) + '&text=' + enc(text)], + ['WhatsApp', 'https://wa.me/?text=' + enc(text + ' ' + page)], + ['LinkedIn', 'https://www.linkedin.com/sharing/share-offsite/?url=' + enc(page)] + ]; + const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200'; + back.innerHTML = ''; + document.body.appendChild(back); + const close = () => back.remove(); + back.addEventListener('click', e => { if (e.target === back) close(); }); + back.querySelector('[data-sh="close"]').addEventListener('click', close); + back.querySelector('[data-sh="copy"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(page); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy this: ' + page, 'ok'); } }); + back.querySelector('[data-sh="save"]').addEventListener('click', () => { + const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); + IAP.status('Your ' + b.label + ' badge is saved.', 'ok'); + }); + // Massifly has no share intent: copy the post text + link, then open the feed composer (Marty, 2026-09-13) + back.querySelector('[data-sh="massifly"]').addEventListener('click', async () => { + try { await navigator.clipboard.writeText(text + ' ' + page); IAP.status('Post copied. Paste it into the Massifly composer; the badge preview appears from the link.', 'ok'); } + catch (e) { IAP.status('Copy this into Massifly: ' + text + ' ' + page, 'ok'); } + window.open('https://massifly.com/account', '_blank', 'noopener'); + }); + const nat = back.querySelector('[data-sh="native"]'); + if (nat) nat.addEventListener('click', async () => { + try { + const file = new File([blob], 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg', { type: 'image/jpeg' }); + if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: b.label + ' badge', text: text + ' ' + page }); + else await navigator.share({ title: b.label + ' badge', text, url: page }); + } catch (e) {} + }); + } + + // milestone stepper under "Your next move": lit nodes for what's done, + // amber glow on the current target — the same ladder the contract pays + function renderSteps(d) { + const el = $('ncSteps'); + if (!el) return; + const b = d.buyerCount || 0; + const steps = [ + { label: 'Joined', sub: 'free account', hit: true }, + { label: 'Spark', sub: 'payouts on', hit: !!d.memberId }, + { label: 'Surge', sub: 'first buyer · 50%', hit: b >= 1 }, + { label: 'Circuit', sub: '2 buyers · +20%', hit: b >= 2 }, + { label: 'Nexus', sub: '5 buyers · +10%', hit: b >= 5 } + ]; + const cur = steps.findIndex(s => !s.hit); + el.innerHTML = steps.map((s, i) => + '
' + + '' + (s.hit ? '✓' : i + 1) + '' + + '' + s.label + '' + s.sub + '
').join(''); + } + // ── overview v3 charts: hand-rolled SVG/CSS, real data only ── + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + + // Paged lists (Marty, 2026-09-19): 25 rows, then a clearly marked next page, on every list + // that grows with the membership. Works on what is already rendered: rows past the page are + // hidden and a control bar goes under the list, so a row's buttons and bindings never change. + // key remembers the page across re-renders of the same list + // host the element the bar is appended to (a wrapper, never a ) + // rowSel the rows, queried inside host + // opts per (default 25); tail: a selector for a drawer that follows its row and pages + // with it; focus: a row predicate, opens on whichever page holds that row + const PAGE_SIZE = 25; + // My line is the longest page on the dashboard: its lists page at 10 (Marty, 2026-09-26) + const LINE_PER = 10; + // Sortable + filterable member lists (Marty, 2026-09-29): the holding tank, "Your line" and the three-level + // downline share one toolbar. Every row carries joined, last seen, surf earnings and wallet/payout state so a + // sponsor can spot "joined days ago, signed in today, earning on their own, wallet linked but payouts off". + const LIST_UI = {}; + const dayStart = () => { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); }; + const activeToday = m => (m.lastSeen || 0) >= dayStart(); + const LIST_SORTS = [ + { k: 'seen', label: 'Last seen', v: m => m.lastSeen || 0 }, + { k: 'joined', label: 'Joined', v: m => m.joined || 0 }, + { k: 'earned', label: 'Surf earnings', v: m => m.earned || 0 }, + { k: 'balance', label: 'Earned balance', v: m => m.balance || 0 }, + { k: 'name', label: 'Name', v: m => String(m.name || '').toLowerCase(), str: true }, + ]; + const LIST_FILTERS = [ + { k: 'today', label: 'Active today', t: m => activeToday(m) }, + { k: 'earning', label: 'Earning', t: m => (m.earned || 0) > 0 }, + { k: 'wallet', label: 'Wallet linked', t: m => !!m.wallet }, + { k: 'nopay', label: 'Wallet, payouts off', t: m => !!m.wallet && !m.activated }, + { k: 'payouts', label: 'Payouts on', t: m => !!m.activated }, + { k: 'nowallet', label: 'No wallet', t: m => !m.wallet }, + ]; + const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set() }); + function listApply(key, rows) { + const st = listState(key); const s = LIST_SORTS.find(x => x.k === st.sort) || LIST_SORTS[0]; + const out = (rows || []).filter(m => m.own || [...st.on].every(k => { const f = LIST_FILTERS.find(x => x.k === k); return !f || f.t(m); })); + out.sort((a, b) => { const x = s.v(a), y = s.v(b); return (s.str ? String(x).localeCompare(String(y)) : x - y) * st.dir; }); + return out; + } + function listBar(key, total, shown, rerender, opts) { + const st = listState(key); const hide = (opts && opts.hide) || []; + const bar = document.createElement('div'); bar.className = 'lst-bar'; + bar.innerHTML = '' + + '' + + '' + LIST_FILTERS.filter(f => !hide.includes(f.k)).map(f => '').join('') + '' + + '' + (shown === total ? total + (total === 1 ? ' person' : ' people') : shown + ' of ' + total) + ''; + bar.querySelector('select').addEventListener('change', e => { st.sort = e.target.value; st.dir = st.sort === 'name' ? 1 : -1; rerender(); }); + bar.querySelector('.lst-dir').addEventListener('click', () => { st.dir = -st.dir; rerender(); }); + bar.querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (st.on.has(k)) st.on.delete(k); else st.on.add(k); rerender(); })); + return bar; + } + const seenAgo = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; const days = Math.floor(d / 86400e3); return days === 1 ? 'yesterday' : days + ' days ago'; }; + const seenChip = m => m.lastSeen ? '' + (activeToday(m) ? 'active today' : 'seen ' + seenAgo(m.lastSeen)) + '' : 'never signed in'; + const earnChip = m => '' + (m.earned || 0).toLocaleString() + ' cr earned'; + const walletChip = m => m.activated ? 'wallet · payouts on' : m.wallet ? 'wallet · payouts off' : 'no wallet'; + const memberChips = m => seenChip(m) + ' ' + earnChip(m) + ' ' + walletChip(m); + // Section pills at the top of My line: one per visible card marked data-jump, the one in view lit up. + // Cards that show or hide themselves (sponsor, upline messages) rebuild the row when they change. + let lineJumpObs = null; + function buildLineJump() { + const nav = document.getElementById('lineJump'); const pane = document.getElementById('pane-line'); if (!nav || !pane) return; + const cards = [...pane.querySelectorAll(':scope > .card[data-jump]')].filter(c => !c.hidden); + nav.innerHTML = cards.map(c => '').join(''); + nav.hidden = cards.length < 2; + const top = document.querySelector('.bo-top'); nav.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); pane.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); + nav.querySelectorAll('[data-jumpto]').forEach(b => b.addEventListener('click', () => { + const c = document.getElementById(b.dataset.jumpto); if (!c) return; + c.scrollIntoView({ behavior: 'smooth', block: 'start' }); + nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x === b)); + })); + if (lineJumpObs) lineJumpObs.disconnect(); + if ('IntersectionObserver' in window) { + const seen = new Map(); + lineJumpObs = new IntersectionObserver(ents => { + for (const e of ents) seen.set(e.target.id, e.isIntersecting ? e.boundingClientRect.top : null); + let best = null; for (const [id, t] of seen) if (t != null && (best == null || t < seen.get(best))) best = id; + if (best) { nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x.dataset.jumpto === best)); const on = nav.querySelector('.chip-t.on'); if (on && nav.scrollWidth > nav.clientWidth) nav.scrollLeft = on.offsetLeft - 16; } + }, { rootMargin: '-120px 0px -55% 0px' }); + cards.forEach(c => lineJumpObs.observe(c)); + } + } + { const pane = document.getElementById('pane-line'); + if (pane && 'MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(pane, { subtree: false, childList: false, attributes: true, attributeFilter: ['hidden'] }); + if (pane) pane.querySelectorAll(':scope > .card[data-jump]').forEach(c => { if ('MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(c, { attributes: true, attributeFilter: ['hidden'] }); }); } + const PAGE_AT = {}; + function pageList(key, host, rowSel, opts) { + if (!host) return; opts = opts || {}; const per = opts.per || PAGE_SIZE; + const rows = [...host.querySelectorAll(rowSel)]; + const old = host.querySelector(':scope > .pgr'); if (old) old.remove(); + if (rows.length <= per) { rows.forEach(r => { r.hidden = false; }); return; } + const pages = Math.ceil(rows.length / per); + let p = PAGE_AT[key] || 1; + if (opts.focus) { const i = rows.findIndex(opts.focus); if (i >= 0) p = Math.floor(i / per) + 1; } + p = Math.min(Math.max(1, p), pages); PAGE_AT[key] = p; + const start = (p - 1) * per; + rows.forEach((r, i) => { + const on = i >= start && i < start + per; r.hidden = !on; + if (opts.tail) { const t = r.nextElementSibling; if (t && t.matches(opts.tail) && !on && !t.hidden) { t.hidden = true; const b = r.querySelector('[aria-expanded]'); if (b) { b.setAttribute('aria-expanded', 'false'); b.textContent = 'Activity \u25BE'; } } } + }); + const bar = document.createElement('div'); bar.className = 'pgr'; + bar.innerHTML = 'Showing ' + (start + 1) + '\u2013' + Math.min(start + per, rows.length) + ' of ' + rows.length + '' + + '' + + 'Page ' + p + ' of ' + pages + '' + + ''; + bar.querySelectorAll('[data-go]').forEach(b => b.addEventListener('click', () => { + PAGE_AT[key] = Number(b.dataset.go); + pageList(key, host, rowSel, Object.assign({}, opts, { focus: null })); + host.scrollIntoView({ behavior: 'smooth', block: 'start' }); + })); + host.appendChild(bar); + } + const CH = { mint: '#43e8c3', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }; + function bars(el, xel, data) { // data: [{v,label,tip,alt}] + if (!el) return; + const max = Math.max(1, ...data.map(d => d.v)); + el.innerHTML = data.length + ? data.map(d => '
').join('') + : '
'.repeat(8); + if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join(''); + } + function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100 + if (!el) return; + const total = segs.reduce((s, x) => s + x.v, 0); + let off = 25, out = ''; + if (total > 0) for (const s of segs) { + const len = s.v / total * 100; + if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; } + out += ''; + off -= len; + } + out += '' + esc(center.big) + '' + + '' + esc(center.small) + ''; + el.innerHTML = out; + } + function legend(el, rows) { + if (el) el.innerHTML = rows.map(r => '
' + + esc(r.label) + ' ' + esc(r.v) + '
').join(''); + } + async function loadCharts(d) { + // credit composition donut + today's viewing ring (live balances) + try { + const st = await (await fetch('/api/my/earn')).json(); + if (!st.error) { + // one rule: a balance is what is NOT committed to a live campaign. Budgets are + // set aside when a campaign starts and spend down inside Campaigns, so these + // numbers only move when a campaign is created, topped up or paused + const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0; + $('dbCredits').textContent = (purchased + earned).toLocaleString(); + // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13) + if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned'; + $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (d.earnedReserved ? ' (+' + d.earnedReserved.toLocaleString() + ' earned and bonus credits working in your live campaigns)' : '') + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : ''); + donut($('chDonut'), + [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }], + { big: (purchased + earned).toLocaleString(), small: 'available' }); + legend($('chDonutLegend'), [ + { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() }, + { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() }, + { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]); + const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done); + donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }], + { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' }); + legend($('chRingLegend'), [ + { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done }, + { color: CH.track, label: 'To go', v: left }, + { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]); + } + } catch (e) {} + // recent on-chain payouts, sized to scale, oldest→newest + try { + let evs = []; + if (d.memberId) { + const a = await (await fetch('/api/my/activity')).json(); + evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12); + } + bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({ + v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6, + label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1), + tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' }))); + if (!evs.length) $('chEarnSub').textContent = d.memberId + ? 'no payouts yet — share your link' : 'activate a package to start earning'; + } catch (e) {} + // campaign delivery: impressions per campaign + try { + const r = await (await fetch('/api/my/campaigns')).json(); + const cs = (r.campaigns || []).slice(0, 8); + bars($('chCampBars'), $('chCampX'), cs.map(c => ({ + v: c.imps || 0, label: String(c.name || c.type).slice(0, 9), + tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks', + alt: c.type === 'text' }))); + if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad'; + } catch (e) {} + } + // ── live updates: subscribe to the chain event stream so the members area + // reacts to on-chain changes (payouts, qualifications) without a refresh ── + let MYID = 0; + // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message. + function playSound(kind) { + try { + const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; + const ctx = window.__iapAC || (window.__iapAC = new AC()); + if (ctx.state === 'suspended') ctx.resume(); + const now = ctx.currentTime; + const tone = (freq, at, dur, type, peak) => { + const o = ctx.createOscillator(), g = ctx.createGain(); + o.type = type || 'sine'; o.frequency.value = freq; + g.gain.setValueAtTime(0.0001, now + at); + g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02); + g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur); + o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02); + }; + if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); } + else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); } + } catch (e) {} + } + function startLiveFeed() { + if (window.__iapFeed || !window.EventSource) return; + try { + const es = new EventSource('/api/feed/live'); + window.__iapFeed = es; + es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); }; + // browser auto-reconnects on error; nothing to do + } catch (e) {} + } + let liveRefreshT = null; + function liveRefresh() { // debounce a burst of events into one refresh + clearTimeout(liveRefreshT); + liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600); + } + // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins, + // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so + // they never replace a personal one. At most one every 4 s; a burst shows the latest. + let liveT = 0, liveQ = null; + function communityToast(msg) { + const now = Date.now(); + if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; } + liveT = now; + let el = document.getElementById('liveToast'); + if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); } + el.textContent = msg; el.hidden = false; el.style.opacity = '1'; + clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000); + } + function handleLiveEvent(ev) { + if (!ev || !ev.type) return; + const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id; + // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications + if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; } + if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; } + if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; } + if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; } + if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; } + const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID); + if (!mine) { + if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package'); + else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL'); + else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's')); + else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts'); + return; + } + if (!MYID) return; + let toast = null, kind = 'ok'; + let sound = null; + if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } + else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } + else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!'; + else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; } + else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.'; + else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!'; + if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); } + } + + // training center: videos + materials (admin-curated via data/training.json) + async function loadTraining() { + try { + const r = await (await fetch('/api/training')).json(); + const el = $('trainingList'); if (!el) return; + const items = r.items || []; + if (!items.length) { el.innerHTML = '

Training materials are being added. Check back soon.

'; return; } + // section pills at the top: one per group, plus All; the active pill filters the list + const groups = [...new Set(items.map(it => it.group).filter(Boolean))]; + const pills = $('trainingPills'); + const want = loadTraining.filter || 'all'; + if (pills) { + pills.hidden = groups.length < 2; + pills.innerHTML = ['all', ...groups].map(g => '').join(''); + pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); })); + } + const shown = want === 'all' ? items : items.filter(it => it.group === want); + let lastGroup = null; + el.innerHTML = shown.map(it => { + // optional section header: entries carry a `group`; a header renders when it changes + let head = ''; + if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '

' + esc(it.group) + '

'; } + const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl); + // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both) + const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : ''); + const media = isVid ? '' : ''; + const links = []; + if (it.videoUrl && !isVid) links.push('Watch'); + if (it.docUrl) links.push('' + esc(it.docLabel || 'Open material') + ''); + return head + '

' + esc(it.title || 'Lesson') + '

' + + (it.desc ? '

' + esc(it.desc) + '

' : '') + + (media ? '

' + media + '

' : '') + + (links.length ? '

' + links.join(' ') + '

' : '') + '
'; + }).join(''); + } catch (e) {} + } + // visual line tree on the Overview: YOU + three levels, qualified directs in gold + function renderRoster(wrap, all) { + const rows = listApply('roster', all); + wrap.querySelectorAll(':scope > .lst-bar, :scope > table, :scope > .pgr, :scope > .lst-none').forEach(n => n.remove()); + wrap.appendChild(listBar('roster', all.length, rows.length, () => renderRoster(wrap, all))); + if (!rows.length) { wrap.insertAdjacentHTML('beforeend', '

Nobody in your line matches those filters.

'); return; } + const t = document.createElement('table'); t.className = 'roster'; + t.innerHTML = rows.map(r => '' + + '' + + '' + + '').join(''); + wrap.appendChild(t); + pageList('roster', wrap, 'table.roster tr', { per: LINE_PER }); + } + async function loadLineTree(buyerCount) { + try { + const r = await (await fetch('/api/my/line')).json(); + const el = $('lineTree'); if (!el) return; + const levels = r.levels || []; + const total = levels.reduce((n, L) => n + L.members.length, 0); + if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow'; + const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + ''; + const rowFor = lvl => { + const L = levels.find(x => x.level === lvl); const members = L ? L.members : []; + // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips") + let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $20+ buy + if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open'; + if (!html) html = '+ open'; + return '
L' + lvl + '
' + html + '
'; + }; + el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3); + // click a chip to drill down: My line opens with that person's Activity panel expanded (Marty, 2026-09-15) + const go = ref => { LINE_FOCUS_REF = ref; setPane('line'); }; + el.querySelectorAll('[data-goref]').forEach(n => { + n.addEventListener('click', () => go(n.dataset.goref)); + n.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(n.dataset.goref); } }); + }); + } catch (e) {} + } + let LINE_FOCUS_REF = null; // set by an Overview chip click; consumed once My line has rendered + // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14) + let newsLoaded = false; + async function loadNews() { + if (newsLoaded || !$('newsCard')) return; newsLoaded = true; + try { + const r = await (await fetch('/api/releases')).json(); + if (!r.notes.length && !r.roadmap.length) return; + let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {} + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const notes = r.notes.slice(0, 3).map(n => '

' + (n.date > seen ? '● ' : '') + '' + esc(n.title) + ' ' + esc(n.date) + '

').join(''); + const rm = r.roadmap.filter(x => x.status === 'building').slice(0, 2).map(x => '

Building: ' + esc(x.title) + (x.eta ? ' (' + esc(x.eta) + ')' : '') + '

').join(''); + $('newsList').innerHTML = notes + rm + '

All release notes and the roadmap →

'; + $('newsCard').hidden = false; + $('newsCard').addEventListener('click', () => { try { localStorage.setItem('iap.news.seen', r.latest || ''); } catch (e) {} $('newsList').querySelectorAll('span[style*="mint"]').forEach(s => { if (s.textContent === '●') s.remove(); }); }, { once: true }); + } catch (e) {} + } + // Leaderboard card: top 5 this week + your own rank + the prize (Marty, 2026-09-14) + async function loadLeaderboard() { + if (!$('lbCard')) return; + try { + const r = await (await fetch('/api/leaderboard?period=week')).json(); + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + let h = r.prize ? '

Prize this week: ' + esc(r.prize) + '

' : ''; + h += r.top.length ? '
' + esc(r.name || r.email || '') + 'joined ' + new Date(r.joined).toLocaleDateString() + '' + memberChips(r) + '' + esc(r.status) + '
' + r.top.slice(0, 5).map(x => '').join('') + '
' + x.rank + '' + esc(x.name) + '' + x.sales + ' sold · $' + x.usd + '
' + : '

No packages sold yet this week. First sale takes the top spot.

'; + h += r.me ? '

You: #' + r.me.rank + ' · ' + r.me.sales + ' sold · $' + r.me.usd + '

' : '

You: no sales yet this week. Sales are $20+ packages bought by people you sponsor.

'; + h += '

Full leaderboard: week, month, all time →

'; + $('lbList').innerHTML = h; $('lbCard').hidden = false; + } catch (e) {} + } + // Getting-started stepper: username -> wallet -> payouts -> first package. The current step gets one big + // button that opens the right tab and pulses the control (Jim: "it wasn't obvious", 2026-09-14) + function renderSteps(d) { + const card = $('gsCard'); if (!card) return; + const hasUser = !!d.username, hasWallet = !!d.address, hasPayouts = !!d.memberId, hasPackage = !!(d.memberId && (d.credits || 0) > 0); + const steps = [ + { k: 'user', t: 'Pick a username', done: hasUser }, + { k: 'wallet', t: 'Link your wallet', done: hasWallet }, + { k: 'payouts', t: 'Switch on payouts', done: hasPayouts }, + { k: 'package', t: 'Your first package', done: hasPackage } + ]; + if (steps.every(x => x.done)) { card.hidden = true; return; } + const cur = steps.find(x => !x.done); + let collapsed = false; try { collapsed = localStorage.getItem('iap.gs.collapsed') === '1'; } catch (e) {} + $('gsSub').innerHTML = steps.filter(x => x.done).length + ' of 4 done · ' + (collapsed ? 'show' : 'hide') + ''; + $('gsToggle').addEventListener('click', e => { e.preventDefault(); try { localStorage.setItem('iap.gs.collapsed', collapsed ? '0' : '1'); } catch (er) {} renderSteps(d); }); + $('gsSteps').hidden = collapsed; $('gsNow').hidden = collapsed; + $('gsSteps').innerHTML = steps.map((x, i) => '
' + (x.done ? '✓' : i + 1) + '' + x.t + '
').join(''); + const copy = { + user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)], + wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')], + payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')], + package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)] + }[cur.k]; + $('gsNow').innerHTML = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; + $('gsGo').addEventListener('click', copy[3]); + card.hidden = false; + } + // member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=#buy. + // We remember the game (through sign-in), tell the server once, and show the offer + the way back to the perk. + try { const fm = /[?&]from=([a-z]{3,20})/.exec(location.search); if (fm) { sessionStorage.setItem('iap.starterFrom', fm[1]); history.replaceState(null, '', '/my' + (location.hash || '')); } } catch (e) {} + async function starterBanner(me) { + let from = null; try { from = sessionStorage.getItem('iap.starterFrom'); } catch (e) {} + let v = null; + if (from) { try { sessionStorage.removeItem('iap.starterFrom'); } catch (e) {} v = await (await fetch('/api/starter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ game: from }) })).json(); } + else v = await (await fetch('/api/starter')).json(); + if (!v || !v.on || !v.game) return; + const pane = document.querySelector('#pane-buy .card'); if (!pane) return; + let box = document.getElementById('starterBox'); if (!box) { box = document.createElement('div'); box.id = 'starterBox'; pane.insertBefore(box, pane.children[1] || null); } + const esc = t => String(t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + box.style.cssText = 'border:1px solid var(--gold, #e2b04a);border-radius:12px;padding:12px 14px;margin:0 0 14px;background:rgba(226,176,74,.08)'; + box.innerHTML = v.eligible + ? 'Welcome from ' + esc(v.game) + '!
Your first package, $5 or more, comes with +' + v.bonus + ' bonus ad credits, and ' + esc(v.perk) + ' waiting for you in ' + esc(v.game) + '.' + : 'You are a member. ' + (v.granted ? 'Your +' + v.bonus + ' welcome credits are in your balance. ' : '') + 'Your ' + esc(v.perk) + ' is waiting in ' + esc(v.game) + '.
Back to ' + esc(v.game) + ' to collect it'; + if (from && !/^#(passes|games)/.test(location.hash)) setPane('buy'); // a game's Buy-a-pass link (#passes) stays on the pass card + } + function jumpTo(pane, id) { + setPane(pane); + setTimeout(() => { const el = id && $(id); if (!el) return; el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.remove('pulse'); void el.offsetWidth; el.classList.add('pulse'); try { el.focus({ preventScroll: true }); } catch (e) {} }, 250); + } + async function loadDashboard() { + try { + loadNews(); loadLeaderboard(); + const d = await (await fetch('/api/my/dashboard')).json(); + if (d.error) return; + chatSync(d); + try { renderSteps(d); } catch (e) {} + MYID = d.memberId || MYID; + startLiveFeed(); + if (!window.__lbChecked) { // daily login bonus, once per session (server guards once/day) + window.__lbChecked = true; + api('/api/my/login-bonus').then(r => { + if (r && r.comeback > 0) { IAP.status('🎉 Welcome back! +' + r.comeback + ' bonus credits for coming back, plus +' + r.granted + ' for signing in today.', 'ok'); playSound('chaching'); setTimeout(loadDashboard, 900); } + else if (r && r.granted > 0) { + IAP.status('🎁 Daily login bonus: +' + r.granted + ' credits' + (r.streak > 1 ? ' · ' + r.streak + '-day streak' : '') + '!', 'ok'); + playSound('chaching'); setTimeout(loadDashboard, 900); + } + }).catch(() => {}); + } + const earnedAv = d.earnedCredits || 0, inCamp = d.inCampaigns || 0; + $('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString(); + $('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : ''); + $('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0'); + usdRate().then(r => { const el = $('dbEarnedUsd'); if (el) el.textContent = r.usd > 0 && d.earnedWei && d.earnedWei !== '0' ? usdOf(d.earnedWei, r) + ' today' : ''; }); + $('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; } + $('dbTeam').textContent = (d.referrals || []).length; + // trend chips: only real, computable facts + const ec = $('dbEarnedChip'); + if (ec && d.earnCount) { ec.hidden = false; ec.textContent = d.earnCount + ' instant payout' + (d.earnCount > 1 ? 's' : ''); } + const bc = $('dbBuyersChip'); + if (bc && d.memberId) { + bc.hidden = false; + bc.textContent = (d.buyerCount || 0) >= 5 ? 'level 3 open' : (d.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'; + } + const tc = $('dbTeamChip'), wk = (d.referrals || []).filter(r => Date.now() - new Date(r.joined) < 6048e5).length; + if (tc && wk) { tc.hidden = false; tc.textContent = '+' + wk + ' this week'; } + setInboxBadge(d.inboxUnread || 0); + if (d.sponsorMsg) showSponsorModal(d.sponsorMsg); + renderBadges(d); + loadFeatured(); + loadLineTree(d.buyerCount || 0); + loadCharts(d); + $('nextMove').textContent = nextMove(d); + renderSteps(d); + const wrap = $('rosterWrap'); + if ((d.referrals || []).length) { + $('rosterEmpty').hidden = true; + renderRoster(wrap, d.referrals); + } + // overview recent-activity widget: chain events + line joins, newest first + try { + const c = await IAP.getConfig(); + const ov = $('ovFeed'); + const rows = []; + if (d.memberId) { + const a = await (await fetch('/api/my/activity')).json(); + for (const ev of [...(a.earnings || []), ...(a.purchases || [])] + .sort((x, y) => y.block - x.block).slice(0, 5)) rows.push(IAP.feedRow(ev, c)); + } + for (const r of (d.referrals || []).slice(0, 3)) { + const div = document.createElement('div'); + div.className = 'row'; + div.innerHTML = '🤝 ' + esc(r.name || r.email || 'A new member') + ' joined your line' + + new Date(r.joined).toLocaleDateString() + ''; + rows.push(div); + } + if (rows.length) { + ov.innerHTML = ''; + rows.slice(0, 6).forEach(r => ov.appendChild(r)); + } + } catch (e) {} + // ready-to-send share message + promo tools, personalized + await SHARE_READY; + const link = shareLink(d.username || d.refCode || d.memberId || ''); + fillPromo(link, d); + // founding-week readiness: shown until every item is done (or the launch moment is a week past) + try { + const cfg = await IAP.getConfig(); const items = IAP.launchChecks(d); const done = items.filter(i => i.done).length; + const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; + const show = done < items.length && !(at && Date.now() > at + 7 * 86400000); + const lm = $('launchMark'); + if (lm) { lm.hidden = !show; lm.innerHTML = show ? 'Launch ready: ' + done + ' of ' + items.length + '. ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + 'Open the founding-week checklist' : ''; } + } catch (e) {} + // people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it + try { + const tw = d.tankWaiting, tn = $('tankNotice'); + if (tn) { + tn.hidden = !(tw && tw.count); + if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 ' + + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line' + + (tw.eligible ? '.' : ' (you need your own $20 package first).'); + } + } catch (e) {} + // Share the presentation (2026-10-15): instantadpay.com/presentation?ref= sets the same sponsor cookie as /join + { const tokP = d.username || d.refCode || d.memberId; const ps = $('promoPresStrip'); + if (ps && tokP) { const pl = 'https://instantadpay.com/presentation?ref=' + encodeURIComponent(tokP); ps.hidden = false; $('promoPresLink').textContent = pl; $('promoPresOpen').href = '/presentation?ref=' + encodeURIComponent(tokP); + $('promoPresCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); IAP.status('Presentation link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; } } + if (d.username) { // wall link rides the username + const wl = location.origin + '/wall/' + d.username; + $('wallLine').textContent = wl; + if ($('promoWallStrip')) { // the same wall link at the top of Promo tools, next to the invite link + $('promoWallStrip').hidden = false; $('promoWallLink').textContent = wl; $('promoWallOpen').href = '/wall/' + d.username; + $('promoWallCopy').onclick = async () => { try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; + } + $('wallCopy').hidden = false; + $('wallOpen').hidden = false; + $('wallOpen').href = '/wall/' + d.username; + $('wallCopy').onclick = async () => { + try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select the link text instead.', 'bad'); } + }; + } + if (d.refCode || d.memberId) { + const pitch = 'I found an advertising site that pays referrals instantly to your own wallet. ' + + 'No withdrawals, no waiting, and every payment is public on a blockchain ledger you can check yourself. ' + + 'Free to join and look around: ' + link; + $('copyPitch').hidden = false; + $('pitchPreview').hidden = false; + $('pitchPreview').textContent = '"' + pitch + '"'; + $('copyPitch').onclick = async () => { + try { await navigator.clipboard.writeText(pitch); IAP.status('Message copied. Paste it anywhere.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select the preview text instead.', 'bad'); } + }; + } + } catch (e) {} + } + + // ── back-office menu: hash-routed panes ─────────────── + const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile']; + const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns', + earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games', + wallet: 'Wallet & account', profile: 'Profile' }; + function setPane(name) { + let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) + if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card + if (!PANES.includes(name)) name = 'overview'; + for (const p of PANES) { + const el = $('pane-' + p); + if (el) el.hidden = p !== name; + } + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => + b.classList.toggle('on', b.dataset.pane === name)); + if ($('boTitle')) $('boTitle').textContent = TITLES[name]; + // member ads: a fresh text ad in the strip under the title, and a banner at the foot of the pane + IAP.adSlot('text', 'adStripTop'); + if ($('adSlotPane-' + name)) IAP.adSlot('banner', 'adSlotPane-' + name); + if (name === 'earn') { setEarnSub(earnSub); loadPdCard(); } // refresh whichever sub-tab is active; PassiveDrip card (2026-10-01) + else if (vidState.token) stopVideo(); + if (name === 'profile') loadLineBanner(); + if (name === 'line') { buildLineJump(); loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); } + if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits + if (name === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); } + if (name === 'pipeline') loadPipeline(); + if (name === 'games') loadGames(paneQ); + if (name === 'help' && window.IAPSupport) IAPSupport.help(paneQ); // help desk tickets (2026-10-16) + document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer + const keepQ = name === 'help' && paneQ ? '?' + paneQ : ''; // Help keeps ?t= so a reload reopens the ticket + if (location.hash !== '#' + name + keepQ) history.replaceState(null, '', '#' + name + keepQ); + } + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => + b.addEventListener('click', () => setPane(b.dataset.pane))); + document.querySelectorAll('.qa [data-goto]').forEach(b => + b.addEventListener('click', () => setPane(b.dataset.goto))); + const qaCopy = document.getElementById('qaCopyInvite'); + if (qaCopy) qaCopy.addEventListener('click', async () => { + const link = document.getElementById('inviteLine').textContent; + if (!link || !link.startsWith('http')) { setPane('line'); return; } + try { await navigator.clipboard.writeText(link); IAP.status('Invite link copied.', 'ok'); } + catch (e) { setPane('line'); } + }); + window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); + if ($('boBurger')) $('boBurger').addEventListener('click', () => + document.getElementById('memberArea').classList.toggle('side-open')); + + async function render() { + // while /api/me answers, show a spinner instead of flashing the sign-in card at a signed-in member + let me = null; + try { me = await IAP.refreshNavWallet(); } catch (e) { me = null; } + if ($('bootSpin')) $('bootSpin').hidden = true; + // one way in: email. A wallet-only session (no account) is sent back to the + // email card with a finish-setup note; verifying the code links that wallet. + const walletOnly = !!(me && me.signedIn && !me.email); + const signedIn = me && me.signedIn && !walletOnly; + $('authArea').hidden = !!signedIn; + $('memberArea').hidden = !signedIn; + if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; + if (!signedIn) return; + if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL + if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews) + // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be + // skipped or dismissed; it resolves only when a username is saved, then the area renders. + if (!me.username) { + if (!render.gating) { render.gating = true; showOnboard(true).then(() => { render.gating = false; render(); }); } + return; + } + // came from a Drip Runner share link: once they have a username, straight back into the game (2026-09-30) + if (me.returnTo === 'driprunner' && !render.toGame) { render.toGame = true; location.href = '/api/my/driprunner'; return; } + if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01) + if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; } + if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02) + if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13) + if (me.returnTo === 'shardsofvalor' && !render.toGame) { render.toGame = true; location.href = '/api/my/shardsofvalor'; return; } // Shards of Valor sent them here to sign in (2026-10-18) + if (me.returnTo === 'pwmint' && !render.toGame) { render.toGame = true; location.href = '/pw/mint/resume'; return; } // PolyWarriors paid mint (2026-10-05) + if (me.pwMint && !me.gkShop && !me.sdShop && !document.getElementById('pwBack')) { const d = document.createElement('a'); d.id = 'pwBack'; document.body.classList.add('hasback'); d.href = '/pw/mint/resume'; d.textContent = 'PolyWarriors mint: buy a package and you go straight back to the game when it settles. Or go back now →'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 44px 14px 16px;border-radius:14px;background:linear-gradient(180deg,#22E5FF,#7A2CFF);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); + // x = not now: clears the bar cookie (the waiting mint order stays and a later package still completes it), Marty 2026-10-11 + const x = document.createElement('button'); x.type = 'button'; x.setAttribute('aria-label', 'Hide'); x.textContent = '×'; x.setAttribute('style', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);width:30px;height:30px;border:0;border-radius:50%;background:rgba(0,0,0,.28);color:#fff;font-size:20px;line-height:30px;cursor:pointer;padding:0'); + x.addEventListener('click', ev => { ev.preventDefault(); ev.stopPropagation(); fetch('/pw/mint/dismiss', { method: 'POST' }).catch(() => {}); d.remove(); document.body.classList.remove('hasback'); if (me) me.pwMint = false; }); d.appendChild(x); } + if (me.returnTo === 'sdshop' && !render.toGame) { render.toGame = true; location.href = '/sd/shop/resume'; return; } + if (me.sdShop && !document.getElementById('sdBack')) { const d = document.createElement('a'); d.id = 'sdBack'; document.body.classList.add('hasback'); d.href = '/sd/shop/resume'; d.textContent = 'Finish your Spooky Doors costume order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:' + (me.gkShop ? '74px' : '14px') + ';z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:#FF8A1F;color:#2a1200;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 5px 0 #C25A06,0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } + if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; document.body.classList.add('hasback'); d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } + if (me.returnTo === 'passivedrip' && !render.toGame) { render.toGame = true; location.href = '/api/my/passivedrip'; return; } // PassiveDrip sent them here to sign in (2026-10-01) + // arrived from an invite page: run the welcome tour and login ad once + if (/[?&]welcome=1/.test(location.search) && !render.welcomed) { + render.welcomed = true; + history.replaceState(null, '', '/my' + (location.hash || '')); + (async () => { + try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {} + await render(); + })(); + } + starterBanner(me).catch(() => {}); + setPane(location.hash.slice(1) || 'overview'); + $('campGate').hidden = !!me.memberId; + $('earnGate').hidden = !!me.memberId; + if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); } + loadDashboard(); + if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket + + const who = []; + if (me.email) who.push(me.email); + // members kept asking whether the wallet was really connected (Marty, 2026-09-12): say it, with a green check + if (me.address) who.push('Wallet connected ' + me.address.slice(0, 8) + '…' + me.address.slice(-6) + ''); + else who.push('No wallet connected yet (link one below)'); + if (me.memberId) who.push('on-chain member #' + me.memberId + '' + + (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : '')); + else if (me.sponsorId) who.push('invited by member #' + me.sponsorId); + $('posLine').innerHTML = who.join('
'); + + $('creditLine').textContent = (me.credits || 0).toLocaleString(); + loadPositions(me); + $('linkCard').hidden = !!me.address; + $('activateCard').hidden = !(me.address && !me.memberId); + $('activityArea').hidden = !me.memberId; + $('campGate').hidden = true; // earned credits fund campaigns for everyone + $('campaignCard').hidden = false; + loadCampaigns(); + + // profile pane state + $('pfCurrent').textContent = me.username ? '@' + me.username + ' is your permanent username. Your invite link, your public page and any banners you shared carry it, so it cannot be changed.' : 'No username yet. Members see you as a number until you pick one. Choose carefully: it is permanent once saved.'; + if (!$('pfUsername').value) $('pfUsername').value = me.username || ''; + $('pfUsername').disabled = !!me.username; $('pfSaveBtn').hidden = !!me.username; + $('pfDetails').innerHTML = 'Email: ' + (me.email || 'none') + '
Wallet: ' + + (me.address ? '' + me.address.slice(0, 10) + '…' + me.address.slice(-6) + '' : 'not linked yet') + + '
On-chain member: ' + (me.memberId ? '#' + me.memberId : 'not yet'); + // the share link works from day one; usernames make it a vanity link + if (me.username || me.refCode || me.memberId) { + await SHARE_READY; + $('inviteLine').textContent = shareLink(me.username || me.refCode || me.memberId); + $('copyInvite').hidden = false; + } else { + $('inviteLine').textContent = 'Sign in with your email to get your link.'; + $('copyInvite').hidden = true; + } + if (me.memberId) { + const bc = me.buyerCount || 0; + $('qualLine').innerHTML = '' + bc + ' qualifying buyer(s) referred
' + + (bc >= 5 ? 'Level 3 unlocked: full three-level earnings' + : bc >= 2 ? 'Level 2 unlocked · ' + (5 - bc) + ' more for level 3' + : (2 - bc) + ' more buyer(s) of $20+ unlock level 2'); + loadActivity(); + } else { + $('qualLine').innerHTML = 'Share your link now. Then switch on payouts (free, above) ' + + 'before your people start buying: the contract locks each buyer to their sponsor at ' + + 'their first purchase, and payments only route to wallets that are switched on.'; + } + } + + // Dollar value at today's POL price (Marty, 2026-10-22): one cached rate from our own server (5 min there, 2 min here), + // shown as "≈ $x.xx" next to POL amounts on the member's own pages. It is today's value, not the value on the payout day. + let USD = null; + async function usdRate() { + if (USD && Date.now() - USD.got < 120000) return USD; + try { const r = await (await fetch('/api/public/polusd')).json(); USD = { usd: Number(r.usd) || 0, at: Number(r.at) || Date.now(), got: Date.now() }; } catch (e) { USD = USD || { usd: 0, at: 0, got: Date.now() }; } + return USD; + } + function usdOf(wei, r) { + let pol = 0; try { pol = Number(BigInt(wei || '0') / 10n ** 12n) / 1e6; } catch (e) {} + const v = pol * ((r && r.usd) || 0); + return '≈ $' + v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + } + function usdNote(r) { + if (!r || !(r.usd > 0)) return ''; + const mins = Math.max(0, Math.round((Date.now() - r.at) / 60000)); + return '1 POL ≈ $' + r.usd.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 }) + ' at today’s price (updated ' + (mins < 1 ? 'just now' : mins + ' min ago') + '). Dollar amounts are what the POL is worth today, not on the day it was paid.'; + } + async function loadActivity() { + try { + const c = await IAP.getConfig(); + const a = await (await fetch('/api/my/activity')).json(); + const fill = (id, evs, empty) => { + const el = $(id); + el.innerHTML = ''; + if (!evs || !evs.length) { el.innerHTML = '
' + empty + '
'; return; } + for (const ev of evs) el.appendChild(IAP.feedRow(ev, c)); + }; + fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.'); + usdRate().then(r => { + const note = $('earnUsdNote'); if (note) note.textContent = usdNote(r); + if (!(r.usd > 0)) return; + const rows = $('earnFeed').querySelectorAll('.row'); let i = 0; + for (const ev of (a.earnings || [])) { const row = rows[i++]; if (!row || !ev.amountWei) continue; const s = document.createElement('span'); s.className = 'usd muted small'; s.textContent = usdOf(ev.amountWei, r); const tx = row.querySelector('.tx'); row.insertBefore(s, tx || null); } + }); + fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.'); + fill('buyFeed', a.purchases, 'No purchases from your wallet yet.'); + } catch (e) {} + initTrace(); + } + // payment trace (2026-09-16): who was paid, who was skipped and why, per purchase + let traceInit = false; + function initTrace() { + if (traceInit || !$('trGo')) return; traceInit = true; + const run = async () => { + const who = ($('trWho').value || '').trim(); const out = $('trOut'); const msg = $('trMsg'); + msg.textContent = 'Reading the chain…'; out.innerHTML = ''; + try { + const c = await IAP.getConfig(); + const r = await (await fetch('/api/my/trace?who=' + encodeURIComponent(who))).json(); + if (r.error) { msg.textContent = r.error; return; } + msg.textContent = ''; + const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody'; + const pol = w => IAP.fmtPol(w) + ' POL'; + const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + let h = '

' + nm(r.memberId) + ' · ' + (r.activated ? 'activated under ' + nm(r.sponsorId) : 'not activated on the chain yet') + ' · ' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' (level 2 needs 2, level 3 needs 5)

'; + if (!r.purchases.length) { out.innerHTML = h + '

No purchases involving ' + nm(r.memberId) + ' yet.

'; return; } + for (const p of r.purchases) { + const isBuyer = p.buyerId === r.memberId; + h += '
' + + '
' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought a $' + (p.priceCents / 100).toFixed(0) + ' package (' + pol(p.paidWei) + ')' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + + (c.explorer ? ' · verify ↗' : '') + '
'; + for (const t of p.tiers) { + const me = t.paidTo === r.memberId, skippedMe = t.skipped.some(x => x.id === r.memberId); + let line = 'Level ' + t.tier + ' (' + t.pct + '%): '; + for (const x of t.skipped) line += '' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'not qualified: had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' qualifying buyers then' : esc(x.reason)) + ') → '; + line += t.paidTo ? '' + nm(t.paidTo) + ' paid ' + pol(t.amountWei) + '' : 'no eligible catcher within reach → company'; + h += '
' + line + '
'; + } + h += '
Platform (20%): ' + pol(p.adminWei) + (isBuyer ? '' : '') + '
'; + } + h += '

A skipped level means that person had not unlocked it when the purchase settled. Qualification never applies backwards; the next purchase after they qualify pays them.

'; + out.innerHTML = h; + } catch (e) { msg.textContent = 'Could not read the chain just now. Try again in a minute.'; } + }; + $('trGo').addEventListener('click', run); + $('trWho').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); run(); } }); + } + + // credit activity ledger under the campaign table (2026-09-16): every earn and spend with its reason + // Archived campaigns: everything they did, none of the clutter and none of the reservation. + function renderArchived(el, r) { + const rows = r.archived || []; + if (!rows.length) return; + const box = document.createElement('div'); + box.className = 'card'; + box.style.marginTop = '18px'; + // what each one gave back = budget not delivered (flat packs are charged in full when bought, so theirs is 0) + const leftOf = c => Math.max(0, Number(c.budget || 0) - Number(c.spent || 0) - Number(c.accrued || 0)); + const returned = rows.reduce((n, c) => n + leftOf(c), 0); + box.innerHTML = '

Archived

' + rows.length + ' finished campaign' + (rows.length === 1 ? '' : 's') + ' · ' + returned.toLocaleString() + ' unspent credit' + (returned === 1 ? '' : 's') + ' returned
' + + '
' + + rows.map(c => '' + + '' + + '' + + '' + + '' + + '' + + '').join('') + + '
NameTypeViews hereClicksSpentReturnedRan until
' + esc(c.name || ('#' + c.id)) + '' + esc(c.type) + '' + Number(c.imps || 0).toLocaleString() + '' + Number(c.clicks || 0).toLocaleString() + '' + Number(c.spent || 0).toLocaleString() + '' + leftOf(c).toLocaleString() + '' + (c.created ? new Date(c.created).toLocaleDateString() : '') + '
' + + '

Archived campaigns keep every number they earned. They serve nothing and reserve nothing, so any budget they had not delivered is back in your Available balance (the Returned column). A campaign that delivered its whole budget has nothing left to return, and visit packs, Golden Door, login and featured runs are paid in full when bought. Restore brings one back, paused.

'; + el.appendChild(box); + box.querySelectorAll('[data-unarch]').forEach(b => b.addEventListener('click', async () => { + b.disabled = true; + try { await api('/api/my/campaigns/' + b.dataset.unarch + '/unarchive'); IAP.status('Restored, and paused. Press Resume when you want it running.', 'ok'); await loadCampaigns(); loadDashboard(); } + catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + })); + } + async function loadCreditActivity(el) { + try { + const r = await (await fetch('/api/my/credits/activity')).json(); + if (!r.items || !r.items.length) return; + const box = document.createElement('div'); box.id = 'creditActivity'; box.style.marginTop = '16px'; + const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + box.innerHTML = '

Credit activity

' + + '

Every credit that came in or went out, newest first. Earned credits are spent before purchased ones, so an earn followed by a buy shows as two lines here. Views a campaign delivers roll up into one line per day.

' + + '
' + + r.items.map(i => '').join('') + + '
' + when(i.ts) + '' + (i.delta > 0 ? '+' : '') + i.delta.toLocaleString() + '' + esc(i.note) + '
'; + el.appendChild(box); + pageList('credits', box, 'tbody tr'); + } catch (e) {} + } + async function loadCampaigns() { + try { + const r = await (await fetch('/api/my/campaigns')).json(); + if (r.error) return; + lastRates = r.rates; + if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.'; + // populate the banner-size dropdown once (ids map to NAS width/height) + if (r.bannerSizes && $('cSize') && !$('cSize').options.length) + $('cSize').innerHTML = r.bannerSizes.map(s => '').join(''); + applyType(); // the default type is banner: show its size + image rows now that the sizes exist + soloHint(); + if ($('spendBanner')) { + $('spendBanner').hidden = false; + $('spendBig').textContent = r.availableCredits.toLocaleString(); + $('spendSub').textContent = '= $' + (r.availableCredits / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' of ad delivery · ' + r.purchasedCredits.toLocaleString() + ' purchased' + (r.creditedCredits ? ' (' + r.creditedCredits.toLocaleString() + ' of it credited to you, spends on anything)' : '') + ' + ' + (r.earnedCredits || 0).toLocaleString() + ' earned' + (r.earnedReserved ? ' (' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits are already working inside your live campaigns)' : '') + (r.positionCount > 1 ? ' · pooled across ' + r.positionCount + ' positions (largest single position ' + (r.largestPosition || 0).toLocaleString() + ')' : ''); + if ($('spendNote')) $('spendNote').textContent = r.inCampaigns + ? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.' + : 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.'; + $('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', r.rates.loginCreditsPerDay + ' cr / day'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '' + x[0] + ' ' + x[1] + '').join(''); + } + $('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString() + + ((r.earnedCredits || r.earnedReserved) ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + (r.earnedCredits || 0) + ' earned' + (r.earnedReserved ? ', ' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits already working inside your live campaigns' : '') + ')' : '') + + (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '') + + ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch + + ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch + + ' views, login ' + r.rates.loginCreditsPerDay + 'cr/day, solo ' + + (r.rates.soloCostPerRecipient || 5) + 'cr/delivery'; + const el = $('campList'); + el.innerHTML = ''; + if (!r.campaigns.length) { el.innerHTML = '

No campaigns yet. Launch your first below.

'; loadCreditActivity(el); return; } + const tbl = document.createElement('div'); + tbl.className = 'tablewrap'; + tbl.innerHTML = '' + + '' + + r.campaigns.map(c => '' + + '' + + '' + + '' + + '' + + (c.type === 'visits' ? '' + : c.type === 'featured' ? '' + : '') + + '' + + '').join('') + '
NameTypeViews hereNetwork viewsClicksSpentBudgetStatus
' + c.name + '' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '' + c.type + (c.type === 'banner' && c.width ? ' ' + c.width + '×' + c.height + '' : '') + (c.dailyCap ? ' cap ' + c.dailyCap + '/day' : '') + (c.geo ? ' tier ' + esc(c.geo.replace(/,/g, '+')) + '' : '') + schedChips(c) + + (c.type === 'visits' && (c.placement === 'golden' || c.placement === 'doors') ? ' ' + (c.placement === 'golden' ? 'Golden Door' : 'Spooky Doors') + '' : '') + '' + c.imps.toLocaleString() + '' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : 'n/a') + '' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '
' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '' + esc(k) + ' ' + v + '').join('') + (c.impsNas ? ' · network: see Network views' : '') + '
' : '') + '
paid up front' + c.imps.toLocaleString() + ' of ' + Number(c.body || 0).toLocaleString() + (c.placement === 'golden' || c.placement === 'doors' ? ' doors' : ' visits') + + (((r.doorStats && r.doorStats[c.id]) || c.placement === 'golden' || c.placement === 'doors') ? (ds => '
\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '
')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '
paid up front' + featRun(c) + '' + c.spent + '' + c.budget + '' + (c.status === 'out' ? (c.type === 'visits' ? 'pack delivered' : 'budget spent') : c.status === 'done' ? '' + (c.type === 'featured' ? 'run ended' : 'ended') + '' : c.scheduled ? 'scheduled' : c.status) + '' + (c.status === 'active' ? '' + : c.status === 'paused' ? '' : '') + + (['paused', 'out', 'done'].includes(c.status) ? ' ' : '') + + (c.type === 'featured' ? ' ' + : c.type === 'visits' ? ' ' + : c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up + : ' ') + + '
'; + el.appendChild(tbl); + pageList('camps', tbl, 'tbody tr'); + renderArchived(el, r); + const note = document.createElement('p'); note.className = 'muted small'; + note.textContent = 'Credits you put into a campaign are set aside the moment you start it, so your Available number drops right away and the campaign spends from its own budget. Featured links and verified-visit packs are paid in full up front; a featured run is sold by the day, so use Extend run to keep it going. Whatever a campaign has not spent comes back to Available when it ends.'; + el.appendChild(note); + loadCreditActivity(el); + el.querySelectorAll('button[data-extend]').forEach(b => b.addEventListener('click', async () => { + const rr = r.rates || {}; const durs = rr.featuredDurations || [1, 2, 7]; const per = rr.featuredPerDay || 40; + const d = await IAP.ask({ title: 'Extend featured run', text: 'How many more days? Choose ' + durs.join(', ') + '. ' + per + ' credits a day, charged now. The days are added after the current run, or start today if it has ended.', type: 'number', placeholder: 'e.g. ' + durs[durs.length - 1], ok: 'Extend' }); + if (!d) return; + try { const x = await api('/api/my/campaigns/' + b.dataset.extend + '/extend', { days: Number(d) }); + IAP.status('Extended ' + x.days + ' day' + (x.days === 1 ? '' : 's') + ' for ' + x.cost + ' credits' + (x.resumed ? '. The run is live again.' : '.'), 'ok'); + await loadCampaigns(); loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('button[data-morevisits]').forEach(b => b.addEventListener('click', async () => { + const per = Number(b.dataset.vper) || (r.rates && r.rates.visitCostPerVisit) || 3; const door = b.dataset.vdoor; // door packs top up at their door price + const what = door === 'golden' ? 'Golden Doors' : door ? 'doors' : 'visits'; + const n = await IAP.ask({ title: 'Buy more ' + what, text: door ? 'How many more ' + what + '? ' + per + ' credits each, charged now like the original pack.' : 'How many more verified visits? ' + per + ' credits each, charged now like the original pack.', type: 'number', placeholder: 'e.g. 50', ok: 'Buy ' + what }); + if (!n) return; + try { const x = await api('/api/my/campaigns/' + b.dataset.morevisits + '/topup', { credits: Math.floor(Number(n)) * per }); + IAP.status('Added ' + x.visits + ' ' + what + ' (' + x.added + ' credits)' + (x.reactivated ? '. The pack is open again.' : '.'), 'ok'); + await loadCampaigns(); loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => { + try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('[data-arch]').forEach(b => b.addEventListener('click', async () => { + const left = Number(b.dataset.archleft) || 0; + const ok = await IAP.confirmBox( + 'It stops appearing in this list but keeps every number it earned, in the Archived section below.' + + (left ? ' Its ' + left.toLocaleString() + ' unspent credits go straight back to your Available balance.' : '') + + ' You can restore it at any time.', + { title: 'Archive ' + b.dataset.archname, ok: 'Archive it', cancel: 'Keep it here' }); + if (!ok) return; + b.disabled = true; + try { const x = await api('/api/my/campaigns/' + b.dataset.arch + '/archive'); + IAP.status('Archived.' + (x.freed ? ' ' + Number(x.freed).toLocaleString() + ' credits released.' : ''), 'ok'); + await loadCampaigns(); loadDashboard(); } + catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + })); + el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => { + const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views. They are set aside now and spend as views are delivered; anything unspent comes back when the campaign ends.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' }); + if (!n) return; + const done = r => { IAP.status('Added ' + r.added + ' credits' + (r.paidFrom ? ', paid from position #' + r.paidFrom : '') + (r.reactivated ? '. The campaign is live again.' : '.'), 'ok'); }; + try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) })); await loadCampaigns(); loadDashboard(); } + catch (e) { + // the ad's own position is short but another of yours has the credits: offer to pay from that one + const opt = e.data && e.data.switchOptions && e.data.switchOptions[0]; + if (!opt) { IAP.status(e.message, 'bad'); return; } + const yes = await IAP.confirmBox('This ad pays from your position #' + e.data.fundId + ', which has ' + e.data.free + ' credits free. Your position #' + opt.memberId + ' has ' + opt.free + ' free. Pay for this top-up from #' + opt.memberId + '? From now on this ad spends from #' + opt.memberId + '.', { title: 'Pay from another position?', ok: 'Pay from #' + opt.memberId, cancel: 'Cancel' }); + if (!yes) return; + try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n), switchTo: opt.memberId })); await loadCampaigns(); loadDashboard(); } + catch (e2) { IAP.status(e2.message, 'bad'); } + } + })); + } catch (e) {} + } + let lastRates = null; + function soloHint() { + if (!lastRates || $('cType').value !== 'solo') return; + const cost = lastRates.soloCostPerRecipient || 5; + const n = Math.floor((Number($('cBudget').value) || 0) / cost); + $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery' + + (n ? ' — this budget reaches ' + n + ' members' : '') + + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.'; + } + $('cBudget').addEventListener('input', soloHint); + // rich solo editor: small toolbar over contenteditable (CSP allows no external editor); + // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort + document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn => + btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); })); + document.querySelectorAll('.ed-bar [data-block]').forEach(btn => + btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); })); + $('edLinkBtn').addEventListener('click', async () => { + const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection + const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); + if (!url) return; + $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } + document.execCommand('createLink', false, url); + }); + // inline media: upload, then drop the element at the cursor (BV-style) + let mediaMode = 'image'; + function insertHtmlAtCursor(html) { + const ed = $('cSoloEd'); + ed.focus(); + if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html); + } + $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); }); + $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); }); + $('cSoloFile').addEventListener('change', async () => { + const f = $('cSoloFile').files[0]; + if (!f) return; + $('edMediaInfo').textContent = 'Uploading ' + f.name + '…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; } + insertHtmlAtCursor(r.type === 'video' + ? '


' + : '


'); + $('edMediaInfo').textContent = f.name + ' inserted'; + } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; } + $('cSoloFile').value = ''; + }); + // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back + $('edRawBtn').addEventListener('click', () => { + const ed = $('cSoloEd'), raw = $('cSoloRaw'); + if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; } + else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; } + }); + const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.', + text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.', + login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. Login ads spend purchased credits only.', + solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.', + video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.', + featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.', + visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' }; + const whereHint = () => { const el = $('cWhere'); if (el) el.textContent = WHERE[$('cType').value] || ''; }; + whereHint(); + // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately + function applyType() { // hoisted: loadCampaigns may run before this line is reached + whereHint(); + const t = $('cType').value; + $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL + if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner'; + $('cSizeRow').hidden = t !== 'banner'; + $('cTitleRow').hidden = t !== 'text' && t !== 'solo'; + $('cBodyRow').hidden = t !== 'text'; + $('cSoloRow').hidden = t !== 'solo'; + $('cSoloHint').hidden = t !== 'solo'; + $('cVideoRow').hidden = t !== 'video'; + $('cFeaturedRow').hidden = t !== 'featured'; + $('cVisitsRow').hidden = t !== 'visits'; + if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)'; + $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; } + // fixed-cost types derive their spend (featured = day slots, visits = flat pack), + // so hide the free-form Budget field for them to avoid confusion + $('cBudgetRow').hidden = (t === 'featured' || t === 'visits'); + if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text'); + // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected + if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10; + if (t === 'visits') visitHint(); + $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)'; + soloHint(); + if (t === 'video') videoHint(); + if (t === 'featured') featHint(); + } + $('cType').addEventListener('change', applyType); + let featStartDay = 0; // selected start-day offset (0 = today) + async function featHint() { + if (!lastRates || !lastRates.featuredDurations) return; + if ($('cFeatDays') && !$('cFeatDays').options.length) + $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys => + '').join(''); + let s = null; + try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {} + if (s && s.occupancy) { + const grid = $('cFeatDaysGrid'); + grid.innerHTML = s.occupancy.map(d => { + const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' }); + const full = d.open <= 0; + return '
' + + '
' + label + '
' + d.count + '/' + d.cap + (full ? ' full' : ' left ' + d.open) + '
'; + }).join(''); + grid.querySelectorAll('.feat-day:not(.full)').forEach(el => + el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); })); + } + const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]); + const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days'; + $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel + + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.'; + } + document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); }); + // where a visits pack runs (Spooky Doors, 2026-10-02): everywhere, behind the doors, or a Golden Door, each with its own price + // function declarations (hoisted): loadCampaigns can run before this point is reached + function visitPlace() { const x = document.querySelector('input[name="cVisitPlace"]:checked'); return x ? x.value : 'all'; } + function placeCost(pl, rr) { rr = rr || lastRates || {}; return pl === 'golden' ? (rr.goldenDoorCost || 6) : pl === 'doors' ? (rr.doorPackCost || 4) : (rr.visitCostPerVisit || 3); } + function sdSeasonOpen(rr) { return new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) < String((rr && rr.sdSeasonEnd) || '2026-11-01'); } + function sdLastDay(rr) { const t = new Date(String((rr && rr.sdSeasonEnd) || '2026-11-01') + 'T12:00:00Z'); t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); } + function visitHint() { + if (!lastRates) return; + const open = sdSeasonOpen(lastRates); + document.querySelectorAll('#cVisitPlaceRow .sd-place').forEach(el => { el.hidden = !open; }); + if (!open && visitPlace() !== 'all') { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; } + document.querySelectorAll('[data-vpcost]').forEach(el => { const p = el.dataset.vpcost; el.textContent = '(' + placeCost(p) + ' credits a ' + (p === 'all' ? 'visit' : 'door') + ')'; }); + const pl = visitPlace(), per = placeCost(pl), min = lastRates.visitMinPack || 20; + const n = Number($('cVisitCount').value) || 0; + const unit = pl === 'golden' ? 'Golden Door' : pl === 'doors' ? 'door' : 'verified visit'; + $('cVisitCount').placeholder = pl === 'all' ? 'How many verified visits?' : pl === 'golden' ? 'How many Golden Doors?' : 'How many doors?'; + $('cVisitHint').textContent = per + ' credits per ' + unit + + (n >= min ? ': ' + n + ' = ' + (n * per).toLocaleString() + ' credits, paid up front' : ' (min ' + min + ')') + + (pl === 'all' ? '. Each is a unique member, dwell + human-check verified.' + : '. Each door is a dwell + human-check verified visit by a Spooky Doors player, at most once a day per player' + + (pl === 'golden' ? '; Golden Doors open before every other door and give the player bonus candy' : '; door packs open before ordinary visits') + + '. They run only in Spooky Doors until the season ends on ' + sdLastDay(lastRates) + ', then any doors left run as normal visits.'); + } + $('cVisitCount').addEventListener('input', visitHint); + document.querySelectorAll('input[name="cVisitPlace"]').forEach(x => x.addEventListener('change', visitHint)); + // video composer: tier dropdown + upload + price hint + function videoHint() { + if (!lastRates || !lastRates.videoTiers) return; + if ($('cWatchSecs') && !$('cWatchSecs').options.length) + $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t => + '').join(''); + const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0]; + const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0; + $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view' + + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : ''; + } + document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); }); + $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); }); + $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click()); + $('cVideoUrl').addEventListener('change', async () => { + const url = $('cVideoUrl').value.trim(); + $('cVideoInfo').textContent = url ? 'checking video…' : ''; + cVidDims = url ? await probeVideoDims(url) : null; + if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video'; + else { $('cVideoInfo').textContent = ''; showVidOrient(); } + }); + $('cVideoFile').addEventListener('change', async () => { + const f = $('cVideoFile').files[0]; + if (!f) return; + $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; } + $('cVideoUrl').value = r.url; + $('cVideoInfo').textContent = f.name + ' uploaded'; + $('cVideoPrev').hidden = false; + $('cVideoPrev').innerHTML = ''; + cVidDims = await probeVideoDims(r.url); showVidOrient(); + } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; } + $('cVideoFile').value = ''; + }); + $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => { + // in raw mode the source of truth is the textarea; sync it back first + let soloBody = $('cSoloEd').innerHTML; + if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value; + const t = $('cType').value; + const isVideo = t === 'video', isFeat = t === 'featured'; + if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value); + await api('/api/my/campaigns', { type: t, name: $('cName').value, + targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value, + title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value, + body: t === 'solo' ? soloBody : $('cBody').value, + videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value), + videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null, + days: Number($('cFeatDays').value), startDay: featStartDay, + count: Number($('cVisitCount').value), placement: t === 'visits' ? visitPlace() : undefined, + dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0, + geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','), + startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0, + endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0, + ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value, + budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) }); + const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null; + IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok'); + // clear EVERY field so no target/creative carries into the next campaign + ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel', + 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt'] + .forEach(id => { if ($(id)) $(id).value = ''; }); + document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; }); + { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; if (t === 'visits') visitHint(); } + $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = ''; + $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = ''; + if ($('edMediaInfo')) $('edMediaInfo').textContent = ''; + cVidDims = null; + await loadCampaigns(); + })); + // defers the busy() lookup to click time (busy is declared below) + function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); } + + // ── verified visits: open a member's site (new tab), dwell, human-check, earn ── + const visState = { token: null, id: null, dwell: 8 }; + async function loadVisitStatus() { + try { + const st = await (await fetch('/api/my/visits')).json(); + if (st.error) return; + $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits'; + $('vsStartBtn').hidden = st.status.count >= st.status.cap; + if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.'; + } catch (e) {} + } + async function loadVisit() { + $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = ''; + let r = null; + try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {} + if (!r || !r.ad) { + $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap + ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + ''; + return; + } + visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8; + $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + '
Open the site and stay ' + visState.dwell + 's.'; + const visit = $('vsVisit'); + visit.href = r.ad.url; visit.hidden = false; + $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true; + // opening the site starts the dwell; then we ask the human-check + visit.onclick = () => { + let left = visState.dwell; + $('vsHint').textContent = 'Counting your visit: ' + left + 's'; + const t = setInterval(async () => { + left--; + if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; } + clearInterval(t); + $('vsHint').textContent = 'One quick check to count the visit:'; + let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); + if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); } + if (c.error) { $('vsHint').textContent = c.error; return; } + renderVisitCheck(c); + }, 1000); + }; + $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false; + } + function renderVisitCheck(c) { + $('vsPrompt').textContent = 'Click the ' + c.prompt + ':'; + const w = $('vsOpts'); w.innerHTML = ''; + c.options.forEach((em, i) => { + const b = document.createElement('button'); + b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em; + b.addEventListener('click', () => answerVisit(i)); + w.appendChild(b); + }); + $('vsCheck').hidden = false; + } + async function answerVisit(i) { + const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json(); + if (r.error) { + if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); } + $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return; + } + $('vsCheck').hidden = true; + $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.'; + $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits'; + IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok'); + loadDashboard(); + } + $('vsStartBtn').addEventListener('click', () => loadVisit()); + + // ── watch-to-earn videos: escape-proof player, server-clock reward ── + const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false }; + // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos + let cVidDims = null; + function probeVideoDims(url) { + return new Promise(resolve => { + if (!url) return resolve(null); + const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; + let done = false; const fin = r => { if (!done) { done = true; resolve(r); } }; + v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); + v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url; + }); + } + function showVidOrient() { + const el = $('cVideoInfo'); if (!el) return; + if (!cVidDims) return; + const portrait = cVidDims.h > cVidDims.w; + el.textContent = (el.textContent ? el.textContent + ' · ' : '') + + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab'); + } + async function loadVideoStatus() { + try { + const st = await (await fetch('/api/my/videos?orientation=landscape')).json(); + if (st.error) return; + $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched'; + if (st.status.left <= 0) { + $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.'; + $('vidStartBtn').hidden = true; + return; + } + $('vidStartBtn').hidden = false; + } catch (e) {} + } + // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13) + function stopVideo() { + const p = $('vidPlayer'); if (!p) return; + const was = !!vidState.token && !vidState.done; + try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {} + vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0; vidState.needsTap = false; + if ($('vidWrap')) $('vidWrap').hidden = true; + if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; } + if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; } + } + document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); }); + async function loadVideoAd() { + let r = null; + try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {} + if (!r || !r.ad) { + // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13) + const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched); + // the tab can run dry while Shorts still has clips, and both count toward the same + // daily total, so say so instead of sending them away (Marty, 2026-09-22) + const toShorts = !capHit && r && r.otherFormat === 'shorts'; + $('vidBox').innerHTML = toShorts + ? '
✓That is every video on this tab' + + 'You have watched all ' + r.status.count + ' of today’s landscape videos. The rest are upright clips that play in Shorts, and they count toward the same daily ' + r.status.cap + '. You have ' + r.status.left + ' left.' + + 'Open Shorts
' + : (capHit || allWatched) + ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
' + : 'No member videos are live right now. Check back when a campaign is running.'; + if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched || toShorts; + $('vidBox').hidden = false; + $('vidWrap').hidden = true; + return; + } + const ad = r.ad; + vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false; + $('vidBox').hidden = true; + $('vidWrap').hidden = false; + $('vidCta').hidden = true; + $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : ''; + const p = $('vidPlayer'); + p.src = ad.videoUrl; + p.currentTime = 0; + // escape-proof: no seeking past what's been watched; track max reached + p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; }; + p.ontimeupdate = () => { + if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime; + const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen)); + $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…'; + if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); } + }; + $('vidStartBtn').textContent = 'Playing…'; + $('vidStartBtn').disabled = true; + vidState.needsTap = false; + // a browser that refuses to autoplay leaves the clip loaded and paused; the button then has to + // START it. Wired to loadVideoAd it threw the clip away and fetched another, so on a phone the + // video could never be played at all (Marty, 2026-09-22) + try { await p.play(); } catch (e) { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; } + $('vidCta').href = ad.ctaUrl; + $('vidCta').textContent = ad.ctaLabel || 'Learn more'; + $('vidCta').hidden = false; + } + async function completeVideo(ad) { + if (vidState.credited) return; + vidState.credited = true; + try { + const r = await (await fetch('/api/my/videowatch', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json(); + if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); } + else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); } + else $('vidHint').textContent = 'That video just ran out of budget — load another.'; + if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched'; + } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); } + $('vidStartBtn').disabled = false; + $('vidStartBtn').textContent = 'Next video'; + } + $('vidStartBtn').addEventListener('click', () => { + const p = $('vidPlayer'); + if (vidState.needsTap && p && p.src && !vidState.done) { // a clip is loaded and waiting on a tap: start it, never replace it + vidState.needsTap = false; + $('vidStartBtn').textContent = 'Playing…'; $('vidStartBtn').disabled = true; + p.play().catch(() => { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; }); + return; + } + loadVideoAd(); + }); + // presence enforcement: pause the watch-to-earn video when the tab/window loses focus, + // resume when it comes back — the viewer must stay on the page for the watch to complete + document.addEventListener('visibilitychange', () => { + const p = $('vidPlayer'); if (!p || !p.src) return; + if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {}); + }); + window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); }); + window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); }); + + // ── unmissable sponsor-message modal on sign-in ── + // Only a message a PERSON wrote reaches here; system notices (payouts, purchase + // confirmations) are kind 'notice' and go straight to the inbox. + // + // loadDashboard() runs on far more than sign-in — it refreshes after every ad view, every + // campaign edit, every chat close. So the modal is shown at most once per page load and + // never twice for the same message, otherwise a member earning credits gets interrupted + // after every single view. + const msgModalShown = new Set(); + function showSponsorModal(msg) { + if (!$('msgModal') || !msg || msgModalShown.has(msg.id)) return; + if (!$('msgModal').hidden) return; // one already open + msgModalShown.add(msg.id); + // An alert is generated by the system, so crediting it to a person ("A message from + // @martbost") is both wrong and misleading about what the member is looking at. + $('mmFrom').textContent = msg.kind === 'alert' + ? 'Action needed on your account' + : 'A message from ' + (msg.fromName || 'your sponsor'); + $('mmSubject').textContent = msg.subject || ''; + $('mmBody').innerHTML = msg.body || ''; // server-sanitized + $('msgModal').hidden = false; + $('mmAck').onclick = async () => { + $('msgModal').hidden = true; + try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {} + setInboxBadge(Math.max(0, (Number($('inboxBadge') && $('inboxBadge').textContent) || 1) - 1)); + }; + } + + // ── coaching: every direct's rung, stalled flag, one-click nudge ── + // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ── + async function pif(email, name, address) { + // Marty, 2026-09-27: the member must see the risk before every PIF. The platform holds no funds; this is a + // wallet-to-wallet gift in good faith, and nothing the site does can recover it. + const ok = await IAP.confirmBox('You are about to send POL from your own wallet directly to ' + name + '\'s wallet, in good faith, so they can buy their first package.\n\nInstantAdPay never holds or moves these funds and cannot reverse or recover them. Nothing obliges ' + name + ' to make a purchase. Only send what you are willing to give.', { title: 'Before you pay it forward', ok: 'I understand, continue', cancel: 'Cancel' }); + if (!ok) return; + let suggest = 25; + try { const { products } = await (await fetch('/api/catalog')).json(); const p20 = (products || []).find(p => p.priceCents === 2000); if (p20 && p20.costWei) suggest = Math.ceil(Number(p20.costWei) / 1e18) + 3; } catch (e) {} + const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $20 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' }); + if (amt === null) return; + const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; } + try { + IAP.status('Confirm the transfer in your wallet…', 'ok'); + const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString(); + const hash = await IAPWallet.sendPol(address, wei); + await api('/api/my/gift', { email, tx: hash, pol }); + IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok'); + playSound && playSound('chaching'); + } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); } + } + // ── holding tank: waiting members, adopt, my open adoptions ── + const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; }; + async function loadTank() { + const el = $('tankList'); if (!el) return; + try { + const r = await (await fetch('/api/my/tank')).json(); + if (r.error) { el.innerHTML = ''; return; } + $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays; + $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now'; + const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason); + $('tankMine').innerHTML = r.mine.length ? '

Your open adoptions

' + r.mine.map(m => '
' + esc(m.name) + '' + + '' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '' + + '' + Math.max(0, Math.ceil((m.expires - Date.now()) / 86400000)) + ' days left' + + '' + + (m.address && !m.bought ? ' ' : '') + '
').join('') : ''; + $('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname))); + $('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); + if (!r.waiting.length) { el.innerHTML = '

The tank is empty. Anyone who joins from the public site without a sponsor lands here.

'; return; } + renderTank(el, r); + } catch (e) {} + } + function renderTank(el, r) { + const rows = listApply('tank', r.waiting); + el.innerHTML = ''; + el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on + el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '
' + esc(w.name) + '' + + 'joined ' + ago(w.joined) + '' + memberChips(w) + '' + + 'last sign-in: ' + ago(w.lastSeen) + '' + + (r.eligible ? '' : '') + '
').join('') + : '

Nobody in the tank matches those filters.

'); + pageList('tank', el, ':scope > .lin-row', { per: LINE_PER }); + el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => { + const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the InstantAdPay holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' }); + if (note === null) return; + try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } + // The announcement cards at the top of the Overview are repeated on a timer, so a member who has read + // one can put it away: dismissed for 24 hours on this browser (Marty, 2026-10-03; it used to come back + // at every sign-in and the cards stacked up), then it shows again so it is never gone for good. + const CARD_SNOOZE_MS = 24 * 3600 * 1000; + function cardHidden(key) { try { const t = Number(localStorage.getItem('iap-hide-' + key)); return t > 0 && Date.now() - t < CARD_SNOOZE_MS; } catch (e) { return false; } } + function cardDismiss(card, key) { + if (!card || card.querySelector('.card-x')) return; + const x = document.createElement('button'); + x.type = 'button'; x.className = 'card-x'; x.innerHTML = '×'; + x.title = 'Hide this for 24 hours'; + x.setAttribute('aria-label', 'Hide this message for 24 hours'); + x.addEventListener('click', () => { try { localStorage.setItem('iap-hide-' + key, String(Date.now())); } catch (e) {} card.hidden = true; }); + (card.querySelector('.card-head') || card).appendChild(x); + } + // Five Dollar Friday card on the Overview: the live wave on Fridays, the date the rest of the week + async function loadFridayCard() { + const card = $('fdfCard'); if (!card) return; + if (cardHidden('fdf')) { card.hidden = true; return; } + try { + const f = await (await fetch('/api/friday')).json(); if (!f.on) { card.hidden = true; return; } + card.hidden = false; + if (f.live && f.today) card.innerHTML = '

\u{1F4B5} It\u2019s Five Dollar Friday

+' + f.pct + '% credits on any pack today
' + + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Every $5+ package bought before midnight Central earns +' + f.pct + '% bonus credits the moment it settles. Your pack pays your sponsor line instantly; your line\u2019s packs pay you.

' + + ' Watch the wave'; + else card.innerHTML = '

\u{1F4B5} Five Dollar Friday

every Friday
' + + '

Every Friday (Central time), any ad package from $5 up earns +' + f.pct + '% bonus credits, added the moment it settles. The whole network buys on the same day, so every line gets paid at once. Next one: ' + (f.nextLabel || 'soon') + '.

' + + ''; + const b = $('fdfBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); + cardDismiss(card, 'fdf'); + } catch (e) {} + } + loadFridayCard(); setInterval(loadFridayCard, 120000); + // Wired Wednesday card on the Overview: the live wave on Wednesdays, the date the rest of the week + async function loadWednesdayCard() { + const card = $('wwCard'); if (!card) return; + if (cardHidden('ww')) { card.hidden = true; return; } + try { + const f = await (await fetch('/api/wednesday')).json(); if (!f.on) { card.hidden = true; return; } + card.hidden = false; + if (f.live && f.today) card.innerHTML = '

⚡ It’s Wired Wednesday

+' + f.pct + '% credits on any $' + f.minUsd + '+ pack today
' + + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + Number(f.today.bonusCredits || 0).toLocaleString() + ' bonus credits wired in, ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Buy any $' + f.minUsd + '+ package before midnight Central and +' + f.pct + '% is wired into your balance the moment it settles, good for any format.

' + + ' How it works'; + else card.innerHTML = '

⚡ Wired Wednesday

every Wednesday
' + + '

Every Wednesday (Central time), any ad package from $' + f.minUsd + ' up earns +' + f.pct + '% bonus credits, wired into your balance the second it settles, purchased-grade so they run on any format, login ads included. Next one: ' + (f.nextLabel || 'soon') + '.

' + + ''; + const b = $('wwBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); + cardDismiss(card, 'ww'); + } catch (e) {} + } + loadWednesdayCard(); setInterval(loadWednesdayCard, 120000); + + // ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ---- + const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }); + const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, ''); + // Pass tiers (2026-10-18, Marty approved the safe form): weekly Game Pass, monthly Explorer and Champion side by side. Paid tiers add + // islands and looks in Shards of Valor, never power and never more POL; the main story is free. End dates in Central time. + const gpCT = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)'; + const GP_TIER_PERKS = { + weekly: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and the Weekly look'], + explorer: ['Everything in the Game Pass, in every game', 'Shards of Valor: up to 4 bonus islands you pick (1 swap a month)', 'Explorer outfits and gear styles for your character'], + champion: ['Everything in Explorer', 'Shards of Valor: every bonus island, now and future', 'Champion outfits and gear styles for your character'], + }; + function renderPassTiers(card, gp, highlight) { + const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier); + const state = top ? '' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '' + : 'No pass active'; + const caps = gp.caps || {}; + const capsLine = caps.enforced ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' : ''; + const box = r => { + const btn = r.waiting ? '' + : r.open ? '' + : 'Not on sale right now. Your pass keeps running.'; + return '

' + esc(r.name) + '

' + + '

$' + r.usd + ' for ' + r.days + ' days

' + + '
    ' + (GP_TIER_PERKS[r.tier] || []).map(x => '
  • ' + esc(x) + '
  • ').join('') + '
' + + '

' + (r.active ? 'Active until ' + esc(gpCT(r.until)) + '' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '

' + + btn + '
'; + }; + card.hidden = false; card.classList.toggle('gp-hl', !!highlight); + card.innerHTML = '

\u{1F39F}️ Game Passes

weekly or monthly · every game
' + + (gp.tierPreview ? '

Admin preview. Explorer and Champion are hidden from members until sovTiers is switched on in Settings.

' : '') + + '

' + state + '

' + + '

Free play pays real POL every day, and the main story of Shards of Valor is free for everyone. Every pass gives the same higher POL caps in every game. The monthly passes add islands to explore and looks in Shards of Valor. Paid passes never make you stronger than players who earn their gear, and they never pay more POL.

' + + '
' + rows.map(box).join('') + '
' + + (capsLine ? '

' + capsLine + '

' : '') + + '

Paid with purchased credits from your packages (earned credits never buy a pass). Passes run side by side: a higher pass shows first, and the one underneath keeps its own end date. No auto-renew: buy again any time and that pass extends from its end date. When a pass ends, nothing you earned in a game is taken away.

'; + card.querySelectorAll('[data-gp-tier]').forEach(b => b.addEventListener('click', async () => { + const r = rows.find(x => x.tier === b.dataset.gpTier); if (!r) return; + const yes = await IAP.confirmBox((r.active ? 'Extend your ' + r.name + ' by ' + r.days + ' days' : 'Get ' + r.name + ' for ' + r.days + ' days') + ' for ' + r.price + ' purchased credits ($' + r.usd + ')? It starts at once. Islands and looks only: no extra power, no extra POL.', { title: r.name, ok: r.active ? 'Extend' : 'Get ' + r.name, cancel: 'Not now' }); + if (!yes) return; + b.disabled = true; + try { + const x = await api('/api/my/gamepass/buy', { tier: r.tier }); + if (x.needPay) { IAP.status(x.message || 'Buy a package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; } + IAP.status(r.name + ' active until ' + gpCT(x.until) + '. Have fun out there.', 'ok'); + await loadGamePassCard(true); + } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + })); + card.querySelectorAll('[data-gp-go]').forEach(b => b.addEventListener('click', () => setPane('buy'))); + if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } + } + // What the Pass adds in each game (Marty, 2026-10-22: members must see what they are buying). Keep in step with the games' perks. + const GP_PERKS = [ + ['PolHunter', '5 missions a day instead of 3, plus 2 Ad Detective cases a day'], + ['Gem Kingdom', 'one free continue every day'], + ['Spooky Doors', 'one extra door every day'], + ['ClutterHunt', '2 bonus hints every day'], + ['SpellWheel', 'daily streak pays 0.30 POL instead of 0.15, plus 1 free hint a day'], + ['PolyBreak', 'daily gem limit 1.5 POL instead of 0.5, plus an extra paddle every round'], + ['PolyWarriors', 'a 4th daily mission, and defense pays 25 Circuits instead of 15'], + ['Drip Runner', 'a free shield at the start of every run'], + ['Road Agent', '2 patrols a day and 25% more scrap'] + ]; + function gpPerksHtml() { + return '

What you get

' + + '' + + '' + + '
Every gameDaily POL caps of 1.50 a day on repeatable rewards (free play 0.30) and 5 a day in all (free play 2), counted across all nine games
WeeklyA seat in the Pass Tournament, POL prizes from 5% of pass sales, paid Mondays
BadgeThe gold Game Pass badge with your name, to share or post
' + + '

In each game

' + + GP_PERKS.map(p => '').join('') + '
' + p[0] + '' + p[1] + '
' + + '

The Pass never changes how much a reward pays: it lets you play and collect more each day.

'; + } + async function loadGamePassCard(highlight) { + const card = $('gpCard'); if (!card) return; + let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} + if (!gp || !(gp.enabled || gp.show)) { card.hidden = true; return; } + if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight); // Explorer / Champion on sale (or admin preview, or a holder) + const caps = gp.caps || {}; const price = gp.price || 500; + const state = gp.active ? 'Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '' + : gp.waiting ? 'Waiting for a $' + (gp.usd || 5) + ' package' : 'Not active'; + const capsLine = caps.enforced + ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' + : gp.capsStart ? 'Account-wide caps start on ' + esc(gpDate(Date.parse(gp.capsStart + 'T17:00:00Z'))) + ': free play ' + gpPol(caps.daily) + ' POL a day on repeatable rewards, 2 POL a day in all; with the Pass 1.50 and 5.' + : 'Account-wide caps are not switched on yet; the games\u2019 own caps stand for now.'; + card.hidden = false; card.classList.toggle('gp-hl', !!highlight); + card.innerHTML = '

\u{1F39F}\uFE0F Game Pass

$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 all nine games
' + + '

' + state + '

' + + '

Free play pays real POL every day. The Pass plays more: higher daily POL caps across every game (1.50 a day on repeatable rewards instead of 0.30, 5 a day in all instead of 2), a seat in the weekly Pass Tournament with POL prizes from ' + (gp.tournament && gp.tournament.pct || 5) + '% of pass sales, extra plays and perks in each game, and the Pass badge. One pass covers your whole account, linked positions included.

' + + gpPerksHtml() + + '

' + capsLine + '

' + + (gp.waiting ? '

Your pass is waiting: buy a $' + (gp.usd || 5) + ' package and it starts the moment the purchase settles. You keep every credit of the package for your ads.

' : '') + + '

' + + (gp.waiting ? '' : '') + + 'Paid with purchased credits from your packages (earned credits never buy a pass). Short? A $' + (gp.usd || 5) + ' package starts it the moment it settles.

'; + const b = $('gpBuy'); if (b) b.addEventListener('click', async () => { + const yes = await IAP.confirmBox((gp.active ? 'Extend your Game Pass by ' + (gp.days || 7) + ' days' : 'Get the Game Pass for ' + (gp.days || 7) + ' days') + ' for ' + price + ' purchased credits? Higher daily caps across all nine games, the weekly Pass Tournament and the Pass perks start at once.', { title: 'Game Pass', ok: gp.active ? 'Extend the Pass' : 'Get the Pass', cancel: 'Not now' }); + if (!yes) return; + b.disabled = true; + try { + const r = await api('/api/my/gamepass/buy'); + if (r.needPay) { IAP.status(r.message || 'Buy a $5 package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; } + IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok'); + await loadGamePassCard(true); + } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + }); + const g = $('gpGoBuy'); if (g) g.addEventListener('click', () => setPane('buy')); + if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } + } + // Overview nudge: a game reported this member hit the free cap (polgrant lastCapHit). Shown once a day per browser, never to pass holders. + async function loadGpNudge() { + const card = $('gpNudge'); if (!card) return; + if (cardHidden('gpnudge')) { card.hidden = true; return; } + let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} + if (!gp || !gp.enabled || gp.active || !gp.lastCapHit || gp.lastCapHit.pass) { card.hidden = true; return; } + const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' }; + card.hidden = false; + card.innerHTML = '

\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '

free play keeps paying; the Pass plays more
' + + '

Every member earns real POL in the games up to the daily cap. The Game Pass raises the caps across all nine games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with purchased credits), adds the weekly Pass Tournament and a perk in every game.

' + + ''; + $('gpNudgeGo').addEventListener('click', () => setPane('games?pass=1')); + try { localStorage.setItem('iap-hide-gpnudge', String(Date.now())); } catch (e) {} // once a day + cardDismiss(card, 'gpnudge'); + } + loadGpNudge(); + // launch-day surprise (Marty, 2026-09-20): PolHunter appears at siteConfig.launchAt, not a minute before. + // The card and the menu entry flip on their own if the dashboard is already open. + let phShown = false; + const LAUNCH_CARD_DAYS = 7; + async function launchReveal() { + try { + const nav = $('polhunterNav'); if (nav) nav.hidden = false; // listed in the menu from launch morning (Marty, 2026-09-21); the card below is the announcement and waits for launchAt + const cfg = await IAP.getConfig(); const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; + if (!at || Date.now() < at) return; + // launch cards retire 7 days after launch (Marty, 2026-10-03: old announcements kept stacking up) + if (Date.now() > at + LAUNCH_CARD_DAYS * 86400000) { const c = $('phLaunch'); if (c) c.hidden = true; return; } + const card = $('phLaunch'); if (!card || phShown) return; + if (cardHidden('phLaunch')) { card.hidden = true; return; } + phShown = true; card.hidden = false; + card.innerHTML = '

\u{1F3AF} New today: PolHunter

Launch-day surprise
' + + '

Missions across our sites. Visit the site, find your personal code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in the wallet on this account, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly POL prizes, and badge cards you can share. Your PolHunter share link puts sign-ups on your InstantAdPay line.

' + + 'Open my PolHunter board The teaser'; + const tb = $('phTrain'); if (tb) tb.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="training"]'); if (m) m.click(); }); + cardDismiss(card, 'phLaunch'); + } catch (e) {} + } + launchReveal(); setInterval(launchReveal, 30000); + // came from PolHunter (iap.return cookie): one card at the top of the Overview that sends them back + // Games hub (2026-10-01): one card per game, the player's own progress where the game reports it + // PassiveDrip, our earning site: a card on the Earn tab (not a game, Marty 2026-10-01) + async function loadPdCard() { + const card = $('pdCard'); if (!card) return; + let j = null; try { j = await (await fetch('/api/my/passivedrip/card')).json(); } catch (e) {} + if (!j || !j.show) { card.hidden = true; return; } + card.hidden = false; $('pdPre').hidden = !j.preview; $('pdLine').textContent = j.line || ''; + } + async function loadGames(q) { + const el = $('gamesGrid'); if (!el) return; + loadGamePassCard(/(^|&)pass=1(&|$)/.test(q || '')).catch(() => {}); + let g = null; try { g = await (await fetch('/api/my/games')).json(); } catch (e) {} + const list = (g && g.games) || []; + if (!list.length) { el.innerHTML = '

No games are open yet. Check back soon.

'; return; } + // a seasonal card (x.season, 2026-10-02) wears the pink limited-time ribbon from the Spooky Doors UI kit + el.innerHTML = list.map(x => '
' + (x.soon ? '' : x.season && x.season.ends ? 'Limited time \u00b7 ends ' + esc(x.season.ends) + '' : '') + '
' + esc(x.tag || '') + '

' + esc(x.name) + (x.preview ? '' + esc(x.previewNote || 'preview, not live') + '' : '') + '

' + esc(x.blurb) + '

' + (x.progress && x.progress.line ? '
' + esc(x.progress.line) + '
' : '') + '

Pays: ' + esc(x.pays || 'POL') + '

' + (x.perk ? '

Members get ' + esc(x.perk) + '

' : '') + (x.soon ? '' + esc(x.soon) + '' : '' + esc(x.cta || 'Play') + '') + '
').join(''); + } + async function loadReturnCard() { + const card = $('phReturn'); if (!card) return; + if (cardHidden('phReturn')) { card.hidden = true; return; } + try { + const me = await (await fetch('/api/me')).json(); + if (me.returnTo !== 'polhunter') { card.hidden = true; return; } + card.hidden = false; + card.innerHTML = '

You came from PolHunter

' + (me.address + ? '

Your wallet is linked, so your board is ready.

Back to PolHunter' + : '

One step left: link the wallet your POL drips will be paid to. The moment it is linked you go straight back.

'); + const b = $('phGoWallet'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="wallet"]'); if (m) m.click(); }); + cardDismiss(card, 'phReturn'); + } catch (e) {} + } + async function loadCoach() { + loadReturnCard(); + loadTank(); + try { + const r = await (await fetch('/api/my/coach')).json(); + const el = $('coachList'); if (!el || r.error) return; + const d = r.directs || []; + $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : ''; + if (!d.length) { el.innerHTML = '

No directs yet. When someone joins through your link they show up here with their next step.

'; return; } + el.innerHTML = d.map(x => '
' + esc(x.name) + (x.stalled ? ' quiet ' + x.quietDays + 'd' : '') + + (x.polWaiting ? ' ' + x.polWaiting.toFixed(2) + ' POL waiting · no wallet' : '') + + (x.rescue && x.rescue.unreached ? ' unreached · tank in ' + x.rescue.rescueInDays + 'd' : '') + (x.bound === false ? ' not bound to you on-chain' : '') + '' + + '' + esc(x.label) + ' → ' + esc(x.next) + '' + + 'rung ' + x.rung + '/6' + + '' + (x.buyerCount ? x.buyerCount + ' buyer' + (x.buyerCount === 1 ? '' : 's') : '') + '' + + '' + + (x.address ? ' ' : '') + + (x.free && x.rescue ? ' ' : '') + + (x.free ? ' ' : '') + '
').join(''); + pageList('coach', el, ':scope > .lin-row', { per: LINE_PER }); + el.querySelectorAll('[data-contacted]').forEach(b => b.addEventListener('click', async () => { + try { await api('/api/my/tank/contacted', { email: b.dataset.contacted }); IAP.status('Marked: you have contacted ' + b.dataset.cname + '.', 'ok'); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); + el.querySelectorAll('[data-nudge]').forEach(b => b.addEventListener('click', async () => { + await openConvo(b.dataset.nudge, b.dataset.nname); + const inp = $('chatInput'); if (inp) { inp.value = b.dataset.say.replace(/\{\{name\}\}/g, b.dataset.nname.replace(/^@/, '')); inp.focus(); } + })); + el.querySelectorAll('[data-release]').forEach(b => b.addEventListener('click', async () => { + if (!(await IAP.confirmBox('Release ' + b.dataset.rname + ' to the holding tank? You stop being their sponsor and another member can adopt them.', { title: 'Release to the tank', ok: 'Release' }))) return; + try { await api('/api/my/tank/release', { email: b.dataset.release }); IAP.status(b.dataset.rname + ' is in the holding tank.', 'ok'); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + // schedule chips on the campaign table (local time) + by-hour view bars + const fmtWhen = ms => new Date(ms).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + // featured run column: days left of the booked total (Hugh, 2026-09-16: "says 14 but it's actually 7") + function featRun(c) { + const total = Number(c.body || 0), now = Date.now(); + if (c.status === 'done' || !c.expires || c.expires <= now) return '' + total + ' day' + (total === 1 ? '' : 's') + ' done'; + const left = Math.max(1, Math.ceil((c.expires - now) / 86400000)); + return '' + left + ' of ' + total + ' day' + (total === 1 ? '' : 's') + ' left'; + } + function schedChips(c) { + const now = Date.now(); let s = ''; + if (c.starts && c.starts > now) s += ' starts ' + fmtWhen(c.starts) + ''; + if (c.expires && c.type === 'featured') { const day = new Date(c.expires - 1).toLocaleDateString([], { month: 'short', day: 'numeric' }); s += ' ' + (c.expires > now ? 'runs through ' : 'ran through ') + day + ''; } + else if (c.expires) s += ' ' + (c.expires > now ? 'ends ' : 'ended ') + fmtWhen(c.expires) + ''; + return s; + } + function geoLine(rows) { + if (!rows || !rows.length) return ''; + return '
' + rows.map(r => esc(r.cc) + ' ' + r.n).join(' · ') + '
'; + } + function hourBars(utc) { + if (!utc || !utc.some(n => n)) return ''; + // rotate the 24 UTC buckets into the viewer's local hours + const local = new Array(24).fill(0); + for (let h = 0; h < 24; h++) local[new Date(Date.UTC(2000, 0, 1, h)).getHours()] += utc[h]; + const max = Math.max(...local); + const lab = h => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'); + return '
' + local.map((n, h) => + '').join('') + + '
views by hour · last 7 days · your time
'; + } + // ── link stats: views, joins, buyers per angle ── + async function loadLinkStats() { + try { + const r = await (await fetch('/api/my/linkstats')).json(); + const t = $('linkStatsTable'); if (!t || r.error) return; + const rows = (r.angles || []).filter(a => a.views || a.joins || a.buyers); + if (!rows.length) { t.innerHTML = 'No views yet. Share your link and the numbers start here.'; return; } + t.innerHTML = 'HookViews (30d)Views (all)JoinedQualifying buyers' + + rows.map(a => '' + esc(a.angle === 'plain' ? 'plain link' : a.angle === 'page' ? 'any page (viral link)' : '?v=' + a.angle) + '' + a.views30 + '' + a.views + '' + a.joins + '' + a.buyers + '').join(''); + const st = $('linkSrcTable'); + if (st) { + const src = (r.sources || []).filter(x => x.views || x.joins); + st.innerHTML = src.length ? 'SourceViews (30d)Views (all)JoinedQualifying buyers' + + src.map(x => '' + esc(x.source) + '' + x.views30 + '' + x.views + '' + x.joins + '' + x.buyers + '').join('') + : 'Sources appear as visits arrive.'; + pageList('linksrc', st.parentElement, 'table tr:has(td)', { per: LINE_PER }); + } + pageList('linkangles', t.parentElement, 'table tr:has(td)', { per: LINE_PER }); + } catch (e) {} + } + // ── prospects: the member's own follow-up list ── + let PP_STATUSES = ['new', 'contacted', 'interested', 'joined', 'bought', 'not now']; + // ── Pipeline: the follow-up board (Marty, 2026-09-15). Stages come from the server; cards never move by hand ── + let PIPE = null, PIPE_KEY = null; + const pipeAgo = ts => { const d = Math.floor((Date.now() - ts) / 86400000); return d <= 0 ? 'today' : d === 1 ? 'yesterday' : d < 30 ? d + 'd ago' : new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); }; + const pipeInvite = () => { const t = ($('inviteLine') && $('inviteLine').textContent) || ''; return /^https?:\/\//.test(t) ? t : ''; }; + function pipeCardHtml(c, showStage) { + const today = new Date(); today.setHours(23, 59, 59, 999); + const due = c.followUp && c.followUp <= today.getTime(); + const chips = []; + if (c.stalled) chips.push('stalled ' + c.quietDays + 'd'); + if (due) chips.push('follow up'); + else if (c.followUp) chips.push('' + new Date(c.followUp).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ''); + if (c.tag) chips.push('' + esc(c.tag) + ''); + if (c.kind === 'member' && c.buyers) chips.push('' + c.buyers + ' buyer' + (c.buyers === 1 ? '' : 's') + ''); + const stage = showStage ? (PIPE.stages.find(s => s.key === c.stage) || {}).label || '' : ''; + return '
' + + '
' + esc(c.name) + '' + (c.kind === 'prospect' ? 'prospect' : (c.lastSeen ? 'seen ' + pipeAgo(c.lastSeen) : 'never signed in')) + '
' + + '
' + esc(stage ? stage + ' · ' + c.next : c.next) + '
' + + (c.note ? '
' + esc(c.note) + '
' : '') + + (chips.length ? '
' + chips.join('') + '
' : '') + '
'; + } + async function loadPipeline() { + try { + const r = await (await fetch('/api/my/pipeline')).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + if (!r.live) { + $('pipeSoon').hidden = false; $('pipeLive').hidden = true; + $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.'; + return; + } + PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false; + const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; } + $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length; + $('pipeDue').innerHTML = r.due.length ? '
' + r.due.map(c => pipeCardHtml(c, true)).join('') + '
' : '

Nothing due. Set a follow-up date on any card and it shows up here.

'; + $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.'; + $('pipeBoard').innerHTML = r.columns.map(col => '

' + esc(col.label) + '' + col.cards.length + '

' + esc(col.hint) + '

' + col.cards.map(c => pipeCardHtml(c, false)).join('') + '
').join(''); + $('pipeBoard').querySelectorAll('.pipe-col').forEach((col, i) => pageList('pipe-' + i, col, ':scope > [data-pk]')); + $('pipeLive').querySelectorAll('[data-pk]').forEach(el => { + el.addEventListener('click', () => openPipeCard(el.dataset.pk)); + el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPipeCard(el.dataset.pk); } }); + }); + if (PIPE_KEY) { const c = allPipeCards().find(x => x.key === PIPE_KEY); if (c) fillPipeCard(c); else { PIPE_KEY = null; $('pipeCard').hidden = true; } } + } catch (e) { IAP.status('Could not load your pipeline.', 'bad'); } + } + function allPipeCards() { return PIPE ? PIPE.columns.flatMap(c => c.cards) : []; } + function fillPipeCard(c) { + $('pipeCardName').textContent = c.name; + const stage = (PIPE.stages.find(s => s.key === c.stage) || {}).label || ''; + $('pipeCardMeta').textContent = stage + (c.kind === 'member' ? ' · joined ' + new Date(c.since).toLocaleDateString() + (c.lastSeen ? ' · last seen ' + pipeAgo(c.lastSeen) : ' · never signed in') + (c.bought ? ' · your qualifying buyer' : '') + (c.buyersPositions ? ' · ' + c.buyers + ' buyers: ' + c.buyersMain + ' on the main wallet, ' + c.buyersPositions + ' on linked positions' : '') : ' · prospect' + (c.contact ? ' · ' + c.contact : '')); + $('pipeCardNext').innerHTML = 'Next for them: ' + esc(c.next) + (c.stalled ? ' quiet ' + c.quietDays + ' days' : ''); + const say = (c.say || '').replace('{{link}}', pipeInvite()); + $('pipeSayBlock').hidden = !say; $('pipeSay').textContent = say; + $('pipeSend').hidden = c.kind !== 'member' || !c.email; + $('pipeFollow').value = c.followUp ? new Date(c.followUp).toISOString().slice(0, 10) : ''; + const sel = $('pipeTag'); sel.innerHTML = PIPE.tags.map(t => '').join(''); + $('pipeNote').value = c.note || ''; $('pipeSaved').textContent = ''; + $('pipeCard').hidden = false; + } + function openPipeCard(key) { + const c = allPipeCards().find(x => x.key === key); if (!c) return; + PIPE_KEY = key; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.toggle('on', el.dataset.pk === key)); + fillPipeCard(c); $('pipeCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); + } + if ($('pipeCardClose')) $('pipeCardClose').addEventListener('click', () => { PIPE_KEY = null; $('pipeCard').hidden = true; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.remove('on')); }); + if ($('pipeSave')) $('pipeSave').addEventListener('click', async () => { + if (!PIPE_KEY) return; + try { await api('/api/my/pipeline/note', { key: PIPE_KEY, note: $('pipeNote').value, followUp: $('pipeFollow').value || null, tag: $('pipeTag').value }); $('pipeSaved').textContent = 'Saved.'; loadPipeline(); } + catch (e) { IAP.status(e.message, 'bad'); } + }); + if ($('pipeCopy')) $('pipeCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('pipeSay').textContent); $('pipeCopy').textContent = 'Copied'; setTimeout(() => { $('pipeCopy').textContent = 'Copy message'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); } }); + if ($('pipeSend')) $('pipeSend').addEventListener('click', () => { + const c = allPipeCards().find(x => x.key === PIPE_KEY); if (!c || !c.email) return; + openConvo(c.email, c.name); + const ta = $('chatInput'); if (ta) { ta.value = $('pipeSay').textContent; ta.dispatchEvent(new Event('input')); ta.focus(); } + }); + async function loadProspects() { + try { + const r = await (await fetch('/api/my/prospects')).json(); + if (r.error) return; + PP_STATUSES = r.statuses || PP_STATUSES; + const sel = $('ppStatus'); if (sel && !sel.options.length) sel.innerHTML = PP_STATUSES.map(s => '').join(''); + const list = r.prospects || []; const el = $('prospectList'); if (!el) return; + if (!list.length) { el.innerHTML = '

Nobody on the list yet.

'; return; } + const today = new Date(); today.setHours(0, 0, 0, 0); + el.innerHTML = list.map(p => { const due = p.nextTs && p.nextTs <= today.getTime() + 86399999; return '
' + esc(p.name) + (due ? ' follow up' : '') + '' + + '' + esc(p.contact || '') + (p.note ? ' · ' + esc(p.note) : '') + '' + + '' + + '' + + '
'; }).join(''); + const save = async (id, patch) => { const p = list.find(x => x.id === Number(id)); if (!p) return; try { await api('/api/my/prospects', Object.assign({}, p, patch)); } catch (e) { IAP.status(e.message, 'bad'); } }; + pageList('prospects', el, ':scope > .lin-row', { per: LINE_PER }); + el.querySelectorAll('[data-pstatus]').forEach(s => s.addEventListener('change', () => save(s.dataset.pstatus, { status: s.value }))); + el.querySelectorAll('[data-pnext]').forEach(i => i.addEventListener('change', () => save(i.dataset.pnext, { next: i.value, nextTs: i.value ? Date.parse(i.value + 'T12:00:00') : null }))); + el.querySelectorAll('[data-pdel]').forEach(b => b.addEventListener('click', async () => { try { await api('/api/my/prospects/remove', { id: b.dataset.pdel }); loadProspects(); } catch (e) { IAP.status(e.message, 'bad'); } })); + } catch (e) {} + } + if ($('prospectForm')) $('prospectForm').addEventListener('submit', async e => { + e.preventDefault(); + try { + await api('/api/my/prospects', { name: $('ppName').value, contact: $('ppContact').value, status: $('ppStatus').value, nextTs: $('ppNext').value ? Date.parse($('ppNext').value + 'T12:00:00') : null }); + $('ppName').value = ''; $('ppContact').value = ''; $('ppNext').value = ''; loadProspects(); + } catch (err) { IAP.status(err.message, 'bad'); } + }); + // ── broadcast templates ── + const BC_TEMPLATES = [ + { label: 'Welcome', subject: 'Welcome to my line: your first three moves', html: '

Glad you are in. Three things today, in this order:

  1. Pick your username on the Profile tab (it becomes your link).
  2. Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
  3. Copy your invite link from My line and send it to one person.

Reply here if you get stuck on any of them. That is what I am here for.

' }, + { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '

Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.

The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.

' }, + { label: 'The $5 test', subject: 'See a payout land in real time', html: '

Want to see the whole thing work? Buy the $5 Micro package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.

When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.

' }, + { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '

You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $20 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.

Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.

' }, + { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '

Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.

Do not wait for the perfect moment. Nobody who waited ever built a line.

' } + ]; + (function () { + const w = $('bcTemplates'); if (!w) return; + w.innerHTML = BC_TEMPLATES.map((t, i) => '').join(''); + w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); })); + })(); + // ── Qualified Start calculator ── + (function () { + const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return; + const CR = { 20: 2000, 50: 5500, 100: 12000, 250: 32500, 500: 70000 }; + const calc = () => { + const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 20; + const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0); + const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.'; + out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + '
$' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share)
$' + net + ' net, plus a little POL for gas in each wallet
' + + '
' + credits.toLocaleString() + ' credits pooled for your own ads
' + level + '
The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
'; + }; + n.addEventListener('input', calc); pk.addEventListener('change', calc); calc(); + })(); + + // ── downline lineage + sponsor broadcast + upline messages ── + async function loadLineage() { + try { + const r = await (await fetch('/api/my/line')).json(); + const el = $('lineageWrap'); + if (r.error || !r.levels || !r.levels.every) return; + if (!r.levels.length || !r.levels.some(L => L.members.length)) { + el.innerHTML = '

No one in your downline yet. Share your link and it fills in here.

'; + return; + } + LINE_DATA = r; renderLineage(el); + } catch (e) {} + } + let LINE_DATA = null; + function renderLineage(el) { + const r = LINE_DATA; if (!r) return; + try { + const all = r.levels.reduce((n, L) => n + L.members.length, 0); + const shown = r.levels.map(L => ({ level: L.level, members: listApply('line', L.members) })); + const kept = shown.reduce((n, L) => n + L.members.length, 0); + el.innerHTML = ''; + el.appendChild(listBar('line', all, kept, () => renderLineage(el))); + el.insertAdjacentHTML('beforeend', !kept ? '

Nobody in your downline matches those filters.

' : shown.map(L => !L.members.length ? '' : + '
Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '
' + + L.members.map(m => '
' + esc(m.name) + (m.own ? ' yours' : '') + '' + + '' + (m.email ? esc(m.email) : (m.memberId ? '#' + m.memberId + '' : '')) + (m.sponsor ? 'sponsored by ' + esc(m.sponsor) + '' : '') + (m.own ? '' : '' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '' + memberChips(m) + '') + '' + + '' + + (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '' + + '' + new Date(m.joined).toLocaleDateString() + '' + + (m.email ? '' : '') + + (m.ref && !m.own ? '' : '') + + '
' + (m.ref && !m.own ? '' : '')).join('') + + '
').join('')); + el.querySelectorAll('[data-cemail]').forEach(b => + b.addEventListener('click', () => openConvo(b.dataset.cemail, b.dataset.cname))); + el.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => toggleLineActivity(b))); + const focusRef = LINE_FOCUS_REF ? LINE_FOCUS_REF.replace(/"/g, '') : null; + el.querySelectorAll('.lin-lvl').forEach((lv, i) => pageList('line-' + i, lv, ':scope > .lin-row', { per: LINE_PER, tail: '.lin-act', focus: focusRef ? row => !!row.querySelector('[data-act="' + focusRef + '"]') : null })); + if (LINE_FOCUS_REF) { + const ref = LINE_FOCUS_REF; LINE_FOCUS_REF = null; + const b = el.querySelector('[data-act="' + ref.replace(/"/g, '') + '"]'); + if (b) { const row = b.closest('.lin-row'); if (row) { row.classList.add('lin-focus'); setTimeout(() => row.classList.remove('lin-focus'), 4000); } toggleLineActivity(b); setTimeout(() => (row || b).scrollIntoView({ behavior: 'smooth', block: 'center' }), 150); } + } + } catch (e) {} + } + // who is working: per-member activity drop-down under the row (any of the three levels) + const lineActCache = {}; + async function toggleLineActivity(btn) { + const box = document.querySelector('[data-actbox="' + btn.dataset.act + '"]'); if (!box) return; + const open = box.hidden; box.hidden = !open; btn.setAttribute('aria-expanded', String(open)); btn.textContent = open ? 'Activity ▴' : 'Activity ▾'; + if (!open) return; + if (!lineActCache[btn.dataset.act]) { + box.innerHTML = 'Loading…'; + try { lineActCache[btn.dataset.act] = await (await fetch('/api/my/line/activity?ref=' + encodeURIComponent(btn.dataset.act))).json(); } catch (e) { lineActCache[btn.dataset.act] = { error: 'Could not load.' }; } + } + const a = lineActCache[btn.dataset.act]; + if (a.error) { box.innerHTML = '' + esc(a.error) + ''; return; } + const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; return Math.round(d / 86400e3) + 'd ago'; }; + const chip = (label, val, cls) => '' + esc(label) + '' + esc(val) + ''; + const working = (a.viewsToday || 0) > 0 || (a.campaignsActive || 0) > 0 || (a.linkViews30 || 0) > 0 || (a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3); + box.innerHTML = chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : '')) + + chip('Joined', new Date(a.joined).toLocaleDateString()) + + chip('Stage', (a.rung || 'Joined') + (a.next ? ' · next: ' + a.next : ''), a.stalled ? 'warn' : '') + + chip('Ads today', (a.viewsToday || 0) + '/' + (a.target || 5) + (a.claimedToday ? ' claimed' : '') + (a.streakDay ? ' · streak day ' + a.streakDay : ''), (a.viewsToday || 0) > 0 ? 'on' : '') + + chip('Campaigns', (a.campaignsActive || 0) + ' active of ' + (a.campaigns || 0) + (a.imps ? ' · ' + a.imps.toLocaleString() + ' views' : ''), (a.campaignsActive || 0) > 0 ? 'on' : '') + + chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '') + + chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '') + + chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn') + + (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '') + + '' + (working ? 'Working' : 'Quiet') + ''; + } + async function loadUplineMessages() { + try { + const r = await (await fetch('/api/my/messages')).json(); + if (r.error) return; + const card = $('upMsgCard'), list = $('upList'); + if (!r.items || !r.items.length) { card.hidden = true; return; } + card.hidden = false; + list.innerHTML = r.items.map(i => '
' + + '
' + esc(i.subject) + '' + + '' + esc(i.fromName) + ' · ' + new Date(i.sent).toLocaleDateString() + '
' + + '
' + (i.body || '') + '
').join(''); + pageList('upmsg', list, ':scope > .promo-block', { per: 5 }); + // opening the pane marks them read + for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {}); + } catch (e) {} + } + // broadcast composer editor (its own small rich editor, server sanitizes) + document.querySelectorAll('[data-bc]').forEach(b => + b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); })); + document.querySelectorAll('[data-bcblock]').forEach(b => + b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); })); + if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => { + const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; + const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); + if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } + }); + // broadcast send (2026-10-05, Brian: "clicking send didn't give me anything to feel it was sent"): a pop-up either way, + // and an expired sign-in keeps the draft so nothing typed is lost + const BC_DRAFT = 'iap.bcDraft'; + try { const d = JSON.parse(localStorage.getItem(BC_DRAFT) || 'null'); if (d && $('bcSubject') && !$('bcSubject').value) { $('bcSubject').value = d.subject || ''; $('bcEd').innerHTML = d.body || ''; if ($('bcScope') && d.scope) $('bcScope').value = d.scope; localStorage.removeItem(BC_DRAFT); } } catch (e) {} + if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', async () => { + const btn = $('bcSendBtn'); btn.disabled = true; const label = btn.textContent; btn.textContent = 'Sending…'; + try { + const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML }); + $('bcSubject').value = ''; $('bcEd').innerHTML = ''; + $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.'; + await IAP.confirmBox('Your broadcast was delivered to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + ' in your line. They see it in their Messages, and get a copy by email. You can send your next broadcast in 24 hours.', { title: '✅ Broadcast sent', ok: 'Done', noCancel: true }); + } catch (e) { + const msg = (e && e.message) || String(e); + if (/sign in/i.test(msg)) { + try { localStorage.setItem(BC_DRAFT, JSON.stringify({ subject: $('bcSubject').value, body: $('bcEd').innerHTML, scope: $('bcScope').value })); } catch (x) {} + if (await IAP.confirmBox('Your sign-in expired, so the broadcast was NOT sent. Your message is saved: sign in again and it will be waiting for you here.', { title: 'Not sent yet', ok: 'Sign in again', cancel: 'Close' })) location.href = '/my#line'; + } else { + await IAP.confirmBox(msg + ' Your message is still in the box.', { title: 'Broadcast not sent', ok: 'OK', noCancel: true }); + } + } finally { btn.disabled = false; btn.textContent = label; } + }); + + // ── solo-ads inbox: list, read view, dwell-gated read reward ── + let ibTimer = null; + function setInboxBadge(n) { + for (const id of ['inboxBadge', 'inboxBadge2']) { + const b = $(id); + if (b) { b.hidden = !n; b.textContent = n; } + } + } + // Earn credits sub-tabs: Watch ads | Inbox + let earnSub = 'watch'; + function setEarnSub(which) { + earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch'; + if (earnSub !== 'videos' && vidState.token) stopVideo(); + const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits'); + if (w) w.hidden = earnSub !== 'watch'; + if (i) i.hidden = earnSub !== 'inbox'; + if (v) v.hidden = earnSub !== 'videos'; + if (vs) vs.hidden = earnSub !== 'visits'; + document.querySelectorAll('.subtabs [data-earn]').forEach(b => + b.classList.toggle('on', b.dataset.earn === earnSub)); + if (earnSub === 'inbox') loadInbox(); + else if (earnSub === 'videos') loadVideoStatus(); + else if (earnSub === 'visits') loadVisitStatus(); + else earnRefresh(); + } + document.querySelectorAll('.subtabs [data-earn]').forEach(b => + b.addEventListener('click', () => setEarnSub(b.dataset.earn))); + // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14) + let tkState = null; + async function loadToolkit() { + try { + const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r; + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' }; + $('tkTierLine').textContent = 'you are at ' + names[r.tier]; + $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
    ' + t.items.map(i => '' + esc(i.t) + '').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join(''); + $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked; + if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $20 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; } + $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits'; + $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.'; + if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); } + renderTkTools(r); + $('tkHistory').innerHTML = r.history.length ? '

Recent

' + r.history.map(h => '
' + esc(h.kind) + ' · ' + new Date(h.ts).toLocaleString() + (h.charged ? ' · ' + h.charged + ' credits' : ' · free') + '
' + esc(h.text).replace(/\n/g, '
') + '
').join('') : ''; + } catch (e) { console.error('toolkit', e); } + } + // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops + const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 }; + async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; } + function renderTkTools(r) { + const at = tkRank[r.tier] || 0; + // Spark + const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark; + if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.'; + else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; } + // Circuit + const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ; + if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.'; + else { loadTkVideos(r); loadTkSplit(); } + // Nexus + const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex; + if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.'; + else { loadTkTeam(); renderTkPartner(r); } + } + let tkVidTimer = null; + async function loadTkVideos(r) { + const box = $('tkVideos'); + if (!r.videoMaker) { box.innerHTML = '

The Video Maker is warming up on the server. Check back shortly.

'; return; } + if (!r.username) { box.innerHTML = '

Pick a username first (Profile); it goes on the end card.

'; return; } + try { + const v = await (await fetch('/api/my/toolkit/videos')).json(); if (v.error) return; + box.innerHTML = v.list.map(x => '
' + tkEsc(x.title) + '' + (x.status === 'done' ? 'Download ' : x.status === 'queued' || x.status === 'working' ? '
' + tkEsc(x.stage || 'Starting') + (x.status === 'working' ? ' · ' + (x.pct || 0) + '%' : '') + '' : '') + '
').join(''); + clearTimeout(tkVidTimer); if (v.list.some(x => x.status === 'queued' || x.status === 'working')) tkVidTimer = setTimeout(() => loadTkVideos(r), 2500); + } catch (e) {} + } + async function loadTkSplit() { + try { + const sp = await (await fetch('/api/my/toolkit/split')).json(); if (sp.error) return; + const rows = sp.rows.filter(x => x.views || x.joins); + $('tkSplit').innerHTML = !rows.length ? '

No link views yet. Share two different angle links this week and the winner shows up here.

' + : '
' + rows.map(x => '').join('') + '
AngleViewsLast 30dJoinsBuyersJoin rate
' + tkEsc(x.angle) + (x.angle === sp.best ? ' (winner so far)' : '') + '
' + tkEsc(x.link) + '
' + x.views + '' + x.views30 + '' + x.joins + '' + x.buyers + '' + x.rate + '%

Rate = joins per 100 views. A winner needs at least 10 views. Send more traffic to the winner, keep testing the rest.

'; + } catch (e) {} + } + let tkTeamData = null; + async function loadTkTeam() { + try { + const t = await (await fetch('/api/my/toolkit/team')).json(); if (t.error || !t.unlocked) return; tkTeamData = t; + $('tkTeamSub').textContent = t.total + ' in three levels (' + t.byLevel.join(' / ') + ') · ' + t.recent + ' new this week · ' + t.stalled.length + ' stalled'; + const list = t.stalled.length ? t.stalled : t.members.slice(0, 12); + $('tkTeam').innerHTML = (t.stalled.length ? '

Stalled first: quiet for a while and not yet past the next rung. One click sends them the right message from you.

' : '

Nobody stalled right now. Your newest people:

') + + list.map(m => '
' + tkEsc(m.name) + ' L' + m.level + ' · ' + tkEsc(m.label) + (m.quietDays ? ' · quiet ' + m.quietDays + 'd' : '') + '
Next: ' + tkEsc(m.next) + '
').join(''); + $('tkGrantTo').innerHTML = t.members.map(m => '').join(''); + } catch (e) {} + } + function renderTkPartner(r) { + const pk = r.partner; + $('tkPartner').innerHTML = pk + ? '

Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.

Invite link with the code: ' + tkEsc(pk.link) + '

Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '

' + : '

Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.

'; + } + document.addEventListener('click', async ev => { + const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return; + if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; } + if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; } + if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; } + if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; } + if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; } + if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; } + if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; } + if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; } + }); + $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; }); + async function tkSendBroadcast() { + const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt); + const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim(); + if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return; + const r = await tkPost('/api/my/broadcast', { subject, body: '

' + tkEsc(body).replace(/\n{2,}/g, '

').replace(/\n/g, '
') + '

', scope: 'all' }); + if (r) IAP.status('Sent to ' + (r.sent || r.count || r.recipients || 'your team') + '.', 'ok'); + } + async function tkGenerate() { + const btn = $('tkGo'); if (btn.disabled) return; btn.disabled = true; btn.textContent = 'Writing…'; + try { + const r = await (await fetch('/api/my/toolkit/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind: $('tkKind').value, angle: $('tkAngle').value, brief: $('tkBrief').value }) })).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + $('tkText').value = r.text; $('tkOut').hidden = false; $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; + IAP.status(r.charged ? r.charged + ' credits used.' : 'Written. ' + r.freeLeft + ' free left this month.', 'ok'); + loadToolkit(); loadDashboard(); + } catch (e) { IAP.status('The engine did not answer. Try again.', 'bad'); } + finally { btn.disabled = false; btn.textContent = 'Write it'; } + } + if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); } + // promo tools: pill menu switches between posts / swipes / banners / wall / videos + function setPromoSub(name) { + const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'games']; + if (['polhunter', 'spookydoors', 'gamebanners'].includes(name)) name = 'games'; // those tabs live inside Games now (2026-10-06) + if (name === 'toolkit') loadToolkit(); + const pill = document.querySelector('.promo-pills [data-promo="' + name + '"]'); + if (!ids.includes(name) || !pill || pill.hidden) name = 'posts'; + ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; }); + document.querySelectorAll('.promo-pills [data-promo]').forEach(b => { + b.classList.toggle('on', b.dataset.promo === name); + b.setAttribute('aria-selected', b.dataset.promo === name ? 'true' : 'false'); + }); + try { localStorage.setItem('iap.promoSub', name); } catch (e) {} + } + document.querySelectorAll('.promo-pills [data-promo]').forEach(b => + b.addEventListener('click', () => setPromoSub(b.dataset.promo))); + try { setPromoSub(localStorage.getItem('iap.promoSub') || 'posts'); } catch (e) { setPromoSub('posts'); } + async function loadInbox() { + try { + const r = await (await fetch('/api/my/inbox')).json(); + if (r.error) return; + $('ibRewardNote').textContent = '+' + r.readCredits + ' credits per real read (up to ' + + r.readCap + ' rewarded reads a day)'; + const el = $('ibList'); + $('inboxReadCard').hidden = true; + $('inboxListCard').hidden = false; + setInboxBadge(r.unread); + if (!r.items.length) { + el.innerHTML = '

No solo ads yet. When a member sends one, it lands here — and reading it pays.

'; + return; + } + el.innerHTML = ''; + for (const i of r.items) { + const d = document.createElement('div'); + d.className = 'ib-row' + (i.read ? '' : ' unread'); + d.innerHTML = '' + + (i.rewarded ? 'claimed' : i.read ? '' : 'new') + + '' + new Date(i.delivered).toLocaleDateString() + ''; + d.querySelector('.sub').textContent = i.subject || '(no subject)'; + d.querySelector('.from').textContent = 'from ' + (i.fromName || 'a member'); + d.addEventListener('click', () => openInboxItem(i.id)); + el.appendChild(d); + } + } catch (e) {} + } + async function openInboxItem(id) { + try { + const r = await (await fetch('/api/my/inbox/' + id)).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + $('inboxListCard').hidden = true; + $('inboxReadCard').hidden = false; + $('ibSubject').textContent = r.subject || '(no subject)'; + $('ibMeta').textContent = 'from ' + (r.fromName || 'a member') + ' · ' + new Date(r.delivered).toLocaleString(); + $('ibBody').innerHTML = r.body || ''; // whitelist-sanitized on the server at submit + const mv = $('ibMedia'); + mv.hidden = !r.mediaUrl; + mv.innerHTML = !r.mediaUrl ? '' + : r.mediaType === 'video' + ? '' + : 'attachment'; + // the read reward needs BOTH the dwell AND an actual click-through to the + // advertiser — the visit is what makes the ad worth the sender's credits + const visit = $('ibVisit'); + visit.href = r.url; + visit.textContent = r.ctaLabel || 'Learn more'; + visit.target = '_blank'; + const btn = $('ibClaimBtn'); + clearInterval(ibTimer); + if (r.rewarded) { + btn.hidden = true; + visit.classList.remove('cta-need'); + $('ibHint').textContent = 'Read reward already claimed for this one.'; + return; + } + let dwellDone = false; + let visited = !!r.visited; + btn.hidden = false; + btn.disabled = true; + visit.classList.toggle('cta-need', !visited); + let left = r.dwell; + const refresh = () => { + if (!dwellDone) { btn.textContent = 'Read it — claim in ' + left + 's'; return; } + if (!visited) { btn.textContent = 'Claim +' + r.reward + ' — visit the ad first'; btn.disabled = true; return; } + btn.textContent = 'Claim +' + r.reward + ' credits'; btn.disabled = false; + }; + $('ibHint').textContent = 'Read the message, click through to the advertiser, then claim your credits.'; + refresh(); + // countdown pauses off-tab; the server separately enforces the dwell on its own clock + ibTimer = setInterval(() => { + if (!tabActive()) return; + left -= 1; + if (left > 0) { refresh(); return; } + clearInterval(ibTimer); + dwellDone = true; + refresh(); + }, 1000); + // clicking the CTA records the visit (and counts the advertiser's click) + visit.onclick = async () => { + visited = true; + visit.classList.remove('cta-need'); + try { await fetch('/api/my/inbox/' + id + '/visit', { method: 'POST' }); } catch (e2) {} + refresh(); + }; + btn.onclick = async () => { + try { + const c = await api('/api/my/inbox/' + id + '/claim'); + IAP.status('+' + c.credited + ' credits for reading. They spend like any earned credits.', 'ok'); + btn.hidden = true; + $('ibHint').textContent = 'Claimed. Head back for the next one.'; + loadDashboard(); + } catch (e2) { IAP.status(e2.message, 'bad'); } + }; + } catch (e) {} + } + $('ibBack').addEventListener('click', ev => { ev.preventDefault(); clearInterval(ibTimer); loadInbox(); }); + + // ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ── + function fillPromo(link, me) { + if (window.IAPPromo) IAPPromo.fill(link, me || {}); + // banner kit + const bwrap = $('promoBanners'); + if (bwrap && !bwrap.dataset.filled) { + bwrap.dataset.filled = '1'; + // one collapsed accordion per size / use, so the kit stays scannable as it grows + const GROUPS = [ + { title: 'Stop chasing shiny objects · share the article with your link', bridge: { page: 'blog/stop-chasing-shiny-objects', name: 'shiny-objects article', short: 'article' }, items: [ + { file: 'iap-shiny-objects-wide-1200x630.jpg', size: '1200×630 · the article cover (widescreen art) · Facebook, X, link previews' }, + { file: 'iap-shiny-objects-wide-1600x896.jpg', size: '1600×896 · full widescreen art · YouTube community, LinkedIn, blogs' }, + { file: 'iap-shiny-objects-1200x630.jpg', size: '1200×630 · tight crop of the portrait art' }, + { file: 'iap-shiny-objects-1080x1080.jpg', size: '1080×1080 · square · Instagram, Facebook, Telegram' }, + { file: 'iap-shiny-objects-1080x1349.jpg', size: '1080×1349 · portrait · Instagram feed, Pinterest' } ] }, + { title: 'Wired Wednesday · share with your /wednesday link', bridge: { page: 'wednesday', name: 'Wired Wednesday', short: 'Wednesday' }, items: [ + { file: 'iap-wired-wednesday-1200x630.jpg', size: '1200×630 · Wired Wednesday · social card, link previews, Daily News' }, + { file: 'iap-wired-wednesday-1080x1080.jpg', size: '1080×1080 · Wired Wednesday · Instagram, Facebook, Telegram' }, + { file: 'iap-wired-wednesday-728x90.png', size: '728×90 · Wired Wednesday · leaderboard' }, + { file: 'iap-wired-wednesday-300x250.png', size: '300×250 · Wired Wednesday · rectangle' } ] }, + { title: 'Five Dollar Friday · share with your /friday link', friday: true, items: [ + { file: 'iap-five-dollar-friday-october-1200x630.jpg', size: '1200×630 · Five Dollar Friday · October porch, bright' }, + { file: 'iap-five-dollar-friday-october-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · October porch, square' }, + { file: 'iap-five-dollar-friday-v2-1200x630.jpg', size: '1200×630 · Five Dollar Friday · loft, Central-time window' }, + { file: 'iap-five-dollar-friday-dark-1200x630.jpg', size: '1200×630 · Five Dollar Friday · dark studio' }, + { file: 'iap-five-dollar-friday-v2-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · square for Instagram and feeds' } ] }, + { title: '600×300 · traffic exchanges and splash pages', items: [ + { file: 'iap-advertise-earn-600x300.png', size: '600×300 · advertise and earn · traffic exchanges, splash pages, safelist mailers' } ] }, + { title: '1200×630 · social posts, link previews, Daily News covers', items: [ + { file: 'iap-hero-1200x630.png', size: '1200×630 · hero · advertise and earn' }, + { file: 'iap-advertise-earn-1200x630.jpg', size: '1200×630 · advertise and earn instantly, locked in code' }, + { file: 'iap-team-build-tiers-1200x630.jpg', size: '1200×630 · team build and instant payments · 50 / 20 / 10 tiers' }, + { file: 'iap-team-build-tiers-v2-1200x630.jpg', size: '1200×630 · team build and instant payments · variant 2' }, + { file: 'iap-instant-payments-tiers-1200x630.jpg', size: '1200×630 · instant payments, direct commissions · tiers' }, + { file: 'iap-instant-payments-tiers-v2-1200x630.jpg', size: '1200×630 · instant payments · variant 2' }, + { file: 'iap-multistream-info-1200x630.jpg', size: '1200×630 · multi-stream revenue · "INFO or message me" CTA' }, + { file: 'iap-multistream-info-v2-1200x630.jpg', size: '1200×630 · multi-stream revenue · variant 2' }, + { file: 'iap-success-path-info-1200x630.jpg', size: '1200×630 · success path, training and coaching · "INFO or message me" CTA' }, + { file: 'iap-success-path-link-1200x630.jpg', size: '1200×630 · success path · "link in the description" (feed posts, Daily News)' }, + { file: 'iap-success-path-coaching-1200x630.jpg', size: '1200×630 · success path · quality network traffic' } ] }, + { title: 'Five Dollar Friday · every Friday, +20% credits on any $5+ pack', items: [ + { file: 'iap-five-dollar-friday-1200x630.jpg', size: '1200×630 · social card, Daily News, feed posts' }, + { file: 'iap-five-dollar-friday-1080x1080.jpg', size: '1080×1080 · Instagram, Facebook, Telegram' }, + { file: 'iap-five-dollar-friday-728x90.png', size: '728×90 · leaderboard' }, + { file: 'iap-five-dollar-friday-300x250.png', size: '300×250 · rectangle' } ] }, + { title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [ + { file: 'iap-1080x1080.png', size: '1080×1080 · square' }, + { file: 'iap-1080x1920.png', size: '1080×1920 · story / reel' } ] }, + { title: '1280×720 · Telegram and group posts', items: [ + { file: 'iap-1280x720.png', size: '1280×720 · group post' } ] }, + { title: 'Leaderboards · 728×90, 468×60, 320×50', items: [ + { file: 'iap-728x90.png', size: '728×90 · leaderboard' }, + { file: 'iap-advertise-earn-728x90.png', size: '728×90 · advertise and earn instantly · Join free' }, + { file: 'iap-ledger-728x90.png', size: '728×90 · advertising that pays you on-chain · See the ledger' }, + { file: 'iap-468x60.png', size: '468×60 · banner' }, + { file: 'iap-ledger-468x60.png', size: '468×60 · advertising that pays you on-chain · See the ledger' }, + { file: 'iap-320x50.svg', size: '320×50 · mobile leaderboard' } ] }, + { title: 'Rectangles and buttons · 336×280, 300×250, 125×125', items: [ + { file: 'iap-336x280.png', size: '336×280 · large rectangle' }, + { file: 'iap-advertise-earn-336x280.png', size: '336×280 · advertise and earn instantly' }, + { file: 'iap-advertise-earn-v2-336x280.png', size: '336×280 · advertise and earn · variant 2' }, + { file: 'iap-300x250.png', size: '300×250 · rectangle' }, + { file: 'iap-advertise-earn-300x250.png', size: '300×250 · advertise and earn instantly' }, + { file: 'iap-team-build-link-300x250.jpg', size: '300×250 · team build and instant payments · "link in the description"' }, + { file: 'iap-125x125.png', size: '125×125 · square button' } ] }, + { title: 'Skyscrapers · 160×600, 120×600', items: [ + { file: 'iap-160x600.png', size: '160×600 · wide skyscraper' }, + { file: 'iap-120x600.png', size: '120×600 · skyscraper' } ] } + ]; + bwrap.innerHTML = ''; + for (const g of GROUPS) { + const det = document.createElement('details'); + det.className = 'pb-acc'; + det.innerHTML = '' + esc(g.title) + '' + g.items.length + (g.items.length === 1 ? ' banner' : ' banners') + '
'; + const grid = det.querySelector('.pb-grid'); + const bridge = g.bridge || (g.friday ? { page: 'friday', name: 'Five Dollar Friday', short: 'Friday' } : null); + if (bridge) { + // the bridge page with this member's referral: any public page + ?ref sets the sponsor cookie + const inv = (document.getElementById('inviteLine') || {}).textContent || ''; + const fl = inv.replace(/\/join\/([^/?#]+).*$/, '/' + bridge.page + '?ref=$1'); + const note = document.createElement('div'); + note.className = 'pb-note'; + note.innerHTML = 'Post any of these with your ' + esc(bridge.name) + ' link: '; + note.querySelector('b').textContent = fl; + const cp = document.createElement('button'); cp.className = 'btn small'; cp.textContent = 'Copy my ' + bridge.short + ' link'; + cp.addEventListener('click', async () => { try { await navigator.clipboard.writeText(fl); IAP.status(bridge.short + ' link copied.', 'ok'); } catch (e) { IAP.status('Copy failed.', 'bad'); } }); + note.appendChild(cp); + grid.before(note); + } + for (const b of g.items) { + const url = location.origin + '/banners/' + b.file; + const d = document.createElement('div'); + d.className = 'pb-item'; + d.innerHTML = 'InstantAdPay banner ' + b.size + '' + + '
' + b.size + '
'; + const dl = document.createElement('a'); + dl.className = 'btn small'; dl.textContent = 'Download'; dl.href = '/banners/' + b.file; dl.setAttribute('download', b.file); + d.querySelector('.pb-row').appendChild(dl); + const btn = document.createElement('button'); + btn.className = 'btn small sec'; + btn.textContent = 'Copy image URL'; + btn.addEventListener('click', async () => { + try { await navigator.clipboard.writeText(url); IAP.status('Banner URL copied.', 'ok'); } + catch (e) { IAP.status('Copy failed.', 'bad'); } + }); + d.querySelector('.pb-row').appendChild(btn); + grid.appendChild(d); + } + bwrap.appendChild(det); + } + } + } + + // ── profile ── (busy2 defers the busy lookup past its TDZ) + $('pfSaveBtn').addEventListener('click', busy2($('pfSaveBtn'), async () => { + const r = await api('/api/my/profile', { username: $('pfUsername').value }); + IAP.status('You are @' + r.account.username + ' now.', 'ok'); + await render(); + })); + + // ── in-dashboard package buying ── + const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' }; + // Card on-ramp: buy POL with a card via MoonPay, delivered to the buyer's own + // wallet. Signed + wallet-prefilled once MoonPay keys are set; generic page + // otherwise. The site never touches funds — MoonPay is merchant of record. + async function openMoonpay(pol) { + try { + let addr = ''; + try { const me = await (await fetch('/api/me')).json(); addr = me.address || ''; } catch (e) {} + const q = '/api/moonpay-url?pol=' + encodeURIComponent(pol || '') + (addr ? '&address=' + encodeURIComponent(addr) : ''); + const r = await (await fetch(q)).json(); + if (r && r.url) { + window.open(r.url, '_blank', 'noopener'); + IAP.status(r.signed + ? 'MoonPay opened in a new tab with your wallet address pre-filled. Choose POL on Polygon, finish the purchase, then come back and buy your package.' + : 'MoonPay opened in a new tab. Choose POL on the Polygon network and paste your own wallet address as the destination, then come back.', 'ok'); + } + } catch (e) { IAP.status('Could not open MoonPay: ' + ((e && e.message) || e), 'bad'); } + } + // ── linked positions (Qualified Start) ── + const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : ''; + let noPayoutAddrs = new Set(); // positions the site refuses to buy from (see siteConfig.noPayoutIds) + async function loadPositions(me) { + try { + const r = await (await fetch('/api/my/positions')).json(); + if (r.error) return; + const list = r.positions || []; + const rows = list.map((p, i) => '
Position ' + (i + 2) + ' ' + short(p.address) + '' + + '' + (p.memberId ? '#' + p.memberId : 'not on-chain yet') + '' + + '' + (p.noPayout ? 'linkage only: no purchases from this position (payouts would reach a retired wallet)' : p.counted ? 'counts as a qualifying buyer' : p.memberId ? 'registered, buy $20+ to count' : 'buy a $20+ package to register it') + '' + + '' + (p.credits || 0).toLocaleString() + ' credits' + (p.balanceWei != null ? ' · ' + (Number(BigInt(p.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '' + + (!p.memberId ? '' : '') + + '
').join(''); + const mainRow = r.main && r.main.address ? '
Position 1 · main ' + short(r.main.address) + '' + + '' + (r.main.memberId ? '#' + r.main.memberId : 'payouts not on yet') + '' + + '' + (r.main.buyerCount || 0) + ' qualifying buyer(s)' + + '' + (r.main.credits || 0).toLocaleString() + ' credits' + (r.main.balanceWei != null ? ' · ' + (Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '
' : ''; + const html = mainRow + rows + (list.length ? '

Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.

' : ''); + if ($('qsList')) $('qsList').innerHTML = html; + // Wallet tab: live POL balance of the linked wallet, and which package it covers + const wb = $('walletBal'); + if (wb && r.main && r.main.address && r.main.balanceWei != null) { + const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000; + const usd = r.polUsd ? polN * r.polUsd : 0; + const pkgs = [5, 20, 50, 100, 250]; + const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : []; + wb.hidden = false; + wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '') + + (r.polUsd ? '
' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : ''); + } + if ($('posList')) $('posList').innerHTML = html; + if ($('posCard')) $('posCard').hidden = !list.length; + // "Buy from" picker: main + every position + const sel = $('buyFrom'); + if (sel) { + const keep = sel.value; + sel.innerHTML = '' + + list.map((p, i) => '').join(''); + noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase()); + if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep; + $('buyFromWrap').hidden = !list.length; + } + document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => { + if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return; + try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => { + const me = await (await fetch('/api/me')).json(); + if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.'); + if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.'); + if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return; + IAP.status('Pick the new account in your wallet, then sign once…'); + const r = await IAPWallet.signIn({ asPosition: true, pick: true }); + $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $20 or larger package.'; + IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $20+ package to count it.', 'ok'); + await loadPositions(); + const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase(); + try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {} + })); + async function loadBuyTiles() { + try { + const { products } = await (await fetch('/api/catalog')).json(); + const wrap = $('boTiles'); + wrap.innerHTML = ''; + products.sort((a, b) => a.priceCents - b.priceCents); + for (const p of products) { + const bonus = p.creditAmount - p.priceCents; + const div = document.createElement('div'); + div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : ''); + div.innerHTML = '
' + (PKG[p.id] || 'Package ' + p.id) + '
' + + '
$' + Math.round(p.priceCents / 100) + '
' + + '
' + p.creditAmount.toLocaleString() + ' credits
' + + '
' + (bonus > 0 ? '+' + bonus.toLocaleString() + ' bonus credits' : ' ') + '
' + + '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
' + + ''; + wrap.appendChild(div); + } + wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => { + try { + b.disabled = true; + // the buyer's credits are read by the member id of their LINKED wallet. + // If they only connected a wallet (e.g. for the faucet) but never linked + // it, link it first (one signature) so the purchase's credits show up. + // retry these through transient failures — mobile drops in-flight + // fetches when the page returns from the wallet app-switch + const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; }; + const meNow = await jretry('/api/me'); + // which of the member's wallets is buying: the main wallet (default) or a + // linked position (Qualified Start). A position registers under the main + // member id on its first buy, so its sponsor is always this member. + const fromSel = $('buyFrom'); + const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null; + if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; } + if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; } + if (!fromPos && !meNow.address) { + IAP.status('Link your wallet first — one quick signature…'); + await IAPWallet.signIn(); + } + const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null); + if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member + await IAPWallet.connect(); + let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); + if (cur !== wantAddr) { + IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…'); + cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); + } + if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.'); + } + const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy'); + if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company + if (!fromPos && !meNow.memberId && spNow.sponsorRouted) IAP.status((spNow.sponsorRouted.from || 'Your sponsor') + ' has not switched on payouts, so this purchase credits ' + spNow.sponsorRouted.to + ' instead. You are not held up; carrying on.', 'ok'); + // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any + // transaction that spends most of the balance ("drain your wallet"), so Trust users + // get a heads-up first; other wallets go straight to the confirmation. + try { + const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy() + const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address); + if (bal < need) { + IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad'); + return; + } + const pct = Number(need * 100n / bal); + const isTrust = /trust/i.test(IAPWallet.walletName() || ''); + if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) { + IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok'); + return; + } + } catch (e) { /* balance read failed: let the wallet decide */ } + IAP.status('Confirm the purchase in your wallet…'); + const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost); + if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.'); + // a game sent them here to pay (PolyWarriors mint, Gem Kingdom Crowns, Spooky Doors costume): go straight back once it settles (Marty 2026-10-08) + const back = document.getElementById('pwBack') ? ['/pw/mint/resume', 'PolyWarriors'] : document.getElementById('gkBack') ? ['/gk/shop/resume', 'Gem Kingdom'] : document.getElementById('sdBack') ? ['/sd/shop/resume', 'Spooky Doors'] : null; + if (back) { IAP.status('Purchase settled on-chain. Taking you back to ' + back[1] + '…', 'ok'); setTimeout(() => { location.href = back[0]; }, 1800); return; } + IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok'); + await render(); + loadBuyTiles(); + } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); } + finally { b.disabled = false; } + })); + // brand new to crypto? buy POL with a card, sent straight to the wallet + const builder = products.find(p => p.priceCents === 5000) || products[products.length - 1]; + const needPol = (builder && builder.costWei) ? Math.max(30, Math.ceil(Number(builder.costWei) / 1e18) + 3) : 30; + const cta = document.createElement('div'); + cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center'; + cta.innerHTML = '

New to crypto? Buy POL with a debit or credit card, Apple Pay, or Google Pay. It lands straight in your own wallet, and this site never touches your money.

' + + ' Wallet and MoonPay guide'; + wrap.appendChild(cta); + const mb = $('moonpayBtn'); if (mb) mb.addEventListener('click', () => openMoonpay(needPol)); + } catch (e) {} + } + loadBuyTiles(); + + // ── earn-by-viewing: daily ad set with dwell, then claim ── + const earnState = { types: ['banner', 'text'], i: 0, timer: null }; + async function earnRefresh() { + try { + const st = await (await fetch('/api/my/earn')).json(); + if (st.error) return null; + $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed'; + loadFridayBank(); + $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : ''); + if ($('earnActLink')) $('earnActLink').onclick = e => { e.preventDefault(); jumpTo('campaigns', 'creditActivity'); }; + const done = st.views >= st.target; + $('earnClaimBtn').hidden = !(done && !st.claimed); + if (st.claimed) { + $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.'; + // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign + const box = $('earnAdBox'); + if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.' + + '
' + + (st.visitsLeft ? '' : '') + + ((st.earnedAvailable != null ? st.earnedAvailable : st.earned) > 0 + ? '' + : '') + '
'; + if (box) box.querySelectorAll('[data-earnnext]').forEach(b => b.addEventListener('click', () => { if (b.dataset.earnnext === 'campaigns') setPane('campaigns'); else setEarnSub('visits'); })); + if ($('earnStartBtn')) $('earnStartBtn').hidden = true; + } else { + if ($('earnStartBtn')) $('earnStartBtn').hidden = done; // set done: the claim button takes over + $('earnHint').textContent = done + ? 'Set complete. Claim your ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' + : (st.views ? (st.target - st.views) + ' more to go, then claim ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' : 'View ' + st.target + ' ads to unlock the daily claim of ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.'); + } + return st; + } catch (e) { return null; } + } + async function earnShowAd() { + // each view happens full screen in its own tab: /view/ frames the + // advertiser's site, runs the countdown, then a human check credits it + const type = earnState.types[earnState.i++ % earnState.types.length]; + let r = null; + try { r = await (await fetch('/api/my/earnview?type=' + type)).json(); } catch (e) {} + const box = $('earnAdBox'); + if (!r || !r.ad || !r.viewUrl) { + await earnRefresh(); + box.innerHTML = '' + (r && r.status && r.status.views >= r.status.target + ? 'Set complete for today.' + : 'No member ads are live in rotation right now. Views resume the moment a campaign is running.') + ''; + return; + } + openAdOverlay(r.viewUrl); + box.innerHTML = 'Watch the countdown and pass the quick check. Your view credits itself and this page updates right away.'; + $('earnStartBtn').textContent = 'View next ad'; + } + // In-page ad overlay: no new tab (mobile and in-app wallet browsers handle tabs + // badly), no window.close needed. The /view page runs the dwell + check inside, + // messages back when it credits or when the user is done. + function openAdOverlay(url) { + closeAdOverlay(); + const back = document.createElement('div'); + back.id = 'adOverlay'; + back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050b09;display:flex;flex-direction:column'; + const x = document.createElement('button'); + x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); + x.textContent = '✕'; + x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; + x.addEventListener('click', closeAdOverlay); + const ifr = document.createElement('iframe'); + ifr.src = url; + ifr.style.cssText = 'flex:1;width:100%;border:0;background:#050b09'; + back.appendChild(ifr); back.appendChild(x); + document.body.appendChild(back); + document.body.style.overflow = 'hidden'; + } + function closeAdOverlay() { + const m = $('adOverlay'); if (m) m.remove(); + document.body.style.overflow = ''; + earnRefresh(); loadDashboard(); + } + window.addEventListener('message', e => { + if (e.origin !== location.origin || !e.data) return; + if (e.data.t === 'iap-view-close') closeAdOverlay(); + else if (e.data.t === 'iap-view-done') { earnRefresh(); loadDashboard(); } + }); + $('earnStartBtn').addEventListener('click', () => earnShowAd()); + // the viewer tab pings localStorage when a view credits; refresh instantly + window.addEventListener('storage', e => { + if (e.key === 'iap-view-done') { earnRefresh(); loadDashboard(); } + }); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible' && $('pane-earn') && !$('pane-earn').hidden) earnRefresh(); + }); + $('earnClaimBtn').addEventListener('click', async () => { + try { + const r = await api('/api/my/claim'); + IAP.status('+' + r.credited + ' credits earned' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Tomorrow\'s claim pays ' + r.nextClaim + '. Spend them in Campaigns.', 'ok'); + await earnRefresh(); + loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + }); + + const busy = (btn, fn) => async () => { + try { btn.disabled = true; await fn(); } + catch (e) { IAP.status((e && e.message) || String(e), 'bad'); } + finally { btn.disabled = false; } + }; + + // passwordless (feature-flagged on config.emailAuth): code replaces passwords + (async () => { + const cfg = await IAP.getConfig(); + if (!cfg.emailAuth) return; + $('passCards').hidden = true; + $('magicCard').hidden = false; + const codeOpts = () => ({ honeypot: $('mcWebsite'), host: $('mcCheck') }); + const start = busy($('mcSendBtn'), async () => { + const r = await IAP.requestCode($('mcEmail').value, codeOpts()); + $('mcCodeRow').hidden = false; + $('mcVerifyBtn').hidden = false; + $('mcSendBtn').hidden = true; + $('mcResend').hidden = false; + if (r.devCode) { $('mcCode').value = r.devCode; IAP.status('Dev mode: code filled in for you.', 'ok'); } + else IAP.status('Code sent. Check your inbox (and spam, the first time).', 'ok'); + $('mcCode').focus(); + }); + $('mcSendBtn').addEventListener('click', start); + $('mcResend').addEventListener('click', busy($('mcResend'), async () => { + const r = await IAP.requestCode($('mcEmail').value, codeOpts()); + if (r.devCode) $('mcCode').value = r.devCode; + IAP.status('Fresh code sent.', 'ok'); + })); + $('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => { + const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); + IAP.status('You are in.', 'ok'); + if (r.next && !r.created) { location.href = r.next; return; } // came from Drip Runner: straight back into the game + if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first + if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad + await render(); + })); + })(); + + // new-member onboarding: choose a username (required), optionally a bio. + // required=true: no skip, no backdrop dismiss, prefilled suggestion, resolves only after a save. + function showOnboard(required) { + return new Promise(resolve => { + const m = $('onboardModal'); if (!m) return resolve(); + m.hidden = false; $('obErr').hidden = true; + $('obSkip').hidden = !!required; + if (required && !$('obUsername').value) { + fetch('/api/my/username-suggest').then(r => r.json()).then(r => { if (r.suggest && !$('obUsername').value) { $('obUsername').value = r.suggest; $('obUsername').select(); } }).catch(() => {}); + } + setTimeout(() => $('obUsername').focus(), 50); + const done = () => { m.hidden = true; resolve(); }; + $('obSkip').onclick = required ? null : done; + $('obUsername').onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); $('obSave').click(); } }; + $('obSave').onclick = async () => { + const u = $('obUsername').value.trim(); + if (required && !u) { $('obErr').hidden = false; $('obErr').textContent = 'Pick a username to continue.'; return; } + try { + if (u) await api('/api/my/profile', { username: u }); + const bio = $('obBio').value.trim(); + if (bio) await api('/api/my/profile-details', { bio }); + done(); + } catch (e) { $('obErr').hidden = false; $('obErr').textContent = e.message || 'Could not save that. Try a different username.'; } + }; + }); + } + + $('signupBtn').addEventListener('click', busy($('signupBtn'), async () => { + const r = await api('/api/signup', { email: $('suEmail').value, password: $('suPass').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); + IAP.status('Welcome aboard. You are in.', 'ok'); + if (!(r.account && r.account.username)) await showOnboard(); + await render(); + })); + $('loginBtn').addEventListener('click', busy($('loginBtn'), async () => { + await api('/api/login', { email: $('liEmail').value, password: $('liPass').value }); + IAP.status('Logged in.', 'ok'); + if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad + await render(); + })); + $('linkBtn').addEventListener('click', busy($('linkBtn'), async () => { + IAP.status('Check your wallet for the free link signature…'); + const lr = await IAPWallet.signIn(); // server binds the wallet to the signed-in email account + if (lr && lr.next) { IAP.status('Wallet linked. Taking you back to PolHunter…', 'ok'); setTimeout(() => { location.href = lr.next; }, 700); return; } // they came from PolHunter: close the loop + IAP.status('Wallet linked. Earnings pay there from now on.', 'ok'); + await render(); + })); + if ($('faucetBtn')) $('faucetBtn').addEventListener('click', busy($('faucetBtn'), async () => { + IAP.status('Connect your wallet first…'); + const addr = await IAPWallet.connect(); + let copied = false; + try { await navigator.clipboard.writeText(addr); copied = true; } catch (e) {} + window.open('https://faucet.polygon.technology/', '_blank', 'noopener'); + $('faucetInfo').innerHTML = 'Your address ' + addr.slice(0, 8) + '…' + addr.slice(-6) + '' + + (copied ? ' is copied' : '') + '. On the faucet, choose Polygon Amoy, paste your address, and request POL. Then come back and buy.'; + IAP.status('Faucet opened in a new tab. Choose Polygon Amoy, paste your address, and request test POL.', 'ok'); + })); + if ($('wcDisconnect')) $('wcDisconnect').addEventListener('click', busy($('wcDisconnect'), async () => { + // fire-and-forget: don't gate the reload on disconnect resolving (it can + // stall). The reload drops all in-memory wallet state and the picker returns. + IAPWallet.disconnect().catch(() => {}); + $('wcDisconnectInfo').textContent = 'Disconnecting — reloading so you can pick a different wallet…'; + IAP.status('Disconnecting — reloading…', 'ok'); + setTimeout(() => location.reload(), 900); + })); + // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) + function sponsorHoldText(sp) { + const who = sp.sponsorName || 'your sponsor'; + if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.'; + if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; + return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; + } + $('activateBtn').addEventListener('click', busy($('activateBtn'), async () => { + const me = await (await fetch('/api/me')).json(); + if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; } + IAP.status('Confirm the free activation in your wallet…'); + const r = await IAPWallet.activate(me.sponsorId || 0); + if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); + IAP.status('Payouts are on. Your invite link is live.', 'ok'); + await render(); + })); + $('copyInvite').addEventListener('click', async () => { + try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); } + }); + $('logoutLink').addEventListener('click', async e => { + e.preventDefault(); + await fetch('/api/auth/logout', { method: 'POST' }); + IAP.status('Logged out.', 'ok'); + await render(); + }); + + // ── welcome tour (viral banner gauntlet): a new member meets their 3-level + // upline's sites, 10 focus-paused seconds each, then unlocks welcome credits. + // Same three levels the contract pays — the tour IS the org chart. + async function showGauntlet() { + try { + const g = await (await fetch('/api/my/gauntlet')).json(); + if (!g.pending || !g.slides || !g.slides.length) return false; + const gate = $('gauntGate'); + gate.hidden = false; + for (let i = 0; i < g.slides.length; i++) { + const s = g.slides[i]; + $('ggWho').textContent = 'Position ' + (i + 1) + ': ' + s.name + (i === 0 ? ' — the person who invited you' : ''); + $('ggProgress').textContent = 'Meeting your line: ' + (i + 1) + ' of ' + g.slides.length; + $('ggFrame').hidden = false; + $('ggFrame').src = s.targetUrl; + let left = g.dwell || 10; + $('ggTimer').textContent = left + 's'; + await new Promise(done => { + const t = setInterval(() => { + if (!tabActive()) return; + left -= 1; + $('ggTimer').textContent = Math.max(0, left) + 's'; + if (left <= 0) { clearInterval(t); done(); } + }, 1000); + }); + } + $('ggFrame').src = 'about:blank'; + $('ggFrame').hidden = true; // avoid a white about:blank panel once the tour is done + $('ggTimer').textContent = '✓'; + $('ggWho').textContent = 'That is your line. When you grow, they earn — and yours starts the day you share.'; + $('ggClaim').hidden = false; + await new Promise(done => { + $('ggClaim').onclick = async () => { + try { + const r = await api('/api/my/gauntlet/complete', { token: g.token }); + IAP.status('+' + r.credited + ' welcome credits unlocked. They spend on real campaigns.', 'ok'); + } catch (e) { IAP.status(e.message, 'bad'); } + done(); + }; + }); + gate.hidden = true; + $('ggClaim').hidden = true; + return true; + } catch (e) { return false; } + } + + // ── line banner (profile): the member's slot on welcome tours + their wall ── + function fillLineBanner(a) { + if (!a) return; + if (a.lineTargetUrl) $('lbTarget').value = a.lineTargetUrl; + if (a.lineBannerUrl) { + $('lbBanner').value = a.lineBannerUrl; + $('lbPreview').hidden = false; + $('lbPreview').innerHTML = 'line banner'; + } + $('lbCurrent').textContent = a.lineTargetUrl + ? 'Live: your next three levels meet ' + a.lineTargetUrl + ' on their welcome tour.' + : 'Not set yet. Until you set one, your tour slot is skipped.'; + } + async function loadLineBanner() { + try { + const a = await (await fetch('/api/me')).json(); + fillLineBanner(a); + fillProfileDetails(a); + // buyerCount + wallUnlocked live on the dashboard payload (chain read), not on /api/me + let d = {}; try { d = await (await fetch('/api/my/dashboard')).json(); } catch (e) {} + fillWallOffers(Object.assign({}, a, { buyerCount: d.buyerCount || 0, wallUnlocked: d.wallUnlocked || 1 })); + } catch (e) {} + } + // ── wall positions 2 & 3: the member's own offers, unlocked by qualifying buyers ── + function fillWallOffers(a) { + if (!a || !$('wallOffersCard')) return; + const unlocked = a.wallUnlocked || 1, bc = a.buyerCount || 0; + const offers = Array.isArray(a.wallOffers) ? a.wallOffers : []; + const NEED = [2, 5]; + for (let i = 0; i < 2; i++) { + const o = offers[i] || {}; + const open = unlocked >= i + 2; + $('woTitle' + i).value = o.title || ''; $('woTarget' + i).value = o.targetUrl || ''; $('woBanner' + i).value = o.bannerUrl || ''; + $('woPrev' + i).hidden = !o.bannerUrl; $('woPrev' + i).innerHTML = o.bannerUrl ? '' : ''; + $('woLock' + i).textContent = open ? 'yours' : 'unlocks at ' + NEED[i] + ' qualifying buyers (' + bc + '/' + NEED[i] + ')'; + $('woSlot' + i).classList.toggle('locked', !open); + } + $('woStatus').textContent = unlocked >= 3 ? 'Fully qualified: all three wall positions are yours.' + : unlocked === 2 ? 'Position 2 is yours. ' + (5 - bc) + ' more qualifying buyer' + (5 - bc === 1 ? '' : 's') + ' and position 3 is too.' + : (2 - bc) + ' more qualifying buyer' + (2 - bc === 1 ? '' : 's') + ' ($20 or more) opens position 2. You can set your links now; they go live the moment a slot unlocks.'; + } + document.querySelectorAll('.wo-upload').forEach(b => b.addEventListener('click', () => { const f = document.querySelector('.wo-file[data-slot="' + b.dataset.slot + '"]'); if (f) f.click(); })); + document.querySelectorAll('.wo-file').forEach(inp => inp.addEventListener('change', async () => { + const i = inp.dataset.slot, f = inp.files[0]; if (!f) return; + $('woInfo' + i).textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('woInfo' + i).textContent = r.error; } + else { $('woBanner' + i).value = r.url; $('woInfo' + i).textContent = 'Uploaded'; $('woPrev' + i).hidden = false; $('woPrev' + i).innerHTML = ''; } + } catch (e) { $('woInfo' + i).textContent = 'Upload failed. Try again.'; } + inp.value = ''; + })); + if ($('woSaveBtn')) $('woSaveBtn').addEventListener('click', busy2($('woSaveBtn'), async () => { + const offers = [0, 1].map(i => ({ title: $('woTitle' + i).value, targetUrl: $('woTarget' + i).value, bannerUrl: $('woBanner' + i).value })); + const r = await api('/api/my/wall-offers', { offers }); + IAP.status('Wall positions saved.', 'ok'); + await loadLineBanner(); + })); + const SOCIALS = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; // video = intro video on the wall, not a social link + function fillProfileDetails(a) { + if (!a) return; + if (a.bio) $('pfBio').value = a.bio; + if (a.avatarUrl) { const p = $('pfAvatarPrev'); p.src = a.avatarUrl; p.hidden = false; } + let soc = {}; try { soc = a.socials ? JSON.parse(a.socials) : {}; } catch (e) {} + for (const p of SOCIALS) if ($('soc-' + p)) $('soc-' + p).value = soc[p] || ''; + if (a.username) { + const link = location.origin + '/wall/' + a.username; + $('pfBioLink').textContent = link; + $('pfViewBio').hidden = false; + $('pfViewBio').href = '/wall/' + a.username; + } + } + let pfAvatar; // pending avatar url + $('pfAvatarBtn').addEventListener('click', () => $('pfAvatarFile').click()); + $('pfAvatarFile').addEventListener('change', async () => { + const f = $('pfAvatarFile').files[0]; + if (!f) return; + $('pfAvatarInfo').textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('pfAvatarInfo').textContent = r.error; $('pfAvatarFile').value = ''; return; } + pfAvatar = r.url; + $('pfAvatarInfo').textContent = 'Uploaded — save to apply.'; + const p = $('pfAvatarPrev'); p.src = r.url; p.hidden = false; + } catch (e) { $('pfAvatarInfo').textContent = 'Upload failed.'; } + $('pfAvatarFile').value = ''; + }); + $('pfDetailsSave').addEventListener('click', busy2($('pfDetailsSave'), async () => { + const body = { bio: $('pfBio').value, socials: {} }; + for (const p of SOCIALS) body.socials[p] = ($('soc-' + p) && $('soc-' + p).value.trim()) || ''; + if (pfAvatar) body.avatarUrl = pfAvatar; + const r = await api('/api/my/profile-details', body); + IAP.status('Profile saved.', 'ok'); + if (r.account) fillProfileDetails(r.account); + })); + $('lbUploadBtn').addEventListener('click', () => $('lbFile').click()); + $('lbFile').addEventListener('change', async () => { + const f = $('lbFile').files[0]; + if (!f) return; + $('lbUpInfo').textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('lbUpInfo').textContent = r.error; $('lbFile').value = ''; return; } + $('lbBanner').value = r.url; + $('lbUpInfo').textContent = 'Uploaded.'; + $('lbPreview').hidden = false; + $('lbPreview').innerHTML = 'line banner'; + } catch (e) { $('lbUpInfo').textContent = 'Upload failed. Try again.'; } + $('lbFile').value = ''; + }); + $('lbSaveBtn').addEventListener('click', busy2($('lbSaveBtn'), async () => { + const r = await api('/api/my/linebanner', { bannerUrl: $('lbBanner').value, targetUrl: $('lbTarget').value }); + IAP.status('Line banner saved. Your next three levels will meet it.', 'ok'); + if (r.account) fillLineBanner(r.account); + })); + + // ── login ad interstitial: after a successful sign-in the sponsor card + // appears; "Open Ad" loads the sponsor's page INSIDE the gate, under our bar + // (countdown, open-in-new-tab, dashboard button), so the timer and the way + // out sit on the ad itself (Brian Holland, 2026-10-09: "no timer, no X"). + // Sites that refuse framing open in a new tab instead, with the bar saying + // so; the timer is not paused, the member is expected to be on the ad. + async function showLoginAd() { + try { + const { ad } = await (await fetch('/api/ads/slot?type=login')).json(); + if (!ad || !ad.targetUrl) return; + const gate = $('loginGate'); + const openBtn = $('lgOpen'); + const goBtn = $('lgContinue'); + const timer = $('lgTimer'); + const frame = $('lgFrame'); + const tab = $('lgOpenTab'); + const body = gate.querySelector('.lgate-body'); + const framed = !!(ad.frameable && frame); + $('lgCreative').innerHTML = ad.imageUrl + ? 'sponsor ad' + : '' + (ad.title ? String(ad.title).replace(/[&<>]/g, '') : 'Visit today\'s sponsor') + ''; + $('lgStatus').textContent = 'Login ad sponsor — click "Open Ad" to begin.'; + const how = $('lgHow'); + if (how) how.textContent = framed + ? 'The sponsor\'s page opens right here under this bar. The timer counts down at the top; when it hits zero, your dashboard button appears beside it.' + : 'This sponsor\'s site does not allow loading inside a frame, so it opens in a new tab. The timer counts down here; come back to this tab when it hits zero for your dashboard button.'; + timer.hidden = true; + goBtn.hidden = true; + if (tab) tab.hidden = true; + if (frame) { frame.hidden = true; frame.src = 'about:blank'; } + if (body) body.hidden = false; + openBtn.disabled = false; + gate.hidden = false; + await new Promise(done => { + openBtn.onclick = () => { + openBtn.disabled = true; + if (framed) { + frame.src = ad.targetUrl; // the click relay counts it, then redirects inside the frame + frame.hidden = false; + if (body) body.hidden = true; + if (tab) { tab.href = ad.siteUrl || ad.targetUrl; tab.hidden = false; } + $('lgStatus').textContent = 'Today\'s sponsor. Have a look; your dashboard button appears when the timer ends.'; + } else { + window.open(ad.targetUrl, '_blank'); // the click relay counts it + $('lgStatus').textContent = 'The sponsor opened in a new tab (that site does not allow framing). View it and come back; the timer runs here.'; + } + let left = ad.dwell || 10; + timer.hidden = false; + timer.textContent = 'Time remaining: ' + left + 's'; + const t = setInterval(() => { + left -= 1; + if (left > 0) { timer.textContent = 'Time remaining: ' + left + 's'; return; } + clearInterval(t); + timer.textContent = 'Time is up'; + timer.classList.add('done'); + $('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.'; + goBtn.hidden = false; + }, 1000); + goBtn.onclick = () => done(); + }; + }); + gate.hidden = true; + if (frame) { frame.src = 'about:blank'; frame.hidden = true; } + if (body) body.hidden = false; + $('lgTimer').classList.remove('done'); + } catch (e) {} + } + + // ── SPONSOR CHAT: two-way threads, presence-aware, with a slide-in drawer ── + let CHAT_ME = null, CHAT_OTHER = null, CHAT_LASTID = 0, CHAT_POLL = null, CHAT_CANMUTE = false, CHAT_IMUTE = false, CHAT_SPONSOR = null, CHAT_LAST_UNREAD = 0; + function chatSync(d) { + CHAT_ME = d.email || CHAT_ME; + CHAT_SPONSOR = (d.sponsor && d.sponsor.email) ? d.sponsor : null; + const link = $('chatMenuBtn'); if (link && link.closest('.bo-links')) link.closest('.bo-links').hidden = !d.email; + setChatBadge(d.chatUnread || 0); + CHAT_LAST_UNREAD = d.chatUnread || 0; + const tog = $('chatAvailToggle'); if (tog) tog.checked = d.chatAvailable !== false; + // Overview quick action + My line card: message-your-sponsor entry points + const qs = $('qaMsgSponsor'); + if (qs) { + if (CHAT_SPONSOR) { qs.hidden = false; qs.dataset.email = CHAT_SPONSOR.email; qs.dataset.name = CHAT_SPONSOR.name || 'your sponsor'; } + else qs.hidden = true; + } + const card = $('sponsorMsgCard'); + if (card) { + card.hidden = !CHAT_SPONSOR; + if (CHAT_SPONSOR && $('sponsorMsgName')) $('sponsorMsgName').textContent = CHAT_SPONSOR.name || 'your sponsor'; + } + } + function setChatBadge(n) { const b = $('chatNavBadge'); if (b) { b.hidden = !n; b.textContent = n > 9 ? '9+' : n; } } + function stopPoll() { if (CHAT_POLL) { clearInterval(CHAT_POLL); CHAT_POLL = null; } } + function startPoll() { stopPoll(); CHAT_POLL = setInterval(() => pullThread(false), 4000); } + // the composer grows with the message up to ~45% of the screen, and keeps any height the member dragged it to (Bradley, 2026-09-13) + function autoGrow(el) { + const cap = Math.max(160, Math.floor(window.innerHeight * 0.45)); + const dragged = Number(el.dataset.dragged || 0); + el.style.height = 'auto'; + el.style.height = Math.min(cap, Math.max(dragged, el.scrollHeight)) + 'px'; + } + function closeDrawer() { stopPoll(); if ($('chatDrawer')) $('chatDrawer').hidden = true; CHAT_OTHER = null; loadDashboard(); } + + async function openThreads() { + const dr = $('chatDrawer'); if (!dr) return; + dr.hidden = false; $('chatConvo').hidden = true; $('chatThreads').hidden = false; + $('chatBack').hidden = true; $('chatMute').hidden = true; $('chatDot').hidden = true; + $('chatTitle').textContent = 'Messages'; $('chatStatus').textContent = ''; + stopPoll(); CHAT_OTHER = null; + $('chatThreads').innerHTML = '

Loading…

'; + try { + const r = await (await fetch('/api/my/chat/threads')).json(); + const list = r.threads || []; + // always offer "message your sponsor" up top when they have one and no thread yet + const hasSponsorThread = CHAT_SPONSOR && list.some(t => t.email === CHAT_SPONSOR.email); + const sponsorRow = (CHAT_SPONSOR && !hasSponsorThread) + ? '
' + + '' + + '
' + esc(CHAT_SPONSOR.name) + '
' + + '
Your sponsor · tap to message
' + : ''; + if (!list.length && !sponsorRow) { $('chatThreads').innerHTML = '
No conversations yet. You can message anyone in your line from “My line”.
'; return; } + $('chatThreads').innerHTML = sponsorRow + list.map(t => + '
' + + '' + + '
' + esc(t.name) + '
' + + '
' + (t.last.fromMe ? 'You: ' : '') + esc((t.last.body || '').slice(0, 64)) + '
' + + (t.unread ? '' + t.unread + '' : '') + '
').join(''); + $('chatThreads').querySelectorAll('.chat-thread').forEach(el => + el.addEventListener('click', () => openConvo(el.dataset.email, el.dataset.name))); + pageList('chat', $('chatThreads'), '.chat-thread'); + } catch (e) { $('chatThreads').innerHTML = '
Could not load messages.
'; } + } + + async function openConvo(email, name) { + if (!email) return; + CHAT_OTHER = email; CHAT_LASTID = 0; + const dr = $('chatDrawer'); if (!dr) return; + dr.hidden = false; $('chatThreads').hidden = true; $('chatConvo').hidden = false; + $('chatBack').hidden = false; $('chatDot').hidden = false; + $('chatTitle').textContent = name || email; $('chatStatus').textContent = '…'; + $('chatMsgs').innerHTML = ''; $('chatBanner').hidden = true; + $('chatInput').disabled = false; $('chatSend').disabled = false; + await pullThread(true); startPoll(); + setTimeout(() => { const i = $('chatInput'); if (i) i.focus(); }, 60); + } + + function renderMsgs(msgs) { + const box = $('chatMsgs'); if (!box) return; + const atBottom = box.scrollTop + box.clientHeight >= box.scrollHeight - 60; + for (const m of msgs) { + if (m.id <= CHAT_LASTID) continue; + CHAT_LASTID = Math.max(CHAT_LASTID, m.id); + const d = document.createElement('div'); + d.className = 'cbub ' + (m.fromMe ? 'me' : 'them'); + d.textContent = m.body; + const t = document.createElement('span'); t.className = 'ct-time'; + t.textContent = new Date(m.sent).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); + d.appendChild(t); box.appendChild(d); + } + if (atBottom) box.scrollTop = box.scrollHeight; + } + + async function pullThread(reset) { + if (!CHAT_OTHER) return; + try { + const r = await (await fetch('/api/my/chat/thread?with=' + encodeURIComponent(CHAT_OTHER) + '&after=' + (reset ? 0 : CHAT_LASTID))).json(); + if (r.error) { $('chatBanner').hidden = false; $('chatBanner').textContent = r.error; return; } + if (reset) { $('chatMsgs').innerHTML = ''; CHAT_LASTID = 0; } + renderMsgs(r.messages || []); + $('chatDot').className = 'pres-dot' + (r.online ? ' on' : ''); + $('chatStatus').textContent = r.online ? 'active now' : (r.available ? 'away · will get your note' : 'not taking live chats · leave a note'); + CHAT_CANMUTE = !!r.canMute; CHAT_IMUTE = !!r.iMute; + const mb = $('chatMute'); mb.hidden = !CHAT_CANMUTE; mb.textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; + const blocked = !!r.blocked; + $('chatInput').disabled = blocked; $('chatSend').disabled = blocked; + if (blocked) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'They are not accepting messages from you right now.'; } + else if (CHAT_IMUTE) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'You muted this member. Unmute to let them message you again.'; } + else $('chatBanner').hidden = true; + } catch (e) {} + } + + async function chatSend() { + const inp = $('chatInput'); if (!inp) return; + const text = inp.value.trim(); if (!text || !CHAT_OTHER) return; + $('chatSend').disabled = true; + try { + const r = await api('/api/my/chat/send', { to: CHAT_OTHER, body: text }); + inp.value = ''; autoGrow(inp); renderMsgs([r.message]); + const box = $('chatMsgs'); box.scrollTop = box.scrollHeight; + } catch (e) { IAP.status(e.message || 'Could not send.', 'bad'); } + finally { $('chatSend').disabled = false; inp.focus(); } + } + + async function toggleMute() { + if (!CHAT_OTHER) return; + try { const r = await api('/api/my/chat/mute', { email: CHAT_OTHER, muted: !CHAT_IMUTE }); CHAT_IMUTE = r.muted; $('chatMute').textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; pullThread(false); } + catch (e) { IAP.status(e.message, 'bad'); } + } + + (function chatInit() { + if (!$('chatDrawer')) return; + const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); }; + on('chatMenuBtn', 'click', e => { if (e && e.preventDefault) e.preventDefault(); openThreads(); }); + on('chatClose', 'click', closeDrawer); + on('chatBack', 'click', openThreads); + on('chatMute', 'click', toggleMute); + on('chatSend', 'click', chatSend); + const inp = $('chatInput'); + if (inp) { + inp.addEventListener('input', () => autoGrow(inp)); + inp.addEventListener('mouseup', () => { const h = inp.getBoundingClientRect().height; inp.dataset.dragged = h > 60 ? String(Math.round(h)) : ''; }); + inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatSend(); } }); + } + on('qaMsgSponsor', 'click', () => { const q = $('qaMsgSponsor'); if (q.dataset.email) openConvo(q.dataset.email, q.dataset.name || 'your sponsor'); }); + on('lineMsgSponsor', 'click', () => { if (CHAT_SPONSOR) openConvo(CHAT_SPONSOR.email, CHAT_SPONSOR.name || 'your sponsor'); }); + on('chatAvailToggle', 'change', async () => { + const t = $('chatAvailToggle'); + try { await api('/api/my/chat/available', { available: t.checked }); IAP.status(t.checked ? 'You are available to chat with your line.' : 'Live chat off. People can still leave you a note.', 'ok'); } + catch (e) { IAP.status(e.message, 'bad'); t.checked = !t.checked; } + }); + // presence heartbeat + new-message notifier: pop + toast when unread rises + setInterval(async () => { + try { + const r = await (await fetch('/api/my/ping')).json(); + const n = r.chatUnread || 0; + if (n > CHAT_LAST_UNREAD) { playSound('pop'); IAP.status('💬 New message from your team.', 'ok'); } + CHAT_LAST_UNREAD = n; setChatBadge(n); + } catch (e) {} + }, 20000); + })(); + + // ad surfaces: a banner greets the sign-in screen; members see live + // banner + text placements inside the back office (they ARE the audience) + IAP.adSlot('banner', 'adSlotLogin'); + IAP.adSlot('banner', 'adSlotOverview'); + IAP.adSlot('banner', 'adSlotSide', { width: 125, height: 125 }); // square button ad in the sidebar + + render(); +})(); + +// ── partner promo codes: typed on the Overview (Marty, 2026-09-12) ── +(function () { + const btn = document.getElementById('promoApply'), inp = document.getElementById('promoCode'), msg = document.getElementById('promoMsg'); + if (!btn || !inp) return; + const say = (t, ok) => { msg.hidden = false; msg.textContent = t; msg.style.color = ok ? 'var(--mint)' : '#ff8a8a'; }; + const go = async () => { + const code = inp.value.trim(); if (!code) { say('Enter a promo code.', false); return; } + btn.disabled = true; + try { + const r = await (await fetch('/api/my/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })).json(); + if (r.error) { say(r.error, false); return; } + say(r.step + ? Number(r.now || 0).toLocaleString() + ' credits added now' + (r.partner ? ' from ' + r.partner : '') + '. The rest of the ' + Number(r.credits).toLocaleString() + ' arrive ' + r.step + ' at a time, one for each day you finish your daily ads, for the next 30 days.' + : 'Added ' + Number(r.credits).toLocaleString() + ' credits' + (r.partner ? ' from ' + r.partner : '') + '. They are in your balance now.', true); + inp.value = ''; if (typeof loadDashboard === 'function') loadDashboard(); + } catch (e) { say('Could not apply that code. Try again.', false); } + finally { btn.disabled = false; } + }; + btn.addEventListener('click', go); inp.addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); +})(); + +// Friday Bonus Hunts card on the Earn tab (2026-09-26). Hoisted so the Earn loader can call it. +async function loadFridayBank() { + const card = document.getElementById('fbankCard'); if (!card) return; + let b; try { const r = await fetch('/api/my/friday-bank', { credentials: 'same-origin' }); if (!r.ok) return; b = await r.json(); } catch (e) { return; } + const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + const wd = d => WD[new Date(d + 'T12:00:00Z').getUTCDay()]; + document.getElementById('fbankCount').textContent = b.banked + ' banked'; + document.getElementById('fbankDays').innerHTML = (b.days || []).map(d => { + const st = d.banked ? ['#43e8c3', '✓'] : d.future ? ['var(--line-strong)', '·'] : d.day === b.today ? ['#ffb238', '○'] : ['var(--line-strong)', '×']; + return '' + st[1] + '' + wd(d.day) + ''; + }).join('') + 'Fri: +' + b.banked + ' hunts'; + const t = (b.days || []).find(d => d.day === b.today); + let msg = ''; + if (b.isFriday) msg = b.banked ? 'It\'s Friday. Your ' + b.banked + ' banked hunt' + (b.banked === 1 ? '' : 's') + ' are live on PolHunter today.' : 'It\'s Friday. Bank hunts Saturday through Thursday for next Friday.'; + else if (t && t.banked) msg = '✓ Today is banked. Come back tomorrow to bank another.'; + else if (t && t.video && t.soloNeeded && !t.solo) msg = '✓ Video watched. Not banked yet: an inbox ad is waiting for you today, and a day only counts once it is opened. Open the inbox ad and today is banked. (On days when nothing is waiting in your inbox, the video alone counts, which is why some days banked without one.)'; + else if (t) msg = 'To bank today: ' + (t.video ? '✓ video watched' : 'watch one video') + (t.soloNeeded ? ' and ' + (t.solo ? '✓ inbox ad opened' : 'open one inbox ad') : ' (no inbox ad waiting, so the video alone counts)') + '.'; + const el = document.getElementById('fbankToday'); el.innerHTML = msg; + el.querySelectorAll('[data-earn-go]').forEach(a => a.addEventListener('click', ev => { ev.preventDefault(); const tab = document.querySelector('[data-earn="' + a.dataset.earnGo + '"]'); if (tab) tab.click(); })); + card.hidden = false; +}