91 Commits

Author SHA1 Message Date
martbost efe9044497 Turkey Drop integration, gated (2026-10-28): the Thanksgiving season game at turkeydropgame.com, same protocol as POL Miner. TD_SSO_SECRET / TD_URL (default https://turkeydropgame.com) / TD_ALT_URLS (default www + turkeydrop.saasy.top) with tdMint/tdOpen/tdIsGameUrl/tdCallback (code defaults only, no env set); GAME_AUTH turkeydrop (in-game sign-in kit, three origins); /api/my/turkeydrop hand-off + iap.return + my.js redirect; refuel game 'turkeydrop' (label "back on the air", receipt kind td-life, note "Turkey Drop back on the air", gameplay only, never POL; refuel.js done text "WFWL is back on the air"); GAMES() card with season TD_SEASON 2026-11-02..2026-12-01 (Limited time ribbon, gone after Nov 30, CDN art game-banners/turkeydrop/og-turkeydrop-clean.jpg, per-action copy: first score milestones + weekly top 3) and STRIP line, both hidden until 'turkeydrop' is in gamesLive (admin preview kept); /api/public/games/all now shows a seasonal game's "Opens" date only once it is in gamesLive (it used to list any pre-season game); growth snapshot "opened today" counts a season start only when live; walletnudge entry (idle until the secret is set); gamestats name; Game Pass: gamepass GAMES/NAMES += turkeydrop, GP_SECRETS, GP_PERKS row "one free back on the air extra life every day" shown only while the game is in the public games list (Spooky Doors row the same, so it drops after Oct 31), pass copy made count-free ("every game" / "all the games": my.js card, perks table, cap nudge, chatbot pass/Friday/tiers answers + fact, friday.html, Friday pass email); promo tools Games entry (turkeydropgame.com/?ref=, og + 11 CDN banners, 2 posts) shown only while listed and from Nov 2; chatbot CANNED turkeydrop + fact follow gamesLive and the season (coming-soon answer without a date before launch, like POL Miner's; season-over answer from Dec 1; KB answer kept out of the prompt unless live), Game Pass answer names the Turkey Drop perk only while live. my.js?v=20261028td, promo.js?v=20261028td, refuel.js?v=20261028td. qa member 0 bugs (2 old admin warnings), qa public 0 bugs (1 old /shorts warning), refuel-fallback + kb all passed; local e2e (23 checks) and chatbot gating (7 checks) passed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:38:01 -05:00
martbost 01154c0856 Member update emails: claim the send slot before building the recipient list (the Sendy opt-in checks take minutes). On 2026-10-28 a retried POL Miner launch email raced the first one: both passed the 'already running' check, 475 members got it twice; stopped by a restart, the rest went out once. A second send now gets 'A send is already running' immediately.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:34:31 -05:00
martbost 7d134e55a2 Game refuel visits never come up empty (Marty 2026-10-28): after every sponsor has been seen, a member video, then a house sponsor (one of Marty's programs, never the game the player is in; 0 credits, no pool income) and, after the doorRepeatDays cooldown, a sponsor seen before again (a real, paid repeat visit, visit_repeat kind refuel). Repeats and house visits count toward the 20-a-day refuel cap. Applies to every game using /refuel (supply crates, paddles, continues, refuels, hints). Earn stays once-ever. Chatbot fact updated. qa/refuel-fallback.mjs (10 checks); member + earn qa clean; qa/door.mjs prints the callbacks on its pre-existing credits failure (admin-seeded packs are house ads, 0 credits, fails on main too)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:23:46 -05:00
martbost 8b28d028a6 All-games promo posts no longer name a game count (said 'Eight games'); list adds the brick breaker and the mining game; promo.js?v=20261028q
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:28:33 -05:00
martbost f1482deb12 POL Miner joins the Game Pass (2026-10-28, Marty): gamepass.GAMES/NAMES += polminer (polgrant accepts it with POLMINER_SSO_SECRET); pass copy "nine games" -> "ten games" (my.js card + perks table, chatbot pass/Friday/tiers answers, friday.html, Friday pass email); GP_PERKS + chatbot perk line "POL Miner: daily crystal limit 1.5 POL instead of 0.5, plus one free supply crate every day" (PolyBreak gem precedent + Gem Kingdom free-continue precedent); Games card art -> Spaces CDN og-polminer-clean.jpg; promo tools Games entry (link polminer.com/?ref=, og + 11 CDN banners, 4 posts) shown only once polminer is in the public games list; my.js?v=20261028pp, promo.js?v=20261028p. qa member 0 bugs (2 old warnings), qa public 0 bugs (1 old /shorts warning), qa/gamepass.mjs same 5 date-based failures as without this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:11:29 -05:00
martbost 6096bf38c6 POL Miner integration, gated (2026-10-28): POLMINER_SSO_SECRET / POLMINER_URL / POLMINER_ALT_URLS with pmMint/pmOpen/pmIsGameUrl/pmCallback; GAME_AUTH polminer (in-game sign-in kit); /api/my/polminer hand-off + iap.return + my.js redirect (my.js?v=20261028pm); refuel game 'polminer' (label "supply crate", receipt kind pm-crate, note "POL Miner supply crate"); GAMES() card (art polminer.com/og-polminer.jpg) and STRIP line, both hidden until 'polminer' is in site config gamesLive; walletnudge entry (idle until the secret is set); gamestats name; chatbot CANNED + systemPrompt fact follow gamesLive (coming-soon answer and fact until launch, its KB answer kept out of the prompt), KNOWLEDGE_DATE 2026-10-28. qa member: 0 bugs (2 old admin warnings), qa public: 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:07:26 -05:00
martbost 1089942bca Game POL pays to any LINKED wallet (Marty approved "build all three", 2026-10-27)
- walletnudge.js: the hourly push hands the member's signature-linked wallet (accounts.address, only set by
  auth.verifyChallenge -> accounts.linkWallet) to every game holding an unpaid balance, activated or not; memberId is the
  on-chain id when there is one, else 0 (a failed chain read falls back to the stored id instead of skipping the row).
  Holding-tank members waiting to switch on payouts no longer have their game POL stuck. Game side unchanged contract:
  signed POST, fill-empty-only (different wallet = 409, retried once a day), idempotent.
- Nudge copy (no linked wallet only): "You've earned X POL in <game>. Link your wallet (one free signature) and it's sent
  automatically, including everything you've earned so far." + /my#wallet; never mentions switching on payouts.
- The IAP -> game /auth tokens already carried wallet: a.address regardless of activation (no change).
- chatbot.js: game-pol-wallet canned answer (ahead of the per-game entries) + GAME POL TO ANY LINKED WALLET prompt fact
- qa/walletnudge.test.cjs (mock game: non-activated push with memberId 0, activated push, chain-read failure, nudge copy,
  409 refusal + daily retry), wired into qa/run.sh member + walletnudge; chatbot-parse routing cases for the new answer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 09:19:10 -05:00
martbost fa5acf0745 Network rate 4:1 (Marty approved 2026-10-27): syndicated delivery costs 1/synRateDivisor of the on-site rate, going forward
rates.synRateDivisor (default 4, Admin > Rates; 1 = the old rule). Network Ad Space impressions charge 1 credit per
impressionsPerCredit x N views (banner 20, text 40 at N=4), through the same chargeCredits path (earned pool first,
then on-chain burn), with their own credit-log line "Network views (1/4 rate)". Fractions are exact: the cumulative
served count carries the remainder. The budget is the limit: NAS bookings, resume, top-up and daily allowances are
sized at the network rate, and a live ad booked at the old rate is topped up once to what its budget now buys.
PassiveDrip: N partner visits use up 1 pack visit (floor on the cumulative count), every partner visit counted in
the new syn_imps column, PD offered visits left x N. Nothing already charged changes. Member Campaigns: network views
and partner visits marked "at 1/4", a note under the table, a Network rate chip. Chatbot canned answer + live AI fact.
Cache tags bumped. QA: qa/run.sh nas (served 8, restart 9, ratio 15), chatbot-sync, run.sh member all passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:05:43 -05:00
martbost 8b03dd2311 Fix NAS phantom delivery on resume/top-up: a stopped NAS ad restarts from its true served count
stopNas zeroes `remaining` after recording the true served count. Resume (setStatus) and topUpCampaign then
used a plain nas.topUp, so assigned - remaining read the zeroed remainder as served and the next reconcileNas
charged it (up to the whole budget). New nas.restart(id, trueServed, add) re-bases assigned on the recorded
count; ads.nasExtend uses it for any stopped ad (remaining 0) and keeps the plain top-up for a running one;
resume tops up only to the budget left. QA: qa/nas-restart.mjs (9 checks; fails on the old code), nas-served 8,
run.sh member all passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:54:08 -05:00
martbost 59607d0c94 One-tap switch on payouts after a holding-tank assignment + reminders (Marty approved 2026-10-27)
- Assignment chat + member email (manual adoption and the 24h auto-assign) carry "Switch on payouts" -> https://instantadpay.com/my?activate=1#wallet
- /my?activate=1: signed in, wallet linked, real sponsor, no hold -> Wallet tab, explainer line, the Activate button's own flow (injected wallet or the WalletConnect picker on a phone). Survives sign-in and the wallet link (sessionStorage); never starts on tankHold, a blocked/routed sponsor or the #1 fallback (/api/me sponsorFallback)
- payTick (in the 15-min readyTick): not activated 24h after the assignment -> ONE member email + ONE in-app notice to the sponsor; 72h -> last member email; stops on memberId / MemberActivated / sponsor change. State tank-ready.json `pay`, each send gated by marks.claim (deploy overlap), record saved before the send; Admin tank view gets payReminders
- Chatbot: tank-activate-link canned answer + system prompt; my.js ?v=20261027pa
- qa/tank-hold.mjs: link texts, reminder schedule on a mocked clock, overlap copy, ?activate=1 browser flows (stubbed wallet)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:29:43 -05:00
martbost e5c55c2d8b Never hold a purchase (Marty 2026-10-27): a holding-tank buyer with no sponsor anywhere goes ahead under the catch position #1; the 24h hold only stops a plain switch-on-payouts. Network alignment still runs first. home.js buys with intent=buy; chatbot + QA updated
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:05:06 -05:00
martbost 4645d5605a Holding tank activation hold (Marty approved 2026-10-27, "hold them for no longer than 24 hours"): a tank member is never bound under the fallback #1
- Align first: a tank member whose email or wallet already has a sponsor on LinkSpin (the inbound registry rows) is placed under that sponsor when they have a real account here, never a sponsor they were released/rescued from, never a loop (recorded in tank-ready.json, shown in Admin tank)
- Hold: /api/me and /api/sponsor answer tankHold {since, until} instead of the fallback sponsor; Wallet tab hides Activate payouts and shows "You're being matched with a sponsor..." with time left, Getting started has no activate button, buy flows (my + home) refuse on tankHold. The 24-hour clock starts when the member is first seen with a wallet linked (already-linked members start at deploy)
- Surface: Ready to activate badge + hours left, ready members on top (My line tank, Admin tank, Overview notice count); one Telegram line per newly ready member (digest when more than 3, e.g. the first tick after deploy)
- Safety net (readyTick every 15 min + hourly sweep): unadopted 24 h after readyAt -> next eligible adopter in rotation (own $20+ buy, fewer than 2 open, signed in within 7 days, not suspended/flagged, not company, not a no-payout chain, not in their own downline; least recently auto-assigned first, ties by earliest qualification) through adopt() with "auto-assigned after 24 hours in the tank", chat + email to both, Telegram pickup "(auto-assigned)". Nobody eligible: keep holding, one admin alert
- tank.eligibility is now exported (the Overview tank notice was silently failing on it)
- Chatbot: tank-hold canned answer, holding-tank answer + system prompt updated, KNOWLEDGE_DATE 2026-10-27
- qa/tank-hold.mjs (mocked clock unit + local copy e2e), wired into run.sh member and run.sh tankhold; cache tags bumped

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:41 -05:00
martbost fc81c6a4db Chatbot: free game caps started 2026-10-26 (Marty moved capsStartDate up from 10-29)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:13:22 -05:00
martbost 06f0a87452 Conversion tracking fixes (Marty approved 2026-10-26): real test pixel, own-click count, own-browser clicks as tests, cost per goal (30 days)
1. Own clicks: auth.onSeen notes the soft key of every InstantAdPay session (lsconv.noteSession, once per 6 h per email + soft key) and the click push carries them as owners [{owner, sk, ts}] (requeued on a failed push), so LinkSpin keeps members' own clicks on their ads, spin links and Banner Spins as tests. /api/ads/click flags a click self for conversions when signed in as the owner OR from a browser the owner signs in from; whether the click is counted and billed is unchanged (still the signed-in check). Linked positions share the owner's email.
2. Send a test conversion now loads the member's real LinkSpin pixel in test mode from the browser (cv.gif?px=..&test=1, reads X-LS-Result: test, the same request LinkSpin's button makes) and falls back to the signed partner call (op test) when the browser cannot load it; CSP connect-src adds https://linkspin.app. The card shows "N from your own clicks, kept as tests and left out" (selfTests from LinkSpin's summary).
4. Cost per goal (30 days): /api/my/conversions returns spend30 = each campaign's spend over the same 30 days from credit_log (ads.spendSince: delivery, login, buy, refund rows by Central day, ref = campaign id). Campaign lines read "Goals and cost per goal (30 days)"; a campaign started inside the window with no log rows uses its spend since start (labelled in the tooltip); an older campaign with no spend on record shows no cost rather than a lifetime figure.
Copy: Conversion tracking card note, /conversion-tracking (test button, own clicks, cost per goal (30 days) row). Chatbot CANNED + FACTS, KNOWLEDGE_DATE 2026-10-26. my.js ?v=20261026cv.
QA: convpixel all passed (new: owners pushed without raw IP, own-browser click self=1 and stranger 0, no re-push within 6 h, spend30 = 200 of the window with the 40-day-old row and another member left out, 50/200 credits each vs lifetime 75, no-log old campaign shows no cost, new campaign uses spend since start, own-click count on the card, test button loads cv.gif?px&test=1 in the browser (routed locally) and falls back to op test); fuel all pass (engine.js / engine-room.js / kit.js untouched, byte-identical with LinkSpin); member walk 0 bugs; public 0 bugs (known /shorts ellipsis warning).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 06:31:18 -05:00
martbost 27d663ca29 Conversion tracking walkthrough video live (Marty approved 2026-10-26): on /conversion-tracking and the Training card
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 04:55:43 -05:00
martbost b239417cc5 Game Pass tier prices = InstantAdPay one-click packages (Marty 2026-10-25): Explorer $20 (was 19.99), Champion $50 (was 39.99), Sovereign $100 (was 99.99), Legend $250 (was 249.99); weekly $5 unchanged. TIER_DEFS and the siteConfig defaults in cents 2000/5000/10000/25000, so the cheapest qualifying package is exactly the pass price (no silent overpay). A pass is still paid by one fresh package of at least the tier price. Member Games card: each tier says it comes with the $X package and its ad credits (my.js ?v=20261025pr). Admin Game Pass note, docs/GAME-PASS.md, chatbot tier fact (price = package, member keeps the package credits; still 'coming soon' while sovTiers is off). sovTiers untouched (0). QA: sov-passes-store + sov-passes-local ALL PASS with the new prices; qa member 0 bugs, qa public 0 bugs; qa/gamepass.mjs 2 date-based fails identical on the previous commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 13:14:29 -05:00
martbost 47638ac1fe Fuel flow IAP -> LinkSpin made obvious (Marty 2026-10-25: "I clicked set up conversion tracking, it took me to LinkSpin and I don't know how to pick up from there"). Engine Room links now follow the site the member is on (engine.js build({site})): Set up conversion tracking on InstantAdPay opens /my#conversions (Campaigns > Conversion tracking card, scrolled to, highlighted, goal box focused; same goals LinkSpin counts) with the /conversion-tracking guide beside the button; buy/refuel/top-up and the Fuel part stay on this site. Only LinkSpin-only tools cross over (Banner Spin -> /links#b, spin link, page, testing), labelled "on LinkSpin" and tagged ?from=iap&task=<job> so LinkSpin shows an arrival strip with Step 1. Streak line and Refuel card get a "Refuel LinkSpin" link to linkspin.app/credits#refuel when the second engine is still open. Part labels wrap cleanly. Chatbot canned + prompt routes, KNOWLEDGE_DATE 2026-10-25. engine.js / engine-room.js stay byte-identical with LinkSpin. QA: fuel 12/12 engine incl. new site-links test, member walk 0 bugs. my.js, fuel.js, engine-room.js ?v=20261025ff.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 09:05:53 -05:00
martbost 7f80d82486 Game Pass tier testing moves to Admin > Game Pass (Marty 2026-10-25): the member Games card shows every account, the admin's included, exactly what a member sees (weekly pass only while sovTiers is off; a holder sees the tier they hold). The /my admin preview note and the admin bypass on GET /api/my/gamepass and POST /api/my/gamepass/buy are gone. New Admin > Game Pass > Tier test and preview card (labelled TEST / PREVIEW): all five tiers as members will see them with on-sale/hidden chips and the admin's own status, Test buy (real waiting order fulfilled by a fresh package), Cancel test order, Give my account (test comp, no sale), End. New admin-only routes GET /api/admin/gamepass/preview, POST /api/admin/gamepass/test-buy | test-cancel | test-comp, always on the signed-in admin's own account. sovTiers untouched. QA: sov-passes-local + store reworked to the new flow (all pass); my.js and admin.js ?v= bumped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:37:17 -05:00
martbost cecba6b313 Wallet-link nudges on for PolyBreak, SpellWheel, PolyWarriors (Marty 2026-10-25; they were push-only); QA walk: signed-out support tickets are members-only (962cdf0), non-member refused 403
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 05:33:43 -05:00
martbost a4642341aa Wallet push: game balances waiting on a wallet the member already linked (on-chain member address, the same one the hand-off token carries) are pushed to the game's signed POST /api/iap/wallet instead of nudged, so the game's own sweep pays them (solanaclick 1.5 POL in Gem Kingdom, 2026-10-25); PolyBreak, SpellWheel, PolyWarriors join the hourly check push-only (no new nudge mail); admin view counts and lists pushes and refusals
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 05:12:15 -05:00
martbost 962cdf08b5 Support tickets are members-only (Marty 2026-10-24, after a throwaway-address 'pentest' ticket IAP-1012): signed-out support form + chatbot handoff need an email that belongs to an account on this site; inbound email opens NEW tickets only for member emails (replies to existing tickets still land)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 11:36:17 -05:00
martbost 13f3ff56f8 Conversion tracking card: goal rows showed 30 (the window length) instead of the goal's conversions
LinkSpin's partnerSummary returns conv = the count and convDays = the window in days; my.js preferred convDays, so every goal read "30" under Conversions (30 days). Now shows g.conv. Also: a goal without a default value (LinkSpin stores 0) no longer adds &value=0 to its snippets or shows 0 as its default. QA mock now matches the real contract (convDays = 30) and asserts the row counts (6, 1). my.js ?v=20261024ct.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 11:08:11 -05:00
martbost bf5cf62caf Conversion tracking member guide at /conversion-tracking (Marty, 2026-10-24: no training existed for the conversion pixel, live since 10-23)
Why track, the click -> landing page -> thank-you page -> counted flow drawn in HTML/CSS (across on desktop, down at 390 px), the 4 steps (goal, landing tag, goal pixel, test incl. the &test=1 page check), copy-paste examples with placeholders for plain HTML, WordPress (footer plugin + Custom HTML block), page builders and Aweber/GetResponse custom thank-you pages, what to do without code on the thank-you page (image pixel = cookie / 24-hour match, hidden lsclk field, LinkSpin.goal for pop-up forms), how to read the report (cost per goal in credits, match methods, tests, 30-day window, own clicks) and a troubleshooting checklist. Copy buttons in conversion-guide.js; frames handled by common.js.
Route + TRAFFIC_PAGES + sitemap + viral-link page list. "How to set it up" link on Campaigns > Conversion tracking. Chatbot CANNED conversion-tracking answer + FACTS line point to the guide (KNOWLEDGE_DATE stays 2026-10-24).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 10:18:51 -05:00
martbost 8ca5ed99e8 NAS 728x90 ad tags load inside a srcdoc iframe: the inline <script> blocked the page below it while networkadspace.com (rhi) was offline for the 2026-10-24 data-center move (PolHunter stalled halfway the same way)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:24:09 -05:00
martbost f322786071 Refuel guide: the walkthrough video (Marty approved 2026-10-24) replaces the banner, plus a 'Why keep refueling' section (steady traffic, useful numbers, fresh creative, the climbing bonus); training card gets the video
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:17:24 -05:00
martbost 5802fd9835 Chatbot: 'How does the refuel streak work?' answered with the Games entry (its fast-path regex claimed any 'refuel'); games-tab now matches game refuels only (Drip Runner, refuel in the game), Monthly Refuel questions (refuel streak/day/bonus/window/kit, my/monthly refuel) reach the refuel answer that links /refuel. Seed refresh updates the live KB on deploy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 08:14:49 -05:00
martbost 1b77825256 Fuel Your Offers member guide at /refuel (Marty, 2026-10-24): the flow drawn in HTML/CSS (works at 390 px), the numbers, the member route, misses, what counts, leader coaching and FAQ, restyled to the site, hero banners/fuel-your-offers-1200x675.jpg as og:image. /refuel without ?t= serves the guide; the games' signed /refuel?t=<token> visit page is unchanged. Added to TRAFFIC_PAGES (game visits with ?t= not counted), the sitemap and the viral-link page list. "How the Refuel streak works" link on the Refuel card (fuel.js) and in the Engine Room (engine-room.js, same file as LinkSpin's).
Engine Room fix: the streak line said "Refuel the other site this cycle" after BOTH sites were refueled; engine.js streakNote() now says "Both engines fueled this cycle: +X% on each", names the other site when only one is done, and quotes next rates when the window is open (test added, 11/11).
Chatbot: CANNED refuel answer + refuelFact point to /refuel, say either site alone keeps the streak, and describe the Pit Stop exactly as refuel.js decides it (another package on a site already refueled this cycle before the window; the other site's first package is the second engine). my.js tags: fuel.js + engine-room.js ?v=20261024rg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 08:07:30 -05:00
martbost 974d888314 Refueled 3 Months badge: title on two lines inside the ring (Marty: text did not fit), ribbonY 0.783, ?v=3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 06:53:03 -05:00
martbost 8ecef442a1 Refuel: final badge art (Engine Started, Refueled 3/6/12, kie.ai, ribbon heights measured) + month-4 Twin Engine Featured bonus is 100 credits (was one Featured day = 40), Marty 2026-10-24; chatbot + test updated; my.js?v=20261024bd
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 06:38:58 -05:00
martbost 6b3cdaaa70 Chatbot: Level 4 override is live (CANNED level4-override + FACTS line; start Mon 2026-10-26 00:00 CT, first payout Mon 2026-11-02 9 AM CT). overrideMode=live + overrideGoLive=1792990800000 set on the site, payer wallet funded (Marty, 2026-10-24).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 06:14:57 -05:00
martbost 15f5374fac Engine Room (Fuel Your Offers stage 4, Marty approved 2026-10-24): a new Members tab (engineNav, pane-engine) on InstantAdPay, shown only while refuelStreak is on, unlocked by the first counted refuel and greyed with one move "Refuel to start your engine" before. engine.js (the same file ships in LinkSpin): facts() gathers one site's member facts (credits free + in campaigns, recent campaigns, clicks this week and last week from click_sources via coach.clicksSince, free login slots; on LinkSpin also goals this month from the conversion pixel counted from the Central-time 1st, and the Banner Spin / spin link / page / testing parts), build() turns both sites' facts + the streak into three plain dials (fuel left vs this cycle's refuel credits incl. bonus with days left at the recent burn; clicks this week against last week with clicks per 1,000 credits; goals this month vs a member-set goal stored with the streak, refuel.setGoal), the streak panel, warning lights (ads at 80%, ads out, refuel day coming, login slot open), six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green / amber / grey with setup links) and one next move from simple ordered rules (refuel window, relaunch, Pit Stop top-up, top up the winner, tracking, Banner Spin, test A/B, cut the loser, keep running). LinkSpin facts arrive through signed /api/partner/engine (cached a minute; LinkSpin down = unknown, never zero); InstantAdPay answers the same call for LinkSpin's panel with its facts + the streak. Member /api/my/engine, /api/my/engine/goal; partner op refuel/goal. engine-room.js (same file both sites): plain SVG dials with aria labels, works at 390 px, colour only for warnings. Chatbot CANNED + FACTS cover the Engine Room. my.js?v=20261024er (PANES + engine), engine-room.js?v=20261024er. qa/refuel-engine.test.cjs 10 checks (switch, locked, each dial, lights, parts, next-move order, facts on stubbed LinkSpin incl. Central month start, goal storage).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 05:55:02 -05:00
martbost 50337bfbbc Refuel Kit (Fuel Your Offers stage 3, Marty approved 2026-10-24): monthly members-only banner sets for InstantAdPay, unlocked by the member's next counted refuel. kit.js (the same file ships in LinkSpin): kits as data in DATA_DIR/kits (month, theme, released, one base image each for 728x90 300x250 468x60 160x600 1200x630, this site's own program only); a counted refuel unlocks the kit of its Central month (refuel.js now keeps rec.kits month -> streak month, exposed in view.kits); kits stay usable after their month, a missed refuel only stops new ones, a kit released early waits for its month. Server-side personalization per member with ffmpeg (badge renderer approach): @username on a dark strip + a QR code (qrcode package) to their own /join link at fixed spots per size; cached in DATA_DIR/kits/out and served publicly at /kitimg/<hmac>.png|jpg|gif (only files rendered for entitled members; names cannot be guessed and change with the art). Streak month 3+ adds an animated GIF (three-frame loop), month 6+ records a BannerKitAI custom-banners credit (entitlement + note, no integration). Member: Promo tools Refuel Kit card (fuel.js?v=20261024kit): Make mine, Animated, Download, Copy image link, "Use in an IAP banner campaign" (opens Campaigns and prefills banner type, size, name, image URL and the member's link). Admin: Settings > Refuel Kit (admin-kits.js): month + theme, upload the five sizes, "Use placeholder art (public/banners)", preview with any username (still or animated), release (needs all five sizes). Behind the refuelStreak switch (myKits { on:false } while off). Chatbot CANNED + FACTS mention the kit. No paid image APIs; placeholder art = existing public/banners. qa/refuel-kit.test.cjs 8 checks (admin validation, switch, unlock by month, Pit Stop does not unlock, kits persist, GIF at 3, credit at 6, exact render sizes for all five, GIF loop, cache, unguessable serving, preview).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 05:44:27 -05:00
martbost 6cc868d10a Monthly Refuel streak (Fuel Your Offers stage 2, Marty approved 2026-10-24), InstantAdPay = source of truth for ONE streak per member across InstantAdPay + LinkSpin. refuel.js: counted refuel = a new $20+ package here (refuelMinIapCents) or $25+ on LinkSpin (reported by LinkSpin) by one of the member's own positions (main or linked); the first sets the refuel day, next due 30 Central days after the last counted refuel, window opens 5 days before, 5-day grace, one free miss per 365 days, else reset. Bonus = purchased-grade credits on the site where bought, credit log kind bonus "Refuel streak month k": one engine 10/15/20/25%, both engines in the same cycle 15/20/30/40% (second site gets the both rate, the first is topped up by the difference), m4+ both = one free Featured day credited (featuredPerDay). Stacks on Friday/Wednesday (separate grants). Pit Stop = half the current rate, once per site per cycle, not a refuel. Badges Engine Started (first refuel) + Refueled 3/6/12 months through postBadgeOnce (placeholder gauge art in public/badges/badge-refuel*.jpg; shown in the strip only once earned). Feed: one line per counted refuel to the payments topic (claim rffeed:<tx>, never a Pit Stop) + Monday roundup after 9 AM CT (claim rfweek:<monday>, skipped at 0). Reminders 5 days before / on the day / last call (email with unsubscribe + notice kind notice) from the site of the last counted refuel. Optional Refuel Day on the 1st (refuelDayPromo, default off). Every decision is made under a member lock (db.withLock: MySQL GET_LOCK across app copies) and stored by tx; every grant is an outbox row keyed by a unique ref and claimed rfg:<ref> before it is applied, so two copies never double-grant. Partner endpoints /api/partner/refuel/purchase|outbox|ack|status (HMAC LS_SYNC_SECRET), member /api/my/refuel, admin /api/admin/refuel (+ /tick, /member). Refuel card on the Overview (fuel.js). Chatbot CANNED + FACTS follow the switch (off: "built, not switched on"), KNOWLEDGE_DATE 2026-10-24. MASTER SWITCH refuelStreak default '0': nothing counted or granted, no reminders, no feed lines, card hidden. qa/refuel.test.cjs 19 checks (switch, ladder, both-engine top-up, grace, free miss incl. 365-day return, Pit Stop once, stacking, idempotency, two concurrent workers, Central day + DST, Refuel Day, badges, reminders, roundup, view). my.js?v=20261024rf, fuel.js?v=20261024rf.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 05:28:49 -05:00
martbost 61c0c52c3b Refill notices: Wired Wednesday in the bonus ladder + deploy-overlap claims (Fuel Your Offers stage 1, Marty approved 2026-10-24). The bonus block now lists Five Dollar Friday AND Wired Wednesday (from their live settings: wednesdayPromo, wednesdayBonusPct 25, wednesdayMinCents 2000, Central time), and takes the member's refuel-streak line from a streakLine(owner) hook (filled in stage 2). Every send is claimed in event_marks first, so the two app copies of a deploy never both email a person. qa/refill.test.cjs (copy, settings, hook, two copies) + run.sh fuel mode.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 05:12:38 -05:00
martbost 7cadeaa2d9 qa: convpixel mode (local copy + mock LinkSpin verifying the HMAC): lsclk on redirects, pushed rows, self clicks, proxies, Campaigns pane cost per goal, LinkSpin down
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 18:01:09 -05:00
martbost 42a1cce2f1 Conversion tracking copy: chatbot CANNED answer + FACTS line, KB FAQ entry for Aweber/GetResponse thank-you pages, home page FAQ question, privacy page section on the click id, landing tag and goal pixel
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 18:01:09 -05:00
martbost ce977698b9 Campaigns > Conversion tracking panel: goals (name, default value, pixel id, 30-day conversions, last test), add goal, landing tag + goal pixel snippets (JS version under a toggle), Send a test conversion, autoresponder thank-you page advice, how-sure legend; each campaign row shows goals and cost per goal in credits from the LinkSpin summary. LinkSpin down: the card says so, the rows omit the goal line. my.js?v=20261023cv
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 18:01:08 -05:00
martbost 46bb7dd9dd Conversion tracking, click side: every /api/ads/click gets a click id (i + 11 hex) appended as lsclk=<id> (existing params and hash kept, an existing lsclk never replaced, unparsable targets unchanged), the owner's own click flagged self. Rows in ad_clicks (MySQL) or a capped JSON file, pushed signed to LinkSpin /api/partner/clicks every 3 s (500 per request, retry with backoff, marked pushed only on ok). Member proxies /api/my/conversions (summary, 60 s cache), /goal (create/update/remove), /test. Admin lssync view shows push stats.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 18:01:02 -05:00
martbost ebdab6c545 Restore each file's original line endings (the override commit rewrote CRLF/LF)
No content change: server.js back to CRLF, my.js/admin.js/html back to LF, so the override
commit's real diff is ~800 lines, not 13,000.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:16:08 -05:00
martbost 43e841721a Level 4 override payer, shipped OFF (Marty approved 2026-10-23)
override.js: the weekly payer for the 3% level-4 override. It pays only when overrideMode is 'live' AND
overrideGoLive is set AND OVERRIDE_PAYER_KEY (or _FILE) is present; otherwise the Monday dry-run report
runs as before. Default stays 'dryrun'. Nothing in this commit moves money.

- Week = Monday 00:00 to Monday 00:00 Central; settled from 9 AM CT the Monday after, weeks in order.
- Plan frozen once per week (claim plan:<week>), one row per recipient (POL wei summed), on the volume.
- Claims fail closed: exclusive file create on the shared volume plus event_marks when MySQL is on.
- Row marked 'sending' before the tx, tx hash stored on acceptance; lost answers become 'review' and are
  never re-sent (settled from the chain index or by the admin). Pre-flight revert = carried, no gas.
- Dust under overrideDustPol (0.01) carried to next week; overridePayCapPol (100) holds the whole week;
  wallet must cover total + gas or nothing is sent; Telegram alerts once each.
- Telegram summary to Marty's private chat says PAID with tx links.
- Members: AwardPaid from the payer emails + on-site notice "Your Level 4 override is paid" and shows in
  Earnings as "Level 4 override" (common.js / my.js tags bumped to 20261023ov).
- Admin: /api/admin/override adds week status + payer state; POST /api/admin/override/pay (only when live)
  and /api/admin/override/resolve; P&L pane card with "Pay this week now" shown only when live.
- Comp plan (earning.html) + Platform Facts card hidden behind data-when="override-live" (shown only when
  overrideMode is live). Chatbot copy drafted in D:/tmp/override-copy, TODO in chatbot.js.
- qa/override.test.cjs (bash qa/run.sh override): 30 checks on a fake chain/signer/DB, throwaway data.

Reconciliation 2026-10-23: the dry run reads every Purchase in chain-index (229 events, full history);
per Central week it matches the index exactly. The ~$1,775 figure was the rolling 7 days 09-10..09-17.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:14:58 -05:00
martbost 87a45169d0 Five Dollar Friday copy: chatbot canned answer + FACTS and the /friday page mention the free 7-day Game Pass perk
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:15:44 -05:00
martbost 38369d6858 Five Dollar Friday Game Pass perk, automatic (Marty 2026-10-23): a $5+ Friday package also gives the buyer a free 7-day Game Pass, once per member per Friday (event_marks claim), not on top of a purchase that itself started a paid pass; on-site notice; the Game Pass badge posts once ever (postBadgeOnce). Switch: fridayPassPerk '0'. Counts as no sale (comp).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:13:20 -05:00
martbost 91f2e2ec74 Game Pass card on Fridays: the package that starts the pass also gets the Five Dollar Friday bonus (pass + 600 ad credits on a $5 pack), from /api/friday live pct (Marty 2026-10-23)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:54:30 -05:00
martbost 4587b5cc58 Campaigns rate strip: login ads show '1,000 cr / 30-day slot' instead of the retired 'Login 100 cr / day' (and the same in the rates line); my.js tag bumped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:36:03 -05:00
martbost eac83c3eee Admin member card: visit packs show delivered visits as 'N of M visits' (Marty 2026-10-23); admin.js tag bumped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:35:22 -05:00
martbost e2eb1578aa Login ads: the AdRevLinks popup starts when the login ad goes live, including a reservation that starts from the line (sized on the slot price), and pauses when it expires/pauses/archives as before (Marty 2026-10-23)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:25:40 -05:00
martbost 89b5969b25 Prepaid login-ad line: when all member slots are taken, members pay now to reserve the next one (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line")
- ads.js: a login buy with every slot taken returns full:true and a reserve offer; with reserve:true it is charged the full slot price at once (purchased credits only, credit log 'Login slot reserved (queue #N)') and stored with status 'queued' + queuedAt, no starts/expires, never served or counted as a slot. First paid, first served.
- Promotion (promoteLoginQueue): on a slot expiring (scheduleSweep), a member pausing a slot, every new login buy, and a one-minute tick. The oldest reservation becomes active, starts now, ends in 30 days; the owner gets an on-site notice (kind 'notice') and an email unless unsubscribed.
- Deploy-overlap safety: the cap decision runs under a lease row in the new app_locks table (one conditional UPDATE takes it, an expired lease can be taken over); every start/cancel/edit is a conditional UPDATE on status='queued', so a reservation starts at most once and a cancel racing a start has exactly one winner. Live login buys and paused-slot resumes also take the lease, so the cap holds for them too.
- A freed slot goes to the line first: a paused slot resumes only while live + queued < loginSlotsMax, with a plain message saying the line is ahead.
- Cancel before the start: full refund as purchased-grade credits (credit log 'Login slot reservation cancelled: refund'), once. Edit target/image/headline before the start, free. Cancelled reservations can be archived.
- Estimated start per place from the live slots' end dates and the reservations ahead, shown in Central time and labelled an estimate.
- db.js: campaigns.queued_at BIGINT NULL, app_locks table + 'login_queue' row, all added on boot.
- server.js: loginLine in GET /api/my/campaigns, POST /api/my/campaigns/:id/cancel-reservation and /edit-reservation (safe-browsing, reach and image checks), GET /api/admin/login-queue, POST /api/admin/login-queue/:id/cancel, the promotion notice hook and the one-minute tick.
- Member UI (my.js, my.html): open slots or the line with place and estimated start on the Login ad form, the button becomes "Reserve the next slot", IAP.confirmBox before paying, In line #N + estimated start in the list, Edit and Cancel and refund. Admin (admin.js, admin.html): Login-ad line card with owner, queued at, place, estimated start, cancel + refund. Tags bumped to 20261023lq.
- chatbot.js: new canned 'login-ads' answer and the LOGIN ADS fact updated (6 slots, the paid line, cancel = full refund before start). The knowledge base seeds the new entry on boot.
- audit.js: queued/cancelled reservations are not per-day login campaigns.
- QA: qa/login-queue.cjs (JSON store end to end) and qa/login-queue-sql.cjs (SQL path guard logic against a fake SQL layer), bash qa/run.sh login-queue. qa/login-slot.mjs pattern follows the refactor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:14:57 -05:00
martbost c45f1769e7 Admin member card: Views column read c.views, which campaigns never had (always 0). Now imps + impsNas (views here plus network views; delivered visits for visit packs)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:02:24 -05:00
martbost 610f47c625 Chatbot: login-ad slots now 6 (raised from 3, Marty 2026-10-23); KNOWLEDGE_DATE 2026-10-23
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 06:34:29 -05:00
martbost a405c2cdd1 Games card: pass wording says what paid passes add (heroes, islands, a higher level cap, new looks); the 'never stronger' line is retired (Marty, 2026-10-22). my.js tag bumped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:14:21 -05:00
martbost 31b167e046 Game Pass package rail, part two: Admin > Game Pass gets a Pass sales table (every sale labelled package / credit-paid (old rule) / package (old rule), pass value, package value, package tx link) and stats passes.pay + sales; the chatbot canned answer, tier fact and system prompt say every pass is paid by a new package bought after tapping Get (sponsor and team paid, credits kept for ads, held credits never buy a pass); docs/GAME-PASS.md "Payment: the package rail" section; release-note update draft (not sent); admin.js tag bumped. Fulfilment stamps the pass at the event time again (as before). Tests: sov-passes store + local rebuilt on order + fresh package (seeded credits never spent), gamepass ALL PASS, member walk 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:49:39 -05:00
martbost 6a3313a861 Game Pass: no pass is ever bought with credits again (Marty, 2026-10-22). Buy only opens a waiting order and sends the member to buy a package of at least the tier price; the order is fulfilled only by a fresh on-chain package Purchase by one of the member's own positions (main or linked), mined after the order was opened (block time, 30 s clock grace), each purchase tx used once across every account. The member keeps the package credits for ads; sponsors and team are paid by the package as usual. Existing passes untouched. Card and confirm copy say so; my.js tag bumped. qa/gamepass.mjs updated for the new flow (older-than-order, too small, another member, replayed tx): ALL PASS.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:42:59 -05:00
martbost 839c867595 Pass tiers restructure (Dallas, Marty approved 2026-10-22): Explorer $19.99 (1999 credits) and Champion $39.99 (3999) for 30 days, new Sovereign $99.99 (9999, 30 days) and Legend $249.99 (24999, 365 days, the yearly pass). One table (gamepass.js TIER_DEFS: rank, names, settings stem, defaults, member-card perks); settings gamePassSovereign*/gamePassLegend* with kill switches; flag()/partner player/hand-off token carry sovereign/legend; buy, waiting orders ($100/$250 package copy), extend from max(now, until), comp/revoke, admin By pass tier table and comp options; chatbot tier fact says coming soon while sovTiers is off. All behind sovTiers (still 0): weekly Game Pass price, length and caps unchanged. Tests: sov-passes store + local extended (all pass), member QA 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 10:26:58 -05:00
martbost 32eefae473 Admin badge repost accepts the Game Pass badge for anyone who has held a pass, even before their next dashboard load records it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:20:28 -05:00
martbost 7e902b9b26 Game Pass badge gets its unlock moment (Orlando bought a pass and nothing appeared): badges with no credit bonus (CELEBRATE_NO_BONUS: gamepass) are recorded once and celebrated like the rest (toast + team post), toast wording without credits, dashboard reloads right after a pass purchase; Promo tools pill renamed back to '✨ Your toolkit' (a member could not find it under 'AI Copy Engine'). QA member 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:17:07 -05:00
martbost 4e51470cf5 Sponsor follow + one network holding tank + Sponsor check (Marty, 2026-10-22, approved 1-3)
Deliberate sponsor changes (tank adoption, dormant-lead rescue, release, adoption window ending, admin edit) are now
recorded (sponsorfollow.json: when, how, the sponsor before, origin) and travel on the LinkSpin sync rows as
sponsorSetAt/By/PrevEmail/Origin. A deliberate change from LinkSpin is applied here (a clear back to the tank included)
only when the member is not bound on the InstantAdPay contract (memberId or wallet on chain), it is newer than our own
deliberate change, and both sides agreed before it (or we have no sponsor). Bound, diverged and race cases change
nothing and are logged. Race within 15 min: the earlier change wins on both. Ordinary bindings keep the first-platform
rule. Accounts with no record behave as before; rows without the new facts hash exactly as before (no resend on deploy).

Network tank: rows carry this site's own adoptions of a person; the waiting list hides someone adopted on LinkSpin, the
two-adoptions limit counts both sites, the 3-day hold applies to a LinkSpin adoption too, follows close local open
adoptions quietly (no chat, mail or feed post).

Admin > Members > Sponsor check: shared members whose sponsor differs or is one-sided, each side's when/how, chain
binding, and Use InstantAdPay's / Use LinkSpin's sponsor (applied on the other site, refused when bound there).
Partner endpoints /api/partner/sponsor-facts and /api/partner/sponsor-apply (same HMAC as the registry rows).

Tests: qa/sponsorfollow.test.cjs 27/27, qa/sponsorfollow-e2e.mjs 20/20 (local IAP + local LinkSpin, throwaway data),
QA member walk 0 bugs. No sponsor was changed on production.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:05:07 -05:00
martbost 06b0924651 Restore LF line endings in badge.js, chatbot.js and my.js (the Game Pass commit 1c29285 rewrote them as CRLF from a Windows text-mode edit; no content change)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:25:02 -05:00
martbost 16ec626d2c Dollar value at today's POL price on the member's own pages (Marty, 2026-10-22, Brian's ask; US dollars, not a dollar token): /api/public/polusd serves the contract's own package rate (Chainlink POL/USD) cached 5 min on the server; Overview 'POL earned' shows '≈ $x.xx today', every Earnings line gets '≈ $x.xx', and a note under Earnings gives the rate, when it was updated, and that it is today's value, not the payout-day value. Browser re-reads at most every 2 min; no outside price service. QA member walk 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:21:29 -05:00
martbost 1c2928553a Game Pass: what you get, game by game (Marty, 2026-10-22: members must see what they are buying). The Game Pass card lists the account-wide caps, the weekly Pass Tournament, the badge, and each of the nine games' perks; new gold Game Pass achievement badge (badge-gamepass.jpg, name on the ribbon at 0.84) unlocked once a member has ever held a pass, shareable and postable like the others; chatbot canned answer + prompt carry the per-game perks and the 2026-10-29 free-cap date, KNOWLEDGE_DATE 2026-10-22; my.js cache tag bumped. QA member walk 0 bugs; qa/gamepass.mjs 2 date-based tournament expectations fail with or without this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 07:40:42 -05:00
martbost 3ee605a8bf Email typo check on new addresses: "Did you mean you@gmail.com?" for gmai.com / gmial.com / hotmial.com / outlook.comz / gmail.con etc., and refuse domains that cannot receive mail (no MX/A). Applies only to addresses with no account yet (existing members always sign in), on sign-in/sign-up, password signup and the support form; skipped when the server has no mail key (local QA). DNS errors fail open. Same emailcheck.js in IAP and LinkSpin. Prompted by SendGrid bounces to gmai.com and outlook.comz (2026-10-22).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 06:09:38 -05:00
martbost 8b1395a90c Chatbot: replies never carry an em dash (scrubbed to a comma)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:57:31 -05:00
martbost 9992dd061d Merge InstantAdPay knowledge-base chatbot + Save as KB entry on support replies
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:52:06 -05:00
martbost 2e0a4af28f Share-link domains: ctbgo.com (active, site config shareDomain) and mylinehq.com (spare) 302 /<name> to /join/<name> (query kept, noindex); member invite line and promo tools now hand out https://ctbgo.com/<name>; old instantadpay.com/join links keep working
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:46:58 -05:00
martbost 6f194596fe Support: no 'Save as KB entry' on LinkSpin tickets (they would land in the InstantAdPay knowledge base; LinkSpin keeps its own)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:39:02 -05:00
martbost 1e040f21ff Chat knowledge base: the assistant answers from maintained entries, and support replies become entries
- kb.js: entries { id, title, questions, answer, tags, pattern, handoff, order, source, updated } in MySQL table kb_entries (created on boot) or DATA_DIR/kb.json without DATABASE_URL. BM25 over title, question variants and tags (answer at a low weight) with word bigrams; the top hits (within 30% of the best, score 3+) go into the system prompt as KNOWLEDGE BASE, and when nothing fits the prompt says to answer "I'm not sure, ask support".
- One source: chatbot.js CANNED seeds the KB (ids c-*, its regex becomes the entry's instant-answer pattern, same first-match order), kb-seed.js seeds the home FAQ, Platform Facts, wallets FAQ and the Coinbase support reply (f-*). The fast path now serves the KB entry, so an admin edit changes the instant answer; the in-code CANNED only answers if the KB store fails. Unedited seeds follow code changes, edited ones are left alone, deleted seeds stay deleted.
- Admin > Knowledge base: list, search, filter by source, add, edit, delete, and Try a question (instant answer or what the AI is given). Support tickets: "Save as KB entry" under each sent reply opens a draft with the member's question and the reply (greeting and sign-off trimmed). Em dashes in admin input become commas.
- chatbot.js: OPENROUTER_URL override for tests; solo-ads answer em dash removed; KNOWLEDGE_DATE 2026-10-20.
- qa/chatbot-sync.mjs: takes the later of KNOWLEDGE_DATE and /api/chat/kb-stamp (newest KB edit by a person, Central day; seed refreshes do not count).
- QA: qa/kb-retrieval.cjs (13 sample questions rank the right entry first, off-topic returns nothing), qa/kb-chat.mjs (local copy + mock OpenRouter: Coinbase answered from the KB, fast path without an AI call, admin CRUD, restart keeps edits), bash qa/run.sh kb; walk covers admin#kb and Save as KB entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:37:09 -05:00
martbost 4df932723e Speed: member reads cached 15 s (cleared on every new chain event) so line, stats and positions stop repeating RPC round trips
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:21:42 -05:00
martbost 0e528ae854 Game sign-in kit: a remembered sign-in on this device opens on 'Continue as @name' (new POST /api/game/auth/resume turns the 29-day kit pass into a fresh hand-off token, no code; pass checked for this game, suspended accounts refused), 'Use a different account' falls back to email; Shards of Valor login ad uses the card view (frames: false)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:26:15 -05:00
martbost 7af47ae921 Speed: catalog reads run in parallel and /api/catalog serves the cached ladder while refreshing in the background (was ~6 s of sequential chain reads on every 20 s miss); position rows read the chain side by side
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:30:30 -05:00
martbost 0aa22e9984 Merge Shards of Valor Explorer/Champion passes (behind sovTiers, default off)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 14:47:30 -05:00
martbost 0688bdeb72 Pass tiers: Explorer ($20/30 days) and Champion ($40/30 days) beside the weekly Game Pass, behind sovTiers (default off, admin-only preview)
Islands and looks in Shards of Valor, never power and never more POL: every tier gets exactly the weekly pass caps and polgrant
still answers pass: true. Per-tier expiry side by side (record.tiers, legacy until mirrors weekly, lazy migration); flag() adds
tier (highest active) and tiers; hand-off token gamePass { active, until, tier }; /api/partner/player pass { active, until, tier,
tiers }. Buy { tier } with purchased credits or a waiting order per tier that a big-enough package fulfils (highest price first,
each tx once). No auto-renew, no proration. Admin: per-tier stats (Central week/month), comp per tier, end-a-tier (refund).
Tournament pool keeps weekly sales only unless passTournamentTierSales. Member card shows three tiers; /my#passes opens it.
Tests: qa/sov-passes-store.cjs, qa/sov-passes-local.mjs (bash qa/run.sh sov-passes). Cache tags my.js/admin.js 20261018tiers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 14:46:51 -05:00
martbost 5e8f2c0b6b Shards of Valor sign-in: /api/my/shardsofvalor hand-off (SOV_SSO_SECRET, Game Pass flag rides along), in-game sign-in entry, Game Pass game list + caps, return-to-game after sign-in; not in the public games list until launch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 14:08:15 -05:00
martbost 34a1de0b15 P&L: Game payouts card, an all-time running total of every game wallet's payouts read from Polygon (incremental, cached); PolHunter ledger detail folded under it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 07:11:25 -05:00
martbost 017017ad63 Login ad in the games: the sponsor interstitial after a fresh in-game sign-in, counted per surface
- Game sign-in kit (game-signin.js): after a fresh email sign-in (never a remembered
  pass) the kit shows the login ad before the hand-off to /auth?t=, same as the
  dashboard: sponsor card, Open Ad (a counted click through /api/ads/click), sponsor
  framed in a full-screen overlay when frameable else a new tab, 10 s countdown
  (loginDwellSeconds), then Continue to the game. No ad, an error, a non-200 or a
  7 s stall all go straight to the game. A game page whose CSP blocks the frame gets a
  new-tab link instead. mount option loginAd: false switches it off.
- GET /api/game/ads/login?game=<slug>: CORS only for that game's GAME_AUTH origins
  (dev: localhost); the dashboard /api/ads/slot route keeps no CORS. Both share
  loginAdFor() (ads.serve: impression + lastShownDay as before). Drip Runner and
  PolyBreak are marked frames: false (their CSP is default-src 'self'), so their ad
  opens in a new tab; frame checks for games ignore an instantadpay.com-only
  frame-ancestors allowance.
- loginshows.js: every login-ad request tallied per Central day, surface (dashboard or
  game slug) and kind (member slot, house, none); MySQL table login_shows (created on
  first use) or DATA_DIR/login-shows.json. GET /api/admin/login-shows + a Login-ad
  showings card on the admin Traffic pane (dashboard vs games, house, no-ad, by game).
- The kit is served no-cache so games pick it up without a tag bump; admin.js tag bumped.
- Chatbot fact updated (slot rules + games), KNOWLEDGE_DATE 2026-10-18.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 06:17:41 -05:00
martbost d520eb67af Login slots: purchased-only at charge time, resume obeys the cap, no top-up on slots
- chargeCredits takes opts.purchasedOnly (new poolShare helper, JSON + MySQL): the
  1,000-credit slot charge draws only the credited purchased-grade pool, the rest burns
  on-chain; viewing credits never pay, even when the member holds enough of them.
- setStatus: resuming a paused member login slot is refused while 3 are live
  (loginSlots() helper, exported).
- topUpCampaign refuses login slots; the dashboard no longer offers Buy more views on one.
- audit: the days-charged check skips 30-day slots (expires set).
- JSON grantWelcome keeps the purchased grade, milestones and streak fields.
- my.js cache tag bumped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 05:57:28 -05:00
martbost 716dd8066f Override dry run: dollar amounts were 100x (cents shown as dollars); POL amounts were right
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:32:01 -05:00
martbost 34d2284051 Level-4 override DRY RUN: 3% of each purchase to the 4th upline with 5+ qualifying buyers, hunting upward up to 25 hops; weekly Monday report to Marty's Telegram + /api/admin/override; no money moves
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:29:52 -05:00
martbost af66f7f865 Help desk translation: member messages in other languages get an English translation (Telegram, admin email, admin view, bot thread); Marty's replies go back in the member's language with his English underneath (OpenRouter, reasoning off; failures fall back to untranslated)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 19:03:30 -05:00
martbost e490e15abf Email intake: iap-support@linkspin.app is the InstantAdPay support alias (NameSilo's forwarder will not deliver to the help. subdomain)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:57:04 -05:00
martbost ad17017250 Help desk email intake: SendGrid Inbound Parse -> /api/inbound/email (secret key) creates tickets or threads replies; robots, bounces, auto-replies and our own mail dropped; ticket mail carries reply+<ref>@ reply-to and Auto-Submitted
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:10:53 -05:00
martbost 524ce843dc Help desk: signed partner API for LinkSpin tickets (LS- refs on the one shared desk)
POST /api/partner/support/{create,list,view,reply,token,token-reply}, signed exactly
like the registry rows (LS_SYNC_SECRET, X-LS-Ts + X-LS-Sig, now one readLsSigned helper
shared with /api/partner/registry). Only platform 'linkspin' tickets are reachable there.

LinkSpin tickets: requester mail, links and footer say LinkSpin support and point at
LS_URL (/support/t/<token>, /help#t=<ref>); no InstantAdPay in-app notice is sent for
them. Telegram ping, admin mail and the support bot's thread/list views mark them
LinkSpin. The member Help pane here lists InstantAdPay tickets only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:04:52 -05:00
martbost 80885705d2 Restore CRLF line endings changed by the previous commit's cache-tag bump (no content change)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:22:02 -05:00
martbost e2d15aa751 Support in the top nav of every public page, and the chat bubble's greeting points to support; cache tags bumped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:20:31 -05:00
martbost 8fe527ab67 Support bot menu: persistent buttons (Open, Waiting, High, Recently closed, Help), command menu via setMyCommands, tappable ticket lists that open the thread
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:01:55 -05:00
martbost 6f6412d908 Help desk in Telegram: @CTBTickets_bot pings with Close/Waiting/High/Open buttons, reply to a ping to answer (/note = internal), /tickets and /t <ref>; secret-header webhook, only Marty's private chat is obeyed; old one-way ping stays as fallback
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:56:54 -05:00
martbost 9be58bd5ef Help desk: support tickets for members (Help pane), the public /support page with private ticket links, chatbot hand-off, and an admin Support pane
- tickets.js: one shared desk (platform iap now, linkspin later), dual-mode store (MySQL tables tickets + ticket_messages, else support.json); refs IAP-<1000+id> / LS-; private no-login link /support/t/<ref>.<HMAC> signed with DATA_DIR/support.key (or SUPPORT_SECRET); ingestEmail() ready for the support@ intake step (threads by Message-ID, then [ref] in the subject from the same sender)
- Member Help pane (/my#help): list with status + unread badge, new ticket (category, subject, message, up to 2 screenshots via /api/my/upload), thread + reply (a reply reopens a closed ticket)
- Public /support: name, email, category, subject, message behind the sign-up walls (honeypot, form age, per-IP limits with the icon check, global cap) plus a per-email cap; confirmation email with the ref and the private link
- Chatbot: CANNED + systemPrompt know the help desk; answers that cannot help (or "talk to a human") offer "Send this to support", which files the last turns as a ticket (members: Help pane; signed out: email + the same guard)
- Admin Support pane: open / waiting / closed / all, platform, category, search; open-count badge; ticket view with requester account info, internal notes, status/priority/category, saved replies (site setting supportTemplates); deep link /admin#support?t=<ref>
- Notifications: new ticket / member reply -> Telegram to Marty's private chat only (supportTelegramChat, default 1289244227, site bot then Hermes fallback, never a group or the Discord relay) + email to ADMIN_EMAIL, max one per ticket per 10 min; Marty's reply -> email "[IAP-1042] subject" + a 'notice' inbox message for members, bursts batched
- support* settings are kept out of /api/config; Support link in the site footer, home footer, member page foot, terms and privacy; "Contact support" errors point at /support
- QA walk: member Help ticket flow, admin Support pane + deep link, internal-note leak check, public /support + private link + tampered token + form-age refusal
- Cache tags: common.js 20261016a, chat.js 20261016a, my.js 20261016r, admin.js 20261016sp, support.js 20261016a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:51:30 -05:00
martbost f0c868ef23 Leader tools: Training section (Leader's Guide PDF, presentation, build-wide video) with cards in My line and Pipeline; #training?g=leader deep link; training entries can name their button; chatbot knows it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:09:55 -05:00
martbost 79e48b3cad Home hero: packages from 5 to 500 dollars; cache tags bumped for the re-voiced platform and partner overview videos
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:25:38 -05:00
martbost 9b7b166097 Presentation: packages scene re-voiced and rebuilt for $5 to $500 (7 packages); captions in 6 languages; cache tags bumped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 12:27:48 -05:00
martbost 4c470d8e3c Packages: Starter $10 (1,000 credits) and Elite $500 (70,000) across tiles, calculators, promo copy, kits, facts, chatbot; tiles sorted by price; cache tags bumped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 12:16:45 -05:00
martbost 084d1ea3d6 Game Pass: tournament/pending answers rows (the field the games' polgrant.js reads), games-side integration test, docs "Games: as built"
- /api/partner/tournament/pending returned only `pending`; every game's polgrant.js tournamentPending() reads `rows`, so
  PolHunter's prize payer would never have seen a row. Answer now carries both (`pending` stays for the admin pane + qa).
- qa/gamepass-games.cjs (bash qa/run.sh gamepass-games): boots a local copy like qa/gamepass.mjs and drives the REAL
  spooky-doors/server/polgrant.js and polhunter/lib/tournament.js against it (fetchPass, daily/progress caps, carry:<day>
  zero-POL call on the next Central day, void, bad secret / IAP down -> retry, retry queue, tournament dry run + live). 44/44.
- qa/gamepass.mjs pins the `rows` field.
- docs/GAME-PASS.md: 3a item 8 updated, "Games: as built" section merged from the games' notes (per game files/refs/perk/tests,
  decisions, the tournament payer and its dry-run claim trap, the integration test).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-16 09:27:46 -05:00
martbost 4d6a0f2f83 Game Pass (IAP side): $5 weekly pass across all nine games + account-wide POL cap service
- gamepass.js: durable pass store, waiting orders fulfilled by the next $5 package, cap ledger
  (daily/total per Central day, progress deferral + next-day carry-forward, idempotent refs kept 90 days,
  void), weekly Pass Tournament (Monday 9 AM Central, marks.claim, prizes recorded for the game faucets),
  admin stats. Settings in site config, caps enforced only from capsStartDate (recorded before).
- server.js: /api/partner/player, /api/partner/polgrant(+/void), /api/partner/tournament/pending|paid,
  /api/my/gamepass(+/buy), /api/admin/gamepass/stats|comp|tournament/run; gamePass claim on every
  sign-in hand-off token; purchase-event fulfilment inside the marks.claim block.
- Members > Games: Game Pass card (Buy via IAP.confirmBox, deep link /my#games?pass=1), Overview nudge
  after a free-cap hit. Admin > Game Pass pane. Chatbot canned answer + FACTS, KNOWLEDGE_DATE 10-16.
- qa/gamepass.mjs scripted test (bash qa/run.sh gamepass), Games tab card in qa/walk.mjs.
- docs/GAME-PASS.md: 3a clarifications + Built section; docs/GAME-PASS-RELEASE.md draft (not sent).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-16 08:18:09 -05:00
125 changed files with 13722 additions and 2294 deletions
+1 -1
View File
@@ -71,7 +71,7 @@ async function view(email) {
try { out.credits = await ads.balances([...ids], acct.email); } catch (e) { out.credits = null; }
try { out.earnedSplit = await ads.earnedSplit(acct.email); } catch (e) {}
// campaigns
try { out.campaigns = (await ads.listCampaigns(acct.email)).map(c => ({ id: c.id, type: c.type, status: c.status, name: c.name || c.title || '', budget: c.budget, spent: c.spent, created: c.created, views: c.views, clicks: c.clicks })); } catch (e) { out.campaigns = []; }
try { out.campaigns = (await ads.listCampaigns(acct.email)).map(c => ({ id: c.id, type: c.type, status: c.status, name: c.name || c.title || '', budget: c.budget, spent: c.spent, created: c.created, views: (Number(c.imps) || 0) + (Number(c.impsNas) || 0), pack: c.type === 'visits' ? (Number(c.body) || 0) : 0, clicks: c.clicks })); } catch (e) { out.campaigns = []; }
// line (3 levels) with wallet / bought / qualified per person
const levels = await accounts.downline(acct.email, 3).catch(() => []);
const boughtIds = new Set(chain.recentEvents(1e9).filter(ev => ev.type === 'Purchase').map(ev => ev.buyerId));
BIN
View File
Binary file not shown.
+3 -3
View File
@@ -12,7 +12,7 @@ function refunded() { const out = {}; try { for (const f of fs.readdirSync(R.dat
async function run() {
const out = { checkedAt: Date.now(), checks: [] };
if (!db.enabled()) { out.checks.push({ name: 'Counters', ok: true, detail: 'JSON mode: not checked', issues: [] }); return out; }
const camps = await db.q("SELECT id, name, type, status, imps, clicks, spent, accrued, budget, created, starts, house FROM campaigns WHERE house=0 OR house IS NULL");
const camps = await db.q("SELECT id, name, type, status, imps, clicks, spent, accrued, budget, created, starts, house, expires FROM campaigns WHERE house=0 OR house IS NULL");
const back = refunded(); for (const c of camps) if (back[c.id]) c.spent = Math.max(0, Number(c.spent) - back[c.id]); // already made right
const logStart = (await db.q('SELECT MIN(day) d FROM camp_hours'))[0].d; const logStartMs = logStart ? Date.parse(logStart + 'T00:00:00Z') : 0;
const byType = t => camps.filter(c => c.type === t);
@@ -48,8 +48,8 @@ async function run() {
{
const rows = await db.q('SELECT campaign_id, COUNT(DISTINCT day) d FROM camp_hours WHERE n>0 GROUP BY campaign_id'); const shown = {}; for (const r of rows) shown[r.campaign_id] = Number(r.d);
const issues = [];
for (const c of byType('login')) { const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
add('login ads: days charged vs days shown', issues, byType('login').length + ' campaigns compared');
for (const c of byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status))) { /* a reservation in the login-ad line is paid up front and has no end date yet (2026-10-23) */ const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
add('login ads: days charged vs days shown', issues, byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status)).length + ' per-day campaigns compared (30-day slots are paid up front)');
}
// 4. featured: a live booking older than two hours must have views
{
+7 -2
View File
@@ -146,10 +146,15 @@ function sessionCookie(token) {
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL / 1000}${IS_PROD ? '; Secure' : ''}`;
}
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
// signs in from, so their own clicks count as tests on LinkSpin). Never throws into the caller.
let seenFn = null; function onSeen(fn) { seenFn = fn; }
async function fromRequest(req) {
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
if (!m) return null;
return impl().get(decodeURIComponent(m[1]));
const s = await impl().get(decodeURIComponent(m[1]));
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
return s;
}
async function refreshMemberId(sess) {
if (!sess) return 0;
@@ -172,4 +177,4 @@ async function logout(req) {
if (s) await impl().drop(s.token);
}
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, refreshMemberId, logout };
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
+1 -1
View File
@@ -8,7 +8,7 @@ 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 } };
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 } , refuelStart: { file: 'badge-refuelstart.jpg', ribbonY: 0.735 }, refuel3: { file: 'badge-refuel3.jpg', ribbonY: 0.783 }, refuel6: { file: 'badge-refuel6.jpg', ribbonY: 0.716 }, refuel12: { file: 'badge-refuel12.jpg', ribbonY: 0.744 } };
let FONT;
function font() {
if (FONT !== undefined) return FONT;
+2 -2
View File
@@ -108,7 +108,7 @@ function head(o) {
+ '</head><body><div class="wrap bl">';
}
function tail() {
return '</div><script src="/assets/common.js?v=20261015a"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
return '</div><script src="/assets/common.js?v=20261023ov"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
}
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="InstantAdPay"><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="" loading="lazy" style="width:100%;border-radius:10px;margin:0 0 12px">' : '') + '<h2>' + esc(p.title) + '</h2><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '</p></a>';
@@ -152,7 +152,7 @@ function rss(posts) {
return '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>InstantAdPay blog</title><link>' + SITE + '/blog</link><description>Coaching and teaching articles from Marty Bostick.</description>' + items + '</channel></rss>';
}
function sitemap(posts) {
const pages = ['/', '/facts', '/blog', '/whats-new', '/leaderboard', '/ledger', '/contract', '/plays', '/wallets', '/earning', '/partners', '/friday', '/wednesday', '/presentation'];
const pages = ['/', '/facts', '/blog', '/whats-new', '/leaderboard', '/ledger', '/contract', '/plays', '/wallets', '/earning', '/partners', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation'];
const u = pages.map(p => '<url><loc>' + SITE + p + '</loc><changefreq>weekly</changefreq></url>').join('')
+ posts.map(p => '<url><loc>' + SITE + '/blog/' + p.slug + '</loc><lastmod>' + new Date(p.updated).toISOString().slice(0, 10) + '</lastmod><changefreq>monthly</changefreq></url>').join('');
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
+19 -9
View File
@@ -149,7 +149,16 @@ async function memberIdByAccount(addr) {
}
async function memberCount() { return toNum(word(await call(SEL.memberCount), 0)); }
async function productCount() { return toNum(word(await call(SEL.productCount), 0)); }
// member reads are cached 15 s (2026-10-20): dashboards ask for the same members many times a minute and every read is
// an RPC round trip; sponsor never changes and a buyer count up to 15 s old is fine for display
const memberCache = new Map();
async function member(id) {
const hit = memberCache.get(Number(id)); if (hit && Date.now() - hit.at < 15000) return hit.v;
const v = await memberRead(id); memberCache.set(Number(id), { at: Date.now(), v });
if (memberCache.size > 5000) memberCache.clear();
return v;
}
async function memberRead(id) {
const r = await call(SEL.members, [id]);
return { account: toAddr(word(r, 0)), sponsorId: toNum(word(r, 1)), buyerCount: toNum(word(r, 2)),
activated: toNum(word(r, 3)) === 1, countedAsBuyer: toNum(word(r, 4)) === 1 };
@@ -162,15 +171,16 @@ async function product(id) {
async function quoteWei(id) { try { return toBig(word(await call(SEL.quoteWei, [id]), 0)); } catch (e) { return null; } }
async function creditBalance(id, type) { return Number(toBig(word(await call(SEL.creditBalance, [id, type || 0]), 0))); }
async function catalog() {
// products and quotes are read side by side, not one after another (2026-10-19: 15 sequential reads took ~6 s
// and every dashboard waited on them)
const n = await productCount();
const out = [];
for (let i = 1; i <= n; i++) {
const p = await product(i);
if (!p.exists || !p.active) continue;
const q = await quoteWei(i);
out.push(Object.assign(p, { costWei: q === null ? null : q.toString() }));
}
return out;
const ids = Array.from({ length: n }, (_, k) => k + 1);
const rows = await Promise.all(ids.map(async i => {
const [p, q] = await Promise.all([product(i), quoteWei(i)]);
if (!p.exists || !p.active) return null;
return Object.assign(p, { costWei: q === null ? null : q.toString() });
}));
return rows.filter(Boolean);
}
// ---- event decode ----
@@ -242,7 +252,7 @@ async function tail() {
const ev = decodeLog(lg);
if (!ev) continue;
ev.ts = Date.now(); // indexed-at time: powers honest time-series charts
state.events.push(ev);
state.events.push(ev); memberCache.clear(); // a new chain event can change any member: drop the 15 s read cache
tally(ev);
if (onEvent) { try { onEvent(ev); } catch (e) { console.error('chain onEvent', e.message); } }
}
+238 -66
View File
@@ -4,15 +4,27 @@
//
// 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;
let PASS_TIERS = null; // () => the live pass tiers (server.js, from gamepass.cfg): the tier fact follows the sovTiers switch
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; }
function init(opts) {
if (opts && typeof opts.gameLive === 'function') GAME_LIVE = opts.gameLive;
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; 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 ''; }
@@ -20,53 +32,108 @@ function key() {
function enabled() { return !!key(); }
// ---- canned answers: instant, free, always in voice ----
const KNOWLEDGE_DATE = '2026-10-15'; // bump whenever the canned answers / prompt are brought up to date
const KNOWLEDGE_DATE = '2026-10-28'; // 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 = [
{ re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i,
{ 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: 'level4-override', title: 'The Level 4 override (3%)', q: ['What is the Level 4 override?', 'Do I earn from my fourth level?', 'How does the 3% override work?'], tags: ['override', 'level 4', 'fourth level', 'commission', 'payouts'],
re: /(level ?(4|four)|4th level|fourth level|override|3 ?%|three percent)/i,
a: 'The Level 4 override is 3% of every package bought four levels below you, paid by the company on top of the three levels the contract pays. It goes to the buyer’s 4th sponsor up if that member has 5 or more qualifying buyers (direct referrals who bought $20 or more, the same bar as level 3). If they do not have 5 yet, it moves up the line to the next member who does, up to 25 steps, and each purchase pays one override to one person. It is paid weekly in POL from a company wallet, every Monday after 9 AM Central for the Monday to Sunday week before, through the contract’s award function, so every payment has a Polygon link, and it shows in your Earnings as "Level 4 override". Weekly totals under 0.01 POL carry over to the next week. It counts purchases from the start date on, not earlier ones. It comes from the platform’s 20% share, so the 50/20/10 split does not change. What you earn depends on real purchases in your line; nothing is guaranteed.' },
{ 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 every game in the network 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; POL Miner daily crystal limit 1.5 POL instead of 0.5 plus one free supply crate every day; 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. Get it in Members > Games > Game Pass: every pass is paid by a NEW package purchase of $5 or more. Tap Get the Pass, then buy the package; the pass starts the moment that purchase settles on chain. Your sponsor and team are paid from that package as usual, and you keep every credit of the package for your ads. Credits you already hold (earned or purchased) never buy a pass, and a package bought before you tapped Get the Pass does not count. Buying again while a pass is active adds 7 days.' },
// game POL to any linked wallet (Marty, 2026-10-27, "build all three"): sits ahead of the per-game entries so "my Gem Kingdom POL never came" lands here
{ id: 'game-pol-wallet', title: 'Getting your game POL (link your wallet)', q: ['Why was my game POL not sent?', 'It says POL is waiting for my wallet', 'Do I need to switch on payouts to get game POL?'], tags: ['games', 'game pol', 'link wallet', 'waiting for your wallet', 'not sent'],
re: /(pol (is )?waiting for (my |your |a )?wallet|link (my |your |a )?wallet to (receive|get)|(game|games|gem ?kingdom|drip ?runner|clutter ?hunt|spooky ?doors|road ?agent|poly ?break|spell ?wheel|poly ?warriors?)\b[^.?!]{0,60}\bpol\b[^.?!]{0,40}\b(not (been )?(paid|sent)|never (paid|sent|arrived|came)|stuck|waiting|pending|switch on|activat\w*)|(switch on|turn on|activate) payouts?[^.?!]{0,40}\b(game|games)\b[^.?!]{0,20}\bpol\b)/i,
a: 'Game POL is paid to the wallet linked to your InstantAdPay account. Linking is one free signature on your Wallet tab (https://instantadpay.com/my#wallet): it is not a transaction and it cannot move funds. Once your wallet is linked, every game sends your POL automatically, usually within the hour, including everything you earned before you linked it (each game still pays once your balance reaches the payout line shown in that game). You do not need to switch on payouts for game POL: a linked wallet is paid even before it is activated, so a member waiting in the holding tank for a sponsor still gets their game POL. If a game already has a different wallet on file for you, it keeps paying that one; open Help if that needs changing.' },
{ 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.' },
{ re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i,
{ 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=<username>), 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.' },
{ re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i,
{ 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.' },
{ re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i,
{ 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.' },
{ re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i,
{ id: 'polminer', title: 'POL Miner mining game', q: ['What is POL Miner?', 'How do Polygon crystals work in POL Miner?', 'What is a supply crate?'], tags: ['games', 'polminer', 'mining', 'polygon crystal', 'supply crate'],
re: /(pol ?miner|mining game|digging game|polygon crystals?|pink crystals?|drill boss(es)?|supply crates?)/i,
a: 'POL Miner (https://polminer.com, also in Members > Games) is a free dig-down mining game. Dig through the layers of dirt and rock, haul ore up to sell for coins, upgrade your pick, lamp, cart and thruster, and beat a drill boss every 30 m to open the way deeper. The rare glowing pink Polygon crystals pay a random amount of POL the first time you dig each one out, each drill boss pays POL the first time you beat it, and so do your first trips to 50, 100, 150 and 200 m. Coins are for upgrades only and never turn into POL. You can play as a guest right away; sign in with your InstantAdPay account in the game and what you earned as a guest is collected. POL collects in your POL Miner balance and is sent automatically to the wallet linked to your InstantAdPay account (one free signature on the Wallet tab) once it reaches the payout amount. Low on lamp power or coins? Park on the SUPPLY pad: a short sponsor visit opens a supply crate with a full lamp and coins.' },
{ id: 'turkeydrop', title: 'Turkey Drop Thanksgiving game', q: ['What is Turkey Drop?', 'How does Turkey Drop pay?', 'What is back on the air in Turkey Drop?'], tags: ['games', 'turkey drop', 'thanksgiving', 'back on the air', 'seasonal'],
re: /(turkey ?drop|turkeydropgame|\bwfwl\b|back on the air|catch(ing)? (the )?turkeys)/i,
a: 'Turkey Drop (https://turkeydropgame.com, also in Members > Games) is the network’s Thanksgiving game, open Nov 2 through Nov 30 (Central time); its card shows in Members > Games only during the season. The WFWL 98.7 radio helicopter is dropping turkeys over the mall in a 70s cartoon world: swing your net and catch them before they splat. Too many splats and the station pulls you off the air. One tap signs you in with your InstantAdPay account. Score milestones pay POL the first time you reach each one, and the top 3 on the weekly leaderboard win a POL prize. POL collects in your Turkey Drop balance and is sent automatically to the wallet linked to your InstantAdPay account (one free signature on the Wallet tab). Pulled off the air? A short sponsor visit puts you back on the air with an extra life; that is gameplay only, never POL. 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.' },
{ re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i,
{ 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.' },
{ re: /(clutter ?hunt|hidden.object|haunted manor)/i,
{ 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.' },
{ re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i,
{ 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.' },
{ re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i,
{ id: 'games-tab', title: 'Games tab and Drip Runner', q: ['Which games pay POL?', 'What is Drip Runner?', 'How do game refuels work?'], tags: ['games', 'drip runner', 'game refuel', 'games tab'],
re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|(?<!(monthly|my|your|the|a) )refuels?(?!(ing)? ?(day|streak|bonus|window|kit|card|guide)))/i, // 2026-10-24: questions about the Monthly Refuel streak go to the 'refuel' entry, not here
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).' },
{ re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i,
{ 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.' },
{ 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,
{ 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.' },
{ re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in Promo tools; they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room tab in your member area: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview (with a Refuel LinkSpin link once this site is done for the cycle). Buy here: https://instantadpay.com/my#buy. The full guide, with the flow step by step: https://instantadpay.com/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
{ 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.' },
{ 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.' },
{ 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. Since 2026-10-23 a $5+ Friday package also gives you a free 7-day Game Pass (once per Friday, all the games); if that package is the one starting a pass you already ordered, it does not add a second week. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' },
// 2026-10-23 conversion pixel (LinkSpin counts, IAP shows): Campaigns > Conversion tracking
{ id: 'conversion-tracking', title: 'Conversion tracking (goal pixel)', q: ['How do I track conversions?', 'Can I see which ad brought a sign-up or sale?', 'Where do I put the goal pixel?', 'What is the landing tag?', 'How do I set up conversion tracking on WordPress?'], tags: ['conversion tracking', 'goal pixel', 'landing tag', 'cost per goal', 'aweber', 'getresponse', 'wordpress', 'setup guide'],
re: /(conver(sion|t)s?.{0,20}(track|pixel|goal)|track(ing)?.{0,30}(conversions?|sign.?ups?|sales|subscribers|leads)|goal pixel|landing tag|tracking pixel|cost per (goal|lead|sale|sign.?up|conversion)|thank.?you page|lsclk)/i,
a: 'Conversion tracking shows which of your ads bring subscribers and sales, not just clicks. It lives in your dashboard under Campaigns > Conversion tracking (https://instantadpay.com/my#campaigns). Three steps: 1) add a goal, like subscriber or sale (a default value is optional); 2) put the landing tag on the page your ad points to; 3) put the goal pixel on your thank-you page. Every click on your ad carries a click id (lsclk=...), and LinkSpin, our sister site, matches each goal to the click: first by the click id still in the address, then the id the landing tag stored, then LinkSpin\'s cookie, and last a 24-hour match on the same connection and browser (the panel says how sure each kind is). Each goal counts once per click, only within 30 days of a real click on your ad, and each campaign shows its goals and its cost per goal (30 days) in credits: the credits that campaign spent in the same 30 days, divided by its goals. Using Aweber or GetResponse? Set the form\'s thank-you (success) page to a page on YOUR site that carries the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL). If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. The Send a test conversion button fires your real pixel in test mode (Last test updates); to check your real thank-you page, add &test=1 to its pixel and open it once. Tests and your own clicks (on your ads, and on your LinkSpin spin links and Banner Spins) never count in your numbers; the card says how many of your own clicks were kept as tests. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://instantadpay.com/conversion-tracking' },
// 2026-10-23 (Marty: "they need to pay for the slot now to get a place in line"): 6 member slots, then a prepaid line
{ id: 'login-ads', title: 'Login ads: slots and the paid line', q: ['How do login ads work?', 'All login ad slots are taken, what now?', 'Can I reserve a login ad slot?', 'Can I cancel my login ad reservation?'], tags: ['login ad', 'login slot', 'reserve', 'queue', 'line', 'refund'],
re: /(log ?in.?ads?|sign.?in ads?|log ?in (ad )?(slots?|sponsor)|(reserve|reservation|queue|place in line|waiting list).{0,40}log ?in|log ?in.{0,40}(slots?|reserve|reservation|queue|place in line|waiting list)|reserve (a |the )?(next )?slot)/i,
a: 'A login ad is your page shown full screen to members right after they sign in, on the dashboard and in the connected games. A slot is a flat buy: 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once up front and never charged per day. Earned credits cannot pay for it. Up to 6 member slots run at once, because they all share the same sign-ins. When all 6 are taken you can reserve the next slot in Members > Campaigns: you pay the same price now, and your place in line is first paid, first served. Your 30 days only start when your turn comes, and the form shows your place and an estimated start date in Central time. That date is an estimate, because a slot can end early if its owner archives it. When your ad starts you get a notice on site and an email. Until it starts you can edit the link, image or headline for free, or cancel it and get every credit back. Once it has started, normal slot rules apply. A freed slot always goes to the line first, so a paused slot can only be resumed when a slot is open with nobody waiting.' },
// 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.
{ 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,
{ 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.' },
{ 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,
{ 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.' },
{ re: /(pyramid|ponzi|scam|scheme)/i,
{ 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.' },
{ re: /(withdraw|cash ?out|payout request|minimum payout)/i,
{ 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).
{ 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,
{ 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.' },
{ 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,
{ id: 'network-rate', title: 'Network views and partner visits cost a quarter of the rate', q: ['Do network views use my credits?', 'How much do Network Ad Space views cost?', 'Why are network views cheaper?'], tags: ['network views', 'network ad space', 'syndication', 'passivedrip', 'partner visits', 'credits', 'rate'],
re: /((network (views?|ad space)|syndicat\w*|partner (sites?|visits?)).{0,60}(credits?|charge[ds]?|cost|spend|balance|budget|free|pay|rate|cheap)|(credits?|charge[ds]?|cost|spend|balance|budget|pay|rate).{0,60}(network (views?|ad space)|syndicat\w*|partner (sites?|visits?)))/i,
a: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs a quarter of the rate: 4 network views cost what 1 view here does, and 4 partner visits use up 1 visit of your pack. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/4 rate)" lines in Credit activity.' },
{ 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.' },
{ 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,
{ 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.' },
{ 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,
{ 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
@@ -75,61 +142,135 @@ const CANNED = [
// ("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).
{ 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,
{ 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.' },
{ 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.' },
{ re: /(qualif|unlock level|level 2|level 3|pass.?up)/i,
{ id: 'tank-hold', title: 'Matched with a sponsor (activation on hold)', q: ['Why can I not switch on payouts?', 'It says I am being matched with a sponsor'], tags: ['holding tank', 'switch on payouts', 'matched with a sponsor', 'ready to activate'],
re: /(being matched|matched with a sponsor|(can.?t|cannot|unable to) (i )?(switch on|turn on|activate) (my )?payouts|activate (button|payouts) (is )?(gone|missing|hidden)|ready to activate)/i,
a: 'You joined without a sponsor, so you are in the holding tank. The contract locks your sponsor for good the first time you switch on payouts or buy, so switching on payouts on its own waits until a real member picks you up. Buying is never held: you can buy a package any time, and with no sponsor it goes through under the company position. Once your wallet is linked, members see you at the top of their holding tank with a Ready to activate badge. If nobody adopts you within 24 hours, the site assigns you to the next eligible member in turn (someone active with their own $20 package). As soon as you have a sponsor, the Switch on payouts button comes back. If you already have a sponsor on LinkSpin with the same email or wallet, you are placed under them right away.' },
{ id: 'tank-activate-link', title: 'Switch on payouts after you were picked up (one-tap link)', q: ['I got a Switch on payouts link from my new sponsor', 'How do I switch on payouts after I was adopted?'], tags: ['holding tank', 'switch on payouts', 'adopted', 'one tap', 'reminder'],
re: /((switch on|turn on|activate) payouts? (link|email|reminder)|activate=1|(picked (me )?up|adopted( me)?).*(switch on|activate)|one.?tap.*(payouts|activate)|reminder.*switch on payouts)/i,
a: 'When a member picks you up from the holding tank (or the site assigns you to one after 24 hours), the chat and the email you get both carry a Switch on payouts link: instantadpay.com/my?activate=1#wallet. Tap it, sign in if asked, and your wallet opens with your new sponsor already filled in. It is one free transaction, no package needed, and it locks that sponsor in as yours on the contract. No wallet linked yet? The same link asks you to link one first (one free signature) and then carries on. On a phone without a wallet browser, the wallet picker opens and hands you to your wallet app to confirm. Nobody, not even the site, can switch payouts on for you: it has to come from your own wallet. If you have not done it 24 hours after you were picked up you get one reminder email (and your sponsor gets a note to give you a nudge), and one last reminder at 72 hours. They stop as soon as your payouts are on or you buy a package.' },
{ 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. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list: their payouts are on hold until someone adopts them, and after 24 hours the site assigns them to the next eligible adopter in turn (own $20 package, fewer than 2 open adoptions, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' },
{ 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.' },
{ 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,
{ 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.' },
{ re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i,
{ 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.' },
{ re: /(referral link|invite link|share link|refer)/i,
{ 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.' },
{ 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,
{ 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.' },
{ re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i,
{ 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.' },
{ re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
{ 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.' },
{ re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i,
{ 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.' },
{ 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.' },
{ 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,
{ 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.' },
{ re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i,
{ 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.' },
{ re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i,
{ 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.' },
{ re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i,
{ 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.' },
{ re: /(verified visit|visit pack|buy visits|visits campaign)/i,
{ 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.' },
{ re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i,
{ 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.' },
{ 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: 'Five packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500. 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.' },
{ re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i,
{ 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.' },
{ re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
{ 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.' },
{ 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,
{ 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).' },
{ re: /(safe|trust|rug|run away|company disappear)/i,
{ 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() {
// PASS TIERS (2026-10-22): the passes above the weekly Game Pass (Explorer, Champion, Sovereign, Legend; names from gamepass.js
// TIER_DEFS). While sovTiers is off the assistant only says they are coming soon; once on, it quotes the live prices and contents.
function passTiersFact() {
let t = null; try { t = PASS_TIERS ? PASS_TIERS() : null; } catch (e) { t = null; }
const soon = '- MORE GAME PASSES: monthly and yearly passes for Shards of Valor are COMING SOON and are not on sale yet. If someone asks about them (or about an Explorer, Champion, Sovereign or Legend pass, or a monthly or yearly pass), say they are coming soon and that the $5 weekly Game Pass is the pass on sale today. Never quote their prices, contents or a launch date.\n';
if (!t || !t.on) return soon;
const rows = (t.rows || []).filter(r => r.sale);
if (!rows.length) return soon;
return '- GAME PASS TIERS (on sale, Members > Games > Game Pass at https://instantadpay.com/my#games): beside the $5 weekly Game Pass, ' + rows.map(r => r.name + ' $' + r.usd + ' for ' + r.days + ' days (' + 'paid by the $' + r.usd + ' package, and the member keeps that package’s ad credits): ' + r.perks.join('; ')).join(' | ')
+ '. Each higher pass includes everything below it. Every pass is a Game Pass in every network game with the SAME daily POL caps (1.50 / 5 POL): a higher pass never pays more POL. Passes run side by side, each with its own end date; no auto-renew; buying again adds the pass length from its end date (or from now if it ended). Every pass is paid by a NEW package purchase of at least its price, made after tapping Get on that pass (since 2026-10-25 every pass price IS a one-click package amount: $5, $20, $50, $100, $250, so the right package is exactly the price); the pass starts when it settles, the sponsor and team are paid from the package as usual, and the member keeps the package credits for ads. Credits already held never buy a pass. Nothing earned in a game is taken away when a pass ends.\n';
}
// SYNDICATED RATE (Marty, 2026-10-27, approved 4:1) follows ads rates().synRateDivisor; the canned answer quotes 1/4, so
// the fast path rewrites it when the admin picks another N, and the AI fact always states the live N.
const SYN_N = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisor()) || 1)); } catch (e) { return 4; } };
const netRateAnswer = n => n === 1 ? 'Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery uses credits at the same rate as views and visits here.'
: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs 1/' + n + ' of the rate: ' + n + ' network views cost what 1 view here does, and ' + n + ' partner visits use up 1 visit of your pack. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/' + n + ' rate)" lines in Credit activity.';
function synFact() { const n = SYN_N(); return '- NETWORK RATE (live, Marty 2026-10-27): delivery ON instantadpay.com is charged at the normal rate. Network Ad Space impressions of banner/text ads cost 1/' + n + ' of the on-site rate (' + n + ' network views = the price of 1 view here; credit log line "Network views (1/' + n + ' rate)"), and PassiveDrip partner visits use up 1 visit of a pack per ' + n + ' partner visits. The budget is the limit, burns follow what was charged, nothing charged before 2026-10-27 changed. AdRevLinks popups and DripOffers clicks are not charged. Game refuels and Spooky Doors are charged as normal visits.' + String.fromCharCode(10); }
// the refuel fact follows the refuelStreak switch: while it is off the assistant says it is not live yet (2026-10-24)
let REFUEL_ON = () => false;
// POL Miner (2026-10-28) follows site config gamesLive: until 'polminer' is in it the assistant only says it is coming soon
let GAME_LIVE = () => false;
const POLMINER_SOON_ANSWER = 'POL Miner, a dig-down mining game where rare Polygon crystals pay POL, is coming soon to the InstantAdPay games. It is not open yet; it will show up on your Games tab (Members > Games) and in the release notes when it launches.';
const pmLive = () => { try { return !!GAME_LIVE('polminer'); } catch (e) { return false; } };
// Turkey Drop (2026-10-28, the Thanksgiving season game) follows gamesLive the same way, and its season (Nov 2 to 30, Central) ends it
const TD_END = '2026-12-01'; // Central day, exclusive (server.js TD_SEASON)
const tdDay = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const tdOver = () => tdDay() >= TD_END;
const tdLive = () => { try { return !!GAME_LIVE('turkeydrop') && !tdOver(); } catch (e) { return false; } };
const TURKEYDROP_SOON_ANSWER = 'Turkey Drop is coming soon to the InstantAdPay games. It is not open yet; it will show up on your Games tab (Members > Games) and in the release notes when it opens.';
const TURKEYDROP_OVER_ANSWER = 'Turkey Drop was the network’s Thanksgiving game, open Nov 2 through Nov 30, and its season is over. The other games are on your Games tab (Members > Games).';
const tdAnswer = () => tdOver() ? TURKEYDROP_OVER_ANSWER : TURKEYDROP_SOON_ANSWER;
const TD_PASS_PERK = ' Turkey Drop one free “back on the air” extra life every day;';
const gpWithTd = a => tdLive() ? String(a).replace('plus one free supply crate every day;', 'plus one free supply crate every day;' + TD_PASS_PERK) : a; // the Game Pass answer names the perk only while Turkey Drop is live
function turkeydropFact() { return tdLive() ? '- TURKEY DROP (Thanksgiving season game, https://turkeydropgame.com, Members > Games; open Nov 2 through Nov 30 Central, its Games card shows a "Limited time, ends Nov 30" ribbon and is gone after): a free 70s-cartoon arcade game. The WFWL 98.7 radio helicopter drops turkeys over the mall; the player swings a net to catch them before they splat; too many splats and the station pulls them off the air. One-tap sign-in with the InstantAdPay account. PAYS POL: the first time a player reaches each score milestone, plus a weekly top-3 leaderboard POL prize. POL collects in the Turkey Drop balance and is paid automatically to the wallet linked on InstantAdPay. BACK ON THE AIR: after being pulled off the air, a short verified sponsor visit (charged to the advertiser like any game refuel visit) gives one extra life; gameplay only, never POL. Game Pass perk: one free back-on-the-air extra life every day. Never state amounts, caps, totals or a season budget.\n' : tdOver() ? '- TURKEY DROP: the Thanksgiving season game (Nov 2 to 30) has ENDED; say the season is over and point to the other games.\n' : '- TURKEY DROP: COMING SOON, not open yet. Never send members to turkeydropgame.com; say it is coming soon to the Games tab, and do not bring it up unless asked.\n'; }
function polminerFact() { return pmLive() ? '- POL MINER (https://polminer.com, Members > Games): a free dig-down mining game. Dig, sell ore for coins, upgrade pick/lamp/cart/thruster, beat a drill boss every 30 m. Pink Polygon crystals pay a random POL amount the first time each one is dug out; each boss pays POL on its first win per account; first trips to 50/100/150/200 m pay POL. Coins never turn into POL. Guests can play and collect at sign-in. POL is paid automatically to the wallet linked on InstantAdPay. The SUPPLY pad opens a sponsored supply crate (full lamp + coins, never POL) after a short sponsor visit.\n' : '- POL MINER: COMING SOON, not open yet. Never send members to polminer.com; say it is coming soon to the Games tab.\n'; }
function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus a 100-credit Featured bonus on InstantAdPay at m4+ (purchased-grade credits, any format). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: another $20+/$25+ package on a site already refueled this cycle, before the next window opens (the other site's first package in the cycle is the second engine instead) = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. ENGINE ROOM: unlocked by the first counted refuel (greyed 'Refuel to start your engine' before), IAP tab Engine Room + LinkSpin Ads screen panel, same data both sites: dials Fuel left (credits free + in campaigns on both sites vs this cycle's refuel credits incl. bonus, days left at the recent burn), Clicks this week (vs last week, clicks per 1,000 credits), Goals this month (conversion pixel conversions since the 1st Central vs the member's own goal); streak panel; warning lights (ads at 80%, ads out, refuel day coming, login slot open); six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green working, amber needs attention, grey not started with a Set it up link); one Next move button from simple rules. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Either site alone keeps the streak (one-engine rates); both sites in one cycle = the bigger bonus; never say both are required. MEMBER GUIDE PAGE (public, 2026-10-24): /refuel on both sites (https://instantadpay.com/refuel and https://linkspin.app/refuel): the flow, the numbers, the member steps, leader coaching and FAQ; point members there for the full picture. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package. ROUTES (2026-10-25): LinkSpin menu item Refuel = https://linkspin.app/credits#refuel (the Refuel panel, scrolled to and highlighted); packages of $25+ there are marked counts for Refuel; https://linkspin.app/credits#buy = the package picker; https://linkspin.app/ads#engine = LinkSpin Engine Room. InstantAdPay Engine Room = https://instantadpay.com/my#engine; its Set up conversion tracking opens https://instantadpay.com/my#conversions (Campaigns > Conversion tracking card, same goals LinkSpin counts). Engine Room links that cross to LinkSpin (Banner Spin, spin link, page, testing, refuel LinkSpin) open LinkSpin with a note at the top naming the job, Step 1, a guide link and Back to InstantAdPay; same email signs in on both.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; }
const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.';
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=<username> link.
- LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company-paid, off-chain decision, on-chain payment. 3% of every package purchase (the POL actually paid) goes to the buyer's 4th upline on the contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = direct referral with a $20+ purchase, same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; the company account (#1) or no qualified upline = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId), shown in Earnings as 'Level 4 override' with a Polygon link and announced by email and an on-site notice. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split 50/20/10 is unchanged. Never promise amounts.
${passTiersFact()}${refuelFact()}${synFact()}${polminerFact()}${turkeydropFact()}- 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=<username> 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=<username>; ?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/<username>. 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.
- CONVERSION TRACKING (LIVE 2026-10-23): Campaigns > Conversion tracking in /my#campaigns. Every click on a member's ad (through /api/ads/click) gets a click id added to the target address as lsclk=<id>; the advertiser adds a goal (name like subscriber or sale, optional default value), puts the LinkSpin landing tag (t.js) on the page the ad points to and the goal pixel (cv.gif image, or the cv.js script) on the thank-you page. LinkSpin (sister site, same email) counts the goals; matching order: click id in the address (url, surest), the id the landing tag stored (stored), LinkSpin's cookie (cookie), a 24-hour match on hashed IP plus browser (soft, least sure). Each goal counts once per click, only within 30 days of a real click, only for the pixel owner's own ads; the advertiser's own clicks (signed in, or from a browser they sign in from; their linked positions share their email so count as them too) and the Send a test conversion button count as tests, never in the numbers; the card shows 'N from your own clicks, kept as tests'. SEND A TEST CONVERSION (2026-10-26) loads the member's real LinkSpin pixel in test mode from their browser (falls back to the signed partner call if the browser blocks it), so Last test updates. Each campaign row shows goals and COST PER GOAL (30 DAYS) in credits (2026-10-26: the credits the campaign spent in the last 30 days, from the credit activity log, divided by its goals in the same 30 days; a campaign started inside the window uses its spend since start; never quote it in dollars). Autoresponder tip: set the Aweber or GetResponse thank-you (success) page to a page on the member's own site carrying the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL); if they cannot, the cookie or the 24-hour match can still count it, less surely. Privacy: the click id is random and nothing personal is sent. SETUP GUIDE (public, 2026-10-24): https://instantadpay.com/conversion-tracking (LinkSpin's copy: https://linkspin.app/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, Last test updates, then remove it), what to do without code on the thank-you page, how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest). Send members there for any setup question.
- 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. Since 2026-10-23 the same $5+ Friday package also gives a FREE 7-day Game Pass automatically (once per member per Friday; not a second week when that package itself fulfils a pass order; the Game Pass badge posts the first time). 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.
@@ -139,11 +280,12 @@ FACTS:
- 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/<username> — 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, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery.
- 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 <date>', 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/<username>) 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.
- TANK ACTIVATION HOLD (2026-10-27, Marty: never default a tank member to the company): a tank member (no sponsor, not activated) can NOT switch on payouts on its own yet (a PURCHASE is NEVER held, Marty 2026-10-27: with no sponsor anywhere a buy goes ahead under the catch position #1); the Wallet tab and Getting started card say "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)." with the time left, and the activate button is hidden. The 24-hour clock starts when they link a wallet; they then show at the top of every holding tank with a green "Ready to activate" badge and hours left, and a post goes to the team's Telegram payments topic. If nobody adopts them in 24 hours, the site auto-assigns them to the next eligible adopter in rotation (own $20+ package, fewer than 2 open adoptions, signed in within 7 days, not suspended; least recently auto-assigned first); the adopter gets a chat + email and Telegram shows the pickup marked (auto-assigned). If nobody is eligible they stay on hold and the admin is alerted; never the company. Someone whose same email or wallet already has a sponsor on LinkSpin is placed under that sponsor instead (not one they were released or rescued from). A member who arrived through a sponsor link is never held. Once they have a sponsor the hold lifts by itself. ONE-TAP SWITCH ON PAYOUTS (2026-10-27): every tank assignment (manual adoption or the 24-hour auto-assign) sends the member a chat and an email with a Switch on payouts link, https://instantadpay.com/my?activate=1#wallet; it opens the Wallet tab and starts the normal Activate payouts flow with the new sponsor prefilled (after sign-in, and after linking a wallet if none is linked yet). It never starts while the hold applies or when no sponsor resolves. The site cannot activate for anyone: activation is one free transaction from the member's own wallet. Not activated 24 hours after the assignment: one reminder email to the member with the same link and one notice to the sponsor ("@x hasn't switched on payouts yet; a nudge from you helps"); at 72 hours one last email to the member only; both stop once the member switches on payouts or buys.
- 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.
@@ -155,16 +297,18 @@ FACTS:
- 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 <date>', 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 the network games (linked positions share it). PAYMENT (changed 2026-10-22): every pass is paid by a NEW on-chain package purchase of at least the pass price ($5 for the weekly pass), bought from one of the member's own positions AFTER tapping Get the Pass. The pass starts the moment that purchase settles. The sponsor and team are paid from that package exactly like any package, and the member keeps every credit of the package for ads. Credits (earned or purchased, old balances included) NEVER buy a pass, and a package bought before tapping Get the Pass does not count; if someone asks why, say the pass is paid by a fresh package so the team that brought them in is paid too. Passes bought before this change keep running. Buying again 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 started 2026-10-26 (moved up from the announced 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): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. 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. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18 and 2026-10-23): 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 6 member slots run at once (raised from 3 on 2026-10-23) because every slot shares the same sign-ins; when all 6 are taken the member can RESERVE THE NEXT SLOT (since 2026-10-23): they pay the full slot price right then (same purchased-credits-only rule, balance drops at once, credit log 'Login slot reserved (queue #N)'), the ad waits in a paid line, first paid first served, and its 30 days do not start until its turn. Members > Campaigns shows their place in line and an ESTIMATED start date in Central time, worked out from the live slots' end dates and the reservations ahead; it is only an estimate because a slot ends early if its owner archives it. The oldest reservation starts automatically the moment a slot frees (a slot expires, or its owner pauses it to end or archive it; also checked every minute), and the owner gets an on-site notice and an email. Before it starts the owner can edit the link, image or headline for free, or cancel for a FULL refund (credited back as purchased credits, credit log 'Login slot reservation cancelled: refund'); after it starts normal slot rules apply. A freed slot goes to the line first: a paused slot can only be resumed while live slots plus reservations leave a place open, otherwise the owner is told the line is ahead of them. The admin can see the line and cancel-and-refund a reservation. 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.
@@ -195,36 +339,43 @@ FACTS:
- 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/<username>; 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=<username> to keep the referral).
- GAME POL TO ANY LINKED WALLET (2026-10-27, Marty): game POL (Drip Runner, Gem Kingdom, ClutterHunt, Spooky Doors, Road Agent, PolyBreak, SpellWheel, PolyWarriors) is paid to the wallet LINKED to the member's InstantAdPay account (one free signature on the Wallet tab, https://instantadpay.com/my#wallet). Activation is NOT needed: a linked wallet that has not switched on payouts (for example a holding-tank member waiting for a sponsor) is paid too. InstantAdPay hands the linked wallet to every game where the member has a balance (hourly, and on every sign-in to a game), and the game sends the POL on its own sweep once the balance reaches that game's payout line, including everything earned before the link. A game that already holds a different wallet keeps paying that one (it is never replaced automatically). Players with no linked wallet get at most three reminders ("X POL is waiting for your wallet": link your wallet, one free signature, and it's sent automatically, including everything you've earned so far), and in the games the reward screen says "Link your wallet to receive this POL" with the same link. Never tell a member to switch on payouts to get game POL.
- 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 (once every page has been visited: a member video, a page seen more than 7 days ago again, or one of the network's own programs, so a game visit is never empty; since 2026-10-28 for every game's refuel, paddle, continue, hint and supply crate), 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/<username>; 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=<username> 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/<code>); 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/<hash> (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. Public: /join/<username> (invite page, ?v=angle), /wall/<username>, /b/<username>/<badge>, /handout/<username>, /ledger, /tx/<hash>, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix.
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/<username> (invite page, ?v=angle), /wall/<username>, /b/<username>/<badge>, /handout/<username>, /ledger, /tx/<hash>, /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.`;
- 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 : '');
}
function askAI(message, historyText) {
// 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() },
{ role: 'system', content: systemPrompt(kbBlock) },
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []),
{ role: 'user', content: String(message).slice(0, 600) }
]
});
const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST',
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 => {
@@ -250,22 +401,43 @@ function askAI(message, historyText) {
});
}
async function answer(message, historyText) {
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.' };
for (const c of CANNED) if (c.re.test(msg)) return { reply: c.a, canned: true };
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.' };
// 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 && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
if (hit && (hit.id === 'polminer' || hit.id === 'c-polminer') && !pmLive()) return { reply: POLMINER_SOON_ANSWER, canned: true, kb: hit.id };
if (hit && (hit.id === 'turkeydrop' || hit.id === 'c-turkeydrop') && !tdLive()) return { reply: tdAnswer(), canned: true, kb: hit.id };
if (hit && (hit.id === 'game-pass' || hit.id === 'c-game-pass')) return Object.assign({ reply: gpWithTd(hit.answer), canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && SYN_N() !== 4) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
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 c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'turkeydrop' && !tdLive() ? { reply: tdAnswer(), canned: true } : c.id === 'game-pass' ? { reply: gpWithTd(c.a), canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : 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);
const hitsOk = hits.filter(h => (pmLive() || !/^(c-)?polminer$/.test(String(h.entry && h.entry.id))) && (tdLive() || !/^(c-)?turkeydrop$/.test(String(h.entry && h.entry.id)))); // not live yet (or season over): keep its answer out of the prompt
kbBlock = kb.promptBlock(hitsOk); kbIds = hitsOk.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++) {
try { return { reply: await askAI(msg, historyText) }; }
// 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, the plain-language contract review at https://instantadpay.com/contract and the live ledger at https://instantadpay.com/ledger cover most of the deep questions, and your sponsor can be reached from Members > My line.' };
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 };
module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt };
+3 -1
View File
@@ -180,6 +180,8 @@ function clickSource(referer) {
} catch (e) { return 'unknown'; }
}
async function recordClick(campaignId, referer) { try { await impl().addClick(Number(campaignId), clickSource(referer), Date.now()); } catch (e) {} }
// clicks on these campaigns since a moment (the Engine Room's clicks-this-week dial, 2026-10-24)
async function clicksSince(campaignIds, since) { if (!campaignIds.length) return 0; const rows = await impl().clicksFor(campaignIds.map(Number)); return rows.filter(r => Number(r.ts) >= since).length; }
async function clickSources(campaignIds) {
const rows = await impl().clicksFor(campaignIds.map(Number));
const out = {};
@@ -358,4 +360,4 @@ function init(opts) { X = arguments[0] || {};
J.load();
}
async function viewsSince(since) { return impl().viewsSince(since); }
module.exports = { init, weeklyDigest, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, refHost, viewsSince };
module.exports = { init, weeklyDigest, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, clicksSince, refHost, viewsSince };
+74 -1
View File
@@ -121,6 +121,7 @@ async function bootstrap() {
await alterSafe('ALTER TABLE campaigns ADD COLUMN height INT NULL'); // banner size (IAB) → also NAS height
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_ad_id INT NULL'); // syndicated NAS sponsorads.ID
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_served INT NOT NULL DEFAULT 0'); // NAS impressions already reconciled into spend
await alterSafe('ALTER TABLE campaigns ADD COLUMN syn_imps INT NOT NULL DEFAULT 0'); // syndicated delivery counted off-site (IAP: PassiveDrip visits; LinkSpin: partner-zone views), charged at 1/synRateDivisor
await alterSafe('ALTER TABLE campaigns ADD COLUMN drip_id INT NULL'); // syndicated DripOffers campaigns.id (2026-09-18)
await alterSafe('ALTER TABLE campaigns ADD COLUMN expires BIGINT NULL'); // featured rotation end time
await alterSafe('ALTER TABLE campaigns ADD COLUMN starts BIGINT NULL'); // featured run start (booked day); any type: scheduled start
@@ -138,6 +139,17 @@ async function bootstrap() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site serves per viewer country
await alterSafe('ALTER TABLE campaigns ADD COLUMN day_spent INT NOT NULL DEFAULT 0');
await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL");
// prepaid login-ad line (2026-10-23): status 'queued' = paid and waiting for a slot (never serves), 'cancelled' = refunded
// before it started; queued_at orders the line (first paid, first served). status is VARCHAR(12), so no change there.
await alterSafe('ALTER TABLE campaigns ADD COLUMN queued_at BIGINT NULL');
// short lease locks shared by every app copy (two run for ~30 s on each deploy): one conditional UPDATE takes a lock
// (holder IS NULL OR lease_until < now), the holder clears it, and an expired lease can be taken over after a crash
await q(`CREATE TABLE IF NOT EXISTS app_locks (
name VARCHAR(40) PRIMARY KEY,
holder VARCHAR(60) NULL,
lease_until BIGINT NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q("INSERT IGNORE INTO app_locks (name, holder, lease_until) VALUES ('login_queue', NULL, 0)");
// linked positions: extra wallets owned by one email account (Qualified Start).
// Each is its own on-chain member sponsored by the account's main member.
await q(`CREATE TABLE IF NOT EXISTS positions (
@@ -332,6 +344,47 @@ async function bootstrap() {
await alterSafe('ALTER TABLE accounts ADD COLUMN joined_via VARCHAR(20) NULL'); // ?v= angle the lead came in on
await alterSafe('ALTER TABLE accounts ADD COLUMN joined_ref VARCHAR(80) NULL'); // referring domain of the first join-page visit
await alterSafe('ALTER TABLE accounts ADD COLUMN wall_offers VARCHAR(2000) NULL'); // JSON [{title,bannerUrl,targetUrl}] for wall positions 2-3 (unlock at 2 / 5 qualifying buyers)
// help desk (2026-10-16, tickets.js): one shared desk for IAP and, later, LinkSpin; email_message_id threads inbound mail
await q(`CREATE TABLE IF NOT EXISTS tickets (
id INT AUTO_INCREMENT PRIMARY KEY,
ref VARCHAR(20) NOT NULL UNIQUE,
platform VARCHAR(12) NOT NULL DEFAULT 'iap',
source VARCHAR(12) NOT NULL DEFAULT 'form',
email VARCHAR(190) NOT NULL,
name VARCHAR(80) NULL,
username VARCHAR(30) NULL,
subject VARCHAR(160) NOT NULL,
category VARCHAR(40) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'open',
priority VARCHAR(8) NOT NULL DEFAULT 'normal',
created BIGINT NOT NULL,
updated BIGINT NOT NULL,
last_member_at BIGINT NULL,
last_admin_at BIGINT NULL,
admin_unread TINYINT NOT NULL DEFAULT 0,
member_unread TINYINT NOT NULL DEFAULT 0,
INDEX (email), INDEX (status, updated), INDEX (platform, updated)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS ticket_messages (
id INT AUTO_INCREMENT PRIMARY KEY,
ticket_id INT NOT NULL,
author VARCHAR(8) NOT NULL,
body TEXT NOT NULL,
internal TINYINT NOT NULL DEFAULT 0,
attachments VARCHAR(400) NULL,
created BIGINT NOT NULL,
email_message_id VARCHAR(250) NULL,
via VARCHAR(12) NOT NULL DEFAULT 'web',
INDEX (ticket_id), INDEX (email_message_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
// help desk translations (2026-10-16): the English of a member message written in another language
await q(`CREATE TABLE IF NOT EXISTS ticket_translations (
message_id INT PRIMARY KEY,
ticket_id INT NOT NULL,
lang VARCHAR(8) NOT NULL,
body_en TEXT NOT NULL,
INDEX (ticket_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
}
// one-time import: only when the tables are empty and JSON files exist
@@ -373,4 +426,24 @@ async function importJsonOnce() {
} catch (e) {}
}
module.exports = { init, enabled, q: (...a) => q(...a) };
// A named lock that holds across every app copy (MySQL GET_LOCK on one dedicated connection), for read-modify-write of a
// record two copies might touch at once (the refuel streak, 2026-10-24). Without a database: a per-process queue.
const localLocks = new Map();
async function withLock(name, fn, secs) {
const key = String(name).slice(0, 60);
if (!enabled() || !pool) {
const prev = localLocks.get(key) || Promise.resolve();
let release; const mine = new Promise(r => { release = r; });
const tail = prev.then(() => mine); localLocks.set(key, tail);
await prev;
try { return await fn(); } finally { release(); if (localLocks.get(key) === tail) localLocks.delete(key); }
}
const conn = await pool.getConnection();
try {
const [[row]] = await conn.query('SELECT GET_LOCK(?, ?) AS ok', [key, Number(secs) || 10]);
if (!row || Number(row.ok) !== 1) throw new Error('lock busy: ' + key);
try { return await fn(); } finally { try { await conn.query('SELECT RELEASE_LOCK(?)', [key]); } catch (e) {} }
} finally { conn.release(); }
}
module.exports = { init, enabled, q: (...a) => q(...a), withLock };
+72
View File
@@ -0,0 +1,72 @@
# Release note draft: the Game Pass (not sent)
Status: DRAFT for Marty's review. Nothing below has been posted, emailed or published. Dates are placeholders until the caps start
date is set in Admin > Settings (`capsStartDate`) and `gamePassEnabled` is switched on.
## Short version (Telegram / feed)
The games now have a Game Pass: $5 for 7 days, all nine games on one account. Free play keeps paying real POL every day. The Pass
plays more: higher daily caps across every game, a seat in the weekly Pass Tournament with POL prizes, extra plays or a perk in each
game, and the Pass badge. Members > Games > Game Pass. From [DATE] the daily POL caps are account-wide: free play 0.30 POL a day on
repeatable rewards and 2 POL a day in all; with the Pass 1.50 and 5. One-time rewards you earn over the cap are never lost; they pay
over the next days.
## Release note (Admin > Releases, member-facing)
**The Game Pass: more game across all nine games**
Every member earns real POL in our games, and that does not change. What is new:
- **The Game Pass.** $5 for 7 days, one pass for your whole account (linked positions share it), covering PolHunter, Gem Kingdom,
SpellWheel, PolyWarriors, Road Agent, ClutterHunt, PolyBreak, Drip Runner and Spooky Doors while its season runs.
- **What it does.** Higher daily POL caps in every game (1.50 POL a day on repeatable play instead of 0.30, and 5 POL a day in all
instead of 2), a place in the weekly **Pass Tournament**, extra plays or a perk in each game (more PolHunter missions, a free
continue in Gem Kingdom, a free hint in SpellWheel and ClutterHunt, an extra patrol in Road Agent, a starting shield in Drip
Runner, an extra paddle in PolyBreak, an extra mission in PolyWarriors, an extra door in Spooky Doors), and the Pass badge.
- **How to get it.** Members > Games > Game Pass. Tap Get the Pass, then buy a new package of $5 or more. The pass starts the
moment that purchase settles. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your
ads. Credits you already hold never buy a pass. Buying again while a pass is active adds 7 days.
- **Account-wide daily caps, from [DATE].** Until now each game had its own daily limit. From [DATE] the limit is one number for
your whole account across all the games, reset at midnight Central: free play 0.30 POL a day on repeatable rewards (finds, daily
puzzles, patrols, gems, drips) and 2 POL a day for everything; with the Pass 1.50 and 5. A one-time reward (a boss, a chapter, a
sector, a room) never changes and is never lost: whatever is over the day's total carries to the next day until it is paid in
full. A 10 POL boss still pays 10 POL, over a few days.
- **The weekly Pass Tournament.** Monday to Sunday, Central time, pass holders are ranked by their plays across all the games. The
prize pool is 5% of that week's pass sales, paid in POL to the top three (50 / 30 / 20) and posted in Game Achievements on
Monday morning.
The Pass does not change what any reward pays. Free play pays; the Pass plays more.
## Announcement timing
- One week before `capsStartDate`: post the short version, publish this note, switch `gamePassEnabled` on so members can buy
ahead of the caps.
- On `capsStartDate`: the caps enforce themselves at midnight Central; nothing to deploy.
- First Monday 9 AM Central after launch: the first tournament settles and posts by itself (only while `gamePassEnabled` is on).
## Wording rules (chatbot, posts, pages)
Never "earn more", "pays for itself", "income". Always "free play pays; the Pass plays more". Reward amounts never change with the
Pass. Caps are per account, per Central day. Deferred progress rewards are "paid over the next days", never "lost".
## Update draft, 2026-10-22: how the Game Pass is paid (not sent)
Status: DRAFT for Marty's review. Nothing has been posted, emailed or published.
**Short version (Telegram / feed)**
A change to how the Game Pass is paid: from today every pass is paid by a new package purchase. Tap Get the Pass in Members >
Games, buy a package of $5 or more, and the pass starts the moment it settles. Your sponsor and team are paid from that package,
and you keep all of its credits for your ads. Credits you already hold no longer buy a pass. Passes you already have keep running.
**Release note (Admin > Releases)**
**The Game Pass is now paid with a new package**
- Tap Get the Pass (or Get on any pass) in Members > Games. Then buy a package of at least the pass price: $5 for the weekly Game
Pass.
- The pass starts the moment that purchase settles on chain. A package bought before you tapped Get does not count.
- Your sponsor and team are paid from that package exactly like any other package, and every credit of the package stays yours for
your ads.
- Credits you already hold, earned or purchased, no longer buy a pass.
- Any pass you already have keeps running to its end date.
+370
View File
@@ -0,0 +1,370 @@
# Game Pass: draft spec (2026-10-16)
> **PAYMENT RULE CHANGED 2026-10-22 (Marty): every pass is paid by a FRESH on-chain package purchase; no pass is ever bought with
> credits again.** See "Payment: the package rail" at the end. Older sections below that mention credits describe the rule as it was.
Marty's direction (10-16): a $5 weekly Game Pass that covers all nine games and raises the daily POL cap; a tighter
free cap so nobody farms the games all day for free. Pass = "more game", never pitched as payback. Free play keeps
paying real POL (the "paid before they ever pay" funnel in the presentation, deck and guide).
## 1. What the games pay today (live settings, 7-day earnings to 2026-10-16)
Two kinds of POL rewards exist in every game:
- **Progress rewards**: one-time per account (first clear of a stage, boss, sector, rival, chapter, room). Finite.
- **Daily play rewards**: repeatable every day (finds, daily puzzle, patrol, gems, drips). This is the "all day" risk.
| Game | Progress rewards (one-time, POL) | Daily play rewards (repeatable) | Game cap/day | Players (7d) | Median / p90 / max per player-day | POL out / week |
|---|---|---|---|---|---|---|
| PolHunter | none | finds 0.05-1.00 (skewed small), 3 missions/day | 40 | 38 | 0.48 / 0.97 / 4.04 | **102.1** |
| Gem Kingdom | stages 0.02-0.15; bosses 0.25 / 0.5 / 2 / 5 / 7.5 / **10** | none | 40 | 25 | 0.46 / 11.35 / **25.49** | **101.4** |
| SpellWheel | levels 0.02-0.05; chapters 0.25-1 | daily puzzle 0.03, streak 0.15 | 20 | 102 | 0.04 / 0.16 / 1.50 | 17.6 |
| Spooky Doors (to Oct 31) | ladder 0.1 / 0.25 / 0.5 / 1 / 2 | none | 25 | 11 | 0.85 / 1.00 / 2.00 | 10.7 |
| PolyWarriors | rivals 0.02-0.10, ladder 0.5, elite 0.12-0.5, elite clear 2 | none (PvP pays Circuits) | 20 | 10 | 0.18 / 1.09 / 4.94 | 8.8 |
| ClutterHunt | per room: clear 0.05, 3-star 0.05, expert 0.15, expert stars 0.10 | none | 20 | 13 | 0.20 / 0.95 / 1.05 | 6.4 |
| PolyBreak | rounds 0.02 / 0.03 / 0.05 | gems 0.01-0.15, up to 0.5/day | 5 | 39 | 0.02 / 0.06 / 0.12 | 1.3 |
| Drip Runner | chapters | drips 0.05, items | 5 | 15 | 0.05 / 0.15 / 0.25 | 1.2 |
| Road Agent | sectors 0.05-1.00 (3.60 total) | patrol 0.03/day | 25 | 5 | 0.08 / 0.16 / 0.16 | 0.5 |
| **All games** | | | | | | **~250 POL/week (~$23 at 9c)** |
PolHunter and Gem Kingdom are 81% of the burn. PolHunter is repeatable play (and every find is a delivered sponsor
visit, so that burn delivers advertiser inventory). Gem Kingdom's burn is its boss amounts: one player took 25.5 POL in
a single day. No other game pays more than 2 POL for any single reward.
## 2. The pass
- **$5, 7 days, all nine games.** One pass per account; buying while active extends by 7 days.
- (Superseded 2026-10-22, see "Payment: the package rail".) Paid with **purchased-grade credits only** (500 credits = the $5 package), through the existing game-purchase path
(`ads.gamePurchase` with `purchasedOnly`, the same rule as PolyWarriors mint passes). A $5 package bought while a pass
order waits fulfils it (the `pwpasses` pattern). Earned credits never buy a pass, or no money enters and the pass is
just a free cap increase.
- Money flow is the normal on-chain split of the $5 package: $2.50 sponsor, $1.00 level 2, $0.50 level 3, $1.00 company.
The company's $1 is what funds the extra POL; the games' 30% pool-share rule is an allowance, not cash.
## 3. Caps (account-wide, across all nine games)
| | Free | Pass |
|---|---|---|
| Daily play rewards (repeatable) | **0.30 POL/day** | **1.50 POL/day** |
| Everything (progress + daily), paced | **2.0 POL/day** | **5.0 POL/day** |
| Progress rewards | unchanged amounts for everyone; excess over the daily total **carries to the next day** (never lost) | same |
Why these numbers:
- Free 0.30/day sits under PolHunter's median (0.48) and SpellWheel's p90 (0.16 stays free). The regular PolHunter
hunter is the natural pass buyer; the casual SpellWheel player never notices.
- Pass 1.50/day is above today's p90 for every game, so a pass holder keeps everything they earn today and more.
Max repeatable per pass week = 10.5 POL (~$0.98), so the pass can never pay for itself and multi-accounting can't win.
- The paced total cap stops the Gem Kingdom spike (25 POL in a day) without changing any reward amount: a 10 POL boss
still pays 10 POL, over a few days.
- Company per pass: $1.00 in, at most $0.98 out if a holder maxes the repeatable cap every day. Realistic use (about
half) nets about $0.50 a pass. Progress rewards were payable to free players already, so the pass adds no cost there.
**DECIDED (Marty, 2026-10-16): Gem Kingdom's bosses stay at 5 / 7.5 / 10 POL.** "We need one that pays out bigger like
that anyway." The paced total cap spreads a big boss payout over a few days; the amounts do not change.
## 3a. API contract (both sides build to this)
> **Built 2026-10-16 (IAP side). Clarifications and additions to this contract, none of them breaking:**
>
> 1. **Where the endpoints live.** `GET /api/partner/player` exists today on each GAME (IAP reads the player's card line from it).
> The pass and caps version below is served by **IAP** (`https://instantadpay.com/api/partner/player`), so a game CALLS it; nothing
> changes on the game's own endpoint. Same for `polgrant`, `polgrant/void` and `tournament/*`: all on IAP.
> 2. **Signature, spelled out.** Each game signs with the shared secret it already holds (its `*_SSO_SECRET`; PolHunter uses
> `HUNT_SSO_SECRET`). 10-minute window on `ts` (ms).
> - `GET /api/partner/player?game=<slug>&m=<memberId>&e=<email>&ts=<ms>&sig=<hex>` with
> `sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts)`, `who` = memberId when > 0, else the lowercased email (the same string
> the games already compute for IAP's calls to them, with `game` added so IAP knows which secret to check).
> - `POST` endpoints: JSON body that includes `game: <slug>`, headers `X-Game-Ts: <ms>` and
> `X-Game-Sig: HMAC-SHA256(secret, ts + '\n' + rawBody)` hex (sign the exact bytes you send).
> - `GET /api/partner/tournament/pending?game=<slug>&ts&sig` with `who = 'tournament'`.
> 3. **`email` is accepted beside `memberId`.** Players who have not linked a wallet have `memberId: 0` in every hand-off token; send
> `email` too (the token has it) and IAP resolves the account by email. A linked position's member id resolves to the owner's
> account: the pass and the caps are per ACCOUNT.
> 4. **Extra fields in answers** (additive): `polgrant` also returns `carried` (POL paid from an earlier day's deferral, already
> inside `allowed`), `capHit` (`'daily'|'total'|null`), `enforced` (false before `capsStartDate`), `repeat` (true when the ref was
> already answered), `voided`. `caps` also has `enforced`, `pass` and `pending` (POL deferred for this game, not yet paid).
> `player` also returns `memberId, username, wallet, suspended, gamePassEnabled`. A suspended account gets `allowed: 0,
> suspended: true` and nothing is recorded (a cleared account can replay the ref).
> 5. **Carry-forward counts against the later day's total cap** (that is what "paced" means): a 10 POL boss on a 2 POL/day free
> account pays 1.7-2.0 a day until done, paid before that day's new grants. Carry-forward only happens on a LATER Central day
> than the deferral and only to the same game; the reply that carries it says `carried`.
> 6. **`void` reverses only that ref's own share** (its `allowed` on its day and whatever of its deferral is still queued). POL it
> already caused to be carried on a later day belongs to that later day and stays. The ref remains answered as voided.
> 7. **Hand-off tokens carry the flag** as `gamePass: { active, until }` (not `pass`, which the in-game sign-in flow already uses for
> its session token). Apply perks from it at sign-in; refresh from `player`/`polgrant` answers.
> 8. **Tournament prize payout seam.** IAP records the winners and POL amounts; a game faucet (Road Agent pattern) pays them:
> `GET /api/partner/tournament/pending` answers `{ ok, rows: [{ week, place, email, memberId, wallet, pol, ... }] }` (the same
> list is also under `pending`, the admin pane's name) for the rows still unpaid, and the paying game calls
> `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. PolHunter's faucet pays them
> (`polhunter/lib/tournament.js`, see "Games: as built"); Admin > Game Pass shows the unpaid rows meanwhile.
> 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the
> Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skipped the credit charge (retired 2026-10-22: there is no charge any more; the dev purchase event takes `minedAt`, `now` and `tx`).
IAP is the single source of truth for the pass and for the account-wide caps. Every game already signs partner calls
with its shared secret (the `/api/partner/player` pattern); the new calls use the same auth.
- `GET /api/partner/player?...` (existing) additionally returns `pass: { active: bool, until: ms|null }` and
`caps: { daily: n, total: n, used: { daily: n, total: n }, day: 'YYYY-MM-DD' }` (Central day).
- `POST /api/partner/polgrant` body `{ memberId, game, kind: 'daily'|'progress', pol, ref }` (ref = the game's own
idempotency key, e.g. `sector:3`, `find:<id>`). Response `{ allowed: n, deferred: n, pass: bool, day }`.
- `kind: 'daily'`: `allowed = min(pol, dailyCapRemaining, totalCapRemaining)`, the rest is DROPPED (never deferred).
- `kind: 'progress'`: `allowed = min(pol, totalCapRemaining)`, the rest is DEFERRED: IAP stores it and the game's
next call (any kind) on a later day gets it added to `allowed` first (carry-forward). Nothing is ever lost.
- Same `ref` twice = same answer (idempotent). Fail closed: if the game cannot reach IAP it grants nothing and retries
the same ref later.
- `POST /api/partner/polgrant/void` `{ memberId, game, ref }` when a game decides not to pay after all (rare).
- Settings on IAP (Admin > Settings, no deploy): `gamePassEnabled`, `gamePassPriceCredits` (500), `gamePassDays` (7),
`capFreeDaily` 0.30, `capFreeTotal` 2.0, `capPassDaily` 1.50, `capPassTotal` 5.0, `capsStartDate` (the free caps apply
only from this Central date; before it, the games' own caps stand, so the change can be announced a week ahead),
`passTournamentPct` 5.
- Pass purchase (superseded 2026-10-22: Buy only opens an order, a fresh package fulfils it): `POST /api/my/gamepass/buy` spends 500 purchased-grade credits (`ads.gamePurchase` with
`purchasedOnly`); a $5 package bought while a pass order waits fulfils it (the `pwpasses` pattern). Buying while active
extends `until` by 7 days. The Games tab shows the card, the state, and the expiry.
- Games get the pass flag at the sign-in hand-off and on every `polgrant` response; apply perks locally.
## 4. Pass perks per game (more game, not more payback)
| Game | Pass perk (besides the higher caps) |
|---|---|
| PolHunter | 5 missions/day instead of 3; Ad Detective twice a day. Finds still require the sponsor visit. |
| Gem Kingdom | one free continue per day (small, so Crowns sales are not undercut) |
| SpellWheel | streak bonus 0.15 -> 0.30; one free hint a day |
| PolyWarriors | +1 daily mission; defense pay 15 -> 25 Circuits; Pass mark on the warrior card |
| Road Agent | 2 patrols/day; +25% scrap. Fuel stays a sponsor visit. |
| ClutterHunt | 2 free hints a day |
| PolyBreak | gem cap 0.5 -> 1.5/day; one extra paddle per round |
| Drip Runner | a shield at the start of every run |
| Spooky Doors | +1 door a day while the season runs |
| All games | **Weekly Pass Tournament**: cross-game leaderboard (finds, clears, wins), prizes from 5% of pass sales (25c per pass) in POL; Pass badge; gold profile frame |
Ad-visit mechanics (fuel, Crowns, hints, refuels) stay as they are. Those verified visits are what advertisers pay for.
## 5. Build outline
1. **IAP (central):** durable `gamepass` map {email: {until, history}}; `GET /api/partner/player` returns `pass:{active, until}`;
new `POST /api/partner/polgrant` {member, game, kind: progress|daily, pol} -> {allowed, deferred} enforcing the
account-wide caps (fail closed when IAP is unreachable; games retry); Games tab card "Game Pass: $5 for 7 days, all
games"; buy flow via purchased credits or the $5 package; admin: passes sold, POL out per pass, cap hits.
2. **Each game:** read the pass flag at the sign-in hand-off; call `polgrant` before every POL grant (replaces each game's
own `dailyCapPol` for the account-wide rule; keep the local cap as a backstop); pace deferred progress rewards (queue,
pays out next day); apply its perk; show "Pass" state and a "Get the Pass" nudge when the free cap is hit.
3. **Tournament:** weekly job on IAP ranks pass holders across games, pays prizes from the games' wallets, posts to the
Game Achievements topic.
4. **Chatbot, release note, presentation games slide, and the guide's games section**: say "free play pays; the Pass
plays more" (never "earn more").
5. **QA:** iap-qa plus a scripted run per game: free cap hit -> nudge; pass bought -> cap raised; progress reward over
the cap -> paid the next day; pass expiry -> back to free caps.
## 6. Rollout
- Announce one week ahead (the free cap change affects today's PolHunter regulars). First week: pass at $5 with a
launch tournament; watch passes sold, POL out per pass, free-tier burn, verified visits delivered.
- Review after 14 days against: company net per pass >= $0.40, free burn under 150 POL/week, no drop in visit deliveries.
## Built (IAP side, 2026-10-16)
Everything below is on IAP, behind `gamePassEnabled` (default off). The caps are recorded from day one and ENFORCED only from
`capsStartDate`, so the change can be announced a week ahead and Admin can read what the caps would have done meanwhile.
**Files**
- `gamepass.js` (new): pass store, waiting orders, cap ledger (`DATA_DIR/gamepass-ledger.json`, refs kept 90 days), tournament,
admin stats, prune. Durable persisted maps `gamepass`, `gporders`, `gpprizes` (added to the DURABLE set in server.js so a deploy
never wipes them).
- `server.js`: settings defaults, init + hourly tournament tick + 6-hourly prune, purchase-event fulfilment (inside the
`marks.claim` block, so two app copies never double-fulfil), partner helpers (`GP_SECRETS`, `gpPartnerCheck`, `gpResolve`,
`gpDevNow`), `polUsdLive()` (catalog rate, 10-minute cache), `gpClaim` (the `gamePass` claim on every sign-in hand-off token,
including PolHunter's), and the endpoints below.
- `public/my.html` + `public/assets/my.js`: the Game Pass card at the top of Members > Games (state, caps line, Buy/Extend with
`IAP.confirmBox`, waiting state with a Buy-a-package button), deep link `/my#games?pass=1` (setPane now strips a `?query` from
the hash and highlights the card), the Overview nudge card `gpNudge` (shown once a day per browser after a game reports a free-cap
hit, never to pass holders). Asset tag bumped to `my.js?v=20261016a`.
- `public/admin.html` + `public/assets/admin.js`: Admin > Game Pass pane (passes sold week/total, active, POL out per pass week,
free/pass cap hits, deferred queue, tournament last run + unpaid prizes, "Settle last week now", comp a pass). Tag
`admin.js?v=20261016gp`.
- `chatbot.js`: canned answer + FACTS line, `KNOWLEDGE_DATE` 2026-10-16.
- `qa/gamepass.mjs` (new, `bash qa/run.sh gamepass`), `qa/walk.mjs` (Games tab card on/off + admin pane), `qa/run.sh`.
- `docs/GAME-PASS-RELEASE.md`: the member-facing release note draft (not sent).
**Settings** (Admin > Settings > Site settings; all read live, no deploy): `gamePassEnabled` ('0'), `gamePassPriceCredits` (500),
`gamePassDays` (7), `capFreeDaily` (0.30), `capFreeTotal` (2.0), `capPassDaily` (1.50), `capPassTotal` (5.0), `capsStartDate` ('',
Central YYYY-MM-DD), `passTournamentPct` (5), `telegramGamesTopicId` ('661565'), `telegramGamesChatId` ('' = the shared echo chat).
**Endpoints**
- Members: `GET /api/my/gamepass` -> `{ enabled, active, until, price, days, usd, waiting, bought, caps, capsStart, lastCapHit,
tournament }`; `POST /api/my/gamepass/buy` -> `{ ok, active, until }` or `{ needPay: true, payUrl: '/my?from=gamepass#buy',
order, price, need }`. Spends `gamePassPriceCredits` purchased-grade credits through `ads.gamePurchase(purchasedOnly)` with the
credit-log label "Game Pass (7 days)"; short = waiting order, fulfilled by the next $5+ package purchase event.
- Games (signed, see 3a): `GET /api/partner/player`, `POST /api/partner/polgrant`, `POST /api/partner/polgrant/void`,
`GET /api/partner/tournament/pending`, `POST /api/partner/tournament/paid`.
- Admin: `GET /api/admin/gamepass/stats`, `POST /api/admin/gamepass/comp { email, why }`,
`POST /api/admin/gamepass/tournament/run { week?, force? }`.
**Tournament job**: hourly tick; once Monday 9 AM Central has passed and the closed week (Mon 00:00 to Mon 00:00 Central) has no
row, exactly one app copy (`marks.claim('gamepass-tournament:<week>')`) ranks the week's pass holders by grants reported through
`polgrant` (progress and daily weigh the same, one point per ref with pol > 0), pool = `passTournamentPct` of the week's pass sales
in USD at the live catalog POL rate, split 50/30/20, rows recorded in `gpprizes` as pending, top 3 posted to the Game Achievements
topic (`telegramGamesTopicId`, only when enabled), winners get an inbox notice (kind `notice`). Comps (`/comp`) are passes, not
sales. If the POL rate is unavailable the tick retries next hour.
**Known limits / follow-ups**
- The cap ledger is a JSON file on the volume (like the other IAP side stores), not a MySQL table: during the ~30 s deploy overlap
two app copies each hold their own copy and the last save wins. A grant answered by the copy that is about to stop could be
re-answered fresh by the other on retry. Move `refs`/`days` into MySQL if the games report drift.
- `qa/gamepass.mjs` stubs the credit charge (`devPaid`) for the "buy -> active" step: `ads.gamePurchase(purchasedOnly)` needs a
position with on-chain package credits, which a local copy without RPC cannot have. The "short -> waiting order -> package fulfils
it" step runs the real path. The purchasedOnly charge itself is the live PolyWarriors mint path.
- Prize POL is not sent by IAP (see 3a item 8): PolHunter's faucet pays the pending rows every 10 minutes behind `GAMEPASS=on`;
the Games pane lists whatever is still unpaid.
- Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the
Game Pass keys show in the Site settings form).
## Pass tiers: Explorer, Champion, Sovereign, Legend (IAP side, 2026-10-18; restructured 2026-10-22)
Spec: `ultima-rpg/docs/IAP-PASSES-SPEC.md`. Marty approved the safe form on 2026-10-18 (never more POL) and Dallas's new structure
on 2026-10-22 (plus Sovereign and the yearly Legend). On 2026-10-25 Marty set every tier price to an InstantAdPay one-click
package amount ($5, $10, $20, $50, $100, $250, $500), so the cheapest qualifying package is exactly the pass price and the pass
comes with that package's ad credits (was $19.99 / $39.99 / $99.99 / $249.99). The weekly pass is unchanged. Everything above weekly stays
switched off for members (`sovTiers` 0) until Marty flips it.
| Tier | Name | Price | Length | In Shards of Valor (each includes everything below) |
|---|---|---|---|---|
| `weekly` | Game Pass | 500 credits ($5) | 7 days | the Game Pass in all nine games, the Sunless Vault, weapons unlocked |
| `explorer` | Explorer | 2000 ($20, the Activation package) | 30 days | weapons, gear, 2 DLC islands |
| `champion` | Champion | 5000 ($50, the Builder package) | 30 days | weapons, gear, 4 DLC islands of your choice, the Druid hero, level cap 30 |
| `sovereign` | Sovereign | 10000 ($100, the Growth package) | 30 days | weapons, gear, all DLC islands, the Necromancer hero, level cap 40 |
| `legend` | Legend | 25000 ($250, the Leader package) | 365 days | weapons, gear, all DLC islands, every hero including the Archer, level cap 40 |
- **One table**: `gamepass.js` `TIER_DEFS` holds the rank, wire key, display name, settings stem, default price/length and the
member-card list for every tier. Rename a tier there (the card, admin pane, charge label and chatbot all read it).
- **Rank**: weekly < explorer < champion < sovereign < legend. Every tier is a Game Pass holder everywhere with exactly the pass
caps; `polgrant` keeps answering `pass: true` (a boolean).
- **Store**: `record.tiers = { weekly: { until }, explorer: { until }, champion: { until }, sovereign: { until }, legend: { until } }`,
the legacy `until` mirrors the weekly tier, bought rows carry `tier` (missing = weekly), waiting orders carry `tier` (missing =
weekly). Lazy migration: a record without `tiers` reads its `until` as the weekly tier.
- **Wire**: `flag()` = `{ active, until, tier, tiers }` (`tier` = highest active, `until` = that tier's end; `tiers` has all five
keys). The hand-off token carries `gamePass: { active, until, tier }`; `GET /api/partner/player` carries
`pass: { active, until, tier, tiers }`, so Shards of Valor sees `sovereign` / `legend`.
- **Buy**: `POST /api/my/gamepass/buy { tier }` (missing = weekly). Every tier above weekly needs `sovTiers` on (and the weekly pass
on); while off, nobody sees or buys them on /my, the admin included (2026-10-25: the member card shows every account the
member view). The admin tests them in Admin > Game Pass > Tier test and preview (`GET /api/admin/gamepass/preview`, `POST
/api/admin/gamepass/test-buy | test-cancel | test-comp { tier }`, always the signed-in admin's own account). Short of purchased credits: a
waiting order per tier; a package of at least the tier price fulfils the highest-priced order it covers (one pass per purchase,
each tx once). Copy names the package that pays for the pass, which since 2026-10-25 is exactly the price: $20 (Explorer), $50
(Champion), $100 (Sovereign), $250 (Legend); the card says the pass comes with that package's ad credits.
- **Renew / expiry**: no auto-renew, no proration. Buying again extends that tier from `max(now, until)` by its length (Legend: 365
days). Tiers run side by side; when a higher one ends the next one shows through. Admin comp takes a tier;
`POST /api/admin/gamepass/revoke { email, tier, why }` ends one tier now (support refunds only, credits are not returned by it).
- **Tournament**: any tier holds a seat; only weekly sales feed the pool unless `passTournamentTierSales` is `1` (then every tier's
sales do).
- **Settings** (defaults): `sovTiers` 0; kill switches `gamePassExplorerEnabled` / `gamePassChampionEnabled` /
`gamePassSovereignEnabled` / `gamePassLegendEnabled` 1 (a `0` stops one tier); `gamePassExplorerPriceCredits` 2000,
`gamePassChampionPriceCredits` 5000, `gamePassSovereignPriceCredits` 10000, `gamePassLegendPriceCredits` 25000;
`gamePassExplorerDays` / `gamePassChampionDays` / `gamePassSovereignDays` 30, `gamePassLegendDays` 365;
`passTournamentTierSales` 0. A value saved in the site settings file wins over these defaults.
- **Chatbot**: while `sovTiers` is off the assistant only says more passes are coming soon (no prices, no contents, no date); once
on, its fact lists each tier on sale with the live price, length and contents.
- **Member UI**: the Games tab card shows the tiers side by side (end dates in Central time); `/my#passes` opens it (the
Shards of Valor Buy button). **Admin**: Game Pass pane "By pass tier" table, comp per tier, end-a-tier button.
- **Tests**: `bash qa/run.sh sov-passes` (store unit checks + a local copy where the admin buys Explorer and Sovereign through the
real `ads.gamePurchase(purchasedOnly)` path with credits seeded by `qa/sov-passes-stub.cjs`, and a Legend order is fulfilled by
a $250 package).
## Games: as built (2026-10-16, local commits only, nothing deployed)
Everything is behind `GAMEPASS=on` (env, default off = today's behaviour, so the games can be deployed before launch). `IAP_URL` is
read where it already existed (default `https://instantadpay.com`). No reward amount changed anywhere; every game's local
`dailyCapPol` / pool / hidden ceiling still stands in FRONT of the IAP call as a backstop and none was raised.
**The shared client `polgrant.js`** (byte-identical copy in every repo, md5 `f3c00b90…116a`; change one, copy to the rest):
`spooky-doors/server/`, `road-agent/server/`, `match3-game/server/`, `seek-game/`, `spellwheel/`, `polybreak/`, `cyber-battle/game/`,
`polhunter/lib/`, `drip-runner/lib/`.
- `grant({ memberId, email, kind, pol, ref })` -> `POST /api/partner/polgrant` `{ game, memberId, email, kind, pol, ref }`, headers
`X-Game-Ts` + `X-Game-Sig` (plus an informational `X-Game`), 6 s timeout. Returns `{ allowed, deferred, carried, pass, day, capHit,
enforced, repeat, suspended, retry: false }` or `{ allowed: 0, retry: true, error }` on ANY non-200 / non-JSON / network error
(fail closed; a 404 "no such member" is also a retry, so the games only call it for signed-in IAP members).
- `email` always rides along (wallet-less members have `memberId: 0`; Drip Runner maps its negative `emailId` to 0). `whoOf()` = the
member id when > 0, else the lowercased email; the pass cache and the retry queue key on it.
- `voidGrant`, `fetchPass` (`GET /api/partner/player`, cached 10 min, fail-soft), `passOf` / `rememberPass` (hand-off claim
`gamePass: { active, until }` + every answer), `view()` for the lobby, `note(resp, kind, nominal)` = the player-facing line.
- Retry queue `polgrantq` in each game's store: `enqueue` dedupes per (who, ref); `retry(pay)` every 5 min, 48 h then `stuck` +
`notify('gpstuck')` once (each game routes it to its faucet alert path); `queued()` keeps a waiting ref from being re-asked.
- Carry-forward collection (SD-pattern games): `carrySweep()` on the existing tick, once a Central day per account with `gpOwed > 0`,
a zero-POL `progress` call with ref `carry:<YYYY-MM-DD>`; IAP folds the carry into `allowed` (`carried`). `gpOwed` is bookkeeping
(`+= deferred`, `-= carried`); the money truth is IAP's. **IAP accepts `pol: 0`** (verified by the integration test below).
- `tournamentPending()` reads `rows` from `GET /api/partner/tournament/pending`; `tournamentPaid(row, tx)` posts
`{ game, id?, week, place, memberId, email, tx }` (PolHunter only).
**Per game**
| Game | Files | Refs (kind) | Pass perk | Tests |
|---|---|---|---|---|
| Spooky Doors (`spooky-doors`) | server/pol.js (quote/settleGrant/grantGated/payQueued/carrySweep), server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `rung:<n>` (progress) | +1 door/day while the season runs | sim 63/63, gamepass 37/37, e2e 200 pass / 3 pre-existing timing fails |
| Road Agent (`road-agent`) | server/pol.js, server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `sector:<n>` (progress); `patrol:<day>`, `patrol:<day>:2` (daily) | 2 patrols/day, +25% scrap | sim pass, gamepass 22/22, e2e pass |
| Gem Kingdom (`match3-game`) | server/pol.js, server/server.js (`/api/continue/free`), src/world.js, src/battle.js, src/game.js, test/gamepass.cjs | `stage:<n>` (progress, bosses included) | one free continue/day, no sponsor visit | kingdom.test pass, gamepass 26/26, vite build ok |
| ClutterHunt (`seek-game`) | pol.js, server.js, public/game.js, public/index.html (`game.js?v=20261016gp`), test/gamepass.js | `<season>:<room>:<clear or stars or xclear or xstars>` (progress) | 2 bonus hints banked once per Central day | gamepass 23/23 |
| SpellWheel (`spellwheel`) | pol.js (`streakPassPol: 0.30`), server.js, public/play.js, public/play.html (`play.js?v=7`), test/gamepass.js | `level:<ch>:<n>`, `chapter:<ch>` (progress); `daily:<day>`, `streak:<day>` (daily) | streak 0.15 -> 0.30, 1 free hint/day | gamepass 25/25 |
| PolyBreak (`polybreak`) | pol.js (`gemDailyPassPol: 1.5`), server.js, public/play.js, public/play.html (`play.js?v=6`), test/gamepass.js | `round:<n>` (progress); `gem:<run>:<id>` (daily) | gem ceiling 0.5 -> 1.5/day; +1 paddle per round | gamepass 27/27, run.js 70/70 |
| PolyWarriors (`cyber-battle/game`) | pol.js, server.js (DEF_PAY_PASS 25), missions.js (3 + pass), public/game.js, public/game.html (`game.js?v=30`), test/gamepass.js | `rival:<id>`, `ladder`, `elite` (progress) | +1 daily mission (4), held defense 15 -> 25 Circuits, Pass row on the profile (card.js untouched) | gamepass 26/26 |
| Drip Runner (`drip-runner`) | lib/ledger.js (chapterDripGated), lib/game.js, server.js, public/play.js, public/play.html (`play.js?v=20261016gp`), test/gamepass.js | `chapter:<n>` (progress; the only POL it pays) | a shield at every run start | gamepass 28/28, run.js pass |
| PolHunter (`polhunter`) | lib/rewards.js (status `capped` / `gp-wait`), lib/detective.js, lib/faucet.js (`HUNT_DRY_RUN`), lib/tournament.js (new), server.js, public/app.js, public/app.html (`app.js?v=22`), test/gamepass.js | `find:<missionId>:<day>`, `detective:<boxId>` (daily) | 5 missions/day (+2), 2 Ad Detective cases/day | gamepass 42/42, run.js pass |
Game commits (local, not pushed): spooky-doors f54ef0c, road-agent d345bbf, match3-game 972dd71, seek-game 9751329, spellwheel b582b72,
polybreak e9c3a54, cyber-battle/game fa76d30, drip-runner a7b1fd9, polhunter 7391fd7 + 08486e1. Spooky Doors, Road Agent and Gem
Kingdom are Vite builds (hashed assets, no `?v=` bump).
**Decisions taken on the games side (flip if wanted)**
1. Advertiser-funded PolHunter missions (`mission.paid`) are NOT gated: the advertiser paid for that completion. Gate them in
polhunter/server.js (`gp.on() && !m.paid`) if the cap should cover them too.
2. A 0-allowed daily reward is still "done": a capped find counts as today's find (status `capped`, never reaches the faucet); a capped
gem/patrol/daily puzzle is recorded as handled with `pol: 0`. The player sees the cap line with the Pass link.
3. Fail closed, visibly: IAP unreachable = the reward is recorded (SD pattern: nothing written until IAP answers, ref queued; PolHunter:
a `gp-wait` row settled by the queue), the player sees "Your reward is recorded and pays as soon as InstantAdPay confirms it."
4. Perks read the cached flag (hand-off claim -> every grant answer -> `fetchPass` every 10 min); a pass bought mid-session shows
within 10 minutes or on the next grant.
5. Deferred progress rewards: the ledger row is written with `pol: allowed` (0 included) so the achievement is marked done; carry comes
back through `carry:<day>` or any later grant.
6. Not built: a per-game admin view of the queue (PolHunter's admin state shows queue + stuck counts and the tournament payer).
**Pass Tournament payer (PolHunter `lib/tournament.js`)**: every 10 min behind `GAMEPASS=on`, only with the faucet wallet configured.
Per pending row: a durable claim in `tourney-claims` BEFORE sending (`id:<id>` or `wk:<week>:<place>`), the tx hash written the
moment the chain has it, then `POST /api/partner/tournament/paid`. A claimed row with a hash is only re-reported, never re-sent; a
claim without a hash is retried after 10 min; a send failure releases the claim, leaves the row pending on IAP and alerts
(`tourneyfail`); low balance alerts once a day. `HUNT_DRY_RUN=on` records `wouldPay` and sends nothing. **Trap:** a claim written
during a dry run is permanent (`c.dry` rows are skipped forever), so a prize row seen while `HUNT_DRY_RUN=on` is never paid after the
flag is turned off unless `tourney-claims.json` on the PolHunter volume is cleared. Prizes bypass the per-find daily cap and the
payout threshold. Admin: `/api/admin/state` -> `tournament` and `gamepass` blocks.
**Integration test (both sides, local)**: `bash qa/run.sh gamepass-games` (qa/gamepass-games.cjs) boots IAP like qa/gamepass.mjs and
drives the REAL `spooky-doors/server/polgrant.js` and `polhunter/lib/tournament.js` against it (needs the sibling game repos under
`../..`): fetchPass free/pass, daily within/over cap, progress deferral, the `carry:<day>` zero-POL call on the next Central day
(`carried` > 0, idempotent repeat), void, bad secret and IAP-down -> `{ allowed: 0, retry: true }`, the retry queue, and the
tournament payer in dry run and live (mocked faucet.send) until IAP's pending list is empty. 2026-10-16: 44/44 after the `rows`
fix on the pending endpoint (the games read `rows`; IAP answered only `pending`).
## Payment: the package rail (2026-10-22, Marty)
**Why.** A pass paid from a credit balance brings in no new money and pays nobody upline: credits come from packages whose POL was
already split on chain ($2.50 sponsor, $1 level 2, $0.50 level 3, $1 company on a $5 package). Today's pass buyer paid from an old
balance. From now on every pass is a fresh package purchase, so the sponsor and team are paid exactly like any package.
**Rule.**
- `POST /api/my/gamepass/buy { tier }` never charges anything. It opens a waiting order for that tier (or returns the one already
open) and answers `{ needPay: true, order, orderTs, package, payUrl, message }`. The card sends the member to Buy credits.
- The order is fulfilled only by an on-chain `Purchase` event (`gamepass.onEvent`, inside the `marks.claim` block, so one app copy
acts) that meets ALL of:
- the buyer id is one of this account's own positions: the main member id (`accounts.byMemberId`) or a linked position
(`accounts.positionByMember`);
- `priceCents` is at least the tier price (setting `gamePass*PriceCredits`, now read as cents; the copy names the package that
covers it: $5, $20, $50, $100, $250);
- the purchase was mined AFTER the order was opened: block time from `eth_getBlockByNumber` (server.js `blockTime` dep), with a
30 s clock grace; if the block cannot be read after 3 tries the indexed-at time is used (never earlier than the block);
- the tx has never paid a pass or an order before (checked across every order and every bought row, every account).
- One pass per purchase: the highest-priced waiting order the package covers. The member keeps every credit of the package.
- Bought row: `{ via: 'package', tier, tx, cents, order, buyerId, usd: <pass price>, packageUsd }`. `buyerId` marks the new rail.
- Existing passes are untouched (never revoked). On 2026-10-22 production held two sales: one `via: 'credits'` (500 credits,
campaign 513) and one `via: 'package'` fulfilled under the old rule (tx 0xdbfb77c7...). No order was left waiting.
- Admin > Game Pass > **Pass sales**: every sale with how it was paid ("package", "credit-paid (old rule)", "package (old rule)"),
pass value, package value and the package tx; the header splits the counts. Stats field `passes.pay` and `sales`.
- Tests: `qa/gamepass.mjs` (order, package mined before the order refused, too small refused, another member refused, fresh package
fulfils, replayed tx refused, extend while active); `qa/sov-passes-store.cjs` and `qa/sov-passes-local.mjs` updated the same way.
- Not changed: the caps, the tiers, the tournament (pool = pass price of each sale), the hand-off claims.
+1 -1
View File
@@ -22,7 +22,7 @@
{
"hours": 192,
"subject": "The one thing nobody tells you about ad platforms..",
"body": "This might be the most important email I send you about InstantAdPay.\n\nBecause there is a detail in how this works that most people do not notice until it is too late.\n\nIt is not about the ad credits, the formats, or even the commission structure.\n\nIt is about timing.\n\nHere is how it works. Your invite link is already live. If someone clicks it, signs up, and buys their first ad package, any package from $5 to $250, you receive 50 percent of that payment. The smart contract pays you in the same transaction. No holding tank, no withdrawal minimum, no waiting.\n\nThat is the upside everyone talks about.\n\nHere is what nobody mentions.\n\nThe moment a person buys their first package through any link, they are locked to that sponsor permanently. Every future package they buy pays that sponsor's line.\n\nSo if someone you know (a friend, a subscriber, a group contact) joins InstantAdPay through someone else's link and buys their first package there, they are locked to that other person for good.\n\n{{paid:You already bought, so your own placement is settled. Your link is live and paying.|If you have not bought yet, your link is still live. It still pays you 50 percent from anyone who clicks it today and buys.}}\n\nBut it will not capture the people you know unless you send it to them.\n\nOne person this week. Just put {{link}} where they will see it. That is all it takes.\n\n{{sponsor}} got their link from somewhere too. Same deal. Now it is your turn to pass it forward.\n\nMarty\n\n{{footer}}"
"body": "This might be the most important email I send you about InstantAdPay.\n\nBecause there is a detail in how this works that most people do not notice until it is too late.\n\nIt is not about the ad credits, the formats, or even the commission structure.\n\nIt is about timing.\n\nHere is how it works. Your invite link is already live. If someone clicks it, signs up, and buys their first ad package, any package from $5 to $500, you receive 50 percent of that payment. The smart contract pays you in the same transaction. No holding tank, no withdrawal minimum, no waiting.\n\nThat is the upside everyone talks about.\n\nHere is what nobody mentions.\n\nThe moment a person buys their first package through any link, they are locked to that sponsor permanently. Every future package they buy pays that sponsor's line.\n\nSo if someone you know (a friend, a subscriber, a group contact) joins InstantAdPay through someone else's link and buys their first package there, they are locked to that other person for good.\n\n{{paid:You already bought, so your own placement is settled. Your link is live and paying.|If you have not bought yet, your link is still live. It still pays you 50 percent from anyone who clicks it today and buys.}}\n\nBut it will not capture the people you know unless you send it to them.\n\nOne person this week. Just put {{link}} where they will see it. That is all it takes.\n\n{{sponsor}} got their link from somewhere too. Same deal. Now it is your turn to pass it forward.\n\nMarty\n\n{{footer}}"
},
{
"hours": 264,
+104
View File
@@ -0,0 +1,104 @@
// Email typo check for NEW addresses (2026-10-22, after SendGrid bounces to gmai.com / outlook.comz).
// Same file lives in InstantAdPay and LinkSpin. Catches:
// 1. near-misses of the big mailbox providers (gmai.com, gmial.com, hotmial.com, yaho.com) -> "Did you mean ...?"
// 2. mistyped endings (.con, .cmo, .comz, .nett) -> "Did you mean ...?"
// 3. domains that cannot receive mail at all (no MX and no A/AAAA record)
// A DNS timeout or server error never blocks anyone (fails open). Only call it where an address enters for the
// first time - existing accounts must always be able to sign in with the address they already have.
const dns = require('dns').promises;
const POPULAR = ['gmail.com', 'googlemail.com', 'yahoo.com', 'ymail.com', 'hotmail.com', 'outlook.com', 'live.com',
'msn.com', 'icloud.com', 'me.com', 'mac.com', 'aol.com', 'protonmail.com', 'proton.me', 'mail.com', 'gmx.com',
'gmx.de', 'yandex.com', 'yandex.ru', 'zoho.com', 'comcast.net', 'att.net', 'verizon.net', 'sbcglobal.net',
'bellsouth.net', 'cox.net', 'charter.net', 'yahoo.co.uk', 'hotmail.co.uk', 'btinternet.com', 'yahoo.fr',
'hotmail.fr', 'orange.fr', 'web.de', 't-online.de', 'libero.it', 'yahoo.com.br', 'outlook.com.br', 'rediffmail.com',
'qq.com', '163.com', 'naver.com', 'seznam.cz', 'wp.pl', 'mail.ru'];
const POP = new Set(POPULAR);
// endings that are typos of .com/.net/.org (real TLDs like .co, .cm, .om are deliberately NOT here)
const BAD_TLD = { con: 'com', cmo: 'com', comm: 'com', comz: 'com', coom: 'com', cpm: 'com', vom: 'com', xom: 'com',
ocm: 'com', cmon: 'com', 'com.com': 'com', nett: 'net', nte: 'net', ent: 'net', ogr: 'org', orgg: 'org', rog: 'org' };
// optimal string alignment distance (Damerau-Levenshtein with adjacent swaps), capped
function dist(a, b) {
if (Math.abs(a.length - b.length) > 2) return 9;
const d = [];
for (let i = 0; i <= a.length; i++) { d[i] = [i]; }
for (let j = 0; j <= b.length; j++) d[0][j] = j;
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const c = a[i - 1] === b[j - 1] ? 0 : 1;
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c);
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
}
}
return d[a.length][b.length];
}
// providers that only ever use ONE domain, so gmail.co / gmail.cm / icloud.net are always typos.
// (outlook, hotmail, yahoo, live have real national domains like hotmail.it, so they are not listed.)
const SINGLE = { gmail: 'gmail.com', googlemail: 'googlemail.com', icloud: 'icloud.com', aol: 'aol.com',
protonmail: 'protonmail.com', ymail: 'ymail.com' };
const split = d => { const i = d.indexOf('.'); return i < 0 ? [d, ''] : [d.slice(0, i), d.slice(i + 1)]; };
function suggestDomain(domain) {
if (POP.has(domain)) return null;
const labels = domain.split('.');
const two = labels.slice(-2).join('.'), last = labels[labels.length - 1];
let d = domain;
if (BAD_TLD[two]) d = labels.slice(0, -2).concat(BAD_TLD[two]).join('.');
else if (BAD_TLD[last]) d = labels.slice(0, -1).concat(BAD_TLD[last]).join('.');
if (POP.has(d)) return d;
const near = nearestPopular(d);
if (near) return near;
return d !== domain ? d : null; // ending fixed but not a known provider: still suggest the fixed ending
}
function nearestPopular(domain) {
const [name, suffix] = split(domain);
if (SINGLE[name] && domain !== SINGLE[name]) return SINGLE[name];
let best = null, bestD = 9;
for (const p of POPULAR) {
const [pn, ps] = split(p);
if (ps !== suffix) continue; // only compare names that share the same ending
const dd = dist(name, pn);
if (dd < bestD) { best = p; bestD = dd; }
}
// 1 edit always counts; 2 edits only for longer names, so short real domains are left alone
return (bestD === 1 || (bestD === 2 && name.length >= 6)) ? best : null;
}
function withTimeout(promise, ms) {
return Promise.race([promise, new Promise((_, rej) => setTimeout(() => rej(Object.assign(new Error('timeout'), { code: 'ETIMEOUT' })), ms))]);
}
// true = has somewhere to deliver, false = definitely cannot receive mail, null = could not tell (fail open)
async function domainReceives(domain) {
const gone = c => c === 'ENOTFOUND' || c === 'ENODATA' || c === 'ESERVFAIL_NXDOMAIN';
try {
const mx = await withTimeout(dns.resolveMx(domain), 3000);
if (mx && mx.length && !(mx.length === 1 && mx[0].exchange === '')) return true; // RFC 7505 null MX = no mail
if (mx && mx.length) return false;
} catch (e) { if (!gone(e.code)) return null; }
try { await withTimeout(dns.resolve4(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
try { await withTimeout(dns.resolve6(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
return false;
}
// -> null when the address is fine, or { error, suggestion } to show the person
async function emailIssue(email) {
const e = String(email || '').trim().toLowerCase();
const at = e.lastIndexOf('@');
if (at < 1) return null; // the caller's own format check handles this
const local = e.slice(0, at), domain = e.slice(at + 1);
const fix = suggestDomain(domain);
if (fix && fix !== domain) {
const suggestion = local + '@' + fix;
return { error: 'Did you mean ' + suggestion + '? Please check the email address.', suggestion };
}
if (POP.has(domain)) return null;
const ok = await domainReceives(domain);
if (ok === false) return { error: 'The email domain "' + domain + '" cannot receive mail. Please check the address.', suggestion: null };
return null;
}
module.exports = { emailIssue, suggestDomain, domainReceives };
+158
View File
@@ -0,0 +1,158 @@
// The Engine Room (Fuel Your Offers stage 4, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
// LinkSpin. Each site gathers its OWN facts (facts shape below) and answers the other's signed /api/partner/engine call
// with them; build() turns both sites' facts + the refuel streak (InstantAdPay is its source of truth) + the member's goal
// into one plain dashboard: three dials, the streak panel, warning lights, six part lights and one "next move".
//
// facts (per site): { site: 'iap'|'linkspin', ok, credits: { available, inCampaigns }, campaigns: [{ id, name, type, status,
// budget, delivered, clicks, created }], clicksWeek, loginFree, buyUrl, adsUrl,
// LinkSpin only: goalsMonth, goalsCount, conv30, parts: { bannerSpin, spinLink, page, testing } each { state, note } }
// Everything is credits and counts. Nothing here is money or a promise.
'use strict';
const DAY = 86400000;
const n0 = v => (typeof v === 'number' && isFinite(v) ? v : Number(v) || 0);
const LINKS = {
iapBuy: 'https://instantadpay.com/my#buy', iapCampaigns: 'https://instantadpay.com/my#campaigns', iapTracking: 'https://instantadpay.com/my#conversions',
lsBuy: 'https://linkspin.app/credits#buy', lsAds: 'https://linkspin.app/ads', lsLinks: 'https://linkspin.app/links', lsBanner: 'https://linkspin.app/links#b', lsPages: 'https://linkspin.app/pages', lsConv: 'https://linkspin.app/conversions',
};
// 2026-10-25 (Marty: "the flow from InstantAdPay to LinkSpin is confusing"): every link points at the screen on the site the
// member is ON when that site can do the job (buy, campaigns, conversion goals: InstantAdPay's Campaigns > Conversion
// tracking card writes the same LinkSpin goals). Only LinkSpin-only tools (Banner Spin, spin links, pages) cross over, and
// engine-room.js tags those links with ?from=<site>&task=<key> so LinkSpin shows an arrival strip with the first step.
const linksFor = site => site === 'linkspin'
? { buy: LINKS.lsBuy, campaigns: LINKS.lsAds, tracking: LINKS.lsConv }
: { buy: LINKS.iapBuy, campaigns: LINKS.iapCampaigns, tracking: LINKS.iapTracking };
const ACTIVE = new Set(['active', 'paused']);
// credits a day across recent campaigns: what each delivered over the days it has run (30 at most), summed
function burnPerDay(camps, now) {
let b = 0;
for (const c of camps) {
const age = Math.max(1, Math.min(30, (now - n0(c.created)) / DAY));
if (c.status !== 'active' && now - n0(c.created) > 30 * DAY) continue;
b += n0(c.delivered) / age;
}
return b;
}
function part(state, label, note, link, key) { return { state, label, note, link, key }; }
function build(o) {
const now = o.now || Date.now();
const rf = o.refuel || { on: false };
if (!rf.on) return { on: false };
const sites = [o.iap, o.ls].filter(f => f && f.ok);
const camps = sites.flatMap(f => (f.campaigns || []).map(c => Object.assign({ site: f.site }, c)));
const recent = camps.filter(c => ACTIVE.has(c.status) || now - n0(c.created) <= 30 * DAY || c.status === 'out');
const locked = !rf.started;
const here = o.site === 'linkspin' ? 'linkspin' : 'iap', L = linksFor(here);
// ---- dial 1: fuel left vs this cycle's refuel ----
const left = sites.reduce((s, f) => s + n0(f.credits && f.credits.available) + n0(f.credits && f.credits.inCampaigns), 0);
const cy = rf.cycle || null;
const refuelCredits = cy ? ['iap', 'linkspin'].reduce((s, k) => s + (cy[k] && cy[k].refueled ? n0(cy[k].credits) + n0(cy[k].bonus) : 0), 0) : 0;
const burn = burnPerDay(recent, now);
const daysLeft = burn > 0 ? Math.floor(left / burn) : null;
const fuel = { left: Math.round(left), refuelCredits: Math.round(refuelCredits), pct: refuelCredits > 0 ? Math.max(0, Math.min(100, Math.round(left / refuelCredits * 100))) : null,
burnPerDay: Math.round(burn), daysLeft, label: 'Fuel left' };
// ---- dial 2: clicks this week, and per 1,000 credits on recent campaigns ----
const clicksWeek = sites.reduce((s, f) => s + n0(f.clicksWeek), 0), clicksPrev = sites.reduce((s, f) => s + n0(f.clicksPrevWeek), 0);
const del = recent.reduce((s, c) => s + n0(c.delivered), 0), clk = recent.reduce((s, c) => s + n0(c.clicks), 0);
// the dial reads this week against last week: half way = the same as last week
const clicks = { week: clicksWeek, prevWeek: clicksPrev, pct: clicksPrev > 0 ? Math.min(100, Math.round(clicksWeek / (2 * clicksPrev) * 100)) : null, per1000: del >= 100 ? Math.round(clk / del * 1000 * 10) / 10 : null, label: 'Clicks this week' };
// ---- dial 3: goals this month (conversion pixel, LinkSpin keeps it for both sites) vs the member's own goal ----
const lsF = o.ls && o.ls.ok ? o.ls : null;
const goalTarget = Math.max(0, Math.round(n0(o.goal))) || null;
const goals = { month: lsF ? n0(lsF.goalsMonth) : null, target: goalTarget, pct: goalTarget && lsF ? Math.min(100, Math.round(n0(lsF.goalsMonth) / goalTarget * 100)) : null, tracking: lsF ? n0(lsF.goalsCount) > 0 : null, label: 'Goals this month' };
// ---- warning lights ----
const low = camps.filter(c => c.status === 'active' && n0(c.budget) > 0 && n0(c.delivered) >= n0(c.budget) * 0.8);
const out = camps.filter(c => c.status === 'out' && now - n0(c.created) <= 60 * DAY);
const running = camps.filter(c => c.status === 'active');
const refuelSoon = rf.active && rf.daysToRefuel != null && rf.daysToRefuel <= 5;
const loginFree = sites.filter(f => n0(f.loginFree) > 0).map(f => f.site);
const warnings = [
{ key: 'low', on: low.length > 0, label: 'Ads at 80%', note: low.length ? low.length + ' ad' + (low.length === 1 ? ' is' : 's are') + ' past 80% of budget' : 'none running low' },
{ key: 'out', on: out.length > 0, label: 'Ads out', note: out.length ? out.length + ' ad' + (out.length === 1 ? '' : 's') + ' finished delivering' + (running.length ? '' : ', nothing running now') : 'none out' },
{ key: 'refuel', on: !!refuelSoon, label: 'Refuel day coming', note: rf.active ? (rf.windowOpen ? 'window open: refuel day ' + rf.refuelDayLabel : 'refuel day ' + rf.refuelDayLabel) : 'no refuel day yet' },
{ key: 'login', on: loginFree.length > 0, label: 'Login slot open', note: loginFree.length ? 'a login-ad slot is free on ' + loginFree.map(s => s === 'iap' ? 'InstantAdPay' : 'LinkSpin').join(' and ') : 'all login slots taken' },
];
// ---- the six parts ----
const P = (lsF && lsF.parts) || {};
const pFuel = !camps.length ? part('grey', 'Fuel', 'no ads yet', L.campaigns, 'ads')
: out.length && !running.length ? part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads')
: low.length || (daysLeft != null && daysLeft < 5) ? part('amber', 'Fuel', daysLeft != null && daysLeft < 5 ? 'about ' + daysLeft + ' days left at your burn' : 'an ad is running low', L.buy, 'refuel')
: running.length ? part('green', 'Fuel', running.length + ' ad' + (running.length === 1 ? '' : 's') + ' running', L.campaigns, 'ads') : part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads');
const pick = (k, label, link, key) => { const x = P[k]; return x ? part(x.state, label, x.note, link, key) : part('grey', label, lsF ? 'not set up' : 'LinkSpin did not answer', link, key); };
const parts = [pFuel, pick('bannerSpin', 'Banner spin', LINKS.lsBanner, 'bannerspin'), pick('spinLink', 'Spin link', LINKS.lsLinks, 'spinlink'), pick('page', 'Page', LINKS.lsPages, 'page'), pick('testing', 'Testing', LINKS.lsLinks, 'testing'),
lsF ? (n0(lsF.goalsCount) === 0 ? part('grey', 'Conversion tracking', 'no goal set', L.tracking, 'conversions') : n0(lsF.conv30) === 0 ? part('amber', 'Conversion tracking', 'no conversions tracked yet', L.tracking, 'conversions') : part('green', 'Conversion tracking', n0(lsF.conv30) + ' in 30 days', L.tracking, 'conversions'))
: part('grey', 'Conversion tracking', 'LinkSpin did not answer', L.tracking, 'conversions')];
// ---- one next move ----
const per1000 = c => n0(c.delivered) >= 200 ? n0(c.clicks) / n0(c.delivered) * 1000 : null;
const ranked = running.filter(c => per1000(c) != null).sort((a, b) => per1000(b) - per1000(a));
const linkFor = c => c.site === 'linkspin' ? LINKS.lsAds : LINKS.iapCampaigns;
const availAll = sites.reduce((s, f) => s + n0(f.credits && f.credits.available), 0);
let next;
const mIap = rf.minUsd ? rf.minUsd.iap : 20, mLs = rf.minUsd ? rf.minUsd.linkspin : 25;
const firstWhy = here === 'linkspin' ? 'A package of $' + mLs + ' or more here (or $' + mIap + '+ on InstantAdPay) starts the streak and lights this room.' : 'A package of $' + mIap + ' or more here (or $' + mLs + '+ on LinkSpin) starts the streak and lights this room.';
if (locked) next = { key: 'start', label: 'Refuel to start your engine', why: firstWhy, link: L.buy, guide: '/refuel' };
else if (rf.windowOpen) next = { key: 'refuel', label: 'Refuel now', why: 'Your refuel window is open: +' + rf.next.single + '% on one site, +' + rf.next.both + '% on each with both. A $' + (here === 'linkspin' ? mLs : mIap) + '+ package here counts.', link: L.buy, guide: '/refuel' };
else if (out.length && !running.length && availAll >= 100) next = { key: 'relaunch', label: 'Relaunch an ad', why: 'Nothing is running and you have ' + Math.round(availAll).toLocaleString('en-US') + ' credits free.', link: linkFor(out[0]) };
else if (daysLeft != null && daysLeft < 5) next = { key: 'pitstop', label: 'Top up' + (rf.pitStop && (rf.pitStop.iap || rf.pitStop.linkspin) ? ' (Pit Stop +' + rf.pitStop.pct + '%)' : ''), why: 'About ' + daysLeft + ' days of fuel left at your current burn.', link: L.buy };
else if (low.length) { const best = low.slice().sort((a, b) => (per1000(b) || 0) - (per1000(a) || 0))[0]; next = { key: 'topup', label: 'Top up the winner', why: '"' + (best.name || 'your ad') + '" is past 80% of its budget.', link: linkFor(best) }; }
else if (parts[5].state === 'grey') next = { key: 'tracking', label: 'Set up conversion tracking', why: here === 'linkspin' ? 'Count signups and sales back to the ad that sent them. Step 1: add a goal, then paste its two snippets on your pages.' : 'Count signups and sales back to the ad that sent them. Step 1: add a goal under Campaigns > Conversion tracking, then paste its two snippets on your pages.', link: parts[5].link, guide: '/conversion-tracking' };
else if (parts[1].state === 'grey') next = { key: 'bannerspin', label: 'Make a Banner Spin', why: 'Test up to 5 banners in one ad slot and let the winner show.' + (here === 'linkspin' ? '' : ' Banner Spin is a LinkSpin tool: the same email signs you in there.'), link: LINKS.lsBanner };
else if (parts[4].state !== 'green') next = { key: 'testing', label: 'Test A against B', why: 'Add a second page to your spin link so the rotation can pick a winner.' + (here === 'linkspin' ? '' : ' Spin links live on LinkSpin: the same email signs you in there.'), link: LINKS.lsLinks };
else if (ranked.length >= 2 && per1000(ranked[0]) > per1000(ranked[ranked.length - 1]) * 1.5) { const worst = ranked[ranked.length - 1]; next = { key: 'cut', label: 'Cut the loser', why: '"' + (worst.name || 'an ad') + '" brings the fewest clicks per 1,000 credits. Pause it and move the credits to "' + (ranked[0].name || 'your best ad') + '".', link: linkFor(worst) }; }
else next = { key: 'cruise', label: 'Keep it running', why: 'Every part is lit. Check again on your refuel day.', link: L.campaigns };
return {
on: true, locked, fuel, clicks, goals,
streak: { active: !!rf.active, months: rf.streak || 0, best: rf.best || 0, refuelDay: rf.refuelDayLabel || null, graceEnd: rf.graceLabel || null, windowOpen: !!rf.windowOpen, next: rf.next || null, pitStop: rf.pitStop || null, freeMiss: rf.freeMiss || null, both: !!(cy && cy.both), note: streakNote(rf, cy) },
warnings, parts, next, site: here, sites: { iap: !!(o.iap && o.iap.ok), linkspin: !!(o.ls && o.ls.ok) }, at: now,
};
}
// this site's own facts for one member. d: { site, adminMember, ads, coach, now?, bannerspin?, rotator?, pages?, convtrack? }
const monthStartCT = now => { const day = new Date(now).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); const [y, m] = day.split('-').map(Number);
for (const off of [5, 6]) { const ts = Date.UTC(y, m - 1, 1, off); const t = new Date(ts); if (t.toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) === day.slice(0, 8) + '01' && Number(t.toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', hour12: false })) % 24 === 0) return ts; } return Date.UTC(y, m - 1, 1, 6); };
async function facts(d, email) {
const now = d.now || Date.now(); const e = String(email || '').toLowerCase();
const out = { site: d.site, ok: true, credits: { available: 0, inCampaigns: 0 }, campaigns: [], clicksWeek: 0, loginFree: 0 };
try { const v = await d.adminMember.view(e); if (v && v.credits) out.credits = { available: n0(v.credits.available), inCampaigns: n0(v.credits.inCampaigns) }; } catch (er) {}
let list = []; try { list = (await d.ads.listCampaigns(e)).filter(c => !c.house && c.type !== 'game'); } catch (er) {}
out.campaigns = list.map(c => ({ id: c.id, name: c.name || null, type: c.type, status: c.status, budget: n0(c.budget), delivered: n0(c.spent), clicks: n0(c.clicks), created: n0(c.created) }));
try { out.clicksWeek = await d.coach.clicksSince(list.map(c => c.id), now - 7 * DAY); out.clicksPrevWeek = Math.max(0, (await d.coach.clicksSince(list.map(c => c.id), now - 14 * DAY)) - out.clicksWeek); } catch (er) {}
try { out.loginFree = n0((await d.ads.loginSlots()).free); } catch (er) {}
if (d.site === 'linkspin') {
const since30 = now - 30 * DAY;
try { out.goalsCount = d.convtrack.goalsOf(e).length; out.goalsMonth = d.convtrack.countSince(e, monthStartCT(now)); out.conv30 = d.convtrack.countSince(e, since30); } catch (er) { out.goalsCount = 0; out.goalsMonth = 0; out.conv30 = 0; }
const parts = {};
let spins = [], rots = [], pgs = [];
try { spins = await d.bannerspin.list(e); } catch (er) {}
try { rots = await d.rotator.list(e); } catch (er) {}
try { pgs = await d.pages.list(e); } catch (er) {}
const liveB = s => s.banners.filter(b => b.active && !b.adminOff);
if (!spins.length) parts.bannerSpin = { state: 'grey', note: 'not set up' };
else { const seen = spins.filter(s => !s.paused && s.imps30 > 0); parts.bannerSpin = seen.length ? { state: 'green', note: seen.reduce((n, s) => n + s.imps30, 0).toLocaleString('en-US') + ' views in 30 days' } : { state: 'amber', note: 'no views yet' }; }
if (!rots.length) parts.spinLink = { state: 'grey', note: 'not set up' };
else { const w = rots.reduce((n, r) => n + n0(r.hits7), 0); parts.spinLink = w > 0 ? { state: 'green', note: w.toLocaleString('en-US') + ' clicks this week' } : { state: 'amber', note: 'no clicks this week' }; }
const pub = pgs.filter(p => p.status === 'published');
parts.page = !pgs.length ? { state: 'grey', note: 'not set up' } : !pub.length ? { state: 'amber', note: 'draft only, not published' } : pub.some(p => n0(p.views) > 0) ? { state: 'green', note: pub.length + ' published' } : { state: 'amber', note: 'published, no views yet' };
const rotTest = rots.some(r => !r.paused && r.destinations.filter(x => x.active).length >= 2);
const rotTraffic = rots.some(r => !r.paused && r.destinations.filter(x => x.active && x.hits7 > 0).length >= 2);
const bsTest = spins.some(s => !s.paused && liveB(s).length >= 2);
const bsTraffic = spins.some(s => !s.paused && liveB(s).filter(b => b.imps30 > 0).length >= 2);
parts.testing = rotTraffic || bsTraffic ? { state: 'green', note: 'two or more versions getting traffic' } : rotTest || bsTest ? { state: 'amber', note: 'two versions set up, waiting for traffic' } : (rots.length || spins.length) ? { state: 'amber', note: 'only one version: add a second to test' } : { state: 'grey', note: 'not set up' };
out.parts = parts;
}
return out;
}
// the streak panel's one line about the next refuel (2026-10-24): once BOTH sites are refueled this cycle it says so,
// and only a cycle with one site done asks for the other one, by name
function streakNote(rf, cy) {
const nx = rf && rf.next; if (!rf || !rf.active || !nx) return '';
if (rf.windowOpen) return 'Window open: next refuel +' + nx.single + '% (+' + nx.both + '% on each with both).';
const iapDone = !!(cy && cy.iap && cy.iap.refueled), lsDone = !!(cy && cy.linkspin && cy.linkspin.refueled);
if ((cy && cy.both) || (iapDone && lsDone)) return 'Both engines fueled this cycle: +' + (nx.secondEngine || (cy.iap && cy.iap.pct) || 0) + '% on each.';
if (nx.secondEngine) return 'Refuel ' + (iapDone ? 'LinkSpin' : 'InstantAdPay') + ' this cycle for +' + nx.secondEngine + '% on both.';
return '';
}
module.exports = { streakNote, build, facts, burnPerDay, monthStartCT, LINKS };
+506
View File
@@ -0,0 +1,506 @@
// Game Pass (2026-10-16): the $5 weekly pass across all the network games (POL Miner 2026-10-28, Turkey Drop for its Nov season), and the account-wide POL cap service the games call
// before every POL grant. IAP is the single source of truth for both; the games keep their own caps only as a backstop.
// Spec: docs/GAME-PASS.md (section 3a is the contract the games build against).
//
// What lives here:
// - the pass store email -> { until, bought: [{ ts, via, tx | credits, usd }], lastCapHit } (durable persisted map 'gamepass')
// - pass orders order -> { status, email, ts, tx } (every pass is paid by a FRESH package purchase: see buy() / onEvent())
// - the cap ledger per member per Central day: used daily/total, deferred queue per game, every answered (game, ref) kept 90 days
// - the weekly Pass Tournament: ranks pass holders by grants reported through polgrant, records POL prizes for the games to pay
// - admin stats
//
// Not to be confused with the in-game SIGN-IN pass (server.js gamePassMint/gamePassOpen): that is a session token the games keep
// in localStorage. This module is the paid Game Pass product. Fields on the wire are `pass: { active, until }` (3a).
//
// Pass tiers (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md; Marty approved the "safe" form): beside the $5 weekly pass, the
// monthly Explorer ($20) and Champion ($40) passes. They sell islands and looks in Shards of Valor, NEVER power and NEVER more
// POL: every tier gets exactly the weekly pass caps (flag().active is true for any tier, so polgrant answers pass: true and
// nothing else changes). Tiers run side by side, each with its own expiry: record.tiers = { weekly: { until }, explorer: { until },
// champion: { until } }; the legacy `until` keeps mirroring the weekly tier (lazy migration: a record with no `tiers` reads its
// `until` as the weekly tier). flag().tier = the highest active tier. Explorer/Champion sales sit behind the site switch
// `sovTiers` (default off; while it is off the admin tests them from Admin > Game Pass, never on the member card). No proration, no auto-renew: buying again
// extends that tier from max(now, until).
// 2026-10-22 (Marty): every pass rides the package rail so sponsors get paid. Buying a pass never spends a credit balance any more
// (today's buyer paid from an old balance, so no new money came in and nobody upline was paid). A pass click opens an order; the
// order is fulfilled ONLY by an on-chain package Purchase of at least the tier price, mined after the order was opened, bought by
// one of that member's own positions (main or linked), each purchase tx used once. The member keeps that package's credits for ads.
// Bought rows: via 'package' (with tx and cents). The two rows from before this change are via 'credits' and 'package' and stay.
// 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 and Champion $39.99 (30 days), plus Sovereign $99.99 (30 days)
// and Legend $249.99 (365 days, the yearly pass), all in TIER_DEFS below and all behind the same sovTiers switch. The weekly
// pass is unchanged ($5 / 7 days / the same caps). Rank weekly < explorer < champion < sovereign < legend.
// 2026-10-25 (Marty): every tier price equals an InstantAdPay one-click package, so the cheapest qualifying package is exactly
// the pass price (no silent overpay): Explorer $20 (was 19.99), Champion $50 (was 39.99), Sovereign $100 (was 99.99), Legend
// $250 (was 249.99); weekly $5 unchanged. The pass comes with that package's ad credits.
'use strict';
const fs = require('fs');
const path = require('path');
const TZ = 'America/Chicago';
const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarriors', 'clutterhunt', 'polybreak', 'driprunner', 'roadagent', 'shardsofvalor', 'polminer', 'turkeydrop'];
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent', shardsofvalor: 'Shards of Valor', polminer: 'POL Miner', turkeydrop: 'Turkey Drop' };
const SHARES = [0.5, 0.3, 0.2]; // tournament prize split, places 1-3
const KEEP_DAYS = 90; // answered refs and day rows are kept this long (idempotency window)
// THE pass table (2026-10-22, Dallas's structure, Marty approved): lowest to highest, a higher tier includes everything below.
// Rename a tier here (name) and nowhere else: the member card, the admin pane, the charge label and the chatbot read it from here.
// key = the wire value the games read (flag().tier / tiers); set = the Admin > Settings stem (gamePass<set>Enabled /
// PriceCredits / Days; weekly keeps its original gamePassPriceCredits / gamePassDays); price = the pass price in cents (100 = $1;
// the setting keeps its old 'PriceCredits' name): the package that pays for a pass must cost at least this much;
// perks = what the member card lists. Every tier is a Game Pass holder everywhere with the SAME caps (no extra POL).
const TIER_DEFS = [
{ key: 'weekly', name: 'Game Pass', set: '', price: 500, days: 7,
perks: ['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 weapons unlocked'] },
{ key: 'explorer', name: 'Explorer', set: 'Explorer', price: 2000, days: 30,
perks: ['Everything in the Game Pass, in every game', 'Shards of Valor: weapons and gear unlocked', 'Shards of Valor: 2 bonus islands'] },
{ key: 'champion', name: 'Champion', set: 'Champion', price: 5000, days: 30,
perks: ['Everything in Explorer', 'Shards of Valor: 4 bonus islands of your choice', 'Shards of Valor: the Druid hero', 'Shards of Valor: level cap 30'] },
{ key: 'sovereign', name: 'Sovereign', set: 'Sovereign', price: 10000, days: 30,
perks: ['Everything in Champion', 'Shards of Valor: every bonus island', 'Shards of Valor: the Necromancer hero', 'Shards of Valor: level cap 40'] },
{ key: 'legend', name: 'Legend', set: 'Legend', price: 25000, days: 365,
perks: ['Everything in Sovereign, for a full year', 'Shards of Valor: every bonus island', 'Shards of Valor: every hero, the Archer included', 'Shards of Valor: level cap 40'] },
];
const TIERS = TIER_DEFS.map(d => d.key); // lowest to highest
const TIER_NAMES = Object.fromEntries(TIER_DEFS.map(d => [d.key, d.name]));
const TIER_DEF = Object.fromEntries(TIER_DEFS.map(d => [d.key, d]));
const tierOk = t => TIERS.includes(t);
const rowTier = b => (b && tierOk(b.tier)) ? b.tier : 'weekly'; // bought rows before 2026-10-18 have no tier: weekly
const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
let R = null; // deps from server.js
let passes, orders, prizes; // durable persisted maps (server.js open-tokens store, DURABLE set)
let L = null; // the cap ledger: { members: { email: { days: {}, deferred: {}, weeks: {} } }, refs: { 'game:ref': {...} } }
let saveTimer = null;
// ---- Central time (no tz lib; same arithmetic as leaderboard.js) ----
function ctParts(ts) {
const s = new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' });
const m = /(\w{3}), (\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/.exec(s);
return { wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(m[1]), y: +m[4], mo: +m[2], d: +m[3], h: +m[5] % 24, mi: +m[6] };
}
function ctMidnight(ts) { const p = ctParts(ts); const guess = Date.UTC(p.y, p.mo - 1, p.d, 5, 0, 0); const q = ctParts(guess); return (q.h === 0 && q.d === p.d) ? guess : guess + 3600000; }
function weekStart(ts) { const p = ctParts(ts); const mid = ctMidnight(ts); return mid - ((p.wd + 6) % 7) * 86400000; }
const dayKey = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
const weekKey = ts => dayKey(weekStart(ts));
const dayLabel = key => new Date(key + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
// ---- settings (Admin > Settings, no deploy) ----
function cfg() {
const sc = R.siteConfig();
const n = (k, d) => { const raw = sc[k]; if (raw === undefined || raw === null || String(raw).trim() === '') return d; const v = Number(raw); return Number.isFinite(v) ? v : d; };
const start = String(sc.capsStartDate || '').trim();
const on = k => ['1', 'true', 'on', 'yes'].includes(String(sc[k]).trim().toLowerCase());
const offExplicit = k => ['0', 'false', 'off', 'no'].includes(String(sc[k]).trim().toLowerCase());
const price = Math.max(1, Math.round(n('gamePassPriceCredits', 500))), days = Math.max(1, Math.round(n('gamePassDays', 7)));
return {
enabled: on('gamePassEnabled'),
price, days,
// per tier: price in purchased-grade credits (100 = $1), length, and whether it is on sale. Every tier above weekly needs the
// master switch sovTiers AND the weekly pass switched on; its own gamePass<Set>Enabled is a kill switch (missing = on).
tierSales: on('sovTiers'),
tiers: Object.fromEntries(TIER_DEFS.map(d => [d.key, d.key === 'weekly' ? { price, days, sale: on('gamePassEnabled') }
: { price: Math.max(1, Math.round(n('gamePass' + d.set + 'PriceCredits', d.price))), days: Math.max(1, Math.round(n('gamePass' + d.set + 'Days', d.days))),
sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePass' + d.set + 'Enabled') }])),
tournamentTierSales: on('passTournamentTierSales'), // off: only weekly pass sales feed the Pass Tournament pool (exactly as before tiers)
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) },
start: /^\d{4}-\d{2}-\d{2}$/.test(start) ? start : '',
pct: Math.max(0, n('passTournamentPct', 5)),
gamesChat: String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(),
gamesTopic: String(sc.telegramGamesTopicId || '').trim(),
};
}
const enforcedOn = (c, day) => !!(c.start && day >= c.start);
// ---- ledger file ----
const FILE = () => path.join(R.dataDir, 'gamepass-ledger.json');
function load() { try { L = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { L = null; } if (!L || typeof L !== 'object') L = { members: {}, refs: {} }; L.members = L.members || {}; L.refs = L.refs || {}; }
function save() { saveTimer = null; try { fs.writeFileSync(FILE(), JSON.stringify(L)); } catch (e) { console.error('gamepass ledger save', e.message); } }
function touch() { if (!saveTimer) saveTimer = setTimeout(save, 500); }
function member(e) { return (L.members[e] = L.members[e] || { days: {}, deferred: {}, weeks: {} }); }
function dayRow(M, day) {
return (M.days[day] = M.days[day] || { daily: 0, total: 0, carried: 0, dropped: 0, deferredOut: 0, grants: 0, hits: { daily: 0, total: 0 },
tier: { free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 } },
would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 } }); // would = what the caps would have done before capsStartDate
}
function init(deps) {
R = deps;
passes = R.persistedMap('gamepass');
orders = R.persistedMap('gporders');
prizes = R.persistedMap('gpprizes');
load();
}
// ---- the pass ----
function rec(e) { return passes.get(e) || null; }
// per-tier expiry (ms, 0 = never held). A record from before tiers has no `tiers`: its legacy `until` is the weekly tier
// (lazy migration, idempotent: every write stores `tiers` and mirrors tiers.weekly into `until`).
function tiersOf(p) {
const out = {}; const T = (p && p.tiers) || {};
for (const k of TIERS) out[k] = Number(T[k] && T[k].until) || 0;
if (p && !p.tiers) out.weekly = Number(p.until) || 0;
return out;
}
function topTier(T, t) { for (let i = TIERS.length - 1; i >= 0; i--) if (T[TIERS[i]] > t) return TIERS[i]; return null; }
// { active, until, tier, tiers }: active = any tier on (every tier is a Game Pass holder everywhere, same caps); tier = the
// highest active tier; until = that tier's end. With nothing active, until is the last end the account ever had (as before
// tiers) or null. tiers = each tier's end while it is active, else null.
function flag(email, now) {
const p = rec(String(email || '').toLowerCase()); const t = now || Date.now(); const T = tiersOf(p); const tier = topTier(T, t);
const tiers = {}; for (const k of TIERS) tiers[k] = T[k] > t ? T[k] : null;
const last = Math.max(...TIERS.map(k => T[k]));
return { active: !!tier, until: tier ? T[tier] : (last || null), tier, tiers };
}
function writeTiers(cur, T, extra) {
const tiers = {}; for (const k of TIERS) if (T[k]) tiers[k] = { until: T[k] };
return Object.assign({}, cur, { until: T.weekly || 0, tiers }, extra || {});
}
function extend(e, via, extra, now, tier) {
tier = tierOk(tier) ? tier : 'weekly';
const c = cfg(); const tc = c.tiers[tier]; const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] };
const T = tiersOf(cur);
const until = Math.max(t, T[tier]) + tc.days * 86400000; T[tier] = until; // renewing early loses nothing: from max(now, until)
const bought = [Object.assign({ ts: t, via, tier, usd: tc.price / 100, days: tc.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
passes.set(e, writeTiers(cur, T, { bought, ts: t }));
return { until, days: tc.days, tier };
}
function waitingOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e) out.push(Object.assign({ order: k }, o, { tier: tierOk(o.tier) ? o.tier : 'weekly' })); return out; }
function waitingOrder(e, tier) { return waitingOrders(e).find(o => o.tier === (tier || 'weekly')) || null; }
// the admin's tier test: drop a waiting order that was opened for testing, so a later real package never fulfils it by surprise
function cancelOrder(email, tier) {
const e = String(email || '').toLowerCase(); const w = waitingOrder(e, tier || 'weekly'); if (!w) return { ok: true, none: true };
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order, tier: w.tier };
}
function comp(email, why, tier, now) { // support comp: counts as no sale
const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }, now, tier);
return { active: true, until: x.until, days: x.days, tier: x.tier };
}
// support refund (never automatic): that tier ends now; the record keeps what it was
function revoke(email, tier, why, now) {
const e = String(email || '').toLowerCase(); if (!tierOk(tier)) return { error: 'unknown tier' };
const t = now || Date.now(); const p = passes.get(e); const T = tiersOf(p);
if (!p || !(T[tier] > t)) return { error: 'No active ' + TIER_NAMES[tier] + ' pass on this account.' };
const was = T[tier]; T[tier] = t;
passes.set(e, writeTiers(p, T, { revokes: [{ ts: t, tier, why: String(why || 'support').slice(0, 80), was }].concat(p.revokes || []).slice(0, 50) }));
return { ok: true, tier, was, until: t };
}
// on sale for this viewer: the tier's own switch, or the admin portal's tier test (Admin > Game Pass) while sovTiers is off
const tierOpen = (c, tier, preview) => !!(c.tiers[tier].sale || (preview && tier !== 'weekly'));
const PACKAGE_USD = [5, 10, 20, 50, 100, 250, 500]; // copy only: the package that covers a price
const packageFor = usd => PACKAGE_USD.find(x => x >= usd) || usd;
// GET /api/my/gamepass: exactly what a member sees, for EVERY account, the admin's included (2026-10-25, Marty: no admin-only
// tier UI on the member card). opts.preview = the admin portal's tier test (GET /api/admin/gamepass/preview): every tier, each
// one open to the admin's own account while sovTiers is off.
function view(email, now, opts) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const f = flag(e, t); const p = rec(e); const w = waitingOrder(e, 'weekly');
const admin = !!(opts && opts.preview); const T = tiersOf(p);
const caps = capsFor(e, t);
// the tier rows this member sees: weekly always; a higher tier while on sale, in the admin preview, or to a current holder (holders
// keep their pass when a sale is switched off, they just cannot buy more)
const passRows = TIERS.filter(k => k === 'weekly' || c.tiers[k].sale || admin || T[k] > t).map(k => {
const tc = c.tiers[k]; return { tier: k, name: TIER_NAMES[k], perks: TIER_DEF[k].perks, price: tc.price, usd: tc.price / 100, days: tc.days, package: packageFor(tc.price / 100),
active: T[k] > t, until: T[k] > t ? T[k] : null, waiting: !!waitingOrder(e, k), sale: !!tc.sale, open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
});
const tiered = passRows.some(r => r.tier !== 'weekly');
return { enabled: c.enabled, active: f.active, until: f.until, tier: f.tier, price: c.price, days: c.days, usd: c.price / 100,
waiting: !!w, waitingSince: w ? w.ts : null, bought: p ? (p.bought || []).length : 0,
caps, capsStart: c.start || null, lastCapHit: p && p.lastCapHit && (t - p.lastCapHit.ts) < 2 * 86400000 ? p.lastCapHit : null,
tournament: { pct: c.pct, shares: SHARES, next: nextTournamentAt(t) },
show: c.enabled || tiered, passes: passRows, tierPreview: tiered && admin && !c.tierSales };
}
// POST /api/my/gamepass/buy { tier }. tier missing = weekly (exactly the pass as it was before tiers). opts.preview = the admin
// portal's tier test (POST /api/admin/gamepass/test-buy, the admin's own account only): a tier that is not on sale still opens an order.
// A pass is ALWAYS paid by a fresh package purchase (2026-10-22, Marty: the pass rides the package rail so sponsors get paid). This never
// spends credits: it opens (or reuses) a waiting order for that tier and sends the member to buy a package of at least the tier price.
// The order is fulfilled by onEvent() below; the member keeps every credit of that package for ads.
function buy(email, now, tier, opts) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
tier = (tier === undefined || tier === null || tier === '') ? 'weekly' : String(tier).toLowerCase();
if (!tierOk(tier)) return { error: 'There is no such pass.' };
const tc = c.tiers[tier]; const name = TIER_NAMES[tier];
if (tier === 'weekly') { if (!c.enabled) return { error: 'The Game Pass is not open yet.' }; }
else if (!tierOpen(c, tier, !!(opts && opts.preview))) return { error: 'The ' + name + ' pass is not open yet.' };
let w = waitingOrder(e, tier); const reused = !!w;
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, tier }); w = Object.assign({ order: k }, orders.get(k)); }
const pkg = packageFor(tc.price / 100);
if (!reused) console.log('gamepass order opened', tier, e, w.order, 'needs a package of', tc.price, 'cents');
return { ok: false, needPay: true, tier, payUrl: tier === 'weekly' ? '/my?from=gamepass#buy' : '/my?from=gamepass&tier=' + tier + '#buy', order: w.order, orderTs: w.ts, reused,
price: tc.price, usd: tc.price / 100, package: pkg,
message: (tier === 'weekly' ? 'Your Game Pass' : 'Your ' + name + ' pass') + ' starts the moment your next package of $' + pkg + ' or more settles on chain. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
}
// A package purchase landing on chain fulfils one of this account's waiting orders: the highest-priced one the package covers.
// Rules (2026-10-22): the buyer must be one of this account's own positions (main member id or a linked position); the purchase must
// be mined AFTER the order was opened (block time, ORDER_SKEW_MS for clock drift); one pass per purchase of $5 or more; each tx used
// once across every account and order. Credit balances never fulfil an order.
const ORDER_SKEW_MS = 30000;
function txUsed(tx) {
if (!tx) return false;
for (const [, o] of orders) if (o && o.tx === tx) return true;
for (const [, p] of passes) if (p && (p.bought || []).some(b => b.tx && b.tx === tx)) return true;
return false;
}
async function ownerOf(ev) { // the account behind the buying position
if (ev.devEmail && !R.isProd) return String(ev.devEmail).toLowerCase();
const id = Number(ev.buyerId) || 0; if (!id) return null;
let a = await R.accounts.byMemberId(id);
if (!a && R.accounts.positionByMember) { const pos = await R.accounts.positionByMember(id); if (pos && pos.email) a = { email: pos.email }; }
return a && a.email ? String(a.email).toLowerCase() : null;
}
async function minedAt(ev) { // block time in ms; the indexed-at time only when the block cannot be read (it is never earlier than the block)
if (ev.devMinedAt && !R.isProd) return Number(ev.devMinedAt);
if (ev.block && R.blockTime) {
for (let i = 0; i < 3; i++) { try { const s = await R.blockTime(ev.block); if (s > 0) return s * 1000; } catch (e) {} await new Promise(r => setTimeout(r, 1500)); }
console.warn('gamepass: block time unavailable for', ev.block, '- using the indexed-at time');
}
return Number(ev.ts) || Date.now();
}
async function onEvent(ev) {
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
const c = cfg(); const cents = ev.priceCents || 0;
if (!TIERS.some(k => cents >= c.tiers[k].price)) return null;
const e = await ownerOf(ev); if (!e) return null;
if (!waitingOrders(e).length) return null;
if (txUsed(ev.tx)) return null; // each purchase counts once, everywhere
const at = await minedAt(ev);
const w = waitingOrders(e).filter(o => cents >= c.tiers[o.tier].price && at + ORDER_SKEW_MS >= o.ts)
.sort((x, y) => c.tiers[y.tier].price - c.tiers[x.tier].price || x.ts - y.ts)[0];
if (!w) { console.log('gamepass: package', String(ev.tx).slice(0, 12), 'by', e, 'fulfils no order (bought before the order or too small)'); return null; }
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
const x = extend(e, 'package', { tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0, usd: c.tiers[w.tier].price / 100, packageUsd: cents / 100 }, (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()), w.tier);
console.log('gamepass fulfilled by package', w.tier, e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents, until', new Date(x.until).toISOString());
return { order: w.order, until: x.until, tier: w.tier };
}
// ---- the caps ----
function capsFor(email, now, game) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const day = dayKey(t); const pass = flag(e, t).active;
const lim = pass ? c.pass : c.free; const M = L.members[e]; const D = M && M.days[day];
const used = { daily: r6(D ? D.daily : 0), total: r6(D ? D.total : 0) };
const out = { daily: lim.daily, total: lim.total, used, day, enforced: enforcedOn(c, day), pass };
if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0));
return out;
}
// POST /api/partner/polgrant. Returns { allowed, deferred, pass, day } (+ carried, capHit, enforced, repeat).
function grant(o) {
const e = String(o.email || '').toLowerCase(); const game = String(o.game || '').toLowerCase(); const kind = o.kind === 'progress' ? 'progress' : 'daily';
const pol = r6(o.pol); const ref = String(o.ref || '').slice(0, 120); const t = o.now || Date.now(); const day = dayKey(t);
if (!e || !GAMES.includes(game) || !ref || !(pol >= 0)) return { error: 'memberId/email, game, kind, pol and ref are required' };
const key = game + ':' + ref;
const prev = L.refs[key];
if (prev) return { allowed: prev.allowed, deferred: prev.deferred, pass: prev.pass, day: prev.day, carried: prev.carried || 0, capHit: prev.capHit || null, enforced: !!prev.enforced, repeat: true, voided: !!prev.voided };
const c = cfg(); const pass = flag(e, t).active; const lim = pass ? c.pass : c.free; const enforced = enforcedOn(c, day);
const M = member(e); const D = dayRow(M, day); const tier = D.tier[pass ? 'pass' : 'free'];
let totalRem = Math.max(0, r6(lim.total - D.total)), dailyRem = Math.max(0, r6(lim.daily - D.daily));
// carry-forward: progress POL deferred on an EARLIER day for this game is paid first, inside today's total cap
let carried = 0; const q = M.deferred[game] || [];
for (const d of q) {
if (d.day >= day || d.left <= 0) continue;
const take = enforced ? Math.min(d.left, Math.max(0, r6(totalRem - carried))) : d.left;
if (take <= 0) break;
d.left = r6(d.left - take); carried = r6(carried + take); d.paid = (d.paid || []).concat([{ day, pol: take, ref }]).slice(-20);
}
M.deferred[game] = q.filter(d => d.left > 0);
if (carried) { D.total = r6(D.total + carried); D.carried = r6(D.carried + carried); tier.allowed = r6(tier.allowed + carried); totalRem = Math.max(0, r6(totalRem - carried)); }
// the new grant
let allowed = pol, deferred = 0, dropped = 0, capHit = null;
const wouldAllowed = kind === 'daily' ? Math.min(pol, dailyRem, totalRem) : Math.min(pol, totalRem);
const wouldHit = wouldAllowed < pol ? (kind === 'daily' && dailyRem <= totalRem ? 'daily' : 'total') : null;
if (enforced) {
allowed = r6(wouldAllowed); capHit = wouldHit;
if (kind === 'daily') { dropped = r6(pol - allowed); if (dropped) D.dropped = r6(D.dropped + dropped); }
else { deferred = r6(pol - allowed); if (deferred) { q.push({ ref, pol, left: deferred, ts: t, day }); M.deferred[game] = q; D.deferredOut = r6(D.deferredOut + deferred); } }
if (capHit) { D.hits[capHit] += 1; tier[capHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1; }
} else if (wouldHit) { // before capsStartDate: everything is allowed, but Admin sees what the caps would have done
D.would[kind === 'daily' ? 'dropped' : 'deferred'] = r6(D.would[kind === 'daily' ? 'dropped' : 'deferred'] + (pol - wouldAllowed));
D.would[wouldHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1;
}
if (kind === 'daily') D.daily = r6(D.daily + allowed);
D.total = r6(D.total + allowed); tier.allowed = r6(tier.allowed + allowed); D.grants += 1;
// tournament activity: one point per reported grant (progress and daily weigh the same)
if (pol > 0) { const wk = weekKey(t); M.weeks[wk] = M.weeks[wk] || {}; M.weeks[wk][game] = (M.weeks[wk][game] || 0) + 1; }
if (capHit) { const p = passes.get(e) || { until: 0, bought: [] }; passes.set(e, Object.assign({}, p, { lastCapHit: { ts: t, day, game, kind: capHit, pass } })); }
const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed };
L.refs[key] = out; touch();
return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false };
}
// POST /api/partner/polgrant/void: the game decided not to pay after all. Reverses this ref's own share (the carry it triggered
// belongs to earlier refs and stays). The ref stays answered, as voided, so a replay is still idempotent.
function voidGrant(o) {
const game = String(o.game || '').toLowerCase(); const ref = String(o.ref || '').slice(0, 120); const key = game + ':' + ref;
const prev = L.refs[key]; if (!prev) return { ok: true, unknown: true };
if (prev.voided) return { ok: true, voided: true, repeat: true };
const M = member(prev.email); const D = dayRow(M, prev.day);
const own = r6(prev.own || 0);
D.total = Math.max(0, r6(D.total - own)); if (prev.kind === 'daily') D.daily = Math.max(0, r6(D.daily - own));
const tier = D.tier[prev.pass ? 'pass' : 'free']; tier.allowed = Math.max(0, r6(tier.allowed - own));
let removed = 0; const q = M.deferred[game] || []; for (const d of q) if (d.ref === ref) { removed = r6(removed + d.left); d.left = 0; } M.deferred[game] = q.filter(d => d.left > 0);
if (removed) D.deferredOut = Math.max(0, r6(D.deferredOut - removed));
const wk = weekKey(prev.ts || Date.now()); if (M.weeks[wk] && M.weeks[wk][game]) M.weeks[wk][game] -= 1;
Object.assign(prev, { voided: true, allowed: 0, deferred: 0, carried: 0, voidedAt: Date.now(), reversed: { allowed: own, deferred: removed } }); touch();
return { ok: true, voided: true, reversed: { allowed: own, deferred: removed } };
}
// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ----
function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; }
function holdersIn(start, end) { // any tier holds a Pass Tournament seat (every tier above weekly includes everything Weekly gives)
const out = [];
for (const [e, p] of passes) { if (!p || !(Math.max(...TIERS.map(k => tiersOf(p)[k])) > start)) continue; if ((p.bought || []).some(b => b.ts < end)) out.push(e); }
return out;
}
const isSale = b => b && b.via !== 'admin'; // comps are passes, not sales
// the pool counts weekly pass sales only, unless passTournamentTierSales adds the sales of every tier above weekly (default off: the pool exactly as before tiers)
function salesIn(start, end, withTiers) { let n = 0, usd = 0; for (const [, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b) && b.ts >= start && b.ts < end && (withTiers || rowTier(b) === 'weekly')) { n += 1; usd += Number(b.usd) || 0; } return { n, usd: Math.round(usd * 100) / 100 }; }
function scoresFor(wk, emails) {
return emails.map(e => { const M = L.members[e]; const g = (M && M.weeks[wk]) || {}; const score = Object.values(g).reduce((n, x) => n + x, 0); const first = ((passes.get(e) || {}).bought || []).reduce((m, b) => Math.min(m, b.ts), Infinity);
return { email: e, score, games: g, first }; }).filter(x => x.score > 0).sort((a, b) => b.score - a.score || a.first - b.first || (a.email < b.email ? -1 : 1));
}
async function runTournament(startTs, opts) {
const c = cfg(); const start = weekStart(startTs); const end = start + 7 * 86400000; const wk = dayKey(start);
if (prizes.get(wk) && !(opts && opts.force)) return prizes.get(wk);
const polUsd = await R.polUsd().catch(() => 0);
if (!(polUsd > 0)) return { error: 'POL rate unavailable; the tournament for the week of ' + wk + ' will be settled on the next hourly pass.' };
const sales = salesIn(start, end, c.tournamentTierSales); const poolUsd = Math.round(sales.usd * c.pct) / 100;
const poolPol = r6(poolUsd / polUsd);
const ranked = scoresFor(wk, holdersIn(start, end));
const winners = [];
for (let i = 0; i < Math.min(3, ranked.length); i++) {
const x = ranked[i]; let a = null; try { a = await R.accounts.byEmail(x.email); } catch (e) {}
winners.push({ place: i + 1, email: x.email, username: (a && a.username) || null, memberId: (a && a.memberId) || 0, wallet: (a && a.address) || null, score: x.score, games: x.games, pol: r6(poolPol * SHARES[i]), usd: Math.round(poolUsd * SHARES[i] * 100) / 100, status: 'pending', tx: null });
}
const row = { week: wk, label: 'week of ' + dayLabel(wk), start, end, sales: sales.n, salesUsd: sales.usd, pct: c.pct, poolUsd, polUsd, poolPol, holders: holdersIn(start, end).length, ranked: ranked.length, winners,
unallocatedPol: r6(poolPol - winners.reduce((n, w) => n + w.pol, 0)), ranAt: Date.now(), posted: false };
prizes.set(wk, row);
console.log('gamepass tournament', wk, 'sales', sales.n, 'pool', poolPol, 'POL', 'winners', winners.length);
if (winners.length && c.enabled) {
const medal = ['\u{1F947}', '\u{1F948}', '\u{1F949}'];
const lines = winners.map(w => medal[w.place - 1] + ' ' + (w.username ? '@' + w.username : 'member #' + (w.memberId || '?')) + ' · ' + w.score + ' plays · ' + w.pol.toFixed(2) + ' POL');
const html = '\u{1F3AE} <b>Game Pass Tournament</b> · ' + row.label + '\n' + lines.join('\n') + '\n' + sales.n + ' pass' + (sales.n === 1 ? '' : 'es') + ' sold · prize pool ' + poolPol.toFixed(2) + ' POL (' + c.pct + '% of pass sales)\n'
+ 'Prizes are paid in POL by the games to the winners’ InstantAdPay wallets. Get the Pass: https://instantadpay.com/my#games?pass=1';
try { await R.telegram(html); row.posted = true; prizes.set(wk, row); } catch (e) { console.error('gamepass tournament post', e.message); }
for (const w of winners) { try { await R.notify(w.email, 'Game Pass Tournament: you placed #' + w.place, '<p>You finished <b>#' + w.place + '</b> in the Game Pass Tournament for the ' + row.label + ' with ' + w.score + ' plays across the games. Your prize of <b>' + w.pol.toFixed(2) + ' POL</b> is paid to the wallet on your InstantAdPay account by the games this week.</p>'); } catch (e) {} }
}
return row;
}
// hourly: once Monday 9 AM Central has passed and the closed week has no row yet, exactly one app copy settles it (marks.claim)
async function tournamentTick(now) {
const t = now || Date.now(); const c = cfg(); if (!c.enabled) return null;
const ws = weekStart(t); if (t < ws + 9 * 3600000) return null; // not yet 9 AM Monday for the week that just closed
const prev = ws - 7 * 86400000; const wk = dayKey(prev);
if (prizes.get(wk)) return null;
if (!holdersIn(prev, ws).length && !salesIn(prev, ws, c.tournamentTierSales).n) { prizes.set(wk, { week: wk, label: 'week of ' + dayLabel(wk), start: prev, end: ws, sales: 0, salesUsd: 0, poolPol: 0, winners: [], ranAt: Date.now(), empty: true }); return null; }
if (!(await R.marks.claim('gamepass-tournament:' + wk))) return null;
return runTournament(prev);
}
// GET /api/partner/tournament/pending: prize rows the games still have to pay (the Road Agent faucet pattern)
function pending() { const out = []; for (const [, row] of prizes) for (const w of row.winners || []) if (w.status === 'pending') out.push({ week: row.week, label: row.label, place: w.place, email: w.email, username: w.username, memberId: w.memberId, wallet: w.wallet, pol: w.pol, usd: w.usd, score: w.score }); return out.sort((a, b) => a.week < b.week ? -1 : a.week > b.week ? 1 : a.place - b.place); }
function markPaid(week, place, tx, by) {
const row = prizes.get(String(week)); if (!row) return { error: 'no such week' };
const w = (row.winners || []).find(x => x.place === Number(place)); if (!w) return { error: 'no such place' };
if (w.status === 'paid') return { ok: true, repeat: true, tx: w.tx };
Object.assign(w, { status: 'paid', tx: String(tx || '').slice(0, 80), paidAt: Date.now(), paidBy: by || null }); prizes.set(String(week), row);
return { ok: true };
}
// ---- admin ----
function monthStart(ts) { const p = ctParts(ts); return ctMidnight(Date.UTC(p.y, p.mo - 1, 1, 17)); } // the 1st of the Central month, 00:00 Central
// per tier: active = accounts whose HIGHEST active tier is this one (each account counted once); sales by Central week / month /
// all time (comps are not sales); renewals30d = purchases in the last 30 days by accounts that held this tier before; expiring7d =
// this tier ends within the next 7 Central days (today included); waitingOrders = orders waiting for a package.
function tierStats(t) {
const ws = weekStart(t), ms = monthStart(t), d30 = t - 30 * 86400000;
const soon = ctMidnight(ctMidnight(t) + 7 * 86400000 + 3 * 3600000); // Central midnight that ends day 7 (DST-safe)
const out = {}; for (const k of TIERS) out[k] = { name: TIER_NAMES[k], active: 0, soldWeek: 0, usdWeek: 0, soldMonth: 0, usdMonth: 0, soldTotal: 0, usdTotal: 0, renewals30d: 0, expiring7d: 0, comped: 0, waitingOrders: 0 };
for (const [, p] of passes) {
if (!p) continue; const T = tiersOf(p); const top = topTier(T, t); if (top) out[top].active += 1;
for (const k of TIERS) if (T[k] > t && T[k] <= soon) out[k].expiring7d += 1;
const rows = p.bought || [];
for (const b of rows) {
const k = rowTier(b); const o = out[k]; if (!isSale(b)) { o.comped += 1; continue; }
const usd = Number(b.usd) || 0; o.soldTotal += 1; o.usdTotal += usd;
if (b.ts >= ws) { o.soldWeek += 1; o.usdWeek += usd; }
if (b.ts >= ms) { o.soldMonth += 1; o.usdMonth += usd; }
if (b.ts >= d30 && rows.some(x => x !== b && rowTier(x) === k && x.ts < b.ts)) o.renewals30d += 1;
}
}
for (const [, o] of orders) if (o.status === 'waiting') out[tierOk(o.tier) ? o.tier : 'weekly'].waitingOrders += 1;
for (const k of TIERS) for (const f of ['usdWeek', 'usdMonth', 'usdTotal']) out[k][f] = Math.round(out[k][f] * 100) / 100;
return out;
}
// every sale row, newest first, labelled by how it was paid. Rows from the new package rail carry buyerId (2026-10-22); the two
// rows from before (one paid with a credit balance, one fulfilled by a package under the old rule) are labelled as such.
function payLabel(b) {
if (b.via === 'credits') return 'credit-paid (old rule)';
if (b.via === 'package') return ('buyerId' in b) ? 'package' : 'package (old rule)';
return String(b.via || '?');
}
function salesList(limit) {
const out = [];
for (const [e, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b)) out.push({ ts: b.ts, email: e, tier: rowTier(b), name: TIER_NAMES[rowTier(b)], via: b.via, label: payLabel(b),
tx: b.tx || null, usd: Number(b.usd) || 0, packageUsd: b.packageUsd || (b.cents ? b.cents / 100 : null), credits: b.credits || null, buyerId: b.buyerId || null });
return out.sort((a, b) => b.ts - a.ts).slice(0, limit || 50);
}
function payMix() {
const m = { credit: { n: 0, usd: 0 }, packageOld: { n: 0, usd: 0 }, package: { n: 0, usd: 0, packageUsd: 0 } };
for (const [, p] of passes) for (const b of (p && p.bought) || []) {
if (!isSale(b)) continue; const usd = Number(b.usd) || 0;
const k = b.via === 'credits' ? 'credit' : (b.via === 'package' && !('buyerId' in b)) ? 'packageOld' : 'package';
m[k].n += 1; m[k].usd = Math.round((m[k].usd + usd) * 100) / 100;
if (k === 'package') m.package.packageUsd = Math.round((m.package.packageUsd + (Number(b.packageUsd) || (b.cents ? b.cents / 100 : 0))) * 100) / 100;
}
return m;
}
function adminStats(now) {
const t = now || Date.now(); const c = cfg(); const ws = weekStart(t); const day = dayKey(t); const wkFrom = dayKey(ws);
let active = 0, soldTotal = 0, usdTotal = 0, soldWeek = 0, usdWeek = 0, waiting = 0, comped = 0;
for (const [, p] of passes) { if (!p) continue; if (topTier(tiersOf(p), t)) active += 1; for (const b of p.bought || []) { if (!isSale(b)) { comped += 1; continue; } soldTotal += 1; usdTotal += Number(b.usd) || 0; if (b.ts >= ws) { soldWeek += 1; usdWeek += Number(b.usd) || 0; } } }
for (const [, o] of orders) if (o.status === 'waiting') waiting += 1;
const wk = { pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, carried: 0, dropped: 0, deferredOut: 0, grants: 0, would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 }, players: 0 };
const today = { allowed: 0, grants: 0, players: 0 };
let qEntries = 0, qPol = 0, qMembers = 0; const byGame = {};
for (const [e, M] of Object.entries(L.members)) {
let inWeek = false;
for (const [d, D] of Object.entries(M.days)) {
if (d < wkFrom) continue; inWeek = true;
for (const k of ['pass', 'free']) { wk[k].allowed = r6(wk[k].allowed + D.tier[k].allowed); wk[k].hitsDaily += D.tier[k].hitsDaily; wk[k].hitsTotal += D.tier[k].hitsTotal; }
wk.carried = r6(wk.carried + D.carried); wk.dropped = r6(wk.dropped + D.dropped); wk.deferredOut = r6(wk.deferredOut + D.deferredOut); wk.grants += D.grants;
for (const k of ['dropped', 'deferred']) wk.would[k] = r6(wk.would[k] + D.would[k]); wk.would.hitsDaily += D.would.hitsDaily; wk.would.hitsTotal += D.would.hitsTotal;
if (d === day) { today.allowed = r6(today.allowed + D.total); today.grants += D.grants; today.players += 1; }
}
if (inWeek) wk.players += 1;
let mine = 0; for (const [g, q] of Object.entries(M.deferred)) for (const x of q) { qEntries += 1; qPol = r6(qPol + x.left); mine += 1; byGame[g] = r6((byGame[g] || 0) + x.left); }
if (mine) qMembers += 1;
const W = M.weeks[wkFrom] || {}; for (const [g, n] of Object.entries(W)) { byGame['plays:' + g] = (byGame['plays:' + g] || 0) + n; }
void e;
}
const rows = [...prizes.values()].sort((a, b) => a.week < b.week ? 1 : -1);
return { enabled: c.enabled, tierSales: c.tierSales, settings: { price: c.price, days: c.days, tiers: c.tiers, tournamentTierSales: c.tournamentTierSales, free: c.free, pass: c.pass, capsStart: c.start || null, pct: c.pct, enforced: enforcedOn(c, day) },
week: { start: ws, label: 'week of ' + dayLabel(wkFrom), day },
tiers: tierStats(t), month: { start: monthStart(t), label: dayLabel(dayKey(monthStart(t))) + ' to date' },
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting, pay: payMix() },
sales: salesList(50),
pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today },
capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would },
deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame },
tournament: { lastRun: rows[0] ? rows[0].ranAt : null, last: rows[0] || null, next: nextTournamentAt(t), pending: pending().length, history: rows.slice(0, 8) } };
}
// ---- housekeeping: answered refs and day rows older than KEEP_DAYS, week tallies older than 10 weeks ----
function prune(now) {
const t = now || Date.now(); const cut = t - KEEP_DAYS * 86400000; const cutDay = dayKey(cut); const cutWeek = dayKey(weekStart(t - 70 * 86400000)); let n = 0;
for (const [k, r] of Object.entries(L.refs)) if ((r.ts || 0) < cut) { delete L.refs[k]; n++; }
for (const [e, M] of Object.entries(L.members)) {
for (const d of Object.keys(M.days)) if (d < cutDay) { delete M.days[d]; n++; }
for (const w of Object.keys(M.weeks)) if (w < cutWeek) { delete M.weeks[w]; n++; }
if (!Object.keys(M.days).length && !Object.keys(M.weeks).length && !Object.values(M.deferred).some(q => q.length)) delete L.members[e];
}
for (const [k, o] of orders) if (o.status === 'waiting' && t - o.ts > 30 * 86400000) orders.delete(k); // a pass order nobody paid for in a month is forgotten
if (n) touch();
return n;
}
module.exports = { init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, TIER_DEFS, flag, view, buy, cancelOrder, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
_ledger: () => L };
+45 -2
View File
@@ -10,7 +10,7 @@ const fs = require('fs');
const path = require('path');
let R = null;
const NAMES = { spookydoors: 'Spooky Doors', gemkingdom: 'Gem Kingdom', clutterhunt: 'ClutterHunt', driprunner: 'Drip Runner', polywarriors: 'PolyWarriors', spellwheel: 'SpellWheel', roadagent: 'Road Agent', polhunter: 'PolHunter', passivedrip: 'PassiveDrip' };
const NAMES = { spookydoors: 'Spooky Doors', gemkingdom: 'Gem Kingdom', clutterhunt: 'ClutterHunt', driprunner: 'Drip Runner', polywarriors: 'PolyWarriors', spellwheel: 'SpellWheel', roadagent: 'Road Agent', polhunter: 'PolHunter', passivedrip: 'PassiveDrip', polybreak: 'PolyBreak', polminer: 'POL Miner', turkeydrop: 'Turkey Drop', shardsofvalor: 'Shards of Valor' };
const wallets = () => Object.fromEntries(String(process.env.GAME_WALLETS || '').split(',').map(x => x.trim()).filter(Boolean).map(x => { const [k, a] = x.split(':'); return [String(k).toLowerCase(), String(a || '').toLowerCase()]; }).filter(([k, a]) => k && /^0x[0-9a-f]{40}$/.test(a)));
const KEY = () => String(process.env.ETHERSCAN_KEY || '').trim();
// money never flows to these from a game wallet as a payout: Marty's fee wallets, the other game wallets
@@ -55,4 +55,47 @@ async function gather(since) {
const totals = games.reduce((t, g) => ({ sentIn: t.sentIn + g.sentIn, payouts: t.payouts + g.payouts, wei: t.wei + g.wei }), { sentIn: 0, payouts: 0, wei: 0n });
return { games, totals, chainChecked: !!KEY() && Object.keys(W).length > 0 };
}
module.exports = { init, handoff, gather, NAMES };
// ---- all-time running total of game payouts, for the admin P&L (Marty 2026-10-18) ----
// Every outgoing POL send from each game wallet to a player, from the wallet's first transaction.
// Kept in DATA_DIR/game-payouts-alltime.json per wallet { block, count, wei, players[] } and topped up
// incrementally (only blocks after the last one seen), so after the first scan a refresh is one call per game.
const AT_FILE = () => path.join(R.dataDir, 'game-payouts-alltime.json');
let atState = null, atAt = 0, atBusy = null;
const sleep = ms => new Promise(r => setTimeout(r, ms));
function atLoad() { if (!atState) { try { atState = JSON.parse(fs.readFileSync(AT_FILE(), 'utf8')); } catch (e) { atState = {}; } } return atState; }
function atSave() { try { fs.writeFileSync(AT_FILE() + '.tmp', JSON.stringify(atState)); fs.renameSync(AT_FILE() + '.tmp', AT_FILE()); } catch (e) {} }
async function atScan(slug, addr) {
const st = atLoad(); let w = st[slug];
if (!w || w.addr !== addr) w = st[slug] = { addr, block: 0, count: 0, wei: '0', players: [] };
const skip = SKIP(), players = new Set(w.players); let wei = BigInt(w.wei), count = w.count, maxBlock = w.block; // committed only when the scan finishes, so a failed page never double-counts
for (let page = 1; page <= 10; page++) { // Etherscan caps page*offset at 10,000; the next refresh carries on from the last block
const url = 'https://api.etherscan.io/v2/api?chainid=137&module=account&action=txlist&address=' + addr + '&startblock=' + (w.block + 1) + '&endblock=99999999&sort=asc&page=' + page + '&offset=1000&apikey=' + KEY();
const r = await fetch(url, { signal: AbortSignal.timeout(20000) }); const j = await r.json();
if (!Array.isArray(j.result)) { if (/no transactions/i.test(String(j.message || ''))) break; throw new Error(String(j.result || j.message || 'etherscan')); }
for (const x of j.result) {
const b = Number(x.blockNumber); if (b > maxBlock) maxBlock = b;
if (x.isError !== '0' || String(x.from).toLowerCase() !== addr || !x.value || x.value === '0') continue;
const to = String(x.to).toLowerCase(); if (skip.has(to)) continue;
count++; wei += BigInt(x.value); players.add(to);
}
if (j.result.length < 1000) break;
await sleep(400);
}
w.block = maxBlock; w.count = count; w.wei = wei.toString(); w.players = [...players]; delete w.error;
}
async function atRefresh() {
const W = wallets();
for (const [slug, addr] of Object.entries(W)) { try { await atScan(slug, addr); } catch (e) { (atLoad()[slug] || {}).error = e.message; } await sleep(400); }
atSave(); atAt = Date.now();
}
// { games: [{ slug, name, count, wei, players }], totals, at }; refreshed at most every 10 minutes, never blocks the page past 25 s
async function allTime() {
if (!KEY()) return { error: 'ETHERSCAN_KEY not set' };
if (Date.now() - atAt > 600000 && !atBusy) atBusy = atRefresh().finally(() => { atBusy = null; });
if (atBusy && !atAt) await Promise.race([atBusy, sleep(25000)]);
const st = atLoad(), W = wallets(), games = [];
for (const slug of Object.keys(W)) { const w = st[slug]; if (!w) continue; games.push({ slug, name: NAMES[slug] || slug, count: w.count, wei: w.wei, players: w.players.length, error: w.error || null }); }
games.sort((a, b) => (BigInt(b.wei) > BigInt(a.wei) ? 1 : -1));
return { games, at: atAt || null, scanning: !!atBusy };
}
module.exports = { init, handoff, gather, allTime, NAMES };
+72
View File
@@ -0,0 +1,72 @@
// Email intake for the help desk (2026-10-16): SendGrid Inbound Parse posts every message sent to the support hosts
// (support@help.instantadpay.com, reply+<ref>@help.instantadpay.com, anything @linkspin.app) here as multipart/form-data.
// We turn it into a new ticket or a reply on an existing one (tickets.ingestEmail), after dropping robots: bounces,
// auto-replies, bulk mail and our own messages, so two autoresponders can never ping-pong. The URL carries a secret key
// (env SUPPORT_INBOUND_KEY); SendGrid retries anything that is not 2xx, so the route always answers 200 once the key passes.
'use strict';
let tickets = null, accounts = null;
function init(d) { tickets = d.tickets; accounts = d.accounts || null; }
const key = () => String(process.env.SUPPORT_INBOUND_KEY || '').trim();
// a small multipart reader: text fields only, files skipped (attachments are not kept yet)
function parseMultipart(buf, contentType) {
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || ''); if (!m) return {};
const boundary = Buffer.from('--' + (m[1] || m[2]).trim());
const out = {}; let pos = buf.indexOf(boundary);
while (pos >= 0) {
const next = buf.indexOf(boundary, pos + boundary.length); if (next < 0) break;
const part = buf.slice(pos + boundary.length + 2, next - 2); // skip CRLF after the boundary and before the next
const sep = part.indexOf('\r\n\r\n');
if (sep > 0) {
const head = part.slice(0, sep).toString('utf8');
const nm = /name="([^"]+)"/i.exec(head);
if (nm && !/filename=/i.test(head)) out[nm[1]] = part.slice(sep + 4).toString('utf8');
}
pos = next;
}
return out;
}
const header = (raw, name) => { const m = new RegExp('^' + name + ':\\s*([^\\r\\n]*(?:\\r?\\n[ \\t][^\\r\\n]*)*)', 'im').exec(raw || ''); return m ? m[1].replace(/\r?\n[ \t]+/g, ' ').trim() : ''; };
const addrOf = s => { const m = /<([^>]+)>/.exec(s || ''); return String(m ? m[1] : s || '').trim().toLowerCase(); };
const nameOf = s => { const m = /^\s*"?([^"<]*?)"?\s*</.exec(s || ''); return m ? m[1].trim() : ''; };
const ROBOT_FROM = /(mailer-daemon|postmaster|no-?reply|do-?not-?reply|bounce|notifications?@)/i;
// keep what the person wrote, not the quoted history under it
function stripQuoted(text) {
let t = String(text || '').replace(/\r\n/g, '\n');
const cuts = [/^On .{3,200}wrote:\s*$/m, /^-{2,}\s*Original Message\s*-{2,}/im, /^From:\s.+\n(?:Sent|Date):\s/m, /^_{10,}\s*$/m];
for (const re of cuts) { const m = re.exec(t); if (m) t = t.slice(0, m.index); }
return t.split('\n').filter(l => !/^\s*>/.test(l)).join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
const htmlToText = h => String(h || '').replace(/<(br|\/p|\/div)[^>]*>/gi, '\n').replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
const perSender = new Map(); // sender -> [timestamps], at most 20 messages an hour become tickets or replies
function flood(addr) { const now = Date.now(); const a = (perSender.get(addr) || []).filter(t => now - t < 3600000); a.push(now); perSender.set(addr, a); return a.length > 20; }
// returns a short outcome string for the log
async function handle(buf, contentType) {
const f = parseMultipart(buf, contentType);
const raw = f.headers || '';
const from = addrOf(f.from); if (!from || !/@/.test(from)) return 'no sender';
let rcpts = []; try { rcpts = (JSON.parse(f.envelope || '{}').to || []).map(addrOf); } catch (e) {}
if (!rcpts.length) rcpts = String(f.to || '').split(',').map(addrOf);
const auto = header(raw, 'Auto-Submitted'), prec = header(raw, 'Precedence');
if ((auto && !/^no$/i.test(auto)) || /bulk|junk|list/i.test(prec) || header(raw, 'X-Autoreply') || header(raw, 'X-Autorespond') || ROBOT_FROM.test(from)) return 'robot dropped: ' + from;
if (/@(instantadpay\.com|help\.instantadpay\.com|linkspin\.app)$/.test(from)) return 'own address dropped';
if (flood(from)) return 'flood dropped: ' + from;
// support@instantadpay.com is forwarded by NameSilo to iap-support@linkspin.app (its forwarder will not deliver to our own
// help. subdomain), so that one address means an InstantAdPay ticket even though it arrives on the LinkSpin host
const iapAlias = r => /^iap-support@linkspin\.app$/.test(r);
const platform = rcpts.some(r => /@linkspin\.app$/.test(r) && !iapAlias(r)) ? 'linkspin' : 'iap';
let subject = String(f.subject || '').replace(/\s+/g, ' ').trim();
const plus = rcpts.map(r => /^reply\+((?:iap|ls)-\d{4,9})@/.exec(r)).find(Boolean); // the reply-to we put on ticket mail
if (plus) { const ref = plus[1].toUpperCase(); if (!subject.toUpperCase().includes(ref)) subject = '[' + ref + '] ' + subject; }
const body = stripQuoted(f.text || htmlToText(f.html)) || '(empty message)';
const r = await tickets.ingestEmail({ from, name: nameOf(f.from), subject, text: body, platform, confirm: true,
// new tickets only from member emails (Marty 2026-10-24); LinkSpin-first members are InstantAdPay accounts too (lsinbound)
canOpen: accounts ? async addr => { try { return !!(await accounts.byEmail(addr)); } catch (e) { return true; } } : null,
messageId: header(raw, 'Message-ID'), inReplyTo: header(raw, 'In-Reply-To'), references: header(raw, 'References') });
if (r && r.error) return 'refused: ' + r.error;
return (r.created ? 'new ticket ' : 'reply on ') + (r.ticket && r.ticket.ref) + ' from ' + from;
}
module.exports = { init, key, handle, stripQuoted, parseMultipart };
+76
View File
@@ -0,0 +1,76 @@
// Knowledge-base seeds that are not CANNED fast-path answers (kb.js): the public FAQ on the home page,
// the Platform Facts page (/facts), the wallets guide's Common questions, and support replies worth
// keeping. An entry here that nobody has edited in Admin > Knowledge base is refreshed when its text
// changes in this file; edit it in the admin pane and it becomes the admin's own.
// House rules: plain words, no em dashes, never a promise of income.
const FAQ = [
{ id: 'f-coinbase', title: 'Can I use my regular Coinbase account?', source: 'ticket',
questions: ['Can I use my regular Coinbase account?', 'Can I use Coinbase?', 'Can I connect my Coinbase exchange account?', 'How do I connect Coinbase?', 'Can I pay from my exchange account?'],
tags: ['coinbase', 'exchange account', 'connect coinbase', 'wallet', 'safepal'],
answer: 'Your regular Coinbase account won\'t connect here. Coinbase is an exchange: they hold the crypto for you, which works for buying and selling. InstantAdPay runs on a smart contract on Polygon, and to buy a package or receive payouts you sign that contract yourself, which only a wallet you control can do. You don\'t need Coinbase Wallet; we recommend SafePal (free, phone app or desktop browser extension). Install it, write down your recovery phrase, add Polygon (POL) and copy your address, send POL from Coinbase choosing the Polygon network (send a small test first), then open instantadpay.com in SafePal\'s browser (or the browser with the extension), sign in with your email and tap Link wallet (one free signature). You only need a wallet to buy a package or receive payouts.' },
{ id: 'f-how-fast', title: 'How fast do I really get paid?', source: 'faq',
questions: ['How fast do I get paid?', 'When does my commission arrive?', 'Is there an approval step for payouts?'],
tags: ['payout', 'speed', 'same transaction', 'ledger'],
answer: 'Payouts happen inside the very transaction that pays for the package. There is no approval step and nobody holding funds. Your share lands in your own wallet the moment your referral\'s purchase confirms, and the public ledger at https://instantadpay.com/ledger lets you watch each one go through.' },
{ id: 'f-what-buying', title: 'What am I actually buying?', source: 'faq',
questions: ['What am I actually buying?', 'What is the product?', 'Do bigger packages give bonus credits?'],
tags: ['product', 'ad delivery', 'credits', 'packages'],
answer: 'You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy. The $5 package mints 500 credits, and the bigger packages mint bonus credits on top, up to 70,000 on the $500 package. Earnings only come from referring people who also buy real ad delivery, and the contract splits every purchase automatically. Nothing is a promise of income.' },
{ id: 'f-refunds', title: 'Refunds', source: 'faq',
questions: ['Can I get a refund?', 'Is my purchase refundable?', 'Can a POL payment be reversed or charged back?', 'What happens if my campaign fails to deliver?'],
tags: ['refund', 'chargeback', 'reverse payment', 'final'],
answer: 'Payments are on-chain and final: a POL payment cannot be reversed, charged back or refunded to a wallet. Unused credits stay in your balance until you spend them. If a campaign fails to deliver because of a platform problem, the platform may return the affected credits to your balance, labeled as returned purchased credits.' },
{ id: 'f-credits-transfer', title: 'Can credits be transferred or turned into POL?', source: 'faq',
questions: ['Can I transfer credits to another member?', 'Can I give my credits to a friend?', 'Can I sell my credits or exchange them for POL?', 'Are credits a token?'],
tags: ['credits', 'transfer', 'cash value', 'token'],
answer: 'No. Credits are advertising credit, not currency. They cannot be transferred between members and cannot be exchanged back into POL or cash. Purchased credits are recorded on-chain and burned as your campaigns spend them; earned credits (welcome, viewing, visits, promo codes) are kept by the site and labeled separately.' },
{ id: 'f-price-feed', title: 'How the POL price of a package is set', source: 'faq',
questions: ['How is the POL price calculated?', 'Why did the POL amount change?', 'What price feed do you use?'],
tags: ['price', 'chainlink', 'pol price', 'rate'],
answer: 'Prices are set in US dollars and paid in POL. The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon, so the POL amount moves with the market. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers. Any package price change waits 24 hours before it takes effect.' },
{ id: 'f-contract', title: 'The contract address and network', source: 'faq',
questions: ['What is the contract address?', 'Which network is the contract on?', 'Is the contract verified?', 'Can the split be changed?'],
tags: ['contract', 'address', 'polygonscan', 'verified', 'polygon'],
answer: 'InstantAdPay runs on Polygon mainnet (chain id 137). The contract is 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 and its source is verified and public. The percentages and qualification rules are constants in the code, there is no function that changes them, and the contract holds no member funds. The plain-language review is at https://instantadpay.com/contract and the reference facts at https://instantadpay.com/facts.' },
{ id: 'f-platform-share', title: 'Where the platform share goes', source: 'faq',
questions: ['Where does the 20 percent platform share go?', 'What are the platform wallets?', 'What happens to a share nobody qualifies for?'],
tags: ['platform', 'platform wallets', 'fees', 'pass-up'],
answer: 'The 20 percent platform share is two fixed 10 percent fees to platform wallet A (0x7627fc78876948ac9d95c1c9eb061e7d6d647b70) and B (0x8b7d33849a2c4d92c985be31e46dc564ba901ad2). Platform income pays for operations, development, marketing and the game rewards. If nobody within 25 steps qualifies for a level, that share goes to wallet A, and every pass-up is recorded on-chain with the reason. Overpayment is returned to the buyer in the same transaction.' },
{ id: 'f-active-viewing', title: 'Why the video or timer paused', source: 'faq',
questions: ['Why did my video ad pause?', 'Why did the countdown stop?', 'Why was my view not counted?'],
tags: ['video', 'timer', 'countdown', 'paused', 'anti-fraud'],
answer: 'Viewing is active only: video ads pause when you switch tabs or the window loses focus, and viewing and visit timers only count while the page is in front. The server also checks the elapsed time, so a view cannot be credited early. Keep the tab in front until the countdown finishes and pass the quick check.' },
{ id: 'f-game-rewards', title: 'Where game POL rewards come from', source: 'faq',
questions: ['Where do the game rewards come from?', 'Are game rewards guaranteed?', 'Why did a game reward not pay?'],
tags: ['games', 'rewards', 'pool', 'pol'],
answer: 'The network games pay small POL rewards for gameplay milestones from game wallets and reward pools the company tops up from platform income (some games also fund a pool from in-game sales). Rewards are per action, paid while the pool covers them, and never guaranteed. You sign in to every game with your InstantAdPay account, so your sponsor carries across them.' },
{ id: 'f-not-investment', title: 'What InstantAdPay is not', source: 'faq',
questions: ['Is this an investment?', 'Is there guaranteed income?', 'Does InstantAdPay hold my money?'],
tags: ['investment', 'income', 'guarantee', 'custody', 'disclaimer'],
answer: 'InstantAdPay is an advertising platform with a referral program, not an investment, token sale or security. Credits are not a token and have no cash value. It does not hold member money: payments are split by the contract in the same transaction. And it is not a guarantee of income: referral payouts happen only when real advertising is bought in your line.' },
{ id: 'f-how-much-pol', title: 'How much POL do I need?', source: 'faq',
questions: ['How much POL do I need?', 'How much POL for fees?', 'What does a package cost in POL?'],
tags: ['pol', 'fees', 'gas', 'buy packages'],
answer: 'The Buy packages tab shows the live POL cost of each package. Have that plus 2 or 3 POL for network fees; there is no other cost. Trust Wallet users should keep about double, because Trust blocks a purchase that spends most of the wallet.' },
{ id: 'f-moonpay-declined', title: 'MoonPay declined my card', source: 'faq',
questions: ['Why did MoonPay decline my card?', 'My card was refused buying POL', 'MoonPay will not take my payment'],
tags: ['moonpay', 'card', 'declined', 'buy pol'],
answer: 'Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy POL on an exchange and withdraw it to your own wallet on the Polygon network. MoonPay is an independent provider with its own fees, limits and a first-time ID check.' },
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
tags: ['wallet', 'position', 'qualified start', 'metamask'],
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
answer: 'Coinbase, Kraken, Binance and most exchanges sell POL. Withdraw it to your own wallet address and pick the Polygon network on the withdrawal screen, never MATIC on Ethereum or another chain. Sending on the wrong network can lose the funds, so send a small test first.' },
{ id: 'f-recovery-phrase', title: 'Recovery phrase and scam safety', source: 'faq',
questions: ['Someone asked for my recovery phrase', 'Will support ever ask for my private key?', 'Someone messaged me asking for money'],
tags: ['recovery phrase', 'private key', 'scam', 'security'],
answer: 'Never share your recovery phrase or private key with anyone. Nobody from InstantAdPay will ever ask for them, and nobody from InstantAdPay will message you first asking for money or wallet access. If someone does, do not reply, and tell support through Help at https://instantadpay.com/my#help.' },
{ id: 'f-conv-thankyou', title: 'Conversion tracking with Aweber or GetResponse', source: 'faq',
questions: ['How do I track sign-ups from my ads?', 'Where do I put the goal pixel?', 'How do I use conversion tracking with Aweber?', 'How do I use conversion tracking with GetResponse?', 'My autoresponder thank-you page is not mine, can I still track?'],
tags: ['conversion tracking', 'goal pixel', 'landing tag', 'aweber', 'getresponse', 'thank you page', 'autoresponder'],
answer: 'Open Campaigns > Conversion tracking, add a goal (like subscriber), then copy its two snippets: the landing tag goes on the page your ad points to, the goal pixel on your thank-you page. Set your autoresponder\'s thank-you (success) page to a page on YOUR site that carries the goal pixel. Aweber: in your sign-up form settings, choose \'Thank You Page: custom page\' and paste your page\'s address. GetResponse: in the form or landing page settings, pick \'Thank-you page: custom URL\' and paste your page\'s address. If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. Use Send a test conversion to check the pixel; tests never count in your numbers.' },
];
module.exports = { FAQ };
+280
View File
@@ -0,0 +1,280 @@
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
// The chatbot answers from maintained entries, and good support replies become entries.
//
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
// updated, created, edited, deleted, seedHash }
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
// path serves the new text.
// source canned | faq | ticket | admin
//
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
//
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
//
// Dual store like the other modules: MySQL table kb_entries when DATABASE_URL is set, else
// DATA_DIR/kb.json (local dev and the QA harness).
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const db = require('./db');
let DATA_DIR = null, SEEDS = [], ready = null;
let cache = null, cacheAt = 0, index = null;
const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
function stem(w) {
if (SYN[w]) return SYN[w];
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
return w;
}
function words(text) {
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
}
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
function terms(text) {
const w = words(text), out = w.slice();
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
return out;
}
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
const K1 = 1.2, B = 0.75;
function fieldText(e, f) {
if (f === 'questions') return (e.questions || []).join(' . ');
if (f === 'tags') return (e.tags || []).join(' . ');
return e[f] || '';
}
function buildIndex(entries) {
const docs = entries.map(e => {
const d = { e, f: {} };
for (const f of Object.keys(FIELDS)) {
const t = terms(fieldText(e, f)), tf = new Map();
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
d.f[f] = { tf, len: t.length };
}
return d;
});
const df = new Map(), avg = {};
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
for (const d of docs) {
const seen = new Set();
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
}
return { docs, df, avg, n: docs.length };
}
function rank(idx, query, k) {
if (!idx || !idx.n) return [];
const qt = [...new Set(terms(query))];
if (!qt.length) return [];
const out = [];
for (const d of idx.docs) {
let s = 0;
for (const t of qt) {
const n = idx.df.get(t); if (!n) continue;
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
for (const f of Object.keys(FIELDS)) {
const tf = d.f[f].tf.get(t); if (!tf) continue;
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
}
}
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
}
out.sort((a, b) => b.score - a.score);
return out.slice(0, k || 5);
}
// keep hits that are close to the best one, and only when the best is a real match
const MIN_SCORE = 3;
function relevant(hits) {
if (!hits.length || hits[0].score < MIN_SCORE) return [];
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
return hits.filter(h => h.score >= floor);
}
// ---------------------------------------------------------------- store
const row = r => ({ id: r.id, title: r.title, questions: parse(r.questions, []), answer: r.answer, tags: parse(r.tags, []), pattern: r.pattern || '',
handoff: !!r.handoff, order: r.ord == null ? null : Number(r.ord), source: r.source, ticketRef: r.ticket_ref || '', seedHash: r.seed_hash || '',
edited: !!r.edited, deleted: !!r.deleted, created: Number(r.created), updated: Number(r.updated) });
function parse(s, d) { try { const v = JSON.parse(s || ''); return Array.isArray(v) ? v : d; } catch (e) { return d; } }
const D = {
async ensure() {
await db.q(`CREATE TABLE IF NOT EXISTS kb_entries (
id VARCHAR(64) PRIMARY KEY,
title VARCHAR(200) NOT NULL,
questions TEXT NULL,
answer TEXT NOT NULL,
tags VARCHAR(800) NULL,
pattern TEXT NULL,
handoff TINYINT NOT NULL DEFAULT 0,
ord INT NULL,
source VARCHAR(16) NOT NULL DEFAULT 'admin',
ticket_ref VARCHAR(20) NULL,
seed_hash CHAR(40) NULL,
edited TINYINT NOT NULL DEFAULT 0,
deleted TINYINT NOT NULL DEFAULT 0,
created BIGINT NOT NULL,
updated BIGINT NOT NULL,
INDEX (deleted, updated)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
},
async all() { return (await db.q('SELECT * FROM kb_entries')).map(row); },
async put(e) {
await db.q(`INSERT INTO kb_entries (id,title,questions,answer,tags,pattern,handoff,ord,source,ticket_ref,seed_hash,edited,deleted,created,updated)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), questions=VALUES(questions), answer=VALUES(answer), tags=VALUES(tags),
pattern=VALUES(pattern), handoff=VALUES(handoff), ord=VALUES(ord), source=VALUES(source), ticket_ref=VALUES(ticket_ref), seed_hash=VALUES(seed_hash),
edited=VALUES(edited), deleted=VALUES(deleted), updated=VALUES(updated)`,
[e.id, e.title, JSON.stringify(e.questions || []), e.answer, JSON.stringify(e.tags || []), e.pattern || null, e.handoff ? 1 : 0, e.order == null ? null : e.order,
e.source, e.ticketRef || null, e.seedHash || null, e.edited ? 1 : 0, e.deleted ? 1 : 0, e.created, e.updated]);
}
};
const J = {
file: () => path.join(DATA_DIR, 'kb.json'),
async ensure() {},
async all() { try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
async put(e) {
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
if (i >= 0) all[i] = e; else all.push(e);
const tmp = J.file() + '.tmp';
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
fs.renameSync(tmp, J.file());
}
};
const store = () => db.enabled() ? D : J;
// ---------------------------------------------------------------- seeds
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
function seedEntry(s) {
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
order: s.order == null ? null : s.order, source: s.source || 'faq' };
}
async function syncSeeds() {
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
const seedIds = new Set(SEEDS.map(s => s.id));
let added = 0, refreshed = 0, retired = 0;
for (const s of SEEDS) {
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
}
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
}
function init(opts) {
DATA_DIR = opts.dataDir; SEEDS = opts.seeds || []; cache = null; index = null;
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
return ready;
}
async function load(force) {
if (ready) await ready;
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
const all = await store().all();
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear();
return cache;
}
const rx = new Map();
function compiled(src) {
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
return rx.get(src);
}
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
// ---------------------------------------------------------------- the chatbot side
async function fastPath(msg) {
const list = (await load()).filter(e => e.pattern).sort(byOrder);
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
return null;
}
async function search(query, k) { await load(); return rank(index, query, k || 5); }
async function context(query, k) { return relevant(await search(query, k || 5)); }
const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)';
function promptBlock(hits) {
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
}
// ---------------------------------------------------------------- the admin side
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
function validate(o, cur) {
o = o || {};
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
const answer = clean(o.answer).slice(0, 4000);
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
if (!title) return { error: 'Give the entry a title or at least one question.' };
if (!answer) return { error: 'The answer is empty.' };
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
}
async function list(q) {
const all = (await load(true)).slice();
if (!q) return all.sort((a, b) => b.updated - a.updated);
const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry));
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
return ranked.concat(plain);
}
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
async function create(o) {
const v = validate(o); if (v.error) return v;
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
await store().put(e); await load(true);
return { ok: true, entry: e };
}
async function update(id, o) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
const v = validate(o, cur); if (v.error) return v;
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
await store().put(e); await load(true);
return { ok: true, entry: e };
}
async function remove(id) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true);
return { ok: true };
}
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
// KNOWLEDGE_DATE already speaks for the code.
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
async function stamp() {
const all = await load();
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
return { updated: max ? ctDay(max) : '', count: all.length };
}
async function test(question) {
const fast = await fastPath(String(question || ''));
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
}
module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
+218
View File
@@ -0,0 +1,218 @@
// The Refuel Kit (Fuel Your Offers stage 3, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
// LinkSpin; each site keeps ITS OWN program's kits (InstantAdPay art promotes InstantAdPay, LinkSpin art promotes
// LinkSpin, never mixed).
//
// A kit is one month's members-only banner set: { month 'YYYY-MM', theme, released, sizes 728x90 300x250 468x60 160x600
// 1200x630 } with one base image per size, stored as data in DATA_DIR/kits/ (kits.json + <month>/<size>.<ext>).
// Admin uploads the base art and previews the personalization; nothing here generates art (real art is Marty's).
//
// Who gets which kit: a counted refuel (the streak in refuel.js, InstantAdPay is the source of truth) unlocks the kit
// of the Central-time month it landed in. The entitlement arrives as { months: { 'YYYY-MM': streakMonthAtUnlock } }
// from opts.entitled(email). Kits stay usable after their month; missing a refuel only stops NEW kits.
// streak month 3+ at unlock an animated GIF version of each banner size
// streak month 6+ at unlock a "custom banners" credit for BannerKitAI: the entitlement and a note only, no integration
//
// Personalized on the server per member: their @username and a QR code to their own link are drawn onto each banner
// with ffmpeg (the badge renderer's approach). Rendered files are cached in DATA_DIR/kits/out/<hash>.<ext> and served
// publicly at /kitimg/<hash>.<ext> (ad networks and IAP banner campaigns load them by URL); the hash is an HMAC of
// member + kit + size + variant + base-art version, so it cannot be guessed and changes when the art changes.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { spawn } = require('child_process');
const SIZES = { '728x90': [728, 90], '300x250': [300, 250], '468x60': [468, 60], '160x600': [160, 600], '1200x630': [1200, 630] };
const ORDER = ['728x90', '300x250', '468x60', '160x600', '1200x630'];
// where the QR and the name go on each size: q = QR box (x, y, side), t = name (x expr, y expr, font px)
const LAYOUT = {
'728x90': { q: ['W-84', 6, 78], t: ['W-96-tw', 'H-30', 18] },
'468x60': { q: ['W-58', 4, 52], t: ['W-68-tw', 'H-24', 14] },
'300x250': { q: ['W-82', 'H-82', 76], t: ['8', 'H-30', 16] },
'160x600': { q: ['(W-120)/2', 'H-128', 120], t: ['(W-tw)/2', 'H-160', 16] },
'1200x630': { q: ['W-212', 'H-212', 182], t: ['32', 'H-66', 34] },
};
let X = {}, DIR = null, OUT = null, FILE = null, SALT = null;
const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
const norm = e => String(e || '').trim().toLowerCase();
function init(opts) {
X = opts || {}; DIR = path.join(X.dataDir, 'kits'); OUT = path.join(DIR, 'out'); FILE = path.join(DIR, 'kits.json');
try { fs.mkdirSync(OUT, { recursive: true }); } catch (e) {}
const sf = path.join(DIR, 'salt'); try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (e) {}
if (!SALT) { SALT = crypto.randomBytes(16).toString('hex'); try { fs.writeFileSync(sf, SALT, { flag: 'wx' }); } catch (e) { try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (er) {} } }
}
const program = () => X.program === 'linkspin' ? 'linkspin' : 'iap';
const brand = () => program() === 'linkspin' ? 'LinkSpin' : 'InstantAdPay';
function load() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.kits = s.kits || {}; s.credits = s.credits || {}; return s; } catch (e) { return { kits: {}, credits: {} }; } }
function save(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s, null, 1)); fs.renameSync(tmp, FILE); }
const ctMonth = ts => new Date(ts || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }).slice(0, 7);
const monthLabel = m => new Date(Date.UTC(Number(m.slice(0, 4)), Number(m.slice(5, 7)) - 1, 15)).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
// ---- admin: the kits ---------------------------------------------------------------------------------
function baseFile(month, size) {
const d = path.join(DIR, month);
for (const ext of ['png', 'jpg', 'gif']) { const f = path.join(d, size + '.' + ext); if (fs.existsSync(f)) return f; }
return null;
}
function kitView(k) {
const sizes = ORDER.map(s => { const f = baseFile(k.month, s); return { size: s, ready: !!f, v: f ? Math.round(fs.statSync(f).mtimeMs) : 0 }; });
return { month: k.month, label: monthLabel(k.month), theme: k.theme || '', released: !!k.released, program: program(), sizes, complete: sizes.every(x => x.ready), updated: k.updated || 0 };
}
function listKits() { const s = load(); return Object.values(s.kits).sort((a, b) => b.month.localeCompare(a.month)).map(kitView); }
function saveKit(b) {
const month = String(b.month || ''); if (!MONTH_RE.test(month)) return { error: 'Month as YYYY-MM.' };
const s = load(); const k = s.kits[month] || { month, theme: '', released: false, created: Date.now() };
if (b.theme != null) k.theme = String(b.theme).trim().slice(0, 80);
if (b.released != null) {
if (b.released && !kitView(k).complete) return { error: 'Upload all five sizes before releasing the kit.' };
k.released = !!b.released;
}
if (b.remove) { delete s.kits[month]; save(s); return { ok: true, removed: true }; }
k.updated = Date.now(); s.kits[month] = k; save(s);
return { ok: true, kit: kitView(k) };
}
const MAGIC = { png: b => b[0] === 0x89 && b[1] === 0x50, jpg: b => b[0] === 0xff && b[1] === 0xd8, gif: b => b.slice(0, 3).toString() === 'GIF' };
function uploadBase(month, size, buf, mime) {
if (!MONTH_RE.test(String(month))) return { error: 'Month as YYYY-MM.' };
if (!SIZES[size]) return { error: 'Size must be one of ' + ORDER.join(', ') + '.' };
const ext = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' }[String(mime || '').split(';')[0].trim()];
if (!ext || !buf || buf.length < 32 || !MAGIC[ext](buf)) return { error: 'Use a PNG, JPG or GIF file.' };
const d = path.join(DIR, month); fs.mkdirSync(d, { recursive: true });
for (const e of ['png', 'jpg', 'gif']) { try { fs.unlinkSync(path.join(d, size + '.' + e)); } catch (er) {} }
fs.writeFileSync(path.join(d, size + '.' + ext), buf);
const s = load(); if (!s.kits[month]) s.kits[month] = { month, theme: '', released: false, created: Date.now() }; s.kits[month].updated = Date.now(); save(s);
return { ok: true, kit: kitView(s.kits[month]) };
}
// placeholder art for tests and previews: the program's existing banners from public/banners (no paid image APIs)
function usePlaceholder(month) {
const pre = program() === 'linkspin' ? 'linkspin-' : 'iap-';
const pick = { '728x90': [pre + '728x90.png'], '300x250': [pre + '300x250.png'], '468x60': [pre + '468x60.png'], '160x600': [pre + '160x600.png'],
'1200x630': program() === 'linkspin' ? ['linkspin-og-1200x630.png'] : ['iap-hero-1200x630.png', 'iap-advertise-earn-1200x630.jpg'] };
const done = [];
for (const size of ORDER) {
const f = pick[size].map(n => path.join(X.publicDir, 'banners', n)).find(p => fs.existsSync(p)); if (!f) continue;
const buf = fs.readFileSync(f); const r = uploadBase(month, size, buf, /\.jpg$/.test(f) ? 'image/jpeg' : 'image/png'); if (r.ok) done.push(size);
}
return { ok: true, sizes: done, kit: kitView(load().kits[month] || { month }) };
}
// ---- the renderer ---------------------------------------------------------------------------------------
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 (/bold\.ttf$/i.test(e.name) || /DejaVuSans-Bold\.ttf$/.test(e.name)) 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 run(args, cwd) {
return new Promise(resolve => {
const p = spawn(X.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'], cwd });
const out = []; let err = '';
p.stdout.on('data', c => out.push(c)); p.stderr.on('data', c => { err += c; });
p.on('error', e => resolve({ code: -1, err: e.message })); p.on('close', code => resolve({ code, out: Buffer.concat(out), err }));
});
}
// one personalized banner: base scaled to the exact size, QR (white quiet zone) and @name on a dark box
async function renderStill(base, size, name, link, stage, outFile) {
const [W, H] = SIZES[size]; const L = LAYOUT[size]; const F = font();
if (!F) return { error: 'No font for the renderer.' };
const qr = X.qrcode || require('qrcode'); // opts.qrcode: a test copy without node_modules
const qrFile = outFile + '.qr.png';
await qr.toFile(qrFile, link, { margin: 1, width: L.q[2], errorCorrectionLevel: 'M', color: { dark: '#000000', light: '#ffffff' } });
const winPath = /:/.test(F); const fontFile = winPath ? path.basename(F) : F;
const ex = v => String(v).replace(/W/g, String(W)).replace(/H/g, String(H));
const tx = String(L.t[0]).replace(/W/g, String(W)).replace(/tw/g, 'text_w'); const ty = ex(L.t[1]);
const showName = stage !== 0, showQr = stage === undefined || stage === 2;
const chain = ['[0:v]scale=' + W + ':' + H + ':flags=lanczos,setsar=1[b]'];
let last = 'b';
if (showQr) { chain.push('[1:v]scale=' + L.q[2] + ':' + L.q[2] + '[q]'); chain.push('[' + last + '][q]overlay=x=' + ex(L.q[0]) + ':y=' + ex(L.q[1]) + '[o]'); last = 'o'; }
if (showName && name) { chain.push('[' + last + ']drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=white:fontsize=" + L.t[2] + ':box=1:boxcolor=0x0b1418@0.72:boxborderw=6:x=' + tx + ':y=' + ty + '[n]'); last = 'n'; }
const args = ['-v', 'error', '-y', '-i', path.resolve(base), '-i', path.resolve(qrFile), '-filter_complex', chain.join(';'), '-map', '[' + last + ']', '-frames:v', '1'];
if (/\.jpg$/.test(outFile)) args.push('-q:v', '3');
args.push(path.resolve(outFile));
const r = await run(args, winPath ? path.dirname(F) : undefined);
try { fs.unlinkSync(qrFile); } catch (e) {}
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'Render failed: ' + String(r.err || '').slice(0, 200) };
return { ok: true };
}
// the animated version (streak month 3+): the banner, then the name, then the name and the QR, looping
async function renderGif(base, size, name, link, outFile) {
const frames = [0, 1, 2].map(i => outFile + '.f' + i + '.png');
for (let i = 0; i < 3; i++) { const r = await renderStill(base, size, name, link, i, frames[i]); if (r.error) return r; }
const list = outFile + '.txt';
fs.writeFileSync(list, frames.map((f, i) => "file '" + path.resolve(f).replace(/\\/g, '/') + "'\nduration " + (i === 2 ? 3 : 1)).join('\n') + "\nfile '" + path.resolve(frames[2]).replace(/\\/g, '/') + "'\n");
const r = await run(['-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', list, '-filter_complex', 'split[a][b];[a]palettegen=max_colors=96[p];[b][p]paletteuse=dither=bayer', '-loop', '0', path.resolve(outFile)]);
for (const f of frames.concat(list)) { try { fs.unlinkSync(f); } catch (e) {} }
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'GIF render failed: ' + String(r.err || '').slice(0, 200) };
return { ok: true };
}
const hashOf = (email, month, size, variant, v) => crypto.createHmac('sha256', SALT).update([norm(email), program(), month, size, variant, v].join('|')).digest('hex').slice(0, 28);
function indexFile() { return path.join(OUT, 'index.json'); }
function noteIndex(h, meta) { let ix = {}; try { ix = JSON.parse(fs.readFileSync(indexFile(), 'utf8')); } catch (e) {} ix[h] = meta; const tmp = indexFile() + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(ix)); fs.renameSync(tmp, indexFile()); }
// render (or reuse) one personalized file; returns { url, file, size, variant, w, h, bytes }
async function personal(who, month, size, variant) {
const base = baseFile(month, size); if (!base) return { error: 'That kit has no ' + size + ' art yet.' };
const v = Math.round(fs.statSync(base).mtimeMs);
const ext = variant === 'gif' ? 'gif' : size === '1200x630' ? 'jpg' : 'png';
const h = hashOf(who.email, month, size, variant, v + '|' + who.name + '|' + who.link);
const out = path.join(OUT, h + '.' + ext);
if (!fs.existsSync(out)) {
const tmp = path.join(OUT, h + '.' + process.pid + '.' + Date.now() + '.' + ext);
let r; try { r = variant === 'gif' ? await renderGif(base, size, who.name, who.link, tmp) : await renderStill(base, size, who.name, who.link, undefined, tmp); } catch (e) { r = { error: 'The banner renderer is not available: ' + e.message }; }
if (r.error) return r;
try { fs.renameSync(tmp, out); } catch (e) { try { fs.unlinkSync(tmp); } catch (er) {} }
noteIndex(h, { email: norm(who.email), month, size, variant, ts: Date.now() });
}
const [w, hh] = SIZES[size];
return { ok: true, url: '/kitimg/' + h + '.' + ext, abs: String(X.siteUrl || '').replace(/\/+$/, '') + '/kitimg/' + h + '.' + ext, file: out, size, variant, w, h: hh, bytes: fs.statSync(out).size, ext };
}
// public serving: only files already rendered for an entitled member
function servePath(name) { const m = /^([a-f0-9]{28})\.(png|jpg|gif)$/.exec(String(name || '')); if (!m) return null; const f = path.join(OUT, m[0]); return fs.existsSync(f) ? { file: f, mime: { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[m[2]] } : null; }
// ---- the member ------------------------------------------------------------------------------------------
async function whoOf(email) {
const w = await X.linkFor(norm(email)); if (!w || !w.link) return null;
return { email: norm(email), name: w.username ? '@' + w.username : '', link: w.link };
}
async function myKits(email) {
const ent = (await X.entitled(norm(email)).catch(() => null)) || null;
if (!ent || !ent.on) return { on: false };
const s = load(); const months = ent.months || {};
const nowMonth = String(ent.today || '').slice(0, 7) || ctMonth(); // a kit released early still waits for its month
const kits = Object.values(s.kits).filter(k => k.released && k.month <= nowMonth).sort((a, b) => b.month.localeCompare(a.month)).slice(0, 12).map(k => {
const streakAt = months[k.month] || 0; const unlocked = streakAt > 0;
return Object.assign(kitView(k), { unlocked, streakAt, gif: unlocked && streakAt >= 3, custom: unlocked && streakAt >= 6 });
});
// the BannerKitAI "custom banners" credit: an entitlement on record, nothing more yet
const customMonths = Object.entries(months).filter(([, k]) => k >= 6).map(([m]) => m);
if (customMonths.length) {
const e = norm(email); const have = s.credits[e] || {}; let changed = false;
for (const m of customMonths) if (!have[m]) { have[m] = { ts: Date.now(), used: false }; changed = true; }
if (changed) { s.credits[e] = have; save(s); }
}
const credits = Object.entries((s.credits[norm(email)] || {})).map(([m, c]) => ({ month: m, used: !!c.used }));
const cur = nowMonth; const who = await whoOf(email).catch(() => null);
return { on: true, program: program(), brand: brand(), link: who ? who.link : null, name: who ? who.name : null, current: cur, currentLabel: monthLabel(cur), unlockedCurrent: !!months[cur],
kits, customCredits: credits, customNote: credits.length ? 'Custom banners made for your own offer with BannerKitAI are coming. Your credit is saved on your account and will be honored when it opens.' : null,
nextRefuel: ent.nextRefuel || null };
}
async function renderFor(email, month, size, variant) {
const mk = await myKits(email); if (!mk.on) return { error: 'The Refuel Kit is not switched on.' };
const k = mk.kits.find(x => x.month === month); if (!k) return { error: 'No such kit.' };
if (!k.unlocked) return { error: 'Your next counted refuel unlocks this kit.' };
if (!SIZES[size]) return { error: 'No such size.' };
if (variant === 'gif' && !k.gif) return { error: 'The animated version comes with a 3-month streak.' };
const who = await whoOf(email); if (!who) return { error: 'Set a username first, so your banners carry your own link.' };
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
}
async function preview(month, size, username, variant) {
const link = String(X.siteUrl || '').replace(/\/+$/, '') + '/join/' + (username || 'yourname');
const who = { email: 'preview@' + program(), name: '@' + (username || 'yourname'), link };
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
}
module.exports = { init, SIZES, ORDER, LAYOUT, listKits, saveKit, uploadBase, usePlaceholder, myKits, renderFor, preview, servePath, ctMonth, monthLabel, font };
+1 -1
View File
@@ -141,7 +141,7 @@ async function renderPage() {
const w = winners();
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
h += '</div><script src="/assets/common.js?v=20261015a"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
h += '</div><script src="/assets/common.js?v=20261023ov"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
return h;
}
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
+61
View File
@@ -0,0 +1,61 @@
// Login-ad showings per day per surface (Marty, 2026-10-18). The sign-in interstitial now runs on
// the dashboard AND inside the games' sign-in kit; before raising the 3-slot cap he wants a week of
// combined numbers. One row per Central day, surface ('dashboard' or a game slug) and kind:
// 'member' (a member's slot was shown), 'house' (the house login ad), 'none' (a sign-in with no
// login ad to show). MySQL table login_shows when the DB is on, else DATA_DIR/login-shows.json.
'use strict';
const fs = require('fs');
const path = require('path');
const db = require('./db');
let DATA_DIR = null, J = null, ready = null;
const ctDay = t => new Date(t === undefined ? Date.now() : t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const FILE = () => path.join(DATA_DIR, 'login-shows.json');
function init(opts) { DATA_DIR = opts.dataDir; }
function ensure() {
if (!ready) ready = db.q(`CREATE TABLE IF NOT EXISTS login_shows (
day VARCHAR(10) NOT NULL, surface VARCHAR(40) NOT NULL, kind VARCHAR(10) NOT NULL, n INT NOT NULL DEFAULT 0,
PRIMARY KEY (day, surface, kind)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`).catch(e => { ready = null; throw e; });
return ready;
}
function load() { if (J) return J; try { J = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { J = {}; } return J; }
// surface: 'dashboard' | game slug; ad: what ads.serve returned (null = nothing to show)
async function record(surface, ad) {
const s = String(surface || 'dashboard').toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 40) || 'dashboard';
const kind = !ad ? 'none' : ad.house ? 'house' : 'member';
const d = ctDay();
try {
if (db.enabled()) {
await ensure();
await db.q('INSERT INTO login_shows (day,surface,kind,n) VALUES (?,?,?,1) ON DUPLICATE KEY UPDATE n=n+1', [d, s, kind]);
} else {
const k = d + '|' + s + '|' + kind, st = load();
st[k] = (st[k] || 0) + 1;
fs.writeFileSync(FILE(), JSON.stringify(st));
}
} catch (e) { console.error('login shows', e.message); }
}
// last `days` Central days, newest first: { day, dashboard: {member,house,none}, games: {member,house,none}, byGame: {slug: shown} }
async function report(days) {
days = Math.max(1, Math.min(90, Number(days) || 14));
const since = ctDay(Date.now() - (days - 1) * 86400000);
let rows = [];
if (db.enabled()) {
await ensure();
rows = (await db.q('SELECT day, surface, kind, n FROM login_shows WHERE day>=?', [since])).map(r => ({ day: String(r.day), surface: r.surface, kind: r.kind, n: Number(r.n) }));
} else {
for (const [k, n] of Object.entries(load())) { const [day, surface, kind] = k.split('|'); if (day >= since) rows.push({ day, surface, kind, n }); }
}
const out = {};
const blank = () => ({ member: 0, house: 0, none: 0 });
for (let i = 0; i < days; i++) { const d = ctDay(Date.now() - i * 86400000); out[d] = { day: d, dashboard: blank(), games: blank(), byGame: {} }; }
for (const r of rows) {
const o = out[r.day]; if (!o || !['member', 'house', 'none'].includes(r.kind)) continue;
if (r.surface === 'dashboard') o.dashboard[r.kind] += r.n;
else { o.games[r.kind] += r.n; if (r.kind !== 'none') o.byGame[r.surface] = (o.byGame[r.surface] || 0) + r.n; }
}
return Object.values(out).sort((a, b) => (a.day < b.day ? 1 : -1));
}
module.exports = { init, record, report };
+176
View File
@@ -0,0 +1,176 @@
// Conversion tracking, InstantAdPay half (Marty approved 2026-10-23). LinkSpin owns goals and conversions;
// this module does three things:
// record(click) every click through /api/ads/click/:id gets an id ('i' + 11 hex) that rides on the target URL as
// ?lsclk=<id>, and the click row is stored here (MySQL ad_clicks, or a capped JSON file locally)
// flush loop unpushed rows go to LinkSpin POST /api/partner/clicks every ~3 s, 500 per request, signed exactly
// like lssync.js (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET). A row is marked pushed only
// after LinkSpin answers ok, so a failure keeps it for the next try (backoff up to 5 minutes).
// LinkSpin upserts by id, so two app copies pushing the same rows during a deploy is harmless.
// conv(email,..) the member's goals and summary through POST /api/partner/conv (op summary/create/update/remove/test),
// summary cached 60 s per email.
// owners (2026-10-26) the soft keys members sign in from ride on the click push, so LinkSpin keeps a member's own
// clicks (ads here, spin links and Banner Spins there) as tests, never counted
// No LS_SYNC_SECRET (or shorter than 32 chars): clicks still get ids and rows, nothing is sent.
// The raw IP is never stored: only the soft key 's:' + sha256(ip + '|' + ua) first 20 hex, same on both sites.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
const stats = { pushed: 0, lastAt: null, lastError: null, errors: 0 };
const cache = new Map(); // email -> { at, data }
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
const on = () => SECRET().length >= 32;
const useDb = () => !!(R && R.db && R.db.enabled());
const JCAP = 5000;
const JFILE = () => path.join(R.dataDir, 'adclicks.json');
function init(deps) {
R = deps;
if (useDb()) ensureTable().catch(e => console.error('lsconv table', e.message));
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 3000); if (timer.unref) timer.unref(); }
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
}
// column names checked against MySQL 8 reserved words (none of id, campaign_id, owner_email, cname, ctype, sk, country,
// device, placement, target, spent, is_self, ts, pushed is reserved)
async function ensureTable() {
await R.db.q(`CREATE TABLE IF NOT EXISTS ad_clicks (
id VARCHAR(16) PRIMARY KEY,
campaign_id INT NOT NULL,
owner_email VARCHAR(190) NOT NULL,
cname VARCHAR(80) NULL,
ctype VARCHAR(12) NULL,
sk VARCHAR(24) NULL,
country VARCHAR(4) NULL,
device VARCHAR(8) NULL,
placement VARCHAR(80) NULL,
target VARCHAR(500) NULL,
spent INT NOT NULL DEFAULT 0,
is_self TINYINT NOT NULL DEFAULT 0,
ts BIGINT NOT NULL,
pushed TINYINT NOT NULL DEFAULT 0,
INDEX (pushed, ts),
INDEX (campaign_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
}
// ---- helpers (pure) ----
const newId = () => 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(String(ip || '') + '|' + String(ua || '')).digest('hex').slice(0, 20);
const deviceOf = ua => /Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/i.test(String(ua || '')) ? 'mobile' : 'desktop';
function placementOf(referer) {
try { const u = new URL(String(referer || '')); if (!/^https?:$/.test(u.protocol)) return null; return (u.host.replace(/^www\./, '') + u.pathname.replace(/\/+$/, '')).replace(/[^\w.\-\/:]/g, '').slice(0, 80) || null; }
catch (e) { return null; }
}
// append lsclk=<id> without touching anything already in the URL (string insert keeps the original encoding of every
// existing param); an existing lsclk is never replaced; a URL that does not parse goes out unchanged
function withClickId(target, id) {
const t = String(target || '');
let u; try { u = new URL(t); } catch (e) { return t; }
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk')) return t;
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
}
// ---- own-click tests (Marty approved 2026-10-26) ----
// A member's own click is a test on LinkSpin, on every click type. LinkSpin knows the soft keys its members sign in from;
// InstantAdPay members may never sign in there, so the soft keys of their InstantAdPay sessions ride along with the click
// push as owners: [{ owner, sk, ts }] (no raw IP, same hash as the click rows). Queued at most once per 6 h per
// email + soft key; a failed push puts them back. Also checked here so an own click is flagged self=1 at the source.
const OWN_MS = 31 * 86400e3, ownSeen = new Map(); let ownQueue = new Map();
function noteSession(email, ip, ua) {
const e = String(email || '').trim().toLowerCase(); if (!e || e.length > 190) return false;
const sk = softKey(ip, ua); const k = e + '|' + sk; const now = Date.now();
if (now - (ownSeen.get(k) || 0) < 6 * 3600e3) return false;
ownSeen.set(k, now); if (ownSeen.size > 50000) ownSeen.delete(ownSeen.keys().next().value);
if (on()) { ownQueue.set(k, { owner: e, sk, ts: now }); if (ownQueue.size > 5000) ownQueue.delete(ownQueue.keys().next().value); }
return true;
}
function isOwnerSk(owner, sk) { const t = ownSeen.get(String(owner || '').toLowerCase() + '|' + sk); return !!(t && Date.now() - t <= OWN_MS); }
function takeOwners() { const out = [...ownQueue.values()].slice(0, 2000); for (const o of out) ownQueue.delete(o.owner + '|' + o.sk); return out; }
function requeueOwners(list) { for (const o of list || []) if (!ownQueue.has(o.owner + '|' + o.sk)) ownQueue.set(o.owner + '|' + o.sk, o); }
// ---- storage ----
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!Array.isArray(jstate.rows)) throw 0; } catch (e) { jstate = { rows: [] }; } return jstate; }
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 500); }
function jcap() { const st = jload(); if (st.rows.length <= JCAP) return; let drop = st.rows.length - JCAP; st.rows = st.rows.filter(r => !(drop > 0 && r.pushed && drop--)); if (st.rows.length > JCAP) st.rows = st.rows.slice(-JCAP); }
// c = the campaign (ads.campaignById shape); returns the stored row
async function record(c, req, opts) {
const o = opts || {};
const ip = o.ip || String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const ua = String(req.headers['user-agent'] || '');
const row = { id: newId(), camp: Number(c.id), cname: String(c.name || c.title || '').slice(0, 80) || null, type: String(c.type || '').slice(0, 12) || null,
owner: String(c.owner || '').toLowerCase(), ts: Date.now(), sk: softKey(ip, ua), c: o.country ? String(o.country).slice(0, 4) : null, dv: deviceOf(ua),
pl: placementOf(req.headers.referer), target: String(o.target || c.targetUrl || '').slice(0, 500), spent: Math.max(0, Math.round(Number(c.spent || 0) + Number(c.accrued || 0))), self: o.self ? 1 : 0 };
if (useDb()) {
await R.db.q('INSERT INTO ad_clicks (id, campaign_id, owner_email, cname, ctype, sk, country, device, placement, target, spent, is_self, ts, pushed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
[row.id, row.camp, row.owner, row.cname, row.type, row.sk, row.c, row.dv, row.pl, row.target, row.spent, row.self, row.ts]);
} else { const st = jload(); st.rows.push(Object.assign({ pushed: 0 }, row)); jcap(); jsave(); }
return row;
}
const fromDb = r => ({ id: r.id, camp: Number(r.campaign_id), cname: r.cname, type: r.ctype, owner: r.owner_email, ts: Number(r.ts), sk: r.sk, c: r.country, dv: r.device, pl: r.placement, target: r.target, spent: Number(r.spent) || 0, self: Number(r.is_self) ? 1 : 0 });
async function unpushed(n) {
if (useDb()) return (await R.db.q('SELECT * FROM ad_clicks WHERE pushed=0 ORDER BY ts LIMIT ?', [n])).map(fromDb);
return jload().rows.filter(r => !r.pushed).slice(0, n).map(r => { const x = Object.assign({}, r); delete x.pushed; return x; });
}
async function markPushed(ids) {
if (!ids.length) return;
if (useDb()) { await R.db.q('UPDATE ad_clicks SET pushed=1 WHERE id IN (?)', [ids]); return; }
const set = new Set(ids); for (const r of jload().rows) if (set.has(r.id)) r.pushed = 1; jsave();
}
async function prune() { // click rows only matter for the 30-day window; keep 120 days for questions
const cut = Date.now() - 120 * 86400e3;
if (useDb()) await R.db.q('DELETE FROM ad_clicks WHERE pushed=1 AND ts<?', [cut]);
else { const st = jload(); const n = st.rows.length; st.rows = st.rows.filter(r => !(r.pushed && r.ts < cut)); if (st.rows.length !== n) jsave(); }
}
// ---- LinkSpin calls ----
async function signedPost(pth, body, timeoutMs) {
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
const r = await fetch(URL_() + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 15000) });
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
if (!r.ok) { const e = new Error((j && j.error) || ('linkspin ' + r.status)); e.status = r.status; e.plain = !!(j && j.error); throw e; }
return j || {};
}
async function flush() {
if (!on() || flushing || Date.now() < nextAt) return { skipped: true };
flushing = true; let sent = 0;
try {
for (let round = 0; round < 20; round++) { // drain a backlog, 500 at a time; owners (own soft keys) ride on the first request
const rows = await unpushed(500); const owners = round === 0 ? takeOwners() : [];
if (!rows.length && !owners.length) break;
let res; try { res = await signedPost('/api/partner/clicks', { clicks: rows, owners }, 20000); } catch (e) { requeueOwners(owners); throw e; }
if (!res || res.ok !== true) { requeueOwners(owners); throw new Error('linkspin answered without ok'); }
if (rows.length) { await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now(); }
if (owners.length) stats.owners = (stats.owners || 0) + owners.length;
if (rows.length < 500) break;
}
fails = 0; nextAt = 0; return { sent };
} catch (e) {
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 3000 * Math.pow(2, Math.min(fails, 7)));
if (fails <= 3 || fails % 20 === 0) console.error('lsconv push', e.message);
return { error: e.message, sent };
} finally { flushing = false; }
}
// op summary is cached 60 s per email; any write clears that email's cache
async function summary(email, fresh) {
const e = String(email || '').toLowerCase();
const hit = cache.get(e); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.data;
const data = await signedPost('/api/partner/conv', { op: 'summary', email: e, days: 30 }, 8000);
cache.set(e, { at: Date.now(), data }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
return data;
}
async function goalOp(email, op, fields) {
const e = String(email || '').toLowerCase();
if (!['create', 'update', 'remove', 'test'].includes(op)) throw new Error('Unknown action.');
const body = Object.assign({ op, email: e }, fields || {});
const out = await signedPost('/api/partner/conv', body, 10000);
cache.delete(e); return out;
}
function adminView() { return { on: on(), url: URL_(), pushed: stats.pushed, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
module.exports = { init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on, noteSession, isOwnerSk };
+46 -9
View File
@@ -16,7 +16,15 @@
// then accounts.listAll leaves unclaimed shells out of every sweep that mails, counts or adopts members.
// - Loop guard: each email is muted in lssync while its row is applied, then lssync records the result as already
// pushed when it equals what LinkSpin sent, so it is not bounced back (see lssync.release). No-op rows change nothing.
// - SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row that carries a DELIBERATE change made on LinkSpin (sponsorSetBy
// adopt / rescue / release / expire / admin) is the one exception to the first-platform rule: it is applied, a clear
// back to the tank included, when the member is not bound on InstantAdPay's contract (no memberId, not on chain), the
// change is newer than our own deliberate change, and the two sides agreed before it (or we have no sponsor). Bound,
// diverged and race cases change nothing here and are logged for Admin > Members > Sponsor check. Applied quietly.
// - NETWORK TANK: a row's `tank` (LinkSpin's own adoptions of the person) is kept as remote state, so our waiting list
// hides someone adopted on LinkSpin and the two-adoptions limit counts both sites.
'use strict';
const SF = require('./sponsorfollow');
const fs = require('fs');
const path = require('path');
@@ -35,7 +43,7 @@ function load() {
}
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('lsinbound save', e.message); } }
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync }
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync, follow (sponsorfollow glue), store (sponsorfollow store) }
function clean(x) {
if (!x || typeof x !== 'object') return null;
@@ -44,9 +52,18 @@ function clean(x) {
const wallet = /^0x[0-9a-f]{40}$/.test(norm(x.wallet)) ? norm(x.wallet) : null;
let sponsorEmail = norm(x.sponsorEmail); if (!EMAIL_RE.test(sponsorEmail) || sponsorEmail === email) sponsorEmail = null;
const profile = x.profile && typeof x.profile === 'object' ? x.profile : null;
return { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
const out = { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
if (SF.isDeliberate(x.sponsorSetBy) && Number(x.sponsorSetAt) > 0) { // a deliberate change on LinkSpin (sponsorfollow.js)
out.sponsorSetAt = Number(x.sponsorSetAt); out.sponsorSetBy = String(x.sponsorSetBy);
const pv = norm(x.sponsorPrevEmail); out.sponsorPrevEmail = EMAIL_RE.test(pv) ? pv : null;
out.sponsorSetOrigin = norm(x.sponsorSetOrigin).replace(/[^a-z]/g, '').slice(0, 20) || 'linkspin';
}
if (Object.prototype.hasOwnProperty.call(x, 'tank')) out.tank = SF.cleanTank(x.tank); // null = LinkSpin has no adoption of them now
return out;
}
const tokenOf = a => a.username || a.code;
// released / rescued / expired back to the tank on purpose here: an ordinary row must not refill the sponsor (sponsorfollow.js)
const emptiedOnPurpose = email => { const pv = R.store && R.store.get(email); return !!(pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail); };
function conflict(sum, email, kind, detail) { sum.conflicts++; note({ type: 'conflict', email, kind, detail: String(detail || '').slice(0, 120) }); }
// would binding `email` under `sp` close a loop (sp already sits below email)?
@@ -94,7 +111,14 @@ async function place(email, depth, ctx) {
ctx.done.add(email); R.lssync.mute(email);
let a = await A.byEmail(email); let wrote = false;
if (!r) return a;
if (!a) {
const inc = SF.incomingOf(r);
if (a && inc && R.follow) {
// a deliberate sponsor change made on LinkSpin: the follow rule decides (never on a member bound here)
const d = await R.follow.applyIncoming(email, r, { sponsorAccount: em => sponsorAccount(em, depth, ctx) });
if (d.apply) { ctx.sum.followed++; wrote = true; delete s.pending[email]; note({ type: 'follow', email, by: r.sponsorSetBy, sponsor: r.sponsorEmail || null, action: d.action }); }
else if (d.action !== 'same' && d.action !== 'ordinary') { ctx.sum.followKept++; note({ type: 'follow-kept', email, by: r.sponsorSetBy, action: d.action, detail: String(d.reason || '').slice(0, 120) }); }
a = await A.byEmail(email);
} else if (!a) {
let tok = '';
if (r.sponsorEmail) {
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
@@ -104,7 +128,9 @@ async function place(email, depth, ctx) {
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
a = x.account;
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail) {
// a new waiting account built from a deliberate change carries the same record, so its row does not echo back
if (x.created && inc && R.store && (!r.sponsorEmail || tok)) R.store.record(email, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'linkspin' });
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail && !emptiedOnPurpose(email)) {
// our own waiting account, still without a sponsor: this row (or a later one) names one
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
if (sp && sp.email !== email && !(await wouldCycle(email, sp))) { await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; wrote = true; }
@@ -119,7 +145,7 @@ async function resolvePending(ctx) {
const s = load(); const A = R.accounts;
for (const [email, spEmail] of Object.entries(s.pending)) {
const a = await A.byEmail(email);
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef) { delete s.pending[email]; continue; } // claimed or bound meanwhile: leave it
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef || emptiedOnPurpose(email)) { delete s.pending[email]; continue; } // claimed, bound or emptied on purpose meanwhile: leave it
const sp = await sponsorAccount(spEmail, 0, ctx); if (!sp) continue;
if (sp.email === email || await wouldCycle(email, sp)) { delete s.pending[email]; conflict(ctx.sum, email, 'sponsor-cycle', spEmail); continue; }
R.lssync.mute(email); ctx.done.add(email);
@@ -129,9 +155,10 @@ async function resolvePending(ctx) {
}
async function handle(rows) {
const s = load(); s.stats.batches++;
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0 };
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
const ctx = { sum, done: new Set() }; const batch = [];
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
try {
for (const r of batch) {
try { await place(r.email, 0, ctx); }
@@ -141,9 +168,9 @@ async function handle(rows) {
} finally {
for (const email of ctx.done) await R.lssync.release(email, s.rows[email]); // loop guard: equal results are not echoed
}
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors']) s.stats[k] += sum[k];
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors', 'followed', 'followKept']) s.stats[k] = (s.stats[k] || 0) + sum[k];
s.last = Object.assign({ at: Date.now() }, sum); save();
return sum;
return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts
}
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
function receive(rows) { const run = chain_.then(() => handle(rows)); chain_ = run.catch(() => {}); return run; }
@@ -151,4 +178,14 @@ function adminView() {
const s = load();
return Object.assign({}, s.stats, { knownRows: Object.keys(s.rows).length, pendingSponsors: Object.keys(s.pending).length, last: s.last || null, lastError: s.stats.lastError || null, recent: s.log.slice(-25).reverse() });
}
module.exports = { init, receive, adminView };
// The holding tank asks (tank.js alignToNetwork, 2026-10-27): does LinkSpin already know a sponsor for this person?
// The newest row LinkSpin sent for the same email, else for the same wallet. LinkSpin's sponsorEmail is always a real
// member there (its sponsorRef; LinkSpin never writes the company fallback into an account). Read only.
function networkSponsor(email, address) {
if (!R) return null; const s = load(); const e = norm(email); const w = norm(address);
const r = s.rows[e];
if (r && r.sponsorEmail && r.sponsorEmail !== e) return { sponsorEmail: r.sponsorEmail, via: 'same email' };
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of Object.values(s.rows)) if (x.wallet === w && x.sponsorEmail && x.sponsorEmail !== e && x.email !== e) return { sponsorEmail: x.sponsorEmail, via: 'same wallet' };
return null;
}
module.exports = { init, receive, adminView, networkSponsor };
+23 -7
View File
@@ -5,8 +5,15 @@
// hash in DATA_DIR/lssync.json and only changed rows go, 100 per request. Catches anything touch() missed.
// LinkSpin upserts the rows and creates shell accounts with their sponsor line, so a new InstantAdPay member is already
// "waiting" on LinkSpin before they ever sign in there. Nothing here moves money; the registry is identity + line only.
//
// Sponsor follow (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail /
// sponsorSetOrigin while the account's sponsor is the result of a deliberate change (tank adoption, rescue, release,
// window expiry, admin edit), and `tank` (this site's own adoptions of the person: count + the open one, or null).
// Rows without those facts hash exactly as before, so nothing is resent on deploy. Until LinkSpin answers proto 2 the
// hash of a row carrying the new facts is not recorded, so it is sent again once LinkSpin runs the new code.
'use strict';
const crypto = require('crypto');
const SF = require('./sponsorfollow');
const fs = require('fs');
const path = require('path');
@@ -20,11 +27,16 @@ function load() { if (state) return state; try { state = JSON.parse(fs.readFileS
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
function init(deps) { R = deps; load(); }
async function rowFor(acct, byRef) {
async function rowFor(acct, byRef, tankMap) {
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
return { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
const row = { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
const T = R.tank && R.tank();
if (T) { try { row.tank = (tankMap ? tankMap.get(String(acct.email).toLowerCase()) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
return row;
}
const carriesNew = r => !!(r.sponsorSetBy || r.tank);
// the member's profile travels too (Marty 2026-10-11: no re-typing on LinkSpin; they can change it there later). Avatar as an
// absolute https URL so the other property can show it; socials as the parsed {platform: url} object.
const PUBLIC = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
@@ -36,7 +48,7 @@ function profileOf(a) {
if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null;
return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
}
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|')).digest('hex').slice(0, 16);
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16);
async function post(rows) {
const raw = JSON.stringify({ rows }); const ts = String(Date.now());
@@ -48,8 +60,9 @@ async function post(rows) {
async function push(rows) {
const st = load(); let sent = 0;
for (let i = 0; i < rows.length; i += 100) {
const chunk = rows.slice(i, i + 100); await post(chunk); sent += chunk.length;
for (const r of chunk) st.hashes[r.email] = hashOf(r);
const chunk = rows.slice(i, i + 100); const res = await post(chunk); sent += chunk.length;
const peerNew = Number(res && res.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1);
for (const r of chunk) { if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); } // an old LinkSpin ignored the new facts: send again later
}
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
}
@@ -65,7 +78,8 @@ async function tick(force) {
try {
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
const sent = rows.length ? await push(rows) : 0;
return { accounts: all.length, changed: rows.length, sent };
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
@@ -82,7 +96,9 @@ async function release(email, sent) {
const a = await R.accounts.byEmail(e);
if (a && sent) {
const r = await rowFor(a); const n = v => String(v || '').toLowerCase();
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail)) { load().hashes[e] = hashOf(r); save(); same = true; }
// a deliberate change from LinkSpin counts as the same only when we now carry that same record (applied, not refused)
const sameFollow = !sent.sponsorSetBy || (Number(r.sponsorSetAt) === Number(sent.sponsorSetAt) && String(r.sponsorSetBy) === String(sent.sponsorSetBy));
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail) && sameFollow) { load().hashes[e] = hashOf(r); save(); same = true; }
}
} catch (err) {}
if (pending.has(e) && !timer) { pending.delete(e); touch(e); } // a touch that queued while muted goes now (the hash check drops it when same)
+2
View File
@@ -44,6 +44,8 @@ async function send(to, subject, text, html, opts) { // html optional (2026-10-0
content
};
if (unsub) msg.headers = { 'List-Unsubscribe': '<' + unsub + '>', 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click' };
if (opts && opts.replyTo) msg.reply_to = { email: String(opts.replyTo) }; // help desk: replies thread back into the ticket
if (opts && opts.headers) msg.headers = Object.assign(msg.headers || {}, opts.headers);
const body = JSON.stringify(msg);
const req = https.request({ hostname: 'api.sendgrid.com', path: '/v3/mail/send', method: 'POST',
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
+12 -1
View File
@@ -133,4 +133,15 @@ async function topUp(nasAdId, addImpressions, days) {
return { ok: true };
}
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, impressionsPerCredit, nasKind };
// restart a STOPPED ad (deactivate zeroed `remaining`) with `addImpressions` more, re-basing `assigned` on the TRUE served
// count we recorded at the stop. A plain topUp would leave assigned - remaining = the whole old allocation, so the
// undelivered part would read back as served (the same trap as deactivate, one step later).
async function restart(nasAdId, trueServed, addImpressions, days) {
if (!enabled()) return { skipped: 'flag-off' };
const add = Math.max(0, Math.floor(Number(addImpressions) || 0)), base = Math.max(0, Math.floor(Number(trueServed) || 0));
await q(`UPDATE sponsorads SET assigned=?, remaining=?, approved=1, EDate=DATE_ADD(NOW(), INTERVAL ? DAY) WHERE ID=?`,
[base + add, add, Number(days || 30), Number(nasAdId)]);
return { ok: true };
}
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, restart, impressionsPerCredit, nasKind };
+366
View File
@@ -0,0 +1,366 @@
// Level-4 override (Marty, decided 2026-10-17, approved to build for real 2026-10-23; design in memory iap-level4-override):
// 3% of every purchase goes to the buyer's 4th upline on the CONTRACT sponsor chain when that member has 5+ qualifying
// buyers (the contract's own buyerCount, the same bar as level 3); an unqualified 4th upline is skipped and the hunt
// climbs (cap 25 hops, mirroring the contract's HOP_CAP). Exactly one recipient per purchase, so it never costs more than
// 3%; company ids (overrideHouseIds) keep it. Funded off-chain from the company's 20% and paid weekly with the contract's
// award(toMemberId) from a pre-funded payer wallet, purchases from overrideGoLive forward only (no back-pay).
//
// MODES (site setting overrideMode):
// 'off' nothing at all.
// 'dryrun' (default) the Monday who-would-be-paid report to Marty's private Telegram. No money moves.
// 'live' pays, but ONLY when overrideGoLive is set AND a payer key is present (env OVERRIDE_PAYER_KEY or
// OVERRIDE_PAYER_KEY_FILE). Missing either one: it reports as a dry run and says why it did not pay.
//
// MONEY SAFETY (why each piece exists):
// - Every "do this once" is a claim that only one running copy of the app can win: an exclusive file create on the
// shared volume (fs 'wx'), plus a row in event_marks when MySQL is on. A deploy runs two copies for ~30 s (the
// 2026-09-25 double Friday bonus); a claim that cannot be checked counts as LOST (fail closed), never as won.
// - A week's plan (who gets how much) is computed once, written to the volume and never recomputed, so a later read
// of buyer counts cannot change an amount that is already being paid.
// - A payout row is marked 'sending' on disk BEFORE the transaction is sent and gets its tx hash the moment the node
// accepts it. A row whose answer was lost is 'review': it is never sent again automatically. The chain index can
// settle it (an AwardPaid from the payer wallet to that member for that exact amount), or the admin does.
// - Amounts under the dust minimum (overrideDustPol, default 0.01 POL) and pre-flight failures (award() would revert,
// no gas spent) are carried to the next week's plan.
// - Hard cap per week (overridePayCapPol, default 100 POL): a plan over the cap is held whole, nothing is sent.
// - The wallet must hold the week's total plus gas for every send, or nothing is sent and Marty is told.
// - Weeks are paid in order; a week that is held or needs review stops the later weeks until it is resolved.
'use strict';
const fs = require('fs');
const path = require('path');
let ethersLib = null; try { ethersLib = require('ethers'); } catch (e) { /* optional: the payer stays off without it */ }
const PCT = 3, MIN_BUYERS = 5, HOP_CAP = 25, LEVEL = 4;
const GAS_LIMIT = 150000n; // award(): reentrancy guard + member read + capped-gas send + event, ~60k; generous headroom
const WEI = 10n ** 18n;
// ---- Central-time week math (pure, shared by every instance) ----
const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
const CT_HOUR = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', hourCycle: 'h23' });
function weekOf(ts) { // the Monday (YYYY-MM-DD, Central) of the week holding ts
const parts = Object.fromEntries(CT.formatToParts(new Date(ts)).map(p => [p.type, p.value]));
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[parts.weekday];
return new Date(Date.UTC(+parts.year, +parts.month - 1, +parts.day - back)).toISOString().slice(0, 10);
}
const ctMidnight = day => { // ms at 00:00 America/Chicago on YYYY-MM-DD (CDT = UTC-5, CST = UTC-6)
for (const off of [5, 6]) { const t = Date.parse(day + 'T0' + off + ':00:00Z'); if (new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', hour: '2-digit', hourCycle: 'h23' }).format(new Date(t)) === '00') return t; }
return Date.parse(day + 'T05:00:00Z');
};
const addDays = (day, n) => new Date(Date.parse(day + 'T12:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const weekBounds = monday => ({ from: ctMidnight(monday), to: ctMidnight(addDays(monday, 7)) });
// the week may be settled from 9 AM Central on the Monday after it
const payableAt = monday => ctMidnight(addDays(monday, 7)) + 9 * 3600000;
const polStr = wei => { const w = BigInt(wei); const s = (w * 10000n / WEI).toString().padStart(5, '0'); return s.slice(0, -4) + '.' + s.slice(-4); };
const toWei = pol => { const [a, b = ''] = String(pol).trim().split('.'); return BigInt(a || '0') * WEI + BigInt((b + '0'.repeat(18)).slice(0, 18) || '0'); };
function create() {
let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null, db = null, now = () => Date.now();
let BRAND = 'InstantAdPay', SITE_URL = 'https://instantadpay.com', HOUSE_DEFAULT = '1', payerOverride = null;
const lastError = { at: 0, msg: '' };
function init(o) {
DATA_DIR = o.dataDir; chain = o.chain; siteConfig = o.siteConfig || siteConfig; notify = o.notify || null; db = o.db || null;
if (o.brand) BRAND = o.brand; if (o.siteUrl) SITE_URL = o.siteUrl; if (o.houseDefault) HOUSE_DEFAULT = String(o.houseDefault);
if (o.payer) payerOverride = o.payer; // tests: a fake signer, never the real chain
if (o.now) now = o.now;
}
const cfg = () => {
const s = siteConfig();
const num = (v, d) => { const n = Number(v); return v === undefined || v === '' || !isFinite(n) ? d : n; };
return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || HOUSE_DEFAULT).split(',').map(x => Number(x.trim())).filter(Boolean),
goLive: Number(s.overrideGoLive || 0), dustWei: toWei(Math.max(0, num(s.overrideDustPol, 0.01)).toFixed(18)), capWei: toWei(Math.max(0, num(s.overridePayCapPol, 100)).toFixed(18)) };
};
// ---- the payer wallet (OVERRIDE_PAYER_KEY; never logged, never returned) ----
function keyHex() {
let k = String(process.env.OVERRIDE_PAYER_KEY || '').trim();
if (!k && process.env.OVERRIDE_PAYER_KEY_FILE) { try { k = fs.readFileSync(process.env.OVERRIDE_PAYER_KEY_FILE, 'utf8').trim(); } catch (e) {} }
if (!k) return null; if (!k.startsWith('0x')) k = '0x' + k;
return /^0x[0-9a-fA-F]{64}$/.test(k) ? k : null;
}
let realPayer = null;
function payer() {
if (payerOverride) return payerOverride;
const k = keyHex(); if (!k || !ethersLib) return null;
if (realPayer) return realPayer;
const c = chain.getConfig(); const urls = (c.rpcs && c.rpcs.length) ? c.rpcs : [c.rpc]; let idx = 0;
const wallet = () => new ethersLib.Wallet(k, new ethersLib.JsonRpcProvider(urls[idx % urls.length], Number(c.chainId), { staticNetwork: true }));
const ctr = w => new ethersLib.Contract(chain.getConfig().contract, ['function award(uint32 toMemberId) payable'], w);
const address = new ethersLib.Wallet(k).address;
realPayer = {
address,
balance: async () => { try { return await wallet().provider.getBalance(address); } catch (e) { idx++; throw e; } },
fees: async () => { const g = await chain.suggestedFees(); return { maxPriorityFeePerGas: BigInt(g.maxPriorityFeePerGas), maxFeePerGas: BigInt(g.maxFeePerGas) }; },
// a revert here (unknown member, a wallet that refuses POL) costs nothing and sends nothing
preflight: async (id, wei) => { await ctr(wallet()).award.staticCall(Number(id), { value: BigInt(wei) }); },
send: async (id, wei, fees) => { const tx = await ctr(wallet()).award(Number(id), Object.assign({ value: BigInt(wei), gasLimit: GAS_LIMIT }, fees)); return { hash: tx.hash, wait: () => tx.wait(1) }; }
};
return realPayer;
}
function liveState() {
const c = cfg(), why = [];
if (c.mode !== 'live') why.push('overrideMode is ' + c.mode + ', not live');
if (!c.goLive) why.push('overrideGoLive is not set');
if (!payerOverride && !keyHex()) why.push('no payer key (OVERRIDE_PAYER_KEY)');
if (!payerOverride && !ethersLib) why.push('ethers is not installed');
return { ready: !why.length, why };
}
// ---- one-time claims, fail closed ----
const dir = (...p) => path.join(DATA_DIR, 'override', ...p);
const mkdirp = d => { try { fs.mkdirSync(d, { recursive: true }); } catch (e) {} };
const safe = k => String(k).replace(/[^a-zA-Z0-9_.:-]/g, '_').replace(/:/g, '__').slice(0, 150);
async function claim(key) {
if (db && db.enabled && db.enabled()) {
try { const r = await db.q('INSERT IGNORE INTO event_marks (k, ts) VALUES (?, ?)', ['ov:' + String(key).slice(0, 150), now()]); if (!(r && r.affectedRows === 1)) return false; }
catch (e) { lastError.at = now(); lastError.msg = 'claim ' + key + ': ' + e.message; return false; }
}
mkdirp(dir('claims'));
try { fs.closeSync(fs.openSync(dir('claims', safe(key)), 'wx')); return true; }
catch (e) { if (e.code !== 'EEXIST') { lastError.at = now(); lastError.msg = 'claim file ' + key + ': ' + e.message; } return false; }
}
const claimed = key => fs.existsSync(dir('claims', safe(key)));
// ---- payout store: one small JSON file per week header and per (week, member) row, each with a single writer ----
const readJ = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { return null; } };
const writeJ = (f, o) => { mkdirp(path.dirname(f)); const tmp = f + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(o)); fs.renameSync(tmp, f); };
const getWeek = wk => readJ(dir('weeks', wk, 'week.json'));
const putWeek = (wk, patch) => { const cur = getWeek(wk) || { week: wk }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'week.json'), o); return o; };
const getRow = (wk, id) => readJ(dir('weeks', wk, 'm' + id + '.json'));
const putRow = (wk, id, patch) => { const cur = getRow(wk, id) || { week: wk, memberId: id }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'm' + id + '.json'), o); return o; };
const rowsOf = wk => { try { return fs.readdirSync(dir('weeks', wk)).filter(f => /^m\d+\.json$/.test(f)).map(f => readJ(dir('weeks', wk, f))).filter(Boolean).sort((a, b) => a.memberId - b.memberId); } catch (e) { return []; } };
const plannedWeeks = () => { try { return fs.readdirSync(dir('weeks')).filter(w => /^\d{4}-\d{2}-\d{2}$/.test(w)).sort(); } catch (e) { return []; } };
// ---- who gets the override on one purchase ----
const memo = new Map();
async function mem(id) {
const c = memo.get(id); if (c && now() - c.t < 600000) return c.v;
const m = await chain.member(id); const v = { sponsorId: m.sponsorId || 0, buyerCount: m.buyerCount || 0 };
memo.set(id, { t: now(), v }); return v;
}
// { recipientId, hops, skipped: [{id, buyers}] } or { recipientId: 0, reason }
async function recipientFor(buyerId) {
const ups = []; let cur = buyerId;
for (let i = 0; i < LEVEL - 1 + HOP_CAP; i++) { const s = (await mem(cur)).sponsorId; if (!s || s === cur) break; ups.push(s); cur = s; }
if (ups.length < LEVEL) return { recipientId: 0, reason: 'line shorter than ' + LEVEL + ' levels' };
const skipped = [], house = cfg().house;
for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) {
const id = ups[i];
if (house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped };
const b = (await mem(id)).buyerCount;
if (b >= MIN_BUYERS) return { recipientId: id, hops: i - (LEVEL - 1), skipped };
skipped.push({ id, buyers: b });
}
return { recipientId: 0, reason: 'no qualified upline within ' + HOP_CAP + ' hops', skipped };
}
// every Purchase in the full-history index (chain.recentEvents keeps the whole history in memory; the file is the fallback)
function purchases() {
try { if (chain && chain.recentEvents) return chain.recentEvents(1e9).filter(e => e.type === 'Purchase'); } catch (e) {}
try { return (JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'chain-index.json'), 'utf8')).events || []).filter(e => e.type === 'Purchase'); } catch (e) { return []; }
}
// purchases in [from, to) (and from overrideGoLive on): one row per purchase + totals per recipient
async function report(from, to) {
const c = cfg(); const rows = [], per = {};
for (const p of purchases()) {
if (p.ts < from || p.ts >= to || (c.goLive && p.ts < c.goLive)) continue;
const wei = BigInt(p.paidWei || '0') * BigInt(PCT) / 100n, usd = Math.round((p.priceCents || 0) * PCT) / 10000; // dollars: price cents x 3% / 100
const r = await recipientFor(p.buyerId).catch(e => ({ recipientId: 0, reason: 'read failed: ' + e.message, readFailed: true }));
rows.push({ tx: p.tx, ts: p.ts, buyerId: p.buyerId, priceCents: p.priceCents, overrideWei: wei.toString(), overrideUsd: usd, recipientId: r.recipientId, hops: r.hops || 0, skipped: r.skipped || [], reason: r.reason || '', readFailed: !!r.readFailed });
if (r.recipientId) { const o = per[r.recipientId] = per[r.recipientId] || { recipientId: r.recipientId, purchases: 0, wei: 0n, usdCents: 0 }; o.purchases++; o.wei += wei; o.usdCents += (p.priceCents || 0) * PCT / 100; }
}
const recipients = Object.values(per).map(o => ({ recipientId: o.recipientId, purchases: o.purchases, wei: o.wei.toString(), pol: Number(o.wei) / 1e18, usd: Math.round(o.usdCents) / 100 })).sort((a, b) => b.usd - a.usd || a.recipientId - b.recipientId);
const paidUsd = recipients.reduce((n, o) => n + o.usd, 0), keptUsd = rows.filter(x => !x.recipientId).reduce((n, x) => n + x.overrideUsd, 0);
return { mode: c.mode, from, to, purchases: rows.length, readFailures: rows.filter(x => x.readFailed).length, recipients,
totals: { wouldPayUsd: Math.round(paidUsd * 100) / 100, wouldPayPol: recipients.reduce((n, o) => n + o.pol, 0), companyKeepsUsd: Math.round(keptUsd * 100) / 100, salesUsd: rows.reduce((n, x) => n + x.priceCents, 0) / 100 }, rows };
}
// last full week, or the week containing `day`
async function week(day) {
const monday = day ? weekOf(Date.parse(day + 'T12:00:00Z')) : weekOf(now() - 7 * 86400000);
const b = weekBounds(monday);
return Object.assign(await report(b.from, b.to), { week: monday, status: weekStatus(monday) });
}
// ---- planning: freeze who gets how much for one closed week (single writer via claim) ----
// carried rows from earlier weeks roll into this plan; under-dust totals are carried again
async function plan(wk) {
if (getWeek(wk)) return getWeek(wk);
const b = weekBounds(wk);
if (now() < b.to) return null; // not closed yet
const r = await report(b.from, b.to);
if (r.readFailures) { lastError.at = now(); lastError.msg = 'week ' + wk + ': ' + r.readFailures + ' sponsor reads failed, plan postponed'; return null; } // never plan on a partial read
if (!await claim('plan:' + wk)) return getWeek(wk); // another copy is planning (or did)
putWeek(wk, { state: 'planning', created: now(), from: b.from, to: b.to, purchases: r.purchases, salesUsd: r.totals.salesUsd, companyKeepsUsd: r.totals.companyKeepsUsd });
const per = {};
for (const o of r.recipients) per[o.recipientId] = { wei: BigInt(o.wei), usd: o.usd, purchases: o.purchases, carriedIn: 0n, carriedFrom: [] };
for (const w of plannedWeeks().filter(w => w < wk)) for (const row of rowsOf(w)) {
if (row.state !== 'carried') continue;
const o = per[row.memberId] = per[row.memberId] || { wei: 0n, usd: 0, purchases: 0, carriedIn: 0n, carriedFrom: [] };
o.wei += BigInt(row.amountWei); o.usd = Math.round((o.usd + (row.usd || 0)) * 100) / 100; o.carriedIn += BigInt(row.amountWei); o.carriedFrom.push(w);
putRow(w, row.memberId, { state: 'rolled', rolledInto: wk });
}
const dust = cfg().dustWei; let total = 0n, n = 0;
for (const [id, o] of Object.entries(per)) {
const st = o.wei < dust ? 'carried' : 'pending'; if (st === 'pending') { total += o.wei; n++; }
putRow(wk, Number(id), { amountWei: o.wei.toString(), usd: o.usd, purchases: o.purchases, carriedInWei: o.carriedIn.toString(), carriedFrom: o.carriedFrom, state: st, note: st === 'carried' ? 'under the ' + polStr(dust) + ' POL minimum, carried to next week' : '' });
}
return putWeek(wk, { state: n ? 'planned' : 'paid', totalWei: total.toString(), recipients: n, planned: now() });
}
// settle rows whose send answer was lost, from the chain index only (AwardPaid from the payer to that member, that amount)
function reconcile(wk, pay) {
if (!pay || !chain.recentEvents) return;
const b = weekBounds(wk), used = overrideTxs(true);
for (const row of rowsOf(wk)) {
if (row.state !== 'review' && row.state !== 'sent') continue;
const hit = chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && e.toId === row.memberId && String(e.amountWei) === String(row.amountWei)
&& String(e.from || '').toLowerCase() === String(pay.address).toLowerCase() && e.ts >= b.to
&& (row.txHash ? String(e.tx).toLowerCase() === String(row.txHash).toLowerCase() : !used.has(String(e.tx).toLowerCase())));
if (hit) putRow(wk, row.memberId, { state: 'paid', txHash: hit.tx, note: 'confirmed from the chain index' });
}
}
// admin decision for a stuck row: 'carry' (you checked the payer wallet and nothing went out) or 'paid' with the tx,
// which must be an AwardPaid in the chain index from the payer wallet to that member for that exact amount
async function resolve(wk, memberId, action, tx) {
const r = getRow(wk, Number(memberId)); if (!r) return { error: 'no such row' };
if (!['review', 'failed', 'sending', 'sent'].includes(r.state)) return { error: 'row is ' + r.state + ', nothing to resolve' };
if (action === 'carry') { putRow(wk, r.memberId, { state: 'carried', note: 'admin: nothing went out, carried to next week (was ' + r.state + ')' }); return finishWeek(wk); }
if (action === 'paid') {
const p = (payerOverride || keyHex()) ? payer() : null;
const hit = p && chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && String(e.tx).toLowerCase() === String(tx || '').toLowerCase());
if (!hit || hit.toId !== r.memberId || String(hit.amountWei) !== String(r.amountWei) || String(hit.from).toLowerCase() !== String(p.address).toLowerCase()) return { error: 'that tx is not an AwardPaid from the payer wallet to #' + r.memberId + ' for ' + polStr(r.amountWei) + ' POL in the chain index' };
putRow(wk, r.memberId, { state: 'paid', txHash: hit.tx, note: 'admin: confirmed tx' }); return finishWeek(wk);
}
return { error: 'action must be carry or paid' };
}
// ---- paying one planned week (live only) ----
async function pay(wk) {
const live = liveState(); if (!live.ready) return { week: wk, paid: 0, why: live.why };
let w = getWeek(wk); if (!w) return { week: wk, why: ['not planned'] };
if (w.state === 'planning') return { week: wk, why: ['plan is being written (or a plan write stopped halfway: needs review if this lasts)'] };
const p = payer(); reconcile(wk, p);
let rows = rowsOf(wk).filter(r => r.state === 'pending');
if (!rows.length) return finishWeek(wk);
const c = cfg(); const total = rows.reduce((n, r) => n + BigInt(r.amountWei), 0n);
if (total > c.capWei) { putWeek(wk, { state: 'held', heldWhy: 'over the weekly cap: ' + polStr(total) + ' POL planned, cap ' + polStr(c.capWei) + ' POL' }); await alertOnce(wk, 'cap', '⛔ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPlanned ' + polStr(total) + ' POL is over the weekly cap of ' + polStr(c.capWei) + ' POL. Nothing was sent. Raise overridePayCapPol or review the plan, then press Pay this week now in admin.'); return { week: wk, held: 'cap' }; }
let fees, bal;
try { fees = await p.fees(); bal = BigInt(await p.balance()); } catch (e) { lastError.at = now(); lastError.msg = 'payer read: ' + e.message; return { week: wk, why: ['payer read failed: ' + e.message] }; }
const gas = BigInt(rows.length) * GAS_LIMIT * fees.maxFeePerGas;
if (bal < total + gas) { putWeek(wk, { state: 'held', heldWhy: 'payer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL, needs ' + polStr(total + gas) + ' (payouts ' + polStr(total) + ' + gas ' + polStr(gas) + ')' }); await alertOnce(wk, 'balance', '⚠️ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPayer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL; this week needs ' + polStr(total + gas) + ' POL (' + polStr(total) + ' payouts + up to ' + polStr(gas) + ' gas). Nothing was sent. Fund it and it pays on the next check (or press Pay this week now).'); return { week: wk, held: 'balance' }; }
putWeek(wk, { state: 'paying', heldWhy: '' });
let sent = 0;
for (const r0 of rows) {
if (!await claim('pay:' + wk + ':' + r0.memberId)) continue; // another copy owns this row
const r = getRow(wk, r0.memberId); if (!r || r.state !== 'pending') continue;
try { await p.preflight(r.memberId, r.amountWei); }
catch (e) { putRow(wk, r.memberId, { state: 'carried', note: 'award() would revert (' + String(e.reason || e.shortMessage || e.message).slice(0, 100) + '); nothing sent, carried to next week' }); continue; }
putRow(wk, r.memberId, { state: 'sending', sendingAt: now() }); // on disk BEFORE the send
let tx;
try { tx = await p.send(r.memberId, r.amountWei, fees); }
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'send error, may or may not have gone out: ' + String(e.shortMessage || e.message).slice(0, 140) }); continue; }
putRow(wk, r.memberId, { state: 'sent', txHash: tx.hash });
console.log('override: week ' + wk + ' #' + r.memberId + ' ' + polStr(r.amountWei) + ' POL tx ' + tx.hash);
try { const rc = await tx.wait(); if (rc && Number(rc.status) === 1) { putRow(wk, r.memberId, { state: 'paid', paidAt: now() }); sent++; } else putRow(wk, r.memberId, { state: 'failed', note: 'reverted on chain (no POL moved except gas); needs review' }); }
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'sent, receipt not confirmed: ' + String(e.message).slice(0, 120) }); }
}
return Object.assign(await finishWeek(wk), { sentNow: sent });
}
async function finishWeek(wk) {
// a send that stopped halfway (no answer in 15 minutes) is never retried: it becomes review
for (const r of rowsOf(wk)) {
if (r.state === 'sending' && now() - (r.sendingAt || r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'the app stopped during the send; it may or may not have gone out' });
if (r.state === 'sent' && now() - (r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'sent, no receipt and not in the chain index after 15 minutes' });
}
reconcile(wk, (payerOverride || keyHex()) ? payer() : null);
const rows = rowsOf(wk); const open = rows.filter(r => ['pending', 'sending', 'sent', 'review', 'failed'].includes(r.state));
if (open.length) {
const stuck = open.filter(r => r.state === 'review' || r.state === 'failed'); // in-flight rows of another copy are not stuck
if (stuck.length) await alertOnce(wk, 'review', '\u{1F50E} <b>Level-4 override needs review</b> · ' + BRAND + ' · week of ' + wk + '\n' + stuck.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL: ' + r.state + (r.txHash ? ' ' + txLink(r.txHash) : '') + ' ' + (r.note || '')).join('\n') + '\nNothing is re-sent automatically. Check the payer wallet on the explorer, then resolve it in admin.');
return { week: wk, state: (getWeek(wk) || {}).state, open: open.length };
}
const w = putWeek(wk, { state: 'paid', done: now() });
await summaryPaid(wk);
return { week: wk, state: w.state };
}
const txLink = h => { const c = chain.getConfig(); return (c.explorer ? c.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + h; };
async function alertOnce(wk, kind, text) { if (!notify) return; if (!await claim('tg:' + wk + ':' + kind)) return; await notify(text, null).catch(() => {}); }
async function summaryPaid(wk) {
if (!notify || !await claim('tg:' + wk + ':paid')) return;
const w = getWeek(wk) || {}, rows = rowsOf(wk), paid = rows.filter(r => r.state === 'paid'), carried = rows.filter(r => r.state === 'carried');
const tot = paid.reduce((n, r) => n + BigInt(r.amountWei), 0n), usd = paid.reduce((n, r) => n + (r.usd || 0), 0);
await notify('\u{1F4B8} <b>Level-4 override PAID</b> · ' + BRAND + ' · week of ' + wk + '\n' + (w.purchases || 0) + ' purchases, $' + Number(w.salesUsd || 0).toFixed(2) + ' sales\n'
+ 'Paid ' + polStr(tot) + ' POL (about $' + usd.toFixed(2) + ' at purchase prices) to ' + paid.length + ' member' + (paid.length === 1 ? '' : 's') + '; company keeps $' + Number(w.companyKeepsUsd || 0).toFixed(2) + ' of the 3%.\n'
+ (paid.map(r => '#' + r.memberId + ': ' + polStr(r.amountWei) + ' POL ($' + (r.usd || 0).toFixed(2) + ') <a href="' + txLink(r.txHash) + '">tx</a>').join('\n') || 'Nobody qualified this week.')
+ (carried.length ? '\nCarried to next week (under the minimum or the wallet refused): ' + carried.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL').join(', ') : '')
+ '\nDetails: ' + SITE_URL + '/api/admin/override?week=' + wk, null).catch(() => {});
}
// weeks the live payer is responsible for: from the go-live week to the last closed one, in order
function dueWeeks(force) {
const c = cfg(); if (!c.goLive) return [];
const out = []; let wk = weekOf(c.goLive);
while (true) { const b = weekBounds(wk); if (now() < b.to) break; if (!force && now() < payableAt(wk)) break; out.push(wk); wk = addDays(wk, 7); if (out.length > 520) break; }
return out;
}
// settle every due week in order; stop at the first one that is not fully paid
async function payDue(opts) {
const o = opts || {}; const results = [];
if (!liveState().ready) return { ready: false, why: liveState().why, results };
for (const wk of dueWeeks(o.force)) {
if (o.week && wk > o.week) break;
let w = getWeek(wk);
if (!w) w = await plan(wk);
if (!w) { results.push({ week: wk, why: ['not planned yet: ' + (lastError.msg || 'waiting')] }); break; }
if (w.state === 'paid') { await summaryPaid(wk); results.push({ week: wk, state: 'paid' }); continue; }
const r = await pay(wk); results.push(r);
if ((getWeek(wk) || {}).state !== 'paid') break;
}
return { ready: true, results };
}
function weekStatus(wk) {
const w = getWeek(wk); if (!w) return { week: wk, state: claimed('plan:' + wk) ? 'planning' : 'not planned' };
const rows = rowsOf(wk);
return { week: wk, state: w.state, heldWhy: w.heldWhy || '', totalWei: w.totalWei, totalPol: w.totalWei ? polStr(w.totalWei) : '0',
rows: rows.map(r => ({ memberId: r.memberId, pol: polStr(r.amountWei), amountWei: r.amountWei, usd: r.usd, purchases: r.purchases, state: r.state, txHash: r.txHash || '', tx: r.txHash ? txLink(r.txHash) : '', note: r.note || '', carriedFrom: r.carriedFrom || [], rolledInto: r.rolledInto || '' })) };
}
async function payerStatus() {
const c = cfg(), live = liveState(); const out = { mode: c.mode, ready: live.ready, why: live.why, goLive: c.goLive || 0, capPol: polStr(c.capWei), dustPol: polStr(c.dustWei), house: c.house, keyPresent: !!(payerOverride || keyHex()), lastError: lastError.msg ? lastError : null };
const p = (payerOverride || keyHex()) ? payer() : null;
if (p) { out.address = p.address; try { out.balancePol = polStr(await p.balance()); } catch (e) { out.balanceError = e.message; } }
return out;
}
// AwardPaid txs this payer made (for the Earnings label and the payout email): tx -> { week, memberId }
let txCache = { at: 0, map: new Map() };
function overrideTxs(fresh) {
if (!fresh && now() - txCache.at < 30000) return txCache.map;
const m = new Map(); for (const wk of plannedWeeks()) for (const r of rowsOf(wk)) if (r.txHash) m.set(String(r.txHash).toLowerCase(), { week: wk, memberId: r.memberId });
txCache = { at: now(), map: m }; return m;
}
const txInfo = tx => { return overrideTxs(true).get(String(tx || '').toLowerCase()) || null; };
// ---- the scheduler: every 30 minutes ----
async function tick() {
const c = cfg(); if (c.mode === 'off') return;
const live = liveState();
if (live.ready) { try { await payDue(); } catch (e) { lastError.at = now(); lastError.msg = 'payDue: ' + e.message; console.error('override pay', e.message); } return; }
// dry run (or 'live' that is not ready): the Monday report, once per week across every copy of the app
const parts = Object.fromEntries(CT_HOUR.formatToParts(new Date(now())).map(p => [p.type, p.value]));
if (parts.weekday !== 'Mon' || Number(parts.hour) < 9 || !notify) return;
const r = await week(); if (r.readFailures) return; // try again in 30 minutes rather than report a partial week
if (!await claim('tg:' + r.week + ':dry')) return;
let st = {}; try { st = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'override-dryrun.json'), 'utf8')); } catch (e) {}
st.lastWeek = r.week; st.reports = Object.assign(st.reports || {}, { [r.week]: { totals: r.totals, recipients: r.recipients, purchases: r.purchases } });
try { fs.writeFileSync(path.join(DATA_DIR, 'override-dryrun.json'), JSON.stringify(st)); } catch (e) {}
const top = r.recipients.slice(0, 8).map(o => '#' + o.recipientId + ': $' + o.usd.toFixed(2) + ' (' + o.pol.toFixed(2) + ' POL, ' + o.purchases + ' buys)').join('\n');
await notify('\u{1F4CA} <b>Level-4 override, DRY RUN</b> · ' + BRAND + ' · week of ' + r.week + '\n' + r.purchases + ' purchases, $' + r.totals.salesUsd.toFixed(2) + ' sales\n'
+ 'Would pay $' + r.totals.wouldPayUsd.toFixed(2) + ' (' + r.totals.wouldPayPol.toFixed(2) + ' POL) to ' + r.recipients.length + ' members; company keeps $' + r.totals.companyKeepsUsd.toFixed(2) + ' of the 3%.\n'
+ (top || 'Nobody qualified this week.') + '\nNo money moved' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
}
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg };
}
const main = create();
module.exports = Object.assign(main, { create, weekOf, ctMidnight, weekBounds, payableAt, polStr, toWei, PCT, MIN_BUYERS, HOP_CAP, LEVEL, GAS_LIMIT });
+7 -2
View File
@@ -8,6 +8,9 @@
// 2. GET <bridge>?a=ptc_served -> [{iapId, received}] (cumulative visits PD delivered per campaign). Delivery is READ
// from PD, never derived: the delta since our last read is applied through ads.applyExternalVisits, which bumps
// imps and closes the pack when the ordered count is reached. Our last-read counters live in DATA_DIR/pdsync.json.
// SYNDICATED RATE (Marty 2026-10-27, 4:1): N = ads.synRateDivisor() partner visits use up ONE visit of the pack
// (floor(now/N) - floor(prev/N) on the cumulative count, so fractions carry exactly); every partner visit is still
// counted in the campaign's syn_imps for the member's stats, and PD is offered (visits left) x N.
//
// FEATURE-FLAGGED: inert unless PD_BRIDGE_URL and PD_BRIDGE_SECRET are set. Geo-restricted campaigns are not sent
// (PassiveDrip's audience is worldwide).
@@ -16,6 +19,7 @@ const fs = require('fs'), path = require('path'), http = require('http'), https
let X = null, FILE = null, S = { served: {}, last: null }, running = false;
function enabled() { return !!(process.env.PD_BRIDGE_URL && process.env.PD_BRIDGE_SECRET); }
const synN = () => { try { return (X && X.ads && X.ads.synRateDivisor) ? X.ads.synRateDivisor() : 1; } catch (e) { return 1; } };
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'pdsync.json'); try { S = Object.assign(S, JSON.parse(fs.readFileSync(FILE, 'utf8'))); } catch (e) {} }
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
@@ -37,7 +41,7 @@ function bridge(action, method, body) {
async function listing() {
const all = await X.ads.adminList(2000);
return all.filter(c => c.type === 'visits' && c.status === 'active' && !c.doorOnly && !c.geo && !(c.starts && c.starts > Date.now()) && /^https?:\/\//.test(c.targetUrl || ''))
.map(c => ({ id: c.id, title: String(c.name || c.title || 'Sponsor').slice(0, 64), desc: String((c.title && String(c.title).toLowerCase() !== String(c.name || '').toLowerCase()) ? c.title : '').slice(0, 128), url: c.targetUrl, visitsLeft: Math.max(0, Number(c.body || 0) - Number(c.imps || 0)) }))
.map(c => ({ id: c.id, title: String(c.name || c.title || 'Sponsor').slice(0, 64), desc: String((c.title && String(c.title).toLowerCase() !== String(c.name || '').toLowerCase()) ? c.title : '').slice(0, 128), url: c.targetUrl, visitsLeft: Math.max(0, Number(c.body || 0) - Number(c.imps || 0)) * synN() }))
.filter(c => c.visitsLeft > 0);
}
@@ -54,7 +58,8 @@ async function sync() {
const id = String(row.iapId); const now = Number(row.received) || 0; const prev = Number(S.served[id] || 0);
if (now <= prev) { if (now < prev) S.served[id] = now; continue; } // PD's counter reset (row recreated): re-baseline, never charge backwards
if (process.env.PD_SYNC_APPLY === '0') { S.served[id] = now; t.ignored = (t.ignored || 0) + (now - prev); continue; } // staging bridge: test views are read and baselined, never counted as delivery
try { const res = await X.ads.applyExternalVisits(Number(id), now - prev, 'PassiveDrip'); S.served[id] = now; t.applied += res.applied || 0; if (res.closed) t.closed++; }
const N = synN(); const units = Math.floor(now / N) - Math.floor(prev / N); // pack visits these partner visits use up
try { const res = await X.ads.applyExternalVisits(Number(id), units, 'PassiveDrip', now - prev); S.served[id] = now; t.applied += res.applied || 0; if (res.closed) t.closed++; }
catch (e) { console.error('pdsync apply', id, e.message); } // one bad row never stops the others; its delta is retried next sync
}
save();
+125 -5
View File
@@ -61,6 +61,14 @@
.kv-row .k{font-family:var(--mono);font-size:12.5px;overflow-wrap:anywhere}
.kv-row input[type=checkbox]{width:auto;justify-self:start}
@media(max-width:700px){.kv-row{grid-template-columns:1fr}}
.gpt-note{margin:0 0 10px;padding:8px 12px;border-radius:8px;background:#fde68a;color:#7c2d12;font-size:13px}
.gpt-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}
.gpt-tier{border:1px dashed var(--line-strong);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:4px}
.gpt-tier.on{border-style:solid;border-color:var(--gold,#e2b04a);box-shadow:0 0 0 1px var(--gold,#e2b04a) inset}
.gpt-tier h4{margin:0;font-size:16px;display:flex;gap:6px;align-items:center;flex-wrap:wrap}
.gpt-tier .gpt-price{margin:0;font-size:18px;font-weight:700}
.gpt-tier ul{margin:4px 0;padding-left:18px;font-size:13px}
.gpt-tier .gpt-acts{display:flex;gap:6px;flex-wrap:wrap;margin-top:auto;padding-top:6px}
</style>
</head>
<body class="bo-body">
@@ -96,11 +104,14 @@
<button data-pane="house" type="button"><svg viewBox="0 0 24 24"><path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8M7 13v5a2 2 0 0 0 4 0v-3"/></svg>House ads</button>
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h10"/></svg>All campaigns</button>
<button data-pane="members" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg>Members</button>
<button data-pane="support" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.1-2.4 3.7"/><path d="M12 17v.5"/></svg>Support<span class="pill" id="supBadge" hidden></span></button>
<button data-pane="kb" type="button"><svg viewBox="0 0 24 24"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H20v15H6.5A2.5 2.5 0 0 0 4 20.5z"/><path d="M4 20.5A2.5 2.5 0 0 0 6.5 21H20v-3"/><path d="M9 8h7M9 11.5h5"/></svg>Knowledge base</button>
<button data-pane="reports" type="button"><svg viewBox="0 0 24 24"><path d="M12 3l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg>Reports<span class="pill" id="repBadge" hidden></span></button>
<button data-pane="traffic" type="button"><svg viewBox="0 0 24 24"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>Traffic</button>
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
<button data-pane="releases" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg>Releases</button>
<button data-pane="pnl" type="button"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg>P&amp;L</button>
<button data-pane="gamepass" type="button"><svg viewBox="0 0 24 24"><rect x="2.5" y="7" width="19" height="11" rx="5.5"/><path d="M7 11v3M5.5 12.5h3"/><circle cx="15.5" cy="11.5" r="1.1"/><circle cx="18" cy="13.5" r="1.1"/></svg>Game Pass</button>
<button data-pane="settings" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>Settings</button>
</nav>
<div class="bo-links">
@@ -229,6 +240,11 @@
</div>
<div class="pane" id="pane-campaigns" hidden>
<div class="card">
<div class="card-head"><h3>Login-ad line</h3><span class="sub" id="lqSub">paid reservations waiting for a slot</span></div>
<p class="small muted" style="margin:0 0 10px">When every member slot is taken, a member can pay now to reserve the next one. The oldest paid reservation starts the moment a slot frees (on expiry, on a pause, and on a one-minute check), before any paused slot can come back. Estimated starts assume every live slot runs its full term. Cancel gives the full price back as purchased credits.</p>
<div class="tablewrap"><table class="adm-table" id="lqTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>All campaigns</h3><span class="sub" id="campSub">newest first</span></div>
<p style="margin:0 0 10px"><input id="campFilter" placeholder="Filter by owner, name, type or status" style="width:100%"></p>
@@ -262,6 +278,13 @@
<p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p>
<div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Sponsor check: InstantAdPay and LinkSpin</h3><span class="sub" id="scSub">members on both sites whose sponsor differs</span></div>
<p class="small muted">Deliberate changes (a tank adoption, a rescue, a release, the end of an adoption window, an admin edit) follow to the other site until the member is bound on that site's contract. Everything else keeps the first sponsor. To settle a difference, pick the side whose sponsor is right: it is applied on the other site, unless the member is already bound there.</p>
<p><button class="btn small" id="scRun" type="button">Run the check</button></p>
<div class="tablewrap"><table class="adm-table" id="scTable"></table></div>
<details style="margin-top:10px"><summary class="small muted">Recent sponsor follow activity on both sites</summary><div class="tablewrap"><table class="adm-table" id="scLog"></table></div></details>
</div>
<div class="card">
<div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div>
<p style="margin:0 0 10px"><div class="card" id="fraudBox" style="margin-bottom:12px"><p class="small muted">Loading duplicate signals…</p></div>
@@ -271,6 +294,49 @@
</div>
</div>
<div class="pane" id="pane-support" hidden>
<div id="spList">
<div class="card">
<div class="card-head"><h3>Support desk</h3><span class="sub" id="spSub">tickets from Help, /support and the chatbot</span></div>
<div class="chips" id="spStatus" style="margin-top:4px"></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
<select id="spPlatform" class="small"><option value="">All platforms</option><option value="iap">InstantAdPay</option><option value="linkspin">LinkSpin</option></select>
<select id="spCategory" class="small"></select>
<input id="spQ" class="small" placeholder="Search ref, email, name, subject" style="flex:1;min-width:200px">
</p>
<div class="tablewrap"><table class="adm-table" id="spTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Saved replies</h3><span class="sub">insert them from any ticket's reply box</span></div>
<div id="spTpls"></div>
<p style="display:flex;gap:10px;flex-wrap:wrap;margin:10px 0 0"><button type="button" class="btn small sec" id="spTplAdd">+ Add a saved reply</button><button type="button" class="btn small" id="spTplSave">Save saved replies</button></p>
</div>
<p class="small muted">New tickets and member replies ping your private Telegram chat (site setting supportTelegramChat) and email ADMIN_EMAIL, at most one ping per ticket every 10 minutes. Your replies email the requester and, for members, land in their Help tab as a quiet inbox notice.</p>
</div>
<div id="spView" hidden></div>
</div>
<div class="pane" id="pane-kb" hidden>
<div id="kbList">
<div class="card">
<div class="card-head"><h3>Knowledge base</h3><span class="sub" id="kbSub">what the chat assistant answers from</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
<input id="kbQ" class="small" placeholder="Search title, questions, answer, tags" style="flex:1;min-width:200px">
<select id="kbSrc" class="small"><option value="">All sources</option><option value="canned">From the code</option><option value="faq">FAQ</option><option value="ticket">From tickets</option><option value="admin">Added here</option></select>
<button type="button" class="btn small" id="kbNew">+ New entry</button>
</p>
<div class="tablewrap"><table class="adm-table" id="kbTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Try a question</h3><span class="sub">which entry answers it, and what the AI is given</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;margin:0"><input id="kbTry" class="small" placeholder="Ask it the way a member would" style="flex:1;min-width:200px"><button type="button" class="btn small sec" id="kbTryGo">Test</button></p>
<div id="kbTryOut" class="small"></div>
</div>
<p class="small muted">Instant answers (a pattern is set) reply on their own with no AI call. For every other question the closest entries go to the AI as its knowledge base, and when nothing fits it says it is not sure and points to support. In a ticket, "Save as KB entry" under your reply turns it into a draft here. Entries from the code follow chatbot.js and kb-seed.js until you edit them.</p>
</div>
<div id="kbEdit" class="card" hidden></div>
</div>
<div class="pane" id="pane-reports" hidden>
<div class="card">
<div class="card-head"><h3>Counters audit</h3><span class="sub" id="audSub">views vs delivery logs, charges vs shows</span></div>
@@ -290,6 +356,7 @@
<div class="pane" id="pane-traffic" hidden>
<div class="card"><div class="card-head"><h3>Games to members</h3><span class="sub" id="stSub">the $5 welcome offer after a game win</span></div><div class="tablewrap"><table class="adm-table" id="trfStarter"></table></div></div>
<div class="card"><div class="card-head"><h3>Login-ad showings</h3><span class="sub" id="lsSub">sign-in interstitials per day, dashboard vs games</span></div><div class="tablewrap"><table class="adm-table" id="trfLogin"></table></div></div>
<div class="card">
<div class="card-head"><h3>Where visitors come from</h3><span class="sub" id="trfSub"></span></div>
<div class="chips" id="trfRange" style="margin:0 0 10px"><button type="button" class="chip-t" data-days="7">7 days</button><button type="button" class="chip-t on" data-days="30">30 days</button><button type="button" class="chip-t" data-days="90">90 days</button><button type="button" class="chip-t" data-days="365">Year</button></div>
@@ -437,9 +504,11 @@
<div class="tablewrap"><table class="adm-table" id="pnlSplit"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>PolHunter payouts</h3><span class="sub">all time, its own faucet</span></div>
<div class="tablewrap"><table class="adm-table" id="pnlHunt"></table></div>
<p class="small muted" style="margin:10px 0 0">Marketing spend, paid in POL from the PolHunter wallet. None of it passes through the ad contract, so it is not in the lines above.</p>
<div class="card-head"><h3>Game payouts</h3><span class="sub">all time, running total</span></div>
<div class="tablewrap"><table class="adm-table" id="pnlGames"></table></div>
<p class="small muted" style="margin:10px 0 0">Marketing spend: every POL send from each game's own payout wallet to a player, read from Polygon since the wallet's first transaction. Top-ups, moves between our wallets and returns to the fee wallets are left out. None of it passes through the ad contract, so it is not in the lines to the left.</p>
<details style="margin-top:10px"><summary class="small">PolHunter detail (its own ledger)</summary>
<div class="tablewrap"><table class="adm-table" id="pnlHunt"></table></div></details>
</div>
<div class="card">
<div class="card-head"><h3>Wallets</h3><span class="sub">live balances</span></div>
@@ -478,8 +547,58 @@
<p class="small" id="burnerLine">…</p>
<p><button class="btn small sec" type="button" id="burnerRun">Run now</button></p>
</div>
<div class="card">
<div class="card-head"><h3>Level 4 override</h3><span class="sub">3% of each purchase to the qualified 4th upline, paid weekly from the payer wallet</span></div>
<p class="small" id="ovPayer">…</p>
<div id="ovWeeks" class="small"></div>
<p><select id="ovWeek"></select> <button class="btn small sec" type="button" id="ovShow">Show week</button> <button class="btn small" type="button" id="ovPay" hidden>Pay this week now</button></p>
<div id="ovOut" class="small"></div>
</div>
</div>
<div class="pane" id="pane-gamepass" hidden>
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-top:0" id="gpStats"><p class="small muted">…</p></div>
<div class="grid c2" style="margin-top:16px">
<div class="card">
<div class="card-head"><h3>This week</h3><span class="sub" id="gpWeekSub"></span></div>
<div id="gpWeek" class="small">…</div>
</div>
<div class="card">
<div class="card-head"><h3>Pass Tournament</h3><span class="sub" id="gpTourSub"></span></div>
<div id="gpTour" class="small">…</div>
<p style="margin:12px 0 0;display:flex;gap:8px;flex-wrap:wrap"><button class="btn small sec" id="gpTourRun" type="button">Settle last week now</button></p>
</div>
</div>
<div class="card">
<div class="card-head"><h3>By pass tier</h3><span class="sub" id="gpTiersSub"></span></div>
<div id="gpTiers" class="small">…</div>
</div>
<div class="card" id="gpTestCard">
<div class="card-head"><h3>Tier test and preview</h3><span class="sub" id="gpTestSub">admin only · your own account</span></div>
<div id="gpTest" class="small">…</div>
</div>
<div class="card">
<div class="card-head"><h3>Pass sales</h3><span class="sub" id="gpSalesSub"></span></div>
<div id="gpSales" class="small">…</div>
</div>
<div class="card">
<div class="card-head"><h3>Comp a pass</h3><span class="sub">support: one pass period, recorded as no sale</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0"><input id="gpCompEmail" placeholder="member email" style="max-width:260px"><select id="gpCompTier"><option value="weekly">Game Pass (weekly)</option><option value="explorer">Explorer (monthly)</option><option value="champion">Champion (monthly)</option><option value="sovereign">Sovereign (monthly)</option><option value="legend">Legend (yearly)</option></select><input id="gpCompWhy" placeholder="why" style="max-width:220px"><button class="btn small" id="gpComp" type="button">Give one pass period</button><button class="btn small sec" id="gpRevoke" type="button">End this tier now (refund)</button></p>
</div>
<p class="small muted">Every pass is paid by a new package purchase of at least its price (since 2026-10-22; credits never buy a pass). The *PriceCredits settings are the pass price in cents. Settings live in Settings &rsaquo; Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Tiers above weekly: sovTiers (1/0, the sale switch for all of them; off = members never see them and the admin tests them in Tier test and preview above, never on the member card), gamePassExplorerEnabled / gamePassChampionEnabled / gamePassSovereignEnabled / gamePassLegendEnabled (0 stops one tier), gamePassExplorerPriceCredits (2000), gamePassChampionPriceCredits (5000), gamePassSovereignPriceCredits (10000), gamePassLegendPriceCredits (25000); since 2026-10-25 every tier price equals a one-click package ($5, $20, $50, $100, $250), gamePassExplorerDays / gamePassChampionDays / gamePassSovereignDays (30), gamePassLegendDays (365), passTournamentTierSales (1 = their sales feed the tournament pool; default 0). Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.</p>
</div>
<div class="pane" id="pane-settings" hidden>
<div class="card" id="kitCard">
<div class="card-head"><h3>Refuel Kit</h3><span class="sub" id="kitSub">monthly members-only banners: unlocked by a counted refuel (needs refuelStreak on)</span></div>
<p class="small muted">Five base images per month for this site's own program: 728x90, 300x250, 468x60, 160x600, 1200x630. Each member's @name and a QR to their own link are drawn on top: keep the right end clear on 728x90 and 468x60 (QR) with room for the name left of it, the bottom-right corner on 300x250 and 1200x630, and the bottom 170 px on 160x600. No income claims in any banner. Release on the 1st; a member unlocks the month's kit with their next counted refuel.</p>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center"><input id="kitMonth" placeholder="YYYY-MM" style="max-width:110px"><input id="kitTheme" placeholder="Theme (e.g. Harvest)" style="max-width:240px">
<button class="btn small" id="kitSave" type="button">Save kit</button><button class="btn small sec" id="kitPlaceholder" type="button">Use placeholder art (public/banners)</button></p>
<div id="kitSizes"></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px">Preview <select id="kitPrevSize"></select><input id="kitPrevName" placeholder="username" style="max-width:160px"><label class="small"><input type="checkbox" id="kitPrevGif" style="width:auto"> animated</label><button class="btn small sec" id="kitPreview" type="button">Preview</button></p>
<div id="kitPrevBox"></div>
<div id="kitList" class="small"></div>
<div id="kitBox"></div>
</div>
<div class="card">
<div class="card-head"><h3>Follow-up emails</h3><span class="sub" id="dripSub">sent to every new free member, hours after sign-up</span></div>
<p class="small muted">One card per email. Placeholders fill in per reader: click a chip to drop it where your cursor is.
@@ -520,7 +639,8 @@
</div>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/admin.js?v=20261006gm"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261027nr"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-kits.js?v=20261024kit"></script>
</body>
</html>
+108
View File
@@ -0,0 +1,108 @@
// Admin > Knowledge base (2026-10-20, kb.js on the server): list, search, add, edit and delete the
// entries the chat assistant answers from, try a question against them, and take a support reply
// straight into a new entry (admin.js calls IAPKB.compose from a ticket's "Save as KB entry").
(function () {
const $ = IAP.$;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function api(path, body, method) {
const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
const r = await (await fetch(path, opts)).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
return r;
}
const ctDay = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', year: 'numeric' }) : '';
const SRC = { canned: 'from the code', faq: 'FAQ', ticket: 'from a ticket', admin: 'added here' };
let entries = [], filter = { q: '', src: '' }, wired = false;
function wire() {
if (wired) return; wired = true;
let t = null;
$('kbQ').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => { filter.q = $('kbQ').value.trim(); load().catch(e => IAP.status(e.message, 'bad')); }, 300); });
$('kbSrc').addEventListener('change', () => { filter.src = $('kbSrc').value; draw(); });
$('kbNew').addEventListener('click', () => compose({}));
$('kbTable').addEventListener('click', e => { const tr = e.target.closest('[data-kbid]'); if (tr) edit(tr.dataset.kbid).catch(err => IAP.status(err.message, 'bad')); });
const go = async () => {
const q = $('kbTry').value.trim(); if (!q) return $('kbTry').focus();
const r = await api('/api/admin/kb/test', { question: q });
$('kbTryOut').innerHTML = (r.fast ? '<p style="margin:6px 0"><b>Instant answer:</b> ' + esc(r.fast.title) + ' <span class="mono muted">' + esc(r.fast.id) + '</span> (no AI call)</p>' : '<p style="margin:6px 0">No instant answer, so this goes to the AI with:</p>')
+ (r.ranked.length ? '<ol style="margin:4px 0 0 18px;padding:0">' + r.ranked.map(h => '<li' + (h.used ? '' : ' class="muted"') + '><a href="#" data-kbopen="' + esc(h.id) + '">' + esc(h.title) + '</a> <span class="mono">' + h.score + '</span>' + (h.used ? ' <b>used</b>' : '') + '</li>').join('') + '</ol>'
: '<p class="muted" style="margin:4px 0">No entry matches, so the assistant is told to say it is not sure and point to support.</p>');
};
$('kbTryGo').addEventListener('click', () => go().catch(e => IAP.status(e.message, 'bad')));
$('kbTry').addEventListener('keydown', e => { if (e.key === 'Enter') go().catch(err => IAP.status(err.message, 'bad')); });
$('kbTryOut').addEventListener('click', e => { const a = e.target.closest('[data-kbopen]'); if (a) { e.preventDefault(); edit(a.dataset.kbopen).catch(err => IAP.status(err.message, 'bad')); } });
}
async function load() {
wire();
$('kbEdit').hidden = true; $('kbList').hidden = false;
const r = await api('/api/admin/kb' + (filter.q ? '?q=' + encodeURIComponent(filter.q) : ''));
entries = r.entries || [];
$('kbSub').textContent = (r.stamp ? r.stamp.count : entries.length) + ' entries' + (r.stamp && r.stamp.updated ? ' · last change ' + r.stamp.updated : '');
draw();
}
function draw() {
const rows = entries.filter(e => !filter.src || e.source === filter.src);
$('kbTable').innerHTML = '<tr><th>Entry</th><th>Asked as</th><th>Source</th><th>Updated</th></tr>'
+ (rows.length ? rows.map(e => '<tr data-kbid="' + esc(e.id) + '" style="cursor:pointer"><td><b>' + esc(e.title) + '</b>' + (e.score != null ? ' <span class="small muted mono">' + e.score + '</span>' : '')
+ '<div class="small muted">' + esc(String(e.answer).slice(0, 140)) + (String(e.answer).length > 140 ? '…' : '') + '</div>'
+ ((e.tags || []).length ? '<div class="small" style="margin-top:3px">' + e.tags.map(t => '<span class="house-tag" style="margin:0 4px 0 0">' + esc(t) + '</span>').join('') + '</div>' : '') + '</td>'
+ '<td class="small">' + (e.questions || []).slice(0, 3).map(esc).join('<br>') + ((e.questions || []).length > 3 ? '<br><span class="muted">+' + (e.questions.length - 3) + ' more</span>' : '') + '</td>'
+ '<td class="small">' + esc(SRC[e.source] || e.source) + (e.pattern ? '<div class="muted">instant</div>' : '') + (e.ticketRef ? '<div class="mono muted">' + esc(e.ticketRef) + '</div>' : '') + (e.edited && e.source !== 'admin' && e.source !== 'ticket' ? '<div class="muted">edited</div>' : '') + '</td>'
+ '<td class="small muted" style="white-space:nowrap">' + esc(ctDay(e.updated)) + '</td></tr>').join('')
: '<tr><td colspan="4" class="muted">No entries here.</td></tr>');
}
async function edit(id) { const r = await api('/api/admin/kb/' + encodeURIComponent(id)); compose(r.entry); }
// e: an existing entry (has id), or a prefill for a new one ({ title, questions, answer, tags, source, ticketRef })
function compose(e) {
wire();
e = e || {};
const isNew = !e.id;
$('kbList').hidden = true; $('kbEdit').hidden = false;
$('kbEdit').innerHTML = '<div class="card-head"><h3>' + (isNew ? 'New entry' : 'Edit entry') + '</h3><span class="sub mono">' + (isNew ? (e.ticketRef ? 'from ' + esc(e.ticketRef) : '') : esc(e.id) + ' · ' + esc(SRC[e.source] || e.source) + (e.ticketRef ? ' · ' + esc(e.ticketRef) : '') + ' · updated ' + esc(ctDay(e.updated))) + '</span></div>'
+ (e.source === 'ticket' && isNew ? '<p class="small" style="margin:0 0 10px;color:var(--amber,#ffb238)">Taken from a support reply. Take out names, emails, member numbers and anything about this one account before saving: entries are shown to the assistant for every member who asks something similar.</p>' : '')
+ (!isNew && (e.source === 'canned' || e.source === 'faq') && !e.edited ? '<p class="small muted" style="margin:0 0 10px">This entry comes from the code (chatbot.js or kb-seed.js) and follows it when the code changes. Saving it here makes it yours: later code changes to this entry are not applied.</p>' : '')
+ '<div style="display:grid;gap:10px">'
+ '<label class="small">Title<input id="kbTitle" maxlength="200" style="width:100%" value="' + esc(e.title || '') + '" placeholder="Can I use my regular Coinbase account?"></label>'
+ '<label class="small">Question variants, one per line (how members actually ask it)<textarea id="kbQs" rows="4" style="width:100%">' + esc((e.questions || []).join('\n')) + '</textarea></label>'
+ '<label class="small">Answer (plain words, no em dashes, never a promise of income; full https links)<textarea id="kbAns" rows="8" maxlength="4000" style="width:100%">' + esc(e.answer || '') + '</textarea></label>'
+ '<label class="small">Tags, comma separated<input id="kbTags" style="width:100%" value="' + esc((e.tags || []).join(', ')) + '" placeholder="coinbase, exchange account, wallet"></label>'
+ '<label class="small"><input type="checkbox" id="kbHandoff"' + (e.handoff ? ' checked' : '') + '> Offer "Send this to support" under this answer</label>'
+ '<details' + (e.pattern ? ' open' : '') + '><summary class="small">Instant answer (advanced)</summary>'
+ '<p class="small muted" style="margin:6px 0">A regular expression (case-insensitive). When a question matches it, this answer is sent as is, with no AI call. The lowest order number wins when several match; the code seeds use 10, 20, 30 and so on. Leave it empty to answer through the AI only.</p>'
+ '<div style="display:grid;grid-template-columns:1fr 110px;gap:8px"><input id="kbPat" class="mono small" value="' + esc(e.pattern || '') + '" placeholder="(coinbase account|regular coinbase)"><input id="kbOrd" class="small" type="number" value="' + (e.order == null ? '' : esc(e.order)) + '" placeholder="order"></div></details>'
+ '</div>'
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 0"><button type="button" class="btn small" id="kbSave">' + (isNew ? 'Add entry' : 'Save') + '</button><button type="button" class="btn small sec" id="kbCancel">Cancel</button>'
+ (isNew ? '' : '<button type="button" class="btn small sec" id="kbDel" style="margin-left:auto">Delete</button>') + '</p>';
$('kbCancel').addEventListener('click', () => { load().catch(err => IAP.status(err.message, 'bad')); });
$('kbSave').addEventListener('click', async () => {
const b = $('kbSave'); if (b.disabled) return; b.disabled = true;
try {
const body = { title: $('kbTitle').value, questions: $('kbQs').value.split('\n'), answer: $('kbAns').value, tags: $('kbTags').value.split(','),
handoff: $('kbHandoff').checked, pattern: $('kbPat').value, order: $('kbOrd').value, source: e.source, ticketRef: e.ticketRef };
if (isNew) await api('/api/admin/kb', body); else await api('/api/admin/kb/' + encodeURIComponent(e.id), body, 'PUT');
IAP.status(isNew ? 'Entry added. The assistant uses it from the next question.' : 'Entry saved.', 'ok');
await load();
} catch (err) { IAP.status(err.message, 'bad'); } finally { b.disabled = false; }
});
if ($('kbDel')) $('kbDel').addEventListener('click', async () => {
if (!(await IAP.confirmBox('Delete "' + (e.title || e.id) + '"? The assistant stops using it right away.', { ok: 'Delete', cancel: 'Keep it' }))) return;
try { await api('/api/admin/kb/' + encodeURIComponent(e.id), undefined, 'DELETE'); IAP.status('Entry deleted.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); }
});
$('kbTitle').focus();
}
// a support reply, tidied into a draft: the greeting and sign-off go, the member's words become the question
function fromTicket(t, question, reply) {
const q = String(question || '').replace(/^[\s\S]*?\bMe: /, '').split(/\nAssistant: /)[0].replace(/\s+/g, ' ').trim().slice(0, 300);
const a = String(reply || '').replace(/^\s*(hi|hello|hey|dear|good (morning|afternoon|evening))\b[^\n]*\n+/i, '')
.replace(/\n+\s*(thanks|thank you|cheers|best|regards|kind regards|talk soon|marty)\b[\s\S]{0,80}$/i, '').trim();
const title = String(t.subject || '').replace(/^Chat:\s*/i, '').trim().slice(0, 200) || q.slice(0, 120);
const tags = String(t.category || '').toLowerCase().split(/\s*&\s*|\s*,\s*/).filter(x => x && x !== 'other');
return { title, questions: q ? [q] : [], answer: a, tags, source: 'ticket', ticketRef: t.ref };
}
window.IAPKB = { load: () => load(), compose, fromTicket };
})();
+40
View File
@@ -0,0 +1,40 @@
// Admin > Settings > Refuel Kit (2026-10-24). The SAME file ships in InstantAdPay and LinkSpin. Upload one month's base art
// (five sizes, this site's own program), preview the personalization (@name + QR to the member's link), then release it.
// Keep the QR corner and the name strip clear in the art (see the layout note on the card).
(function () {
const $ = id => document.getElementById(id);
if (!$('kitBox')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const say = m => { $('kitSub').textContent = m; };
const api = async (url, opt) => { const r = await fetch(url, Object.assign({ cache: 'no-store' }, opt || {})); const j = await r.json().catch(() => ({})); if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status)); return j; };
const post = (url, body) => api(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
const nextMonth = () => { const d = new Date(); const ct = new Date(d.toLocaleString('en-US', { timeZone: 'America/Chicago' })); ct.setDate(1); ct.setMonth(ct.getMonth() + 1); return ct.getFullYear() + '-' + String(ct.getMonth() + 1).padStart(2, '0'); };
let sizes = [];
async function load() {
try {
const d = await api('/api/admin/kits'); sizes = d.sizes;
if (!$('kitMonth').value) $('kitMonth').value = nextMonth();
$('kitList').innerHTML = d.kits.length ? d.kits.map(k => '<div style="border:1px solid var(--line,#ccd);border-radius:8px;padding:10px;margin:8px 0">'
+ '<b>' + esc(k.label) + '</b> ' + (k.theme ? '&middot; ' + esc(k.theme) + ' ' : '') + '<span class="small muted">(' + esc(k.month) + ')</span> '
+ (k.released ? '<span class="badge">released</span>' : '<span class="badge amber">draft</span>') + '<div class="small" style="margin:6px 0">'
+ k.sizes.map(s => s.size + ': ' + (s.ready ? 'ready' : '<b>missing</b>')).join(' &middot; ') + '</div>'
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small sec" type="button" data-kedit="' + esc(k.month) + '" data-theme="' + esc(k.theme) + '">Edit</button>'
+ '<button class="btn small' + (k.released ? ' sec' : '') + '" type="button" data-krel="' + esc(k.month) + '" data-on="' + (k.released ? '0' : '1') + '"' + (!k.complete && !k.released ? ' disabled title="upload all five sizes first"' : '') + '>' + (k.released ? 'Unrelease' : 'Release to members') + '</button></div></div>').join('') : '<p class="small muted">No kits yet.</p>';
$('kitList').querySelectorAll('[data-kedit]').forEach(b => b.addEventListener('click', () => { $('kitMonth').value = b.dataset.kedit; $('kitTheme').value = b.dataset.theme; say('editing ' + b.dataset.kedit); }));
$('kitList').querySelectorAll('[data-krel]').forEach(b => b.addEventListener('click', async () => { try { await post('/api/admin/kits', { month: b.dataset.krel, released: b.dataset.on === '1' }); load(); } catch (e) { say(e.message); } }));
$('kitSizes').innerHTML = sizes.map(s => '<label class="small" style="display:block;margin:4px 0">' + s + ' <input type="file" accept="image/png,image/jpeg,image/gif" data-ksize="' + s + '"></label>').join('');
$('kitSizes').querySelectorAll('[data-ksize]').forEach(inp => inp.addEventListener('change', async () => {
const f = inp.files && inp.files[0]; if (!f) return; const m = $('kitMonth').value.trim();
try { await api('/api/admin/kits/upload?month=' + encodeURIComponent(m) + '&size=' + inp.dataset.ksize, { method: 'POST', headers: { 'Content-Type': f.type }, body: f }); say(inp.dataset.ksize + ' uploaded for ' + m); load(); } catch (e) { say(e.message); }
}));
$('kitPrevSize').innerHTML = sizes.map(s => '<option>' + s + '</option>').join('');
} catch (e) { say('Could not load: ' + e.message); }
}
$('kitSave').addEventListener('click', async () => { try { await post('/api/admin/kits', { month: $('kitMonth').value.trim(), theme: $('kitTheme').value }); say('saved'); load(); } catch (e) { say(e.message); } });
$('kitPlaceholder').addEventListener('click', async () => { try { const r = await post('/api/admin/kits/placeholder', { month: $('kitMonth').value.trim() }); say('placeholder art: ' + r.sizes.join(', ')); load(); } catch (e) { say(e.message); } });
$('kitPreview').addEventListener('click', () => {
const q = 'month=' + encodeURIComponent($('kitMonth').value.trim()) + '&size=' + encodeURIComponent($('kitPrevSize').value) + '&username=' + encodeURIComponent($('kitPrevName').value || 'yourname') + ($('kitPrevGif').checked ? '&variant=gif' : '') + '&t=' + Date.now();
$('kitPrevBox').innerHTML = '<img alt="preview" style="max-width:100%;border:1px solid #ccd" src="/api/admin/kits/preview?' + q + '">';
});
load();
})();
+64
View File
@@ -0,0 +1,64 @@
// Admin > Members > Sponsor check (2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
// Lists members on both sites whose sponsor differs (or is set on one side only), with when and how each side's sponsor
// was set and whether each side is bound on its contract. "Use X's sponsor" applies X's sponsor on the OTHER site; the
// server refuses when the member is already bound there. Nothing runs until the admin presses "Run the check".
(function () {
const $ = id => document.getElementById(id);
if (!$('scRun')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit' };
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
function side(f) {
if (!f) return '<span class="muted">no account</span>';
const sp = f.sponsorEmail ? esc(f.sponsorName || f.sponsorEmail) + '<br><span class="small muted">' + esc(f.sponsorEmail) + '</span>' : f.deadLink ? '<span class="badge amber">dead link: ' + esc(f.sponsorRef) + '</span>' : '<span class="muted">none (in the tank)</span>';
const how = [];
if (f.prov) how.push('<b>' + esc(HOW[f.prov.by] || f.prov.by) + '</b> ' + esc(day(f.prov.at)) + (f.prov.origin ? ' on ' + esc(NAME[f.prov.origin] || f.prov.origin) : '') + (f.prov.prevEmail ? ', before: ' + esc(f.prov.prevEmail) : ''));
else how.push('no deliberate change on record; account made ' + esc(day(f.created)) + (f.joinedVia ? ' via ' + esc(f.joinedVia) : '') + (f.joinedRef ? ' (' + esc(f.joinedRef) + ')' : ''));
for (const a of (f.adoptions || []).slice(-3)) how.push('tank: ' + esc(a.status) + ' by ' + esc(a.adopter) + ' ' + esc(day(a.ts)));
if (f.remoteTank && f.remoteTank.open) how.push('adopted on the other site by ' + esc(f.remoteTank.adopterEmail));
if (f.pending) how.push('<span class="badge amber">follow waiting: ' + esc(f.pending.why || '') + '</span>');
for (const l of (f.log || []).filter(x => x.conflict).slice(0, 2)) how.push('<span class="badge amber">' + esc(l.action) + '</span> ' + esc(l.reason || '') + ' ' + esc(day(l.ts)));
const bound = f.bound ? '<span class="badge">bound on chain' + (f.memberId ? ': member #' + f.memberId : '') + (f.activation ? ', on-chain sponsor #' + f.activation.sponsorId + ', block ' + f.activation.block : '') + '</span>' : '<span class="muted small">not bound on chain' + (f.wallet ? ' (wallet linked)' : '') + '</span>';
return sp + '<div class="small" style="margin-top:4px">' + how.join('<br>') + '</div><div style="margin-top:4px">' + bound + '</div>';
}
let last = null;
async function run() {
$('scRun').disabled = true; $('scSub').textContent = 'checking both sites...';
try {
const r = await (await fetch('/api/admin/sponsor-check', { cache: 'no-store' })).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
last = r;
if (r.peerError) { $('scSub').textContent = 'could not read the other site: ' + r.peerError; $('scTable').innerHTML = ''; return; }
const differ = r.rows.filter(x => x.kind === 'differ').length;
$('scSub').textContent = r.shared + ' on both sites, ' + r.same + ' match, ' + differ + ' differ, ' + (r.rows.length - differ) + ' set on one side only (' + day(r.at) + ')';
$('scTable').innerHTML = '<tr><th>Member</th><th>InstantAdPay sponsor</th><th>LinkSpin sponsor</th><th>Settle it</th></tr>' + (r.rows.length ? r.rows.map(x => {
const iapBound = !!(x.iap && x.iap.bound), lsBound = !!(x.ls && x.ls.bound);
return '<tr><td>' + esc(x.username ? '@' + x.username : '') + '<br><span class="small muted">' + esc(x.email) + '</span><br><span class="small muted">' + esc(x.kind === 'differ' ? 'different sponsors' : x.kind === 'iap-only' ? 'sponsor on InstantAdPay only' : 'sponsor on LinkSpin only') + '</span></td>'
+ '<td>' + side(x.iap) + '</td><td>' + side(x.ls) + '</td><td class="act">'
+ '<button class="btn small sec" data-scuse="instantadpay" data-email="' + esc(x.email) + '"' + (lsBound ? ' disabled title="bound on the LinkSpin contract: its sponsor there cannot change"' : '') + '>Use InstantAdPay\'s sponsor</button><br>'
+ '<button class="btn small sec" style="margin-top:6px" data-scuse="linkspin" data-email="' + esc(x.email) + '"' + (iapBound ? ' disabled title="bound on the InstantAdPay contract: its sponsor there cannot change"' : '') + '>Use LinkSpin\'s sponsor</button></td></tr>';
}).join('') : '<tr><td colspan="4" class="muted">Every shared member has the same sponsor on both sites.</td></tr>');
const logs = [].concat((r.follow && r.follow.recent) || []).map(l => Object.assign({ where: r.here }, l)).concat(((r.peerFollow && r.peerFollow.recent) || []).map(l => Object.assign({ where: r.here === 'linkspin' ? 'instantadpay' : 'linkspin' }, l))).sort((a, b) => b.ts - a.ts).slice(0, 60);
$('scLog').innerHTML = '<tr><th>When</th><th>Site</th><th>Member</th><th>What</th><th>From</th><th>To</th><th>Why</th></tr>' + (logs.length ? logs.map(l => '<tr><td class="when">' + esc(day(l.ts)) + '</td><td>' + esc(NAME[l.where] || l.where) + '</td><td class="small">' + esc(l.email || '') + '</td><td>' + (l.conflict ? '<span class="badge amber">' + esc(l.action) + '</span>' : esc(l.action)) + (l.by ? ' <span class="small muted">' + esc(HOW[l.by] || l.by) + '</span>' : '') + '</td><td class="small">' + esc(l.from || '-') + '</td><td class="small">' + esc(l.to || '(tank)') + '</td><td class="small muted">' + esc(l.reason || '') + '</td></tr>').join('') : '<tr><td colspan="7" class="muted">nothing yet</td></tr>');
} catch (e) { $('scSub').textContent = e.message; say(e.message, 'bad'); }
finally { $('scRun').disabled = false; }
}
$('scRun').addEventListener('click', run);
document.addEventListener('click', async e => {
const b = e.target.closest('[data-scuse]'); if (!b || b.disabled) return;
const use = b.dataset.scuse, email = b.dataset.email; const row = last && last.rows.find(x => x.email === email); if (!row) return;
const from = use === 'instantadpay' ? row.iap : row.ls; const target = use === 'instantadpay' ? 'LinkSpin' : 'InstantAdPay';
const who = from && from.sponsorEmail ? (from.sponsorName || from.sponsorEmail) : 'no sponsor (back to the holding tank)';
let ok = false;
try { ok = await IAP.confirmBox('Set ' + email + "'s sponsor on " + target + ' to ' + who + '? The other site keeps what it has. This is refused if the member is already bound on the ' + target + ' contract.', { title: 'Use ' + NAME[use] + "'s sponsor", ok: 'Apply on ' + target, cancel: 'Cancel' }); } catch (err) { ok = false; }
if (!ok) return;
b.disabled = true;
try {
const r = await (await fetch('/api/admin/sponsor-check/resolve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, use }) })).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
say('Done: ' + email + ' now has ' + who + ' on ' + target + '.', 'ok'); await run();
} catch (err) { say(err.message, 'bad'); b.disabled = false; }
});
})();
+293 -7
View File
@@ -44,16 +44,18 @@
});
// ── panes ──
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings };
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', kb: 'Knowledge base', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, kb: () => window.IAPKB.load(), reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings };
function setPane(name) {
const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email)
if (!TITLES[name]) name = 'overview';
document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; });
document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.classList.toggle('on', b.dataset.pane === name));
$('boTitle').textContent = TITLES[name];
if (location.hash.slice(1) !== name) history.replaceState(null, '', '#' + name);
const keepQ = name === 'support' && paneQ ? '?' + paneQ : '';
if (location.hash.slice(1) !== name + keepQ) history.replaceState(null, '', '#' + name + keepQ);
$('adminArea').classList.remove('side-open');
loaders[name]().catch(e => IAP.status(e.message, 'bad'));
return loaders[name](paneQ).catch(e => IAP.status(e.message, 'bad'));
}
document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.addEventListener('click', () => setPane(b.dataset.pane)));
document.addEventListener('click', e => { const g = e.target.closest('[data-goto]'); if (g) setPane(g.dataset.goto); });
@@ -72,6 +74,7 @@
$('chainLine').textContent = c.chainName + (c.rehearsal ? ' · rehearsal' : '');
} catch (e) {}
setPane(location.hash.slice(1) || 'overview');
supportBadge();
}
// ── overview ──
@@ -253,10 +256,31 @@
// ── all campaigns ──
let allCamps = [];
async function loadCampaigns() {
loadLoginLine().catch(e => IAP.status(e.message, 'bad'));
const r = await api('/api/admin/campaigns');
allCamps = r.campaigns || [];
drawCamps();
}
// prepaid login-ad line (2026-10-23): paid reservations waiting for a slot, oldest paid first. Dates in Central time.
const lqWhen = ts => ts ? esc(ctWhen(ts)) : '<span class="muted">unknown</span>'; // ctWhen (below) prints Central time
async function loadLoginLine() {
const d = await api('/api/admin/login-queue');
$('lqSub').textContent = d.used + ' of ' + d.max + ' member slots live · ' + d.queued + ' paid reservation' + (d.queued === 1 ? '' : 's') + ' in line · ' + d.free + ' open';
$('lqTable').innerHTML = '<tr><th>Place</th><th>ID</th><th>Owner</th><th>Campaign</th><th>Paid</th><th>Queued at</th><th>Estimated start</th><th></th></tr>'
+ (d.queue.length ? d.queue.map(c => '<tr><td><b>#' + c.place + '</b></td><td>#' + c.id + '</td><td><span class="trunc" title="' + esc(c.owner) + '">' + esc(c.owner) + '</span></td>'
+ '<td>' + esc(c.name) + '<div><a class="small trunc" href="' + esc(c.targetUrl) + '" target="_blank" rel="noopener">' + esc(c.targetUrl) + '</a></div></td>'
+ '<td class="mono small">' + Number(c.paid || 0).toLocaleString() + '</td><td class="small muted">' + lqWhen(c.queuedAt) + '</td><td class="small">' + lqWhen(c.estStart) + '</td>'
+ '<td class="act"><button class="btn small sec" data-lqcancel="' + c.id + '" data-lqowner="' + esc(c.owner) + '" data-lqpaid="' + Number(c.paid || 0) + '">Cancel + refund</button></td></tr>').join('')
: '<tr><td colspan="8" class="muted">Nobody is waiting. When every slot is taken, members can pay now to reserve the next one.</td></tr>');
}
document.addEventListener('click', async e => {
const b = e.target.closest('[data-lqcancel]'); if (!b) return;
const ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.lqowner + '? The full ' + Number(b.dataset.lqpaid || 0).toLocaleString() + ' credits go back to them as purchased credits, and everyone behind moves up one place.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' });
if (!ok) return;
b.disabled = true;
try { const r = await api('/api/admin/login-queue/' + b.dataset.lqcancel + '/cancel', {}); IAP.status('Reservation #' + r.id + ' cancelled, ' + Number(r.refunded || 0).toLocaleString() + ' credits refunded.', 'ok'); await loadCampaigns(); }
catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
});
function drawCamps() {
const q = ($('campFilter').value || '').trim().toLowerCase();
const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q));
@@ -270,8 +294,13 @@
async function loadTank() {
try {
const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return;
$('tankAdmSub').textContent = r.waiting.length + ' waiting · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window';
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>');
const nReady = r.waiting.filter(w => w.ready).length;
$('tankAdmSub').textContent = r.waiting.length + ' waiting' + (nReady ? ' (' + nReady + ' ready to activate)' : '') + ' · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window · ready members held ' + (r.holdHours || 24) + ' h, then auto-assigned in rotation';
// ready = wallet linked: activation is held (never the company) until someone adopts them or the 24-hour safety net assigns them (2026-10-27)
const left = w => { const ms = (w.holdUntil || 0) - Date.now(); if (ms <= 0) return 'assigning now'; const m = Math.round(ms / 60000); return (m >= 60 ? Math.floor(m / 60) + ' h ' + (m % 60) + ' min' : m + ' min') + ' left'; };
const rb = w => w.ready ? ' <span class="badge" style="background:rgba(34,197,94,.15);border-color:#22c55e;color:#22c55e">Ready to activate · ' + left(w) + '</span>' : '';
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>')
+ ((r.aligned || []).length ? '<tr><th colspan="4">Aligned to their network sponsor (LinkSpin) instead of the tank</th></tr>' + r.aligned.slice(0, 15).map(x => '<tr><td>' + esc(x.email) + '</td><td>' + esc(x.toName || x.to) + '</td><td class="when">' + when(x.at) + '</td><td class="muted">' + esc(x.via || '') + '</td></tr>').join('') : '');
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
} catch (e) {}
}
@@ -429,7 +458,7 @@
h += '<div><h4 style="margin:0 0 6px">Payouts received</h4><div class="tablewrap"><table class="adm-table"><tr><th>When</th><th>From</th><th>Tier</th><th>Amount</th></tr>'
+ (d.received.length ? d.received.map(r => '<tr><td class="small">' + when(r.ts) + '</td><td>#' + r.buyerId + (d.names[r.buyerId] ? ' @' + esc(d.names[r.buyerId]) : '') + '</td><td>' + r.tier + '</td><td>' + polOf(r.amountWei) + ' POL</td></tr>').join('') : '<tr><td colspan="4" class="muted">Nothing received yet.</td></tr>') + '</table></div></div></div>';
h += '<h4 style="margin:18px 0 6px">Campaigns (' + d.campaigns.length + ')</h4><div class="tablewrap"><table class="adm-table"><tr><th>#</th><th>Type</th><th>Status</th><th>Budget</th><th>Spent</th><th>Views</th><th>Clicks</th><th>Created</th></tr>'
+ (d.campaigns.length ? d.campaigns.map(c => '<tr><td>' + c.id + '</td><td>' + esc(c.type) + '</td><td>' + esc(c.status) + '</td><td>' + Number(c.budget || 0).toLocaleString() + '</td><td>' + Number(c.spent || 0).toLocaleString() + '</td><td>' + Number(c.views || 0).toLocaleString() + '</td><td>' + Number(c.clicks || 0).toLocaleString() + '</td><td class="small muted">' + when(c.created) + '</td></tr>').join('') : '<tr><td colspan="8" class="muted">No campaigns.</td></tr>') + '</table></div>';
+ (d.campaigns.length ? d.campaigns.map(c => '<tr><td>' + c.id + '</td><td>' + esc(c.type) + '</td><td>' + esc(c.status) + '</td><td>' + Number(c.budget || 0).toLocaleString() + '</td><td>' + Number(c.spent || 0).toLocaleString() + '</td><td>' + (c.pack ? Number(c.views || 0).toLocaleString() + ' <span class="muted small">of ' + Number(c.pack).toLocaleString() + ' visits</span>' : Number(c.views || 0).toLocaleString()) + '</td><td>' + Number(c.clicks || 0).toLocaleString() + '</td><td class="small muted">' + when(c.created) + '</td></tr>').join('') : '<tr><td colspan="8" class="muted">No campaigns.</td></tr>') + '</table></div>';
$('mcBody').innerHTML = h;
if (location.hash !== '#members') history.replaceState(null, '', '#members');
loadTrace(d);
@@ -598,6 +627,7 @@
});
async function loadTraffic() {
loadPromos().catch(e => IAP.status(e.message, 'bad'));
loadLoginShows().catch(e => IAP.status(e.message, 'bad'));
const d = await (await fetch('/api/admin/traffic?days=' + trfDays)).json();
if (d.error) throw new Error(d.error);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
@@ -616,6 +646,19 @@
$('trfAngles').innerHTML = '<tr><th>Angle</th><th>Join-page<br>views</th><th>Signups</th><th>View &rarr;<br>signup</th></tr>' + (d.angles.length ? d.angles.map(a => '<tr><td>' + esc(a.angle) + '</td><td>' + n(a.views) + '</td><td>' + n(a.signups) + '</td><td>' + pct(a.signups, a.views) + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">No angle data yet.</td></tr>');
$('trfDaily').innerHTML = '<tr><th>Day</th><th>Page views</th><th>Signups</th></tr>' + (d.daily.length ? d.daily.slice().reverse().map(x => '<tr><td>' + esc(x.day) + '</td><td>' + n(x.hits) + '</td><td>' + n(x.signups) + '</td></tr>').join('') : '<tr><td colspan="3" class="muted">Nothing yet.</td></tr>');
}
// login-ad showings per Central day (2026-10-18): the dashboard gate vs the games' sign-in kit, member slot vs house ad,
// and sign-ins that had no login ad to show. A week of these decides whether the 3-slot cap goes up.
async function loadLoginShows() {
const d = await (await fetch('/api/admin/login-shows?days=14')).json();
if (d.error) throw new Error(d.error);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const n = v => Number(v || 0).toLocaleString(), shown = x => x.member + x.house;
const week = d.days.slice(0, 7).reduce((a, x) => { a.dash += shown(x.dashboard); a.games += shown(x.games); return a; }, { dash: 0, games: 0 });
$('lsSub').textContent = 'last 7 days: ' + n(week.dash + week.games) + ' shown (' + n(week.dash) + ' dashboard, ' + n(week.games) + ' games) · slots ' + d.slots.used + ' of ' + d.slots.max + ' taken';
$('trfLogin').innerHTML = '<tr><th>Day (CT)</th><th>Dashboard<br>shown</th><th>Games<br>shown</th><th>Total<br>shown</th><th>Of which<br>house ad</th><th>Sign-ins with<br>no login ad</th><th>By game</th></tr>'
+ d.days.map(x => '<tr><td>' + esc(x.day) + '</td><td>' + n(shown(x.dashboard)) + '</td><td>' + n(shown(x.games)) + '</td><td><b>' + n(shown(x.dashboard) + shown(x.games)) + '</b></td><td>' + n(x.dashboard.house + x.games.house) + '</td><td>' + n(x.dashboard.none + x.games.none) + '</td><td class="small">'
+ (Object.keys(x.byGame).length ? Object.entries(x.byGame).map(([g, v]) => esc(g) + ' ' + n(v)).join(', ') : '<span class="muted">-</span>') + '</td></tr>').join('');
}
// ── blog: coaching articles, public at /blog (Marty, 2026-09-12) ──
let blCur = null; // slug being edited, or null for a new one
function blCount() {
@@ -713,6 +756,7 @@
}
async function loadPnl() {
loadOverride().catch(() => {}); // its own request: does not wait for the chain reads below
const r = await api('/api/admin/pnl?days=' + pnlDays);
const px = r.polUsd || 0;
const platUsd = (Number(BigInt(r.platformWei || '0') / 10n ** 14n) / 10000) * px;
@@ -745,6 +789,22 @@
+ '<tr><td class="muted small">Hunters paid</td><td class="mono">' + Number(t.hunters || 0) + '</td><td class="muted small">today ' + Number(t.today || 0).toFixed(3) + ' POL</td></tr>';
}
}
// every game's payouts, all time, running total (Marty, 2026-10-18). PassiveDrip is a drip
// program rather than a game, so it sits under the total instead of inside it.
const ga = r.gamesAll, gaEl = $('pnlGames');
if (gaEl) {
if (!ga || ga.error || !Array.isArray(ga.games) || !ga.games.length) gaEl.innerHTML = '<tr><td colspan="4" class="muted small">' + (ga && ga.scanning ? 'Reading the game wallets from Polygon for the first time. Refresh in a minute.' : 'Game payout figures unavailable' + (ga && ga.error ? ' (' + esc(ga.error) + ')' : '') + '.') + '</td></tr>';
else {
const wp = w => Number(BigInt(w) / 10n ** 12n) / 1e6, games = ga.games.filter(g => g.slug !== 'passivedrip'), pd = ga.games.find(g => g.slug === 'passivedrip');
const row = (name, w, n, pl, cls) => '<tr' + (cls ? ' class="' + cls + '"' : '') + '><td>' + name + '</td><td class="mono">' + wp(w).toFixed(4) + '</td><td class="mono">$' + (wp(w) * px).toFixed(2) + '</td><td class="mono small">' + Number(n).toLocaleString() + ' to ' + Number(pl).toLocaleString() + '</td></tr>';
const tw = games.reduce((t, g) => t + BigInt(g.wei), 0n), tn = games.reduce((t, g) => t + g.count, 0);
gaEl.innerHTML = '<tr><th>Game</th><th>POL</th><th>USD now</th><th>Payouts to players</th></tr>'
+ games.map(g => row(esc(g.name) + (g.error ? ' <span class="chip flat">stale</span>' : ''), g.wei, g.count, g.players)).join('')
+ '<tr><td><b>All game payouts</b></td><td class="mono"><b>' + wp(tw).toFixed(4) + '</b></td><td class="mono"><b>$' + (wp(tw) * px).toFixed(2) + '</b></td><td class="mono small">' + tn.toLocaleString() + ' payouts</td></tr>'
+ (pd ? row('<span class="muted">PassiveDrip (not a game)</span>', pd.wei, pd.count, pd.players) : '')
+ '<tr><td colspan="4" class="muted small">Read ' + (ga.at ? new Date(ga.at).toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', minute: '2-digit', month: 'short', day: 'numeric' }) + ' CT' : 'just now') + (ga.scanning ? ', refreshing' : '') + '. Updates every 10 minutes.</td></tr>';
}
}
$('pnlSplit').innerHTML ='<tr><th>Line</th><th>POL</th><th>USD now</th></tr>'
+ [['Level 1 (50%)', r.byTier[1]], ['Level 2 (20%)', r.byTier[2]], ['Level 3 (10%)', r.byTier[3]], ['Platform (20% + pass-ups)', r.platformWei]].map(x => '<tr><td>' + x[0] + '</td><td class="mono">' + pol(x[1]) + '</td><td class="mono">' + usdOf(x[1], px) + '</td></tr>').join('');
const W = r.wallets || {}, B = r.balances || {};
@@ -810,6 +870,29 @@
});
document.querySelectorAll('#pnlPeriods [data-days]').forEach(b => b.addEventListener('click', () => { pnlDays = Number(b.dataset.days); document.querySelectorAll('#pnlPeriods [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadPnl().catch(e => IAP.status(e.message, 'bad')); }));
if ($('pnlFixedSave')) $('pnlFixedSave').addEventListener('click', async () => { try { await api('/api/admin/site', { pnlFixedMonthlyUsd: Number($('pnlFixed').value) || 0 }, 'PATCH'); IAP.status('Saved.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
// Level 4 override (2026-10-23): week status from /api/admin/override; the pay button exists only while the live payer is ready
const OV_STATE = { 'not planned': 'not planned', planning: 'planning', planned: 'pending', paying: 'paying', held: 'held', paid: 'paid' };
async function loadOverride(week) {
if (!$('ovPayer')) return;
let r; try { r = await (await fetch('/api/admin/override' + (week ? '?week=' + encodeURIComponent(week) : ''), { cache: 'no-store' })).json(); } catch (e) { $('ovPayer').textContent = 'Could not read the override: ' + e.message; return; }
const pz = r.payer || {};
$('ovPayer').textContent = 'Mode: ' + (pz.mode || '?') + (pz.ready ? ' · PAYING automatically each Monday after 9 AM CT' : ' · not paying (' + (pz.why || []).join('; ') + ')')
+ (pz.address ? ' · payer wallet ' + pz.address + ' holds ' + (pz.balancePol || '?') + ' POL' : '') + ' · weekly cap ' + (pz.capPol || '?') + ' POL · minimum ' + (pz.dustPol || '?') + ' POL'
+ (pz.goLive ? ' · purchases from ' + new Date(pz.goLive).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT' : '') + (pz.lastError ? ' · last error: ' + pz.lastError.msg : '');
$('ovPay').hidden = !pz.ready;
const sel = $('ovWeek'); if (!sel.options.length) { const now = new Date(); for (let i = 0; i < 10; i++) { const d = new Date(now.getTime() - i * 7 * 86400000); const v = d.toISOString().slice(0, 10); sel.innerHTML += '<option value="' + v + '">week containing ' + v + '</option>'; } sel.selectedIndex = 1; }
$('ovWeeks').innerHTML = (r.dueWeeks || []).length ? '<table><tr><th>Week of</th><th>Status</th><th>Total</th></tr>' + r.dueWeeks.map(w => '<tr><td>' + esc(w.week) + '</td><td>' + esc(OV_STATE[w.state] || w.state) + (w.heldWhy ? ' <span class="muted">(' + esc(w.heldWhy) + ')</span>' : '') + '</td><td class="mono">' + esc(w.totalPol || '0') + ' POL</td></tr>').join('') + '</table>' : '';
const st = r.status || {}; const t = r.totals || {};
$('ovOut').innerHTML = '<p>Week of ' + esc(r.week || '') + ': ' + (r.purchases || 0) + ' purchases, $' + Number(t.salesUsd || 0).toFixed(2) + ' sales. Override due: $' + Number(t.wouldPayUsd || 0).toFixed(2) + ' (' + Number(t.wouldPayPol || 0).toFixed(4) + ' POL) to ' + (r.recipients || []).length + ' members; company keeps $' + Number(t.companyKeepsUsd || 0).toFixed(2) + '. Payout status: <b>' + esc(OV_STATE[st.state] || st.state || '?') + '</b>' + (st.heldWhy ? ' (' + esc(st.heldWhy) + ')' : '') + '.</p>'
+ ((st.rows || []).length ? '<table><tr><th>Member</th><th>POL</th><th>USD</th><th>Status</th><th></th></tr>' + st.rows.map(x => '<tr><td>#' + x.memberId + '</td><td class="mono">' + esc(x.pol) + '</td><td class="mono">$' + Number(x.usd || 0).toFixed(2) + '</td><td>' + esc(x.state) + (x.note ? ' <span class="muted">' + esc(x.note) + '</span>' : '') + '</td><td>' + (x.tx ? '<a target="_blank" rel="noopener" href="' + esc(x.tx) + '">tx</a>' : '') + '</td></tr>').join('') + '</table>'
: (r.recipients || []).length ? '<table><tr><th>Member</th><th>POL</th><th>USD</th><th>Buys</th></tr>' + r.recipients.map(x => '<tr><td>#' + x.recipientId + '</td><td class="mono">' + Number(x.pol).toFixed(4) + '</td><td class="mono">$' + Number(x.usd).toFixed(2) + '</td><td>' + x.purchases + '</td></tr>').join('') + '</table>' : '');
}
if ($('ovShow')) $('ovShow').addEventListener('click', () => loadOverride($('ovWeek').value));
if ($('ovPay')) $('ovPay').addEventListener('click', async () => {
const wk = $('ovWeek').value;
if (!await IAP.confirmBox('This sends real POL from the payer wallet for every closed week up to the week containing ' + wk + ' that is not paid yet. Each member is paid once; anything already paid is skipped.', { title: 'Pay the override now?', ok: 'Pay now' })) return;
try { const r = await api('/api/admin/override/pay', { week: wk }); IAP.status('Override: ' + (r.results || []).map(x => x.week + ' ' + (x.state || x.held || (x.why || []).join(', '))).join(' · '), 'ok'); loadOverride(wk); } catch (e) { IAP.status(e.message, 'bad'); }
});
if ($('burnerRun')) $('burnerRun').addEventListener('click', async () => { try { const r = await api('/api/admin/burner/run', {}); IAP.status('Burner ran: ' + (r.burned || 0) + ' burned.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
async function loadAudit() {
if (!$('audTable')) return;
@@ -822,6 +905,107 @@
} catch (e) { $('audSub').textContent = e.message; }
}
if ($('audRun')) $('audRun').addEventListener('click', busy($('audRun'), loadAudit));
// ── help desk (2026-10-16): one shared desk (IAP now, LinkSpin later); newest activity first ──
const SP_STATUS = { open: 'Open', waiting_on_member: 'Waiting on member', closed: 'Closed' };
const SP_AUTHOR = { member: 'Member', admin: 'You', system: 'System' };
const ctWhen = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
const spLink = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '<a href="$1" target="_blank" rel="noopener nofollow">$1</a>');
let spFilter = { status: 'open', platform: '', category: '', q: '' }, spTemplates = [], spCats = [];
async function supportBadge() {
try { const c = await api('/api/admin/support/counts'); $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : c.open; return c; } catch (e) { return null; }
}
async function loadSupport(q) {
const ref = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(q || '') || [])[1];
if (ref) return openTicket(ref);
$('spView').hidden = true; $('spList').hidden = false;
const qs = new URLSearchParams(Object.entries(spFilter).filter(([, v]) => v)).toString();
const [r, tp] = await Promise.all([api('/api/admin/support' + (qs ? '?' + qs : '')), spTemplates.length ? Promise.resolve({ templates: spTemplates }) : api('/api/admin/support/templates')]);
spTemplates = tp.templates || []; spCats = r.categories || spCats;
const c = r.counts || {};
$('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : (c.open || '');
$('spSub').textContent = (c.open || 0) + ' open · ' + (c.waiting_on_member || 0) + ' waiting on member · ' + (c.unread || 0) + ' unread';
const chip = (v, label, n) => '<button type="button" class="chip-t' + (spFilter.status === v ? ' on' : '') + '" data-spst="' + v + '">' + label + (n != null ? ' (' + n + ')' : '') + '</button>';
$('spStatus').innerHTML = chip('open', 'Open', c.open || 0) + chip('waiting_on_member', 'Waiting on member', c.waiting_on_member || 0) + chip('closed', 'Closed', c.closed || 0) + chip('', 'All');
if (!$('spCategory').options.length) $('spCategory').innerHTML = '<option value="">All categories</option>' + spCats.map(x => '<option>' + esc(x) + '</option>').join('');
$('spTable').innerHTML = '<tr><th>Ticket</th><th>Subject</th><th>From</th><th>Category</th><th>Status</th><th>Last activity</th></tr>'
+ (r.tickets.length ? r.tickets.map(t => '<tr data-spref="' + esc(t.ref) + '" style="cursor:pointer"><td class="mono small">' + (t.adminUnread ? '<b style="color:var(--amber,#ffb238)">●</b> ' : '') + esc(t.ref)
+ (t.platform !== 'iap' ? ' <span class="small muted">' + esc(t.platform) + '</span>' : '') + (t.priority === 'high' ? ' <b style="color:var(--bad)">high</b>' : '') + '</td>'
+ '<td>' + (t.adminUnread ? '<b>' + esc(t.subject) + '</b>' : esc(t.subject)) + '<div class="small muted">' + esc(t.source) + '</div></td>'
+ '<td class="small">' + esc(t.name || '') + '<div class="muted">' + esc(t.email) + (t.username ? ' · @' + esc(t.username) : '') + '</div></td>'
+ '<td class="small">' + esc(t.category) + '</td><td class="small">' + esc(SP_STATUS[t.status] || t.status) + '</td><td class="small muted" style="white-space:nowrap">' + esc(ctWhen(t.updated)) + '</td></tr>').join('')
: '<tr><td colspan="6" class="muted">No tickets here.</td></tr>');
drawTemplates();
}
$('spStatus').addEventListener('click', e => { const b = e.target.closest('[data-spst]'); if (!b) return; spFilter.status = b.dataset.spst; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
$('spPlatform').addEventListener('change', () => { spFilter.platform = $('spPlatform').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
$('spCategory').addEventListener('change', () => { spFilter.category = $('spCategory').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
let spQT = null; $('spQ').addEventListener('input', () => { clearTimeout(spQT); spQT = setTimeout(() => { spFilter.q = $('spQ').value.trim(); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }, 350); });
$('spTable').addEventListener('click', e => { const tr = e.target.closest('[data-spref]'); if (tr) { history.replaceState(null, '', '#support?t=' + tr.dataset.spref); openTicket(tr.dataset.spref).catch(err => IAP.status(err.message, 'bad')); } });
async function openTicket(ref) {
const v = await api('/api/admin/support/' + encodeURIComponent(ref));
if (!spTemplates.length) { try { spTemplates = (await api('/api/admin/support/templates')).templates || []; } catch (e) {} }
if (!spCats.length) spCats = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other'];
drawTicket(v); supportBadge();
}
function drawTicket(v) {
const t = v.ticket, rq = v.requester || {};
$('spList').hidden = true; $('spView').hidden = false;
const sel = (id, opts, cur) => '<select id="' + id + '" class="small">' + opts.map(o => '<option value="' + esc(o[0]) + '"' + (o[0] === cur ? ' selected' : '') + '>' + esc(o[1]) + '</option>').join('') + '</select>';
const stOpts = Object.entries(SP_STATUS);
$('spView').innerHTML = '<p style="margin:0 0 10px"><a href="#support" id="spBack">‹ All tickets</a></p>'
+ '<div class="card"><div class="card-head" style="flex-wrap:wrap;gap:8px"><h3 style="margin:0">' + esc(t.subject) + '</h3><span class="sub mono">' + esc(t.ref) + ' · ' + esc(t.platform) + ' · via ' + esc(t.source) + ' · opened ' + esc(ctWhen(t.created)) + '</span></div>'
+ '<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:6px 0 0"><label class="small muted">Status ' + sel('spSt', stOpts, t.status) + '</label>'
+ '<label class="small muted">Priority ' + sel('spPr', [['normal', 'Normal'], ['high', 'High']], t.priority) + '</label>'
+ '<label class="small muted">Category ' + sel('spCat', spCats.map(c => [c, c]), t.category) + '</label></div></div>'
+ '<div class="card"><div class="card-head"><h3>Requester</h3><span class="sub">' + (rq.member ? 'member account' : 'no account with this email') + '</span></div>'
+ kv([['Name', esc(t.name || '(not given)')], ['Email', esc(t.email)]].concat(rq.member ? [
['Account', (rq.username ? '@' + esc(rq.username) : '(no username yet)') + (rq.memberId ? ' · member #' + rq.memberId : ' · free member') + ' · <a href="#" id="spMember" data-email="' + esc(rq.email) + '">open member card</a>'],
['Wallet linked', rq.wallet ? 'yes' : 'no'], ['Joined', esc(ctWhen(rq.created))], ['Last seen', esc(ctWhen(rq.lastSeen) || 'never')]] : []).concat([['Private link', '<span class="mono small" style="word-break:break-all">' + esc(v.link) + '</span>']]))
+ '</div>'
+ '<div class="card"><div class="card-head"><h3>Thread</h3><span class="sub">' + v.messages.length + ' message' + (v.messages.length === 1 ? '' : 's') + '</span></div>'
+ v.messages.map(m => '<div style="border:1px solid ' + (m.internal ? 'rgba(242,201,76,.55)' : m.author === 'admin' ? 'rgba(67,232,195,.45)' : 'var(--line)') + ';background:' + (m.internal ? 'rgba(242,201,76,.07)' : m.author === 'admin' ? 'rgba(67,232,195,.05)' : 'transparent') + ';border-radius:12px;padding:10px 14px;margin:8px 0">'
+ '<div class="small muted" style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap"><b>' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '</b><span>' + esc(ctWhen(m.created)) + '</span></div>'
+ '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:6px">' + spLink(m.body) + '</div>'
+ (m.author === 'admin' && !m.internal && t.platform !== 'linkspin' && window.IAPKB ? '<p style="margin:8px 0 0"><button type="button" class="btn small sec" data-kbsave="' + m.id + '">Save as KB entry</button></p>' : '')
+ (m.bodyEn ? '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:8px;padding:8px 10px;border-left:3px solid var(--accent,#43e8c3);background:rgba(67,232,195,.07);border-radius:6px"><span class="small muted">🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)</span>\n' + spLink(m.bodyEn) + '</div>' : '')
+ ((m.attachments || []).length ? '<div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment" style="max-width:180px;max-height:140px;border-radius:8px;border:1px solid var(--line)"></a>').join('') + '</div>' : '') + '</div>').join('')
+ '</div>'
+ '<div class="card"><div class="card-head"><h3>Reply</h3><span class="sub">emailed to the requester' + (rq.member ? ' and put in their Help tab and inbox' : '') + '</span></div>'
+ '<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0 0 8px"><select id="spTpl" class="small"><option value="">Insert a saved reply…</option>' + spTemplates.map((x, i) => '<option value="' + i + '">' + esc(x.name) + '</option>').join('') + '</select></p>'
+ '<textarea id="spBody" rows="7" style="width:100%" maxlength="5000" placeholder="Write your reply"></textarea>'
+ '<p style="display:flex;gap:14px;flex-wrap:wrap;align-items:center;margin:10px 0 0"><label class="small"><input type="checkbox" id="spInternal"> Internal note (only you see it, nothing is sent)</label>'
+ '<label class="small muted">Then set status ' + sel('spAfter', stOpts, 'waiting_on_member') + '</label>'
+ '<button type="button" class="btn small" id="spSend">Send reply</button></p></div>';
$('spView').querySelectorAll('[data-kbsave]').forEach(b => b.addEventListener('click', async () => { // a good reply becomes a knowledge-base draft (2026-10-20)
const i = v.messages.findIndex(x => String(x.id) === b.dataset.kbsave); if (i < 0) return;
const asked = v.messages.slice(0, i).reverse().find(x => x.author === 'member' && !x.internal);
const draft = window.IAPKB.fromTicket(t, asked ? (asked.bodyEn || asked.body) : t.subject, v.messages[i].body);
await setPane('kb'); window.IAPKB.compose(draft);
}));
$('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } };
$('spSt').addEventListener('change', () => patch({ status: $('spSt').value }));
$('spPr').addEventListener('change', () => patch({ priority: $('spPr').value }));
$('spCat').addEventListener('change', () => patch({ category: $('spCat').value }));
if ($('spMember')) $('spMember').addEventListener('click', async e => { e.preventDefault(); await setPane('members'); openMember(e.target.dataset.email); });
$('spTpl').addEventListener('change', () => { const x = spTemplates[Number($('spTpl').value)]; if (x) { const b = $('spBody'); b.value = (b.value ? b.value.replace(/\s+$/, '') + '\n\n' : '') + x.body; b.focus(); } $('spTpl').value = ''; });
$('spInternal').addEventListener('change', () => { $('spAfter').value = $('spInternal').checked ? t.status : 'waiting_on_member'; $('spSend').textContent = $('spInternal').checked ? 'Save note' : 'Send reply'; });
$('spSend').addEventListener('click', busy($('spSend'), async () => {
const internal = $('spInternal').checked;
if (!internal && !(await IAP.confirmBox('Send this reply to ' + t.email + '?', { ok: 'Send', cancel: 'Not yet' }))) return;
drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref) + '/reply', { body: $('spBody').value, internal, status: $('spAfter').value }));
supportBadge(); IAP.status(internal ? 'Note saved.' : 'Reply sent.', 'ok');
}));
}
function drawTemplates() {
$('spTpls').innerHTML = spTemplates.map((x, i) => '<div class="sp-tpl" style="border:1px solid var(--line);border-radius:10px;padding:10px;margin:0 0 8px"><div style="display:flex;gap:8px"><input class="small" data-tn="' + i + '" value="' + esc(x.name) + '" placeholder="name" style="flex:1"><button type="button" class="btn small sec" data-tdel="' + i + '">Remove</button></div>'
+ '<textarea class="small" data-tb="' + i + '" rows="3" style="width:100%;margin-top:6px">' + esc(x.body) + '</textarea></div>').join('') || '<p class="small muted">No saved replies. Add one below.</p>';
}
const readTemplates = () => [...document.querySelectorAll('#spTpls [data-tn]')].map(el => ({ name: el.value, body: document.querySelector('#spTpls [data-tb="' + el.dataset.tn + '"]').value }));
$('spTpls').addEventListener('click', e => { const b = e.target.closest('[data-tdel]'); if (!b) return; spTemplates = readTemplates(); spTemplates.splice(Number(b.dataset.tdel), 1); drawTemplates(); });
$('spTplAdd').addEventListener('click', () => { spTemplates = readTemplates(); spTemplates.push({ name: '', body: '' }); drawTemplates(); const n = document.querySelector('#spTpls [data-tn="' + (spTemplates.length - 1) + '"]'); if (n) n.focus(); });
$('spTplSave').addEventListener('click', busy($('spTplSave'), async () => { const r = await api('/api/admin/support/templates', { templates: readTemplates() }, 'PUT'); spTemplates = r.templates || []; drawTemplates(); IAP.status('Saved replies saved.', 'ok'); }));
async function loadReports() {
loadAudit();
const [r, b] = await Promise.all([api('/api/admin/reports'), api('/api/admin/burns')]);
@@ -919,6 +1103,7 @@
loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'],
loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'],
burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'],
synRateDivisor: ['Network rate divisor (N)', 'Network Ad Space views and PassiveDrip visits cost 1/N of the on-site rate; 1 = same rate as on-site; whole numbers'],
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
@@ -1008,6 +1193,107 @@
catch (e) { $('siteErr').textContent = e.message; $('siteErr').hidden = false; }
}));
// ---- Game Pass (2026-10-16): passes sold, active, POL out per pass week, cap hits, deferred queue, tournament ----
async function loadGamePass() {
const r = await api('/api/admin/gamepass/stats');
const pol = n => Number(n || 0).toFixed(2); const usd = n => '$' + Number(n || 0).toFixed(2);
const tile = (v, lb, cls, sub) => '<div class="statx' + (cls ? ' ' + cls : '') + '"><div><div class="nv">' + v + '</div><div class="lb">' + lb + '</div>' + (sub ? '<span class="chip flat">' + sub + '</span>' : '') + '</div></div>';
const P = r.passes || {}, W = (r.pol && r.pol.week) || {}, H = (r.capHits && r.capHits.week) || { free: {}, pass: {} }, Q = r.deferredQueue || {}, T = r.tournament || {}, S = r.settings || {};
$('gpStats').innerHTML = tile(r.enabled ? 'ON' : 'OFF', 'Game Pass', r.enabled ? 'c-cyan' : '', S.enforced ? 'caps enforced' : S.capsStart ? 'caps from ' + S.capsStart : 'caps recorded only')
+ tile(P.soldWeek || 0, 'Passes sold this week', 'c-violet', usd(P.usdWeek) + ' · ' + (P.soldTotal || 0) + ' all time')
+ tile(P.active || 0, 'Active passes', 'c-cyan', (P.waitingOrders || 0) + ' waiting for a package')
+ tile(pol(W.pass), 'POL to pass holders this week', 'c-amber', (P.soldWeek ? pol(W.perPass) + ' per pass sold' : 'no passes sold yet'))
+ tile(pol(W.free), 'POL to free players this week', '', (W.players || 0) + ' players · ' + (W.grants || 0) + ' grants')
+ tile((H.free.daily || 0) + (H.free.total || 0), 'Free cap hits this week', 'c-amber', (H.free.daily || 0) + ' daily · ' + (H.free.total || 0) + ' total')
+ tile((H.pass.daily || 0) + (H.pass.total || 0), 'Pass cap hits this week', '', (H.pass.daily || 0) + ' daily · ' + (H.pass.total || 0) + ' total')
+ tile(Q.entries || 0, 'Deferred queue', 'c-violet', pol(Q.pol) + ' POL · ' + (Q.members || 0) + ' members');
$('gpWeekSub').textContent = r.week ? r.week.label + ' · today ' + r.week.day : '';
const would = (r.capHits && r.capHits.would) || {};
$('gpWeek').innerHTML = '<table class="adm-table">'
+ '<tr><td>Carried forward (deferred progress paid on a later day)</td><td class="num">' + pol(W.carried) + ' POL</td></tr>'
+ '<tr><td>Dropped (daily play over the daily cap)</td><td class="num">' + pol(W.dropped) + ' POL</td></tr>'
+ '<tr><td>Deferred out (progress over the total cap, pays later)</td><td class="num">' + pol(W.deferredOut) + ' POL</td></tr>'
+ (S.enforced ? '' : '<tr><td colspan="2" class="muted">Before capsStartDate, what the caps WOULD have done: ' + pol(would.dropped) + ' POL dropped, ' + pol(would.deferred) + ' POL deferred, ' + ((would.hitsDaily || 0) + (would.hitsTotal || 0)) + ' cap hits.</td></tr>')
+ '<tr><td>Caps: free ' + S.free.daily + ' / ' + S.free.total + ' · pass ' + S.pass.daily + ' / ' + S.pass.total + ' POL (daily play / everything, per day)</td><td class="num">' + S.price + ' credits · ' + S.days + ' days</td></tr>'
+ '</table>'
+ (Q.byGame && Object.keys(Q.byGame).length ? '<p class="muted" style="margin:8px 0 0">By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '</p>' : '');
// per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month
const TS = r.tiers || {}, TC = S.tiers || {};
$('gpTiersSub').textContent = 'Tiers above weekly, sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' tier sales';
$('gpTiers').innerHTML = '<table class="adm-table"><tr><th>Tier</th><th>Price</th><th class="num">Active</th><th class="num">Sold week</th><th class="num">Sold month</th><th class="num">All time</th><th class="num">Renewals 30d</th><th class="num">Ending in 7 days</th><th class="num">Comped</th><th class="num">Waiting</th></tr>'
+ (Object.keys(TS).length ? Object.keys(TS) : ['weekly', 'explorer', 'champion', 'sovereign', 'legend']).map(k => { const x = TS[k] || {}, c = TC[k] || {}; return '<tr><td style="white-space:nowrap">' + esc(x.name || k) + (c.sale ? '' : '<br><span class="chip flat">not on sale</span>') + '</td><td style="white-space:nowrap">' + (c.price || 0) + ' cr<br>' + (c.days || 0) + ' d</td><td class="num">' + (x.active || 0) + '</td><td class="num">' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + '</td><td class="num">' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + '</td><td class="num">' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + '</td><td class="num">' + (x.renewals30d || 0) + '</td><td class="num">' + (x.expiring7d || 0) + '</td><td class="num">' + (x.comped || 0) + '</td><td class="num">' + (x.waitingOrders || 0) + '</td></tr>'; }).join('')
+ '</table><p class="muted" style="margin:8px 0 0">Every tier gets the same pass caps (no extra POL). Each higher tier includes everything below it and adds Shards of Valor content (Legend is yearly).</p>';
// pass sales by how they were paid (2026-10-22: every new pass is a fresh package purchase; the old credit-paid rows stay, labelled)
const PM = P.pay || {}, SL = r.sales || [];
$('gpSalesSub').textContent = (PM.package ? PM.package.n : 0) + ' paid by a new package (' + usd(PM.package && PM.package.usd) + ' pass value, packages ' + usd(PM.package && PM.package.packageUsd) + ')'
+ ' · ' + (PM.credit ? PM.credit.n : 0) + ' credit-paid (old rule, ' + usd(PM.credit && PM.credit.usd) + ')' + ' · ' + (PM.packageOld ? PM.packageOld.n : 0) + ' package under the old rule (' + usd(PM.packageOld && PM.packageOld.usd) + ')';
const txLink = h => h ? '<a href="/tx/' + esc(h) + '" target="_blank" rel="noopener">' + esc(String(h).slice(0, 10)) + '…</a>' : '';
$('gpSales').innerHTML = !SL.length ? '<p class="muted">No pass sold yet.</p>' : '<table class="adm-table"><tr><th>When</th><th>Member</th><th>Pass</th><th>Paid by</th><th class="num">Pass</th><th class="num">Package</th><th>Package tx</th></tr>'
+ SL.map(x => '<tr><td style="white-space:nowrap">' + when(x.ts) + '</td><td>' + esc(x.email) + '</td><td>' + esc(x.name || x.tier) + '</td><td>' + esc(x.label) + (x.credits ? ' · ' + x.credits + ' cr' : '') + '</td><td class="num">' + usd(x.usd) + '</td><td class="num">' + (x.packageUsd ? usd(x.packageUsd) : '') + '</td><td>' + txLink(x.tx) + '</td></tr>').join('')
+ '</table>';
await loadGpTest();
$('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid';
const L = T.last;
$('gpTour').innerHTML = !L ? '<p class="muted">No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).</p>'
: '<p><b>' + esc(L.label) + '</b>: ' + (L.sales || 0) + ' pass' + (L.sales === 1 ? '' : 'es') + ' sold (' + usd(L.salesUsd) + '), pool ' + pol(L.poolPol) + ' POL at $' + Number(L.polUsd || 0).toFixed(4) + ' per POL, ' + (L.holders || 0) + ' holders, ' + (L.ranked || 0) + ' with plays' + (L.posted ? ' · posted to Telegram' : '') + '</p>'
+ (L.winners && L.winners.length ? '<table class="adm-table">' + L.winners.map(w => '<tr><td>#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + '</td><td>' + w.score + ' plays</td><td class="num">' + pol(w.pol) + ' POL</td><td>' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + '</td></tr>').join('') + '</table>' : '<p class="muted">No pass holder reported any plays that week.</p>')
+ ((T.history || []).length > 1 ? '<p class="muted" style="margin:8px 0 0">Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '</p>' : '');
}
// Tier test and preview (2026-10-25, Marty): the member Games card shows the admin exactly what a member sees, so every tier test lives
// here. Every action touches ONLY the signed-in admin's own account; a test buy opens the same waiting order a member gets (a fresh
// package on /my fulfils it, sponsors paid as usual), a test comp starts the tier at once with no sale recorded.
async function loadGpTest() {
const box = $('gpTest'); if (!box) return;
let g; try { g = await api('/api/admin/gamepass/preview'); } catch (e) { box.innerHTML = '<p class="muted">' + esc(e.message) + '</p>'; return; }
const ct = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)';
const len = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days';
const rows = g.passes || [];
$('gpTestSub').textContent = 'TEST / PREVIEW · admin only · acts on your own account: ' + g.email;
const card = r => {
const sale = r.tier === 'weekly' ? !!g.enabled : !!r.sale;
const st = r.active ? '<b>Your account: active until ' + esc(ct(r.until)) + '</b>' : r.waiting ? '<b>Your account: test order waiting for a $' + r.package + ' package</b>' : 'Your account: not active';
const acts = (r.waiting ? '<a class="btn small" href="/my?from=gamepass#buy" target="_blank" rel="noopener">Buy the $' + r.package + ' package on /my</a><button class="btn small sec" type="button" data-gpt-cancel="' + esc(r.tier) + '">Cancel test order</button>'
: '<button class="btn small" type="button" data-gpt-buy="' + esc(r.tier) + '">Test buy (real order, $' + r.package + ' package)</button>')
+ '<button class="btn small sec" type="button" data-gpt-comp="' + esc(r.tier) + '">Give my account ' + esc(r.name) + ' now (test)</button>'
+ (r.active ? '<button class="btn small sec" type="button" data-gpt-end="' + esc(r.tier) + '">End my ' + esc(r.name) + ' now</button>' : '');
return '<div class="gpt-tier' + (r.active ? ' on' : '') + '"><h4>' + esc(r.name) + ' <span class="chip flat">' + (sale ? 'on sale: members see it' : 'hidden from members') + '</span></h4>'
+ '<p class="gpt-price">$' + r.usd + ' <span class="small muted">for ' + len(r.days) + '</span></p>'
+ '<ul>' + (r.perks || []).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul>'
+ '<p class="small" style="margin:4px 0">' + st + '</p><div class="gpt-acts">' + acts + '</div></div>';
};
box.innerHTML = '<p class="gpt-note"><b>Test / preview, admin only.</b> ' + (g.tierPreview ? 'The passes above the weekly Game Pass are hidden from members until sovTiers is switched on in Settings (it stays off until the paid tiers launch). ' : '')
+ 'These are the tier cards as members will see them. Every button here acts on your own account (' + esc(g.email) + ') and nobody else’s. The member Games card on /my shows you exactly what a member sees: while you hold a test tier it shows that tier the way it would for any member who holds one.</p>'
+ '<div class="gpt-grid">' + rows.map(card).join('') + '</div>'
+ '<p class="muted" style="margin:10px 0 0"><b>Test buy</b> opens the same waiting order a member gets: a fresh package of at least the price, bought on /my by one of your positions, starts it (sponsors paid as usual). Cancel a test order you will not pay, or a later real package of that size fulfils it. <b>Give my account</b> starts one pass period at once, recorded as comped (no sale); <b>End</b> stops it. '
+ 'To test it in game, open <b>Shards of Valor &gt; Passes</b> (key P) after signing in to the game again from /my Games: the game reads your highest tier from InstantAdPay at sign-in.</p>';
const tierName = k => (rows.find(r => r.tier === k) || {}).name || k;
box.querySelectorAll('[data-gpt-buy]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptBuy; const r = rows.find(x => x.tier === k);
if (!(await IAP.confirmBox('Open a TEST order for ' + tierName(k) + ' on your own account (' + g.email + ')? It starts when a fresh $' + r.package + ' or bigger package from one of your positions settles on chain. Members still cannot see or buy this tier.', { title: 'Test buy: ' + tierName(k), ok: 'Open the test order', cancel: 'Not now' }))) return;
const x = await api('/api/admin/gamepass/test-buy', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' is waiting for a $' + x.package + ' package on ' + x.email + '.', 'ok'); await loadGpTest();
})));
box.querySelectorAll('[data-gpt-cancel]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptCancel; await api('/api/admin/gamepass/test-cancel', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' cancelled.', 'ok'); await loadGpTest();
})));
box.querySelectorAll('[data-gpt-comp]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptComp;
if (!(await IAP.confirmBox('Give your own account (' + g.email + ') one ' + tierName(k) + ' period now, for testing? It is recorded as comped (no sale) and shows in the game the next time you sign in to it.', { title: 'Test ' + tierName(k), ok: 'Give it to me', cancel: 'Not now' }))) return;
const x = await api('/api/admin/gamepass/test-comp', { tier: k }); IAP.status(tierName(k) + ' on your account until ' + when(x.until) + ' (test).', 'ok'); await loadGamePass();
})));
box.querySelectorAll('[data-gpt-end]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptEnd;
if (!(await IAP.confirmBox('End ' + tierName(k) + ' on your own account now?', { title: 'End test tier', ok: 'End it now', cancel: 'Keep it' }))) return;
await api('/api/admin/gamepass/revoke', { email: g.email, tier: k, why: 'admin tier test' }); IAP.status(tierName(k) + ' on your account ended.', 'ok'); await loadGamePass();
})));
}
$('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); }));
$('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); }));
$('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => {
const email = $('gpCompEmail').value.trim(), tier = $('gpCompTier').value; if (!email) { IAP.status('Enter the member email first.', 'bad'); return; }
if (!(await IAP.confirmBox('End the ' + tier + ' pass on ' + email + ' now? Use this only for a support refund; it does not return any credits by itself.', { title: 'End a pass tier', ok: 'End it now', cancel: 'Keep it' }))) return;
const r = await api('/api/admin/gamepass/revoke', { email, tier, why: $('gpCompWhy').value }); IAP.status(r.tier + ' pass on ' + r.email + ' ended (was until ' + when(r.was) + ').', 'ok'); await loadGamePass();
}));
async function loadSettings() {
const [r, s, d] = await Promise.all([api('/api/admin/rates'), api('/api/admin/site'), api('/api/admin/drip')]);
ratesObj = r.rates || {}; drawRates();
+63 -2
View File
@@ -1,4 +1,6 @@
// 24/7 assistant widget: floating bubble, slide-up panel, /api/chat.
// Hand-off (help desk, 2026-10-16): when the answer cannot help, or they ask for a person, the widget offers
// "Send this to support", which files the last few turns as a ticket (members: their Help pane; signed out: their email).
(function () {
const root = document.createElement('div');
root.id = 'iapChat';
@@ -7,10 +9,11 @@
+ '<div class="ch-head"><b>Ask anything</b><span class="ch-sub">Real answers, around the clock</span>'
+ '<button id="iapChatClose" aria-label="Close chat" type="button">×</button></div>'
+ '<div class="ch-msgs" id="iapChatMsgs">'
+ '<div class="ch-m bot">Hey. Ask me how the payments work, what the packages buy, or anything else. Straight answers only, no income hype.</div>'
+ '<div class="ch-m bot">Hey. Ask me how the payments work, what the packages buy, or anything else. Straight answers only, no income hype. Need a person instead? Tap <b>Send this to support</b> below, or use the <a href="/support" style="color:inherit;text-decoration:underline">support page</a>.</div>'
+ '</div>'
+ '<div class="ch-input"><input id="iapChatIn" placeholder="Type your question…" maxlength="600">'
+ '<button id="iapChatSend" type="button">Send</button></div>'
+ '<div style="text-align:center;font-size:12px;padding:4px 0 8px"><a href="#" id="iapChatHuman" style="color:inherit;opacity:.75">Need a person? Send this to support</a></div>'
+ '</div>';
document.body.appendChild(root);
@@ -18,6 +21,7 @@
const msgs = $('iapChatMsgs');
const input = $('iapChatIn');
let history = [];
const turns = []; // { who: 'me' | 'bot', text } for the support hand-off
const add = (text, who) => {
const d = document.createElement('div');
@@ -29,11 +33,18 @@
msgs.scrollTop = msgs.scrollHeight;
return d;
};
function offerHandoff() {
if (msgs.querySelector('.ch-handoff')) return;
const d = document.createElement('div'); d.className = 'ch-m bot ch-handoff';
d.innerHTML = '<button type="button" class="btn small" style="margin:0">Send this to support</button>';
d.querySelector('button').addEventListener('click', handoff);
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
}
async function send() {
const q = input.value.trim();
if (!q) return;
input.value = '';
add(q, 'me');
add(q, 'me'); turns.push({ who: 'me', text: q });
const wait = add('…', 'bot');
try {
const r = await (await fetch('/api/chat', { method: 'POST',
@@ -41,12 +52,61 @@
body: JSON.stringify({ message: q, history: history.slice(-4).join(' | ') }) })).json();
wait.remove();
add(r.reply || r.error || 'No answer came back. Try again.', 'bot');
if (r.reply) turns.push({ who: 'bot', text: r.reply });
history.push('Q: ' + q, 'A: ' + (r.reply || ''));
if (r.handoff) offerHandoff();
} catch (e) {
wait.remove();
add('Connection hiccup. Try that again.', 'bot');
offerHandoff();
}
}
async function post(body) {
const g = window.IAP && IAP.guard;
if (g) await g.formSettled();
return (await fetch('/api/support/chatbot', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.assign({ transcript: turns.slice(-8), fts: g ? g.FORM_TS : 0, fage: g ? Date.now() - g.FORM_TS : 0 }, body)) })).json();
}
function done(r) {
const old = msgs.querySelector('.ch-handoff'); if (old) old.remove();
const f = msgs.querySelector('.ch-hform'); if (f) f.remove();
add(r.member ? 'Sent to support as ticket ' + r.ref + '. Marty will reply in Help in your dashboard and by email: ' + location.origin + r.link
: 'Sent to support as ticket ' + r.ref + '. We emailed you a private link to follow it, and Marty will reply there: ' + location.origin + r.link, 'bot');
}
async function handoff(e) {
if (e && e.preventDefault) e.preventDefault();
if (msgs.querySelector('.ch-hform')) return;
let me = null; try { me = await (await fetch('/api/me')).json(); } catch (err) {}
if (me && me.signedIn && me.email) {
const ok = window.IAP && IAP.confirmBox ? await IAP.confirmBox('Send this chat to support as a ticket? Marty will reply in Help in your dashboard and by email.', { ok: 'Send it', cancel: 'Not now' }) : true;
if (!ok) return;
try { const r = await post({}); if (r.error) throw new Error(r.error); done(r); } catch (err) { add(err.message || 'Could not send it. Try the Help tab in your dashboard.', 'bot'); }
return;
}
// signed out: an email so Marty can reply, plus the same invisible walls as sign-up
const d = document.createElement('div'); d.className = 'ch-m bot ch-hform';
d.innerHTML = 'Where should Marty reply?'
+ '<input class="hp-field" type="text" tabindex="-1" aria-hidden="true" autocomplete="off" id="iapChatHp">'
+ '<input id="iapChatEmail" type="email" placeholder="your email" maxlength="190" autocomplete="email" style="width:100%;margin-top:6px;box-sizing:border-box">'
+ '<input id="iapChatNote" placeholder="anything to add (optional)" maxlength="600" style="width:100%;margin-top:6px;box-sizing:border-box">'
+ '<div id="iapChatCheck" hidden style="margin-top:6px"></div>'
+ '<button type="button" class="btn small" id="iapChatGo" style="margin-top:8px">Send to support</button> <span class="small" id="iapChatErr"></span>';
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
$('iapChatEmail').focus();
$('iapChatGo').addEventListener('click', async () => {
const btn = $('iapChatGo'); if (btn.disabled) return; btn.disabled = true; $('iapChatErr').textContent = '';
try {
let pick = null, r = null;
for (let i = 0; i < 4; i++) {
r = await post({ email: $('iapChatEmail').value.trim(), note: $('iapChatNote').value.trim(), hp_field_x9: window.IAP && IAP.guard ? IAP.guard.hpValue($('iapChatHp')) : '', pick });
if (r.challenge && window.IAP && IAP.guard) { pick = await IAP.guard.iconCheck($('iapChatCheck'), r.challenge, r.error); continue; }
break;
}
if (!r || r.error) throw new Error((r && r.error) || 'Could not send it.');
done(r);
} catch (err) { $('iapChatErr').textContent = err.message; btn.disabled = false; }
});
}
$('iapChatBtn').addEventListener('click', () => {
const p = $('iapChatPanel');
p.hidden = !p.hidden;
@@ -54,5 +114,6 @@
});
$('iapChatClose').addEventListener('click', () => { $('iapChatPanel').hidden = true; });
$('iapChatSend').addEventListener('click', send);
$('iapChatHuman').addEventListener('click', handoff);
input.addEventListener('keydown', e => { if (e.key === 'Enter') send(); });
})();
+16 -3
View File
@@ -35,6 +35,7 @@ window.IAP = (function () {
+ '<a href="/ledger" data-p="ledger">Live ledger</a>'
+ '<a href="/leaderboard" data-p="leaderboard">Leaderboard</a>'
+ '<a href="/contract" data-p="contract">The contract</a>'
+ '<a href="/support" data-p="support">Support</a>'
+ '<a href="/my" data-p="my">Members</a>'
+ '</span><span id="navWallet" class="muted">…</span></div>';
document.body.prepend(nav);
@@ -56,7 +57,7 @@ window.IAP = (function () {
f.innerHTML = '<div>© ' + new Date().getFullYear() + ' InstantAdPay</div>'
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
+ '<a href="/">How it works</a><a href="/presentation">Presentation</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a>'
+ '<a href="/facts">Platform facts</a><a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/disclaimer">Disclaimer</a></div>';
+ '<a href="/facts">Platform facts</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/disclaimer">Disclaimer</a></div>';
document.body.appendChild(f);
}
async function refreshNavWallet() {
@@ -92,7 +93,7 @@ window.IAP = (function () {
case 'AdminPaid': return '🏛 platform fee settled: ' + pol(ev.amountWei);
case 'BuyerCounted': return '⭐ ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer(s)';
case 'MemberActivated': return '👤 ' + nm(ev.id) + ' activated a payout wallet';
case 'AwardPaid': return '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
case 'AwardPaid': return ev.override ? '🏅 Level 4 override' + (ev.overrideWeek ? ' (week of ' + ev.overrideWeek + ')' : '') + ': ' + pol(ev.amountWei) + ' → ' + nm(ev.toId) : '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
case 'CreditsConsumed': return '📣 ' + nm(ev.memberId) + ' ran ads: −' + ev.amount.toLocaleString() + ' credits';
case 'PriceCached': return '🔮 oracle price refreshed';
case 'FallbackPriceUsed': return '🔮 cached price bridged an oracle gap';
@@ -263,7 +264,8 @@ window.IAP = (function () {
}
function ask(o) { return dialog(Object.assign({ type: 'text', value: '', placeholder: '' }, o || {})); }
function confirmBox(text, o) { return dialog(Object.assign({ type: 'none', text, ok: 'Yes', cancel: 'No' }, o || {})); }
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $ };
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $,
guard: { FORM_TS, iconCheck, hpValue, formSettled } }; // guard: the sign-up walls, reused by the support form and the chatbot hand-off
})();
// shown inside someone else's frame (traffic exchanges, 2026-10-03): sign-in, join and off-site links open in a new tab,
// because browsers refuse our session cookie inside another site's frame
@@ -282,3 +284,14 @@ window.IAP = (function () {
if (sign || a.host !== location.host) { a.target = '_blank'; a.rel = 'noopener'; }
}, true);
})();
// Level 4 override copy (2026-10-23): blocks marked data-when="override-live" stay hidden until the site setting
// overrideMode is 'live' and overrideGoLive is set; [data-ov-start] gets the start date in Central time
(function () {
var els = document.querySelectorAll('[data-when="override-live"]'); if (!els.length || !window.IAP) return;
IAP.getConfig().then(function (c) {
if (String(c.overrideMode || '') !== 'live' || !Number(c.overrideGoLive)) return;
var d = new Date(Number(c.overrideGoLive)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'long', day: 'numeric', year: 'numeric' });
document.querySelectorAll('[data-ov-start]').forEach(function (e) { e.textContent = d; });
els.forEach(function (e) { e.hidden = false; });
}).catch(function () {});
})();
+17
View File
@@ -0,0 +1,17 @@
// Conversion tracking guide (/conversion-tracking, 2026-10-24): the Copy buttons on the code examples. Copies the text of
// the <pre> in the same box (placeholders included). Frame handling (traffic exchanges) is common.js's, like every page.
(function () {
function flash(b, t) { var o = b.getAttribute('data-label') || b.textContent; b.setAttribute('data-label', o); b.textContent = t; setTimeout(function () { b.textContent = o; }, 1600); }
document.querySelectorAll('[data-copy]').forEach(function (b) {
b.addEventListener('click', function () {
var box = b.closest('.cg-code'); var pre = box && box.querySelector('pre'); if (!pre) return;
var text = pre.textContent;
var done = function () { flash(b, 'Copied'); };
var fallback = function () {
try { var r = document.createRange(); r.selectNodeContents(pre); var s = window.getSelection(); s.removeAllRanges(); s.addRange(r); var ok = document.execCommand && document.execCommand('copy'); flash(b, ok ? 'Copied' : 'Selected'); }
catch (e) { flash(b, 'Select and copy'); }
};
try { if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, fallback); else fallback(); } catch (e) { fallback(); }
});
});
})();
+81
View File
@@ -0,0 +1,81 @@
// The Engine Room (2026-10-24). The SAME file ships in InstantAdPay (Members > Engine Room) and LinkSpin (Ads screen panel).
// Plain dials, real numbers, colour only for warnings. Renders into #erRoot from /api/my/engine; hidden while the
// refuelStreak switch is off. Unlocked by the first counted refuel, greyed "Refuel to start your engine" until then.
(function () {
const root = document.getElementById('erRoot'); if (!root) return;
const host = document.getElementById(root.dataset.host || 'erPanel');
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const n = v => Number(v || 0).toLocaleString('en-US');
// a link on this site becomes a plain path; a link to the other site carries ?from=<this site>&task=<job> so the other
// site opens with an arrival strip naming the job and its first step (2026-10-25, Marty lost the thread on LinkSpin)
const TASK = { tracking: 'conversions', start: 'refuel', refuel: 'refuel', pitstop: 'refuel', bannerspin: 'bannerspin', testing: 'testing', relaunch: 'ads', topup: 'ads', cut: 'ads', cruise: 'ads' };
let FROM = 'iap';
const siteOf = u => /linkspin/i.test(u.host) ? 'linkspin' : 'iap'; // which site a link belongs to, by its host (also right on a local copy)
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return u.href; } catch (e) { return url; } };
// "Refuel LinkSpin this cycle..." gets a way there (2026-10-25): the other site's buy screen, tagged for its arrival strip
const otherBuy = note => { const m = /^Refuel (LinkSpin|InstantAdPay) /.exec(note || ''); if (!m) return '';
const url = m[1] === 'LinkSpin' ? 'https://linkspin.app/credits#refuel' : 'https://instantadpay.com/my#buy';
return ' <a href="' + esc(go(url, 'refuel')) + '">Refuel ' + m[1] + (ext(url) ? ' &#8599;' : '') + '</a>'; };
const ext = url => { try { const u = new URL(url); return u.host !== location.host && siteOf(u) !== FROM; } catch (e) { return false; } };
const css = '.er{display:grid;gap:14px}.er-locked{opacity:.45;filter:grayscale(1);pointer-events:none}.er-dials{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr));gap:12px}'
+ '.er-dial{border:1px solid rgba(127,127,127,.3);border-radius:10px;padding:10px 12px;text-align:center;min-width:0}.er-dial svg{width:100%;max-width:200px;height:auto;display:block;margin:0 auto}'
+ '.er-dial .v{font-size:22px;font-weight:700;margin-top:-6px}.er-dial .c{font-size:12px;opacity:.8}.er-row{display:flex;flex-wrap:wrap;gap:8px}'
+ '.er-light{display:flex;gap:6px;align-items:center;border:1px solid rgba(127,127,127,.3);border-radius:999px;padding:4px 10px;font-size:12.5px}.er-dot{width:10px;height:10px;border-radius:50%;background:rgba(127,127,127,.45);flex:none}'
+ '.er-dot.on{background:#e8a317}.er-dot.green{background:#2fa36b}.er-dot.amber{background:#e8a317}.er-dot.grey{background:rgba(127,127,127,.45)}.er-parts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));gap:8px}'
+ '.er-part{border:1px solid rgba(127,127,127,.3);border-radius:8px;padding:8px 10px;font-size:13px;display:grid;gap:3px;min-width:0}.er-part b{display:flex;flex-wrap:wrap;gap:2px 6px;align-items:center}.er-next{border:1px solid rgba(127,127,127,.4);border-radius:10px;padding:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}'
+ '.er-next .w{flex:1 1 220px;font-size:13px}.er-h{font-size:12px;letter-spacing:.06em;text-transform:uppercase;opacity:.75;margin:0}.er-streak{font-size:13.5px;line-height:1.5}.er-goal{display:flex;gap:6px;align-items:center;justify-content:center;margin-top:6px;font-size:12px}.er-goal input{width:70px}';
if (!document.getElementById('erCss')) { const st = document.createElement('style'); st.id = 'erCss'; st.textContent = css; document.head.appendChild(st); }
// a plain 180-degree dial; pct null = no reading
function dial(pct, value, caption, aria, warn) {
const p = pct == null ? 0 : Math.max(0, Math.min(100, pct));
const a = Math.PI * (1 - p / 100); const x = 100 + 80 * Math.cos(a), y = 100 - 80 * Math.sin(a);
const col = warn ? '#e8a317' : 'currentColor';
return '<div class="er-dial" role="img" aria-label="' + esc(aria) + '"><svg viewBox="0 0 200 112" aria-hidden="true"><path d="M20 100 A80 80 0 0 1 180 100" fill="none" stroke="rgba(127,127,127,.3)" stroke-width="14" stroke-linecap="round"/>'
+ (pct == null ? '' : '<path d="M20 100 A80 80 0 0 1 ' + x.toFixed(1) + ' ' + y.toFixed(1) + '" fill="none" stroke="' + col + '" stroke-width="14" stroke-linecap="round"/>') + '</svg>'
+ '<div class="v">' + esc(value) + '</div><div class="c">' + caption + '</div></div>';
}
function view(d) {
const f = d.fuel, c = d.clicks, g = d.goals, s = d.streak;
const fuelCap = (f.refuelCredits ? n(f.left) + ' of ' + n(f.refuelCredits) + ' credits this cycle' : n(f.left) + ' credits on both sites') + (f.daysLeft != null ? '<br>about ' + n(f.daysLeft) + ' days at your burn (' + n(f.burnPerDay) + ' a day)' : '');
const fuelAria = 'Fuel left: ' + n(f.left) + ' credits' + (f.pct != null ? ', ' + f.pct + ' percent of this cycle’s refuel' : '') + (f.daysLeft != null ? ', about ' + f.daysLeft + ' days at your current burn' : '');
const clickCap = (c.prevWeek ? 'last week: ' + n(c.prevWeek) + ' (half way = the same)<br>' : '') + (c.per1000 != null ? n(c.per1000) + ' clicks per 1,000 credits' : 'clicks per 1,000 credits: not enough delivery yet') + '<br>all ads, both sites';
const goalCap = (g.month == null ? 'LinkSpin did not answer' : g.tracking ? (g.target ? 'goal: ' + n(g.target) + ' this month' : 'set a goal for the month') : 'set up conversion tracking') + '<span class="er-goal"><label>goal <input type="number" min="0" max="100000" data-er-goal value="' + (g.target || '') + '" aria-label="Your goal for this month"></label><button class="btn small sec" type="button" data-er-save>Save</button></span>';
const dials = '<div class="er-dials">'
+ dial(f.pct, f.pct != null ? f.pct + '%' : n(f.left), 'Fuel left<br>' + fuelCap, fuelAria, f.daysLeft != null && f.daysLeft < 5)
+ dial(c.pct, n(c.week), 'Clicks this week<br>' + clickCap, 'Clicks this week: ' + n(c.week) + (c.prevWeek ? ', last week ' + n(c.prevWeek) : '') + (c.per1000 != null ? ', ' + c.per1000 + ' per 1,000 credits' : ''), false)
+ dial(g.pct, g.month == null ? '?' : n(g.month), 'Goals this month<br>' + goalCap, 'Goals this month: ' + (g.month == null ? 'unknown' : g.month) + (g.target ? ' of ' + g.target : ''), false) + '</div>';
const streak = '<div class="er-streak"><p class="er-h">Streak</p>' + (s.active ? '<b>' + s.months + ' month' + (s.months === 1 ? '' : 's') + '</b>' + (s.both ? ', both engines this cycle' : '') + '. Refuel day <b>' + esc(s.refuelDay) + '</b>, grace to ' + esc(s.graceEnd) + ' (Central).'
+ (typeof s.note === 'string' ? (s.note ? ' ' + esc(s.note) + otherBuy(s.note) : '') : s.next ? (s.windowOpen ? ' Window open: next refuel +' + s.next.single + '% (+' + s.next.both + '% on each with both).' : s.both ? ' Both engines fueled this cycle.' : s.next.secondEngine ? ' Refuel the other site this cycle for +' + s.next.secondEngine + '% on both.' : '') : '') // s.note from engine.js (2026-10-24: no 'refuel the other site' once both are done)
+ (s.pitStop ? ' Pit Stop: +' + s.pitStop.pct + '% ' + (s.pitStop.iap || s.pitStop.linkspin ? 'available' : 'used') + ' this cycle.' : '') + (s.best > s.months ? ' Best: ' + s.best + '.' : '') : 'Not started.') + '</div>';
const warns = '<div><p class="er-h">Warning lights</p><div class="er-row">' + d.warnings.map(w => '<span class="er-light" title="' + esc(w.note) + '"><span class="er-dot' + (w.on ? ' on' : '') + '" aria-hidden="true"></span>' + esc(w.label) + ': ' + (w.on ? '<b>on</b>' : 'off') + '<span class="sr" style="position:absolute;left:-9999px"> (' + esc(w.note) + ')</span></span>').join('') + '</div></div>';
const parts = '<div><p class="er-h">The six parts</p><div class="er-parts">' + d.parts.map(p => '<div class="er-part"><b><span class="er-dot ' + p.state + '" aria-hidden="true"></span>' + esc(p.label) + ' <span style="font-weight:400;opacity:.75">(' + (p.state === 'green' ? 'working' : p.state === 'amber' ? 'needs attention' : 'not started') + ')</span></b><span>' + esc(p.note) + '</span>'
+ (p.state !== 'green' && p.link ? '<a href="' + esc(go(p.link, p.key)) + '">' + (p.state === 'grey' ? 'Set it up' : 'Fix it') + (ext(p.link) ? ' on ' + (FROM === 'iap' ? 'LinkSpin' : 'InstantAdPay') + ' &#8599;' : '') + '</a>' : '') + '</div>').join('') + '</div></div>';
const nextLink = go(d.next.link, TASK[d.next.key]);
const next = '<div class="er-next"><div class="w"><p class="er-h">Next move</p><b>' + esc(d.next.label) + '</b><br>' + esc(d.next.why)
+ (d.next.guide ? '<br><a href="' + esc(d.next.guide) + '" target="_blank" rel="noopener" style="font-size:12.5px">' + (d.next.key === 'tracking' ? 'Step-by-step setup guide' : 'How the Refuel streak works') + '</a>' : '') + '</div>'
+ '<a class="btn' + (d.locked ? '' : ' pri') + '" href="' + esc(nextLink) + '">' + esc(d.next.label) + (ext(d.next.link) ? ' on ' + (FROM === 'iap' ? 'LinkSpin' : 'InstantAdPay') : '') + '</a></div>';
const how = d.next.guide === '/refuel' ? '' : '<p style="margin:0;font-size:12.5px"><a href="/refuel" target="_blank" rel="noopener">How the Refuel streak works</a></p>'; // the member guide (2026-10-24)
if (d.locked) return '<div class="er">' + next + how + '<div class="er-locked" aria-hidden="true">' + dials + warns + parts + '</div></div>';
return '<div class="er">' + next + dials + streak + how + warns + parts + '<p class="small muted" style="margin:0;font-size:12px;opacity:.75">Numbers cover InstantAdPay and LinkSpin together' + (d.sites && (!d.sites.iap || !d.sites.linkspin) ? ' (one site did not answer just now)' : '') + '. Credits buy ad delivery only.</p></div>';
}
async function load(fresh) {
try {
const d = await (await fetch('/api/my/engine' + (fresh ? '?fresh=1' : ''), { cache: 'no-store' })).json();
window.FUEL = window.FUEL || {}; window.FUEL.engine = d;
if (!d || !d.on) { if (host) host.hidden = true; return; }
if (host) host.hidden = false;
if (d.error) { root.innerHTML = '<p class="small muted">' + esc(d.error) + '</p>'; return; }
FROM = d.site === 'linkspin' ? 'linkspin' : 'iap';
root.innerHTML = view(d);
const save = root.querySelector('[data-er-save]');
if (save) save.addEventListener('click', async () => {
const v = root.querySelector('[data-er-goal]').value; save.disabled = true;
try { const r = await (await fetch('/api/my/engine/goal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ goal: Number(v) || 0 }) })).json(); if (r.error) throw new Error(r.error); load(true); }
catch (e) { save.disabled = false; save.textContent = 'Try again'; }
});
} catch (e) { if (host) host.hidden = true; }
}
window.ENGINE_ROOM = { load };
load(); setInterval(() => { if (!document.hidden) load(); }, 120000);
window.addEventListener('cr:signedin', () => load(true)); // LinkSpin's in-shell sign-in: the panel loaded signed out
})();
+113
View File
@@ -0,0 +1,113 @@
// Fuel Your Offers (2026-10-24): the Refuel card on the Overview. Hidden while the refuelStreak switch is off
// (/api/my/refuel answers { on:false }). Everything here is ad credits, never cash.
(function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const n = v => Number(v || 0).toLocaleString('en-US');
const goBuy = () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); else location.hash = '#buy'; };
window.FUEL = window.FUEL || {};
const HOW = '<p class="small" style="margin:8px 0 0"><a href="/refuel" target="_blank" rel="noopener">How the Refuel streak works</a></p>'; // the member guide (2026-10-24)
function siteLine(name, s, minUsd) {
if (s && s.refueled) return '<li><b>' + name + '</b>: refueled ' + esc(s.dayLabel ? 'on ' + s.dayLabel : '') + ', +' + s.pct + '% (' + n(s.bonus) + ' bonus credits)</li>';
return '<li><b>' + name + '</b>: not yet this cycle (a $' + minUsd + '+ package counts)</li>';
}
function cardHtml(v) {
const head = '<div class="card-head"><h3>⛽ Monthly Refuel</h3><span class="sub">' + (v.active ? 'streak: ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') : 'not started') + '</span></div>';
if (!v.active) {
const lapsed = v.started ? '<p>Your last streak ended' + (v.misses && v.misses[0] ? ' after ' + esc(v.misses[0].day) : '') + '. Your next package of $' + v.minUsd.iap + '+ here (or $' + v.minUsd.linkspin + '+ on LinkSpin) starts it again at month 1.</p>' : '';
return head + (lapsed || '<p>Refuel your ads every month and the bonus grows. A package of <b>$' + v.minUsd.iap + ' or more</b> here, or $' + v.minUsd.linkspin + ' or more on LinkSpin, starts your streak and sets your own refuel day.</p>')
+ '<p class="small">Month 1 <b>+' + v.ladder.single[0] + '%</b> bonus ad credits, month 2 +' + v.ladder.single[1] + '%, month 3 +' + v.ladder.single[2] + '%, month 4 and up +' + v.ladder.single[3] + '%. Refuel both InstantAdPay and LinkSpin in the same cycle and each gets +' + v.ladder.both.join('%, +') + '%. It stacks on Five Dollar Friday and Wired Wednesday.</p>'
+ '<button class="btn" type="button" data-fuel-buy>Start my streak</button>' + HOW;
}
const c = v.cycle || {};
const when = v.windowOpen
? '<p><b>Your refuel window is open.</b> Refuel day: <b>' + esc(v.refuelDayLabel) + '</b>, grace to ' + esc(v.graceLabel) + ' (Central time). Your next refuel earns <b>+' + v.next.single + '%</b>, or +' + v.next.both + '% on each site when you refuel both.</p>'
: '<p>Next refuel day: <b>' + esc(v.refuelDayLabel) + '</b> (Central time). The window opens ' + esc(v.opensLabel) + ' and the grace runs to ' + esc(v.graceLabel) + '.</p>';
const sites = c.month ? '<p class="small" style="margin-bottom:2px">This cycle (month ' + c.month + (c.both ? ', both engines' : '') + '):</p><ul class="small" style="margin-top:0">' + siteLine('InstantAdPay', c.iap, v.minUsd.iap) + siteLine('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</ul>' : '';
let twin = '';
if (!v.windowOpen && c.month && !c.both) twin = '<p class="small">Refuel ' + (c.iap && c.iap.refueled ? 'LinkSpin ($' + v.minUsd.linkspin + '+)' : 'InstantAdPay ($' + v.minUsd.iap + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to <b>+' + v.next.secondEngine + '%</b>; the one you already refueled is topped up to match.'
// the second engine is on the other site: a direct way there (2026-10-25), landing on LinkSpin's Refuel panel with an arrival strip
+ (c.iap && c.iap.refueled ? ' <a href="https://linkspin.app/credits?from=iap&amp;task=refuel#refuel" target="_blank" rel="noopener">Refuel LinkSpin &#8599;</a> (same email signs you in)' : '') + '</p>';
let pit = '';
if (v.pitStop) {
const here = v.pitStop.iap ? 'available here (+' + v.pitStop.pct + '% on a $' + v.minUsd.iap + '+ top-up, once this cycle)' : v.pitStop.usedIap ? 'used here this cycle' : null;
if (here) pit = '<p class="small"><b>Pit Stop:</b> ' + here + '. It keeps your ads running between refuel days; it does not count as your refuel.</p>';
}
const miss = '<p class="small muted">' + (v.freeMiss.available ? 'You have one free miss this year: if a grace passes, your streak is kept once.' : 'Your free miss for this year is used.') + (v.best > v.streak ? ' Best streak: ' + v.best + ' months.' : '') + '</p>';
return head + when + sites + twin + pit + miss + '<button class="btn" type="button" data-fuel-buy>' + (v.windowOpen ? 'Refuel now' : 'Buy a package') + '</button>' + HOW;
}
async function loadRefuelCard() {
const card = $('rfCard'); if (!card) return;
try {
const v = await (await fetch('/api/my/refuel', { cache: 'no-store' })).json();
window.FUEL.refuel = v;
if (!v || !v.on) { card.hidden = true; return; }
card.innerHTML = cardHtml(v); card.hidden = false;
card.querySelectorAll('[data-fuel-buy]').forEach(b => b.addEventListener('click', goBuy));
} catch (e) { card.hidden = true; }
}
window.FUEL.loadRefuelCard = loadRefuelCard;
loadRefuelCard(); setInterval(loadRefuelCard, 300000);
// ---- the Refuel Kit (Promo tools): this month's members-only banners, with your @name and a QR to your link ----
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
const IAP_SIZES = ['728x90', '300x250', '468x60', '160x600'];
let kitData = null;
async function render(month, size, variant) {
const r = await (await fetch('/api/my/kits/render', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ month, size, variant }) })).json();
if (r.error) throw new Error(r.error);
return r;
}
// prefill the banner form under Campaigns with the kit image and the member's own link
function useInCampaign(r, month) {
const m = document.querySelector('.bo-menu [data-pane="campaigns"]'); if (m) m.click();
setTimeout(() => {
const set = (id, v, ev) => { const el = $(id); if (!el) return; el.value = v; el.dispatchEvent(new Event(ev || 'input', { bubbles: true })); };
set('cType', 'banner', 'change'); set('cSize', r.size, 'change');
set('cName', 'Refuel Kit ' + month + ' ' + r.size); set('cImage', r.abs); if (kitData && kitData.link) set('cTarget', kitData.link);
const el = $('cName'); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
say('Banner form filled with your kit banner and your link. Set a budget and launch.', 'ok');
}, 250);
}
function kitHtml(k, d) {
const head = '<div class="card-head"><h3>Refuel Kit: ' + esc(k.label) + (k.theme ? ' &middot; ' + esc(k.theme) : '') + '</h3><span class="sub">' + (k.unlocked ? 'yours' : 'locked') + '</span></div>';
if (!k.unlocked) return head + '<p class="small">Members-only banners for ' + esc(k.label) + '. Your next counted refuel unlocks them: a package of $20+ here, or $25+ on LinkSpin' + (d.nextRefuel ? ' (your refuel day: ' + esc(d.nextRefuel) + ')' : '') + '.</p>';
return head + '<p class="small">Five banners with your ' + esc(d.name || 'name') + ' and a QR code to your own link drawn on each one. They stay yours after the month ends.' + (k.gif ? ' Your streak also unlocks the animated version.' : '') + '</p>'
+ '<div class="kit-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px">'
+ k.sizes.filter(s => s.ready).map(s => '<div class="kit-cell" data-month="' + esc(k.month) + '" data-size="' + s.size + '" style="border:1px solid var(--line,#2a4650);border-radius:8px;padding:8px;min-width:0">'
+ '<div class="small muted">' + s.size + (s.size === '1200x630' ? ' (social posts)' : '') + '</div><div class="kit-img" style="margin:6px 0;min-height:30px"></div>'
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small" type="button" data-kit="make">Make mine</button>'
+ (k.gif && s.size !== '1200x630' ? '<button class="btn small sec" type="button" data-kit="gif">Animated</button>' : '') + '</div></div>').join('')
+ '</div>';
}
function cellReady(cell, r, month) {
const box = cell.querySelector('.kit-img');
box.innerHTML = '<img src="' + esc(r.url) + '" alt="Your ' + esc(r.size) + ' Refuel Kit banner" style="max-width:100%;height:auto;display:block">'
+ '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:6px"><a class="btn small sec" href="' + esc(r.url) + '" download>Download</a>'
+ '<button class="btn small sec" type="button" data-kit="copy">Copy image link</button>'
+ (IAP_SIZES.includes(r.size) ? '<button class="btn small" type="button" data-kit="use">Use in an IAP banner campaign</button>' : '') + '</div>';
box.querySelector('[data-kit="copy"]').addEventListener('click', () => { try { navigator.clipboard.writeText(r.abs); say('Image link copied.', 'ok'); } catch (e) { say(r.abs); } });
const u = box.querySelector('[data-kit="use"]'); if (u) u.addEventListener('click', () => useInCampaign(r, month));
}
async function loadKitCard() {
const card = $('rkCard'); if (!card) return;
try {
const d = await (await fetch('/api/my/kits', { cache: 'no-store' })).json();
kitData = d;
if (!d || !d.on || !d.kits || !d.kits.length) { card.hidden = true; return; }
card.innerHTML = d.kits.slice(0, 3).map(k => '<div class="rk-kit" style="margin-bottom:14px">' + kitHtml(k, d) + '</div>').join('')
+ (d.customNote ? '<p class="small"><b>Custom banners credit:</b> ' + esc(d.customNote) + '</p>' : '')
+ '<p class="small muted">Ad credits buy delivery only. No banner may promise income.</p>';
card.hidden = false;
card.querySelectorAll('.kit-cell button[data-kit]').forEach(b => b.addEventListener('click', async () => {
const cell = b.closest('.kit-cell'); b.disabled = true; const was = b.textContent; b.textContent = 'Drawing your banner...';
try { cellReady(cell, await render(cell.dataset.month, cell.dataset.size, b.dataset.kit === 'gif' ? 'gif' : 'still'), cell.dataset.month); }
catch (e) { say(e.message, 'err'); }
b.disabled = false; b.textContent = was;
}));
} catch (e) { card.hidden = true; }
}
window.FUEL.loadKitCard = loadKitCard;
loadKitCard();
})();
+106 -5
View File
@@ -3,7 +3,10 @@
from the player's browser; the game only ever receives its normal hand-off token, which it opens at /auth.
Host page sets theme through CSS variables on .iapsi (--si-*). Usage:
IAPSignin.mount(el, { game: 'driprunner', ref: 'skycash', oneTap: 'https://instantadpay.com/api/my/driprunner' });
IAPSignin.enter('wallet'); // nudge: opens InstantAdPay in a new tab, already signed in */
IAPSignin.enter('wallet'); // nudge: opens InstantAdPay in a new tab, already signed in
After a fresh sign-in (never on a remembered pass) the kit shows the InstantAdPay login ad before the hand-off,
same as the dashboard: sponsor card, Open Ad (a counted click), 10 s countdown, then Continue. Any ad error,
or no ad to show, goes straight to the game. mount option loginAd: false switches it off (2026-10-18). */
(function () {
var IAP = 'https://instantadpay.com';
try { var me = document.currentScript && document.currentScript.src; if (me) IAP = new URL(me).origin; } catch (e) {}
@@ -27,9 +30,83 @@
+ '.iapsi .lk{background:none;border:0;padding:0;font:inherit;font-size:13.5px;color:var(--mu);text-decoration:underline;cursor:pointer}.iapsi .lk[disabled]{opacity:.5;cursor:default;text-decoration:none}'
+ '.iapsi form{display:grid;gap:12px;margin:0}.iapsi .row{display:flex;gap:14px;flex-wrap:wrap;justify-content:space-between}.iapsi label.ck{display:flex!important;gap:10px;align-items:flex-start;font-size:13px;color:var(--mu);margin:0}.iapsi .ck input{margin:3px 0 0;width:auto!important;flex:0 0 auto;height:auto;padding:0}.iapsi .ck span{flex:1}.iapsi .err:empty{display:none}'
+ '.iapsi .err{color:var(--si-bad,#ff8a8a);font-size:14px;min-height:1px}.iapsi .fine{font-size:12px;color:var(--mu)}.iapsi .fine a{color:var(--mu)}'
+ '.iapsi .hp{position:absolute;left:-9999px;width:1px;height:1px;opacity:0}.iapsi .chal{display:flex;gap:8px;flex-wrap:wrap}.iapsi .chal button{font-size:26px;width:52px;height:52px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);cursor:pointer}';
+ '.iapsi .hp{position:absolute;left:-9999px;width:1px;height:1px;opacity:0}.iapsi .chal{display:flex;gap:8px;flex-wrap:wrap}.iapsi .chal button{font-size:26px;width:52px;height:52px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);cursor:pointer}'
// login-ad gate (full screen, above the game page)
+ '.iapla{position:fixed;inset:0;z-index:2147483000;display:flex;flex-direction:column;background:var(--si-ground,#0d0b1a);color:var(--si-ink,#f2efff);font-family:var(--si-font,system-ui,sans-serif)}'
+ '.iapla-bar{display:flex;align-items:center;gap:10px 14px;flex-wrap:wrap;padding:10px 16px;background:var(--si-panel,#17142b);border-bottom:1px solid var(--si-line,rgba(255,255,255,.18))}'
+ '.iapla-brand{font-weight:800;font-size:15px;white-space:nowrap}.iapla-brand em{color:var(--si-accent,#7c5cff);font-style:normal}.iapla-note{flex:1;min-width:140px;font-size:13px;color:var(--si-muted,#b7b0d6)}'
+ '.iapla-timer{font-weight:700;font-size:14px;border:1px solid var(--si-line,rgba(255,255,255,.3));border-radius:999px;padding:4px 12px;white-space:nowrap}.iapla-timer.done{color:var(--si-accent,#7c5cff);border-color:var(--si-accent,#7c5cff)}'
+ '.iapla-btn{font:inherit;font-weight:700;font-size:14px;padding:9px 14px;border:0;border-radius:10px;background:var(--si-accent,#7c5cff);color:var(--si-accent-ink,#fff);cursor:pointer;text-decoration:none;white-space:nowrap}'
+ '.iapla-btn.sec{background:transparent;color:var(--si-ink,#f2efff);border:1px solid var(--si-line,rgba(255,255,255,.3))}.iapla-btn[disabled]{opacity:.55;cursor:default}.iapla-btn.big{font-size:17px;padding:13px 22px}'
+ '.iapla-frame{flex:1;border:0;width:100%;background:#fff;min-height:0}.iapla-body{flex:1;display:grid;place-items:center;padding:24px 16px;overflow:auto}'
+ '.iapla-card{max-width:560px;text-align:center;display:grid;gap:16px;justify-items:center}.iapla-card p{margin:0;font-size:14px;line-height:1.5;color:var(--si-muted,#b7b0d6)}'
+ '.iapla-eye{font-size:12px;letter-spacing:.12em;text-transform:uppercase}.iapla-card img{max-width:100%;max-height:50vh;border-radius:12px;border:1px solid var(--si-line,rgba(255,255,255,.18))}'
+ '.iapla-link{display:inline-block;font-size:20px;font-weight:700;color:var(--si-ink,#f2efff);background:var(--si-field,rgba(255,255,255,.06));border:1px solid var(--si-line,rgba(255,255,255,.18));border-radius:14px;padding:18px 22px}'
+ '.iapla [hidden]{display:none!important}';
function styleOnce() { if (document.getElementById('iapsiCss')) return; var s = document.createElement('style'); s.id = 'iapsiCss'; s.textContent = CSS; document.head.appendChild(s); }
// the login ad after a fresh sign-in. `then` (the hand-off) always runs exactly once: when the gate is done,
// when there is no ad, or on any error or a slow answer, so an ad can never hold a player out of the game.
function loginAd(game, then) {
var over = false; function go() { if (over) return; over = true; try { then(); } catch (e) {} }
var ctl = null; try { ctl = new AbortController(); } catch (e) {}
var slow = setTimeout(function () { if (ctl) try { ctl.abort(); } catch (e) {} go(); }, 7000);
fetch(IAP + '/api/game/ads/login?game=' + encodeURIComponent(game || ''), { credentials: 'omit', signal: ctl ? ctl.signal : undefined })
.then(function (r) { return r.ok ? r.json() : {}; })
.then(function (j) { clearTimeout(slow); if (over) return; var ad = j && j.ad; if (!ad || !ad.targetUrl) return go(); gate(ad, go); })
.catch(function () { clearTimeout(slow); go(); });
}
function gate(ad, go) {
var abs = function (u) { return /^https?:/i.test(u) ? u : IAP + u; };
var click = abs(ad.targetUrl), site = ad.siteUrl || click, framed = !!ad.frameable, started = false, t = null;
var g = document.createElement('div'); g.className = 'iapla'; g.setAttribute('role', 'dialog'); g.setAttribute('aria-label', 'Login sponsor');
g.innerHTML = '<div class="iapla-bar"><span class="iapla-brand">Instant<em>AdPay</em></span>'
+ '<span class="iapla-note" data-st>Login ad sponsor. Tap "Open Ad" to begin.</span>'
+ '<span class="iapla-timer" data-tm hidden></span>'
+ '<a class="iapla-btn sec" data-tab target="_blank" rel="noopener" hidden>Open site in a new tab \u2197</a>'
+ '<button class="iapla-btn" type="button" data-go hidden>Continue to the game</button></div>'
+ '<iframe class="iapla-frame" data-fr hidden sandbox="allow-scripts allow-same-origin allow-forms allow-popups" referrerpolicy="no-referrer" title="Sponsor site"></iframe>'
+ '<div class="iapla-body" data-bd><div class="iapla-card"><p class="iapla-eye">Today\'s login sponsor</p>'
+ (ad.imageUrl ? '<img src="' + esc(ad.imageUrl) + '" alt="sponsor ad">' : '<span class="iapla-link">' + esc(ad.title || 'Visit today\'s sponsor') + '</span>')
+ '<button class="iapla-btn big" type="button" data-open>Open Ad</button>'
+ '<p>' + (framed ? 'The sponsor\'s page opens right here under this bar. When the timer hits zero, your Continue button appears beside it.'
: 'This sponsor\'s site opens in a new tab. The timer counts down here; come back when it hits zero to continue to the game.') + '</p></div></div>';
var q = function (k) { return g.querySelector('[data-' + k + ']'); };
var st = q('st'), tm = q('tm'), tab = q('tab'), btn = q('go'), fr = q('fr'), bd = q('bd'), open = q('open');
function finish() { clearInterval(t); document.removeEventListener('securitypolicyviolation', csp); try { g.remove(); } catch (e) {} go(); }
// a game page whose CSP refuses the frame: offer the sponsor in a new tab instead (the timer keeps running)
function csp(ev) {
if (!started || !framed || !/frame|child|default/.test(String(ev.violatedDirective || ev.effectiveDirective || ''))) return;
var b = String(ev.blockedURI || '');
fr.hidden = true; bd.hidden = true; tab.hidden = false;
tab.href = (!b || b.indexOf(IAP) === 0) ? click : site; // blocked before our click relay ran: the tab is the counted click
st.textContent = 'This game cannot show the sponsor here. Open it in a new tab; the timer runs here.';
}
document.addEventListener('securitypolicyviolation', csp);
open.addEventListener('click', function () {
if (started) return; started = true; open.disabled = true;
if (framed) {
fr.src = click; // the click relay counts it, then redirects inside the frame
fr.hidden = false; bd.hidden = true; tab.href = site; tab.hidden = false;
st.textContent = 'Today\'s sponsor. Have a look; your Continue button appears when the timer ends.';
} else {
try { window.open(click, '_blank'); } catch (e) {} // the click relay counts it
st.textContent = 'The sponsor opened in a new tab. View it and come back; the timer runs here.';
}
var left = Math.max(1, Number(ad.dwell) || 10);
tm.hidden = false; tm.textContent = 'Time remaining: ' + left + 's';
t = setInterval(function () {
left -= 1;
if (left > 0) { tm.textContent = 'Time remaining: ' + left + 's'; return; }
clearInterval(t); tm.textContent = 'Time is up'; tm.className = 'iapla-timer done';
st.textContent = 'Thanks for the look. Your game is ready.'; btn.hidden = false;
try { btn.focus(); } catch (e) {}
}, 1000);
});
btn.addEventListener('click', finish);
document.body.appendChild(g);
}
function mount(el, opt) {
styleOnce(); opt = opt || {};
var game = opt.game, ref = String(opt.ref || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 40), src = String(opt.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30);
@@ -39,9 +116,13 @@
function err(m) { var e = el.querySelector('.err'); if (e) e.textContent = m || ''; }
function busy(on) { var b = el.querySelector('.go'); if (b) { b.disabled = !!on; if (on) b.dataset.l = b.textContent, b.textContent = 'One moment…'; else if (b.dataset.l) b.textContent = b.dataset.l; } }
function done(r) {
if (r.pass) ls(PASS_KEY, JSON.stringify({ p: r.pass, exp: Date.now() + 29 * 86400000, email: email }));
if (r.pass) { var prev = getPass(); ls(PASS_KEY, JSON.stringify({ p: r.pass, exp: Date.now() + 29 * 86400000, email: email || (prev && prev.email) || '', name: r.username || (prev && prev.name) || '' })); }
if (r.needUsername) return stepName(r);
if (r.token) return onToken(r.token);
if (r.token) { // a fresh sign-in: the login ad first (fails open to the hand-off)
if (opt.loginAd === false) return onToken(r.token);
el.innerHTML = '<h2>You are in</h2><p>One moment\u2026</p>';
try { return loginAd(game, function () { onToken(r.token); }); } catch (e) { return onToken(r.token); }
}
err('Something went wrong. Try again.');
}
function stepEmail(msg) {
@@ -119,7 +200,27 @@
});
setTimeout(function () { try { f.u.focus(); } catch (e) {} }, 50);
}
stepEmail();
// signed in on this device before (the 29-day pass): one tap, no code (Dallas 2026-10-19: "only a name and login with
// InstantAdPay, it should take care of the rest"). Remembered sign-ins skip the login ad, as before.
function stepResume(saved) {
var who = saved.name ? '@' + saved.name : (saved.email || 'your InstantAdPay account');
el.innerHTML = '<h2>' + esc(opt.title || 'Sign in to play') + '</h2><p>You are signed in on this device as <b>' + esc(who) + '</b>.</p>'
+ '<div class="err" role="alert"></div><button class="go" type="button" data-go>Continue as ' + esc(who) + '</button>'
+ '<div class="row"><button class="lk" type="button" data-other>Use a different account</button></div>';
el.querySelector('[data-go]').addEventListener('click', function () {
err(''); busy(true);
post('/api/game/auth/resume', { game: game, pass: saved.p }).then(function (x) {
busy(false);
if (x.ok && x.pass) ls(PASS_KEY, JSON.stringify({ p: x.pass, exp: Date.now() + 29 * 86400000, email: saved.email || '', name: x.username || saved.name || '' }));
if (x.ok && x.needUsername) return stepName(x);
if (x.ok && x.token) return onToken(x.token);
ls(PASS_KEY, null); stepEmail(x.error || 'Your sign-in expired. Start again with your email.');
});
});
el.querySelector('[data-other]').addEventListener('click', function () { ls(PASS_KEY, null); stepEmail(); });
}
var saved = opt.resume === false ? null : getPass();
if (saved) stepResume(saved); else stepEmail();
}
// nudge: open InstantAdPay in a new tab already signed in (the pass posts in a form, never in a URL)
+4 -3
View File
@@ -16,7 +16,8 @@
const { products } = await (await fetch('/api/catalog')).json();
const wrap = document.getElementById('tiles');
wrap.innerHTML = '';
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' };
products.sort((a, b) => a.priceCents - b.priceCents);
for (const p of products) {
const bonus = p.creditAmount - p.priceCents; // credits above 1cr/cent = bulk bonus
const div = document.createElement('div');
@@ -44,7 +45,7 @@
IAP.status('Confirm the purchase in your wallet…');
// resolve the sponsor at buy time: a code referrer who activated since
// page load still gets locked in
const spNow = await (await fetch('/api/sponsor')).json();
const spNow = await (await fetch('/api/sponsor?intent=buy')).json(); // intent=buy: never held (Marty 2026-10-27)
const r = await IAPWallet.buy(Number(btn.dataset.id), spNow.sponsorId || 0, btn.dataset.cost);
if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.');
IAP.status('Purchase settled on-chain. Credits are yours, payouts delivered. Watch it on the ledger.', 'ok');
@@ -153,7 +154,7 @@
setB($id('dcB3'), l3open, qualifies ? (5 - d) + ' more buyer(s)' : 'needs $20+ buyers');
$id('dcQualNote').textContent = qualifies
? 'Buyers of $20 or more count toward your qualification. 2 unlock level 2, 5 unlock level 3.'
: 'Heads up: $5 packages pay your level 1 but do not qualify buyers, so levels 2 and 3 stay locked in this scenario.';
: 'Heads up: packages under $20 pay your level 1 but do not qualify buyers, so levels 2 and 3 stay locked in this scenario.';
};
['dcDirects', 'dcPkg', 'dcSpread'].forEach(x => $id(x).addEventListener('input', recalc));
recalc();
+2 -2
View File
@@ -130,10 +130,10 @@
}
}).catch(() => {});
// package ladder (dollar constants + live POL quote)
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' };
fetch('/api/catalog').then(r => r.json()).then(c => {
const wrap = $('jnLadder'); if (!wrap || !c.products) return;
wrap.innerHTML = c.products.filter(p => p.active !== false).map(p =>
wrap.innerHTML = c.products.filter(p => p.active !== false).sort((a, b) => a.priceCents - b.priceCents).map(p =>
'<div class="jn-pk"><div class="n">' + (NAMES[p.id] || 'Package ' + p.id) + '</div><div class="p">' + IAP.fmtUsd(p.priceCents) + '</div><div class="c">' + Number(p.creditAmount).toLocaleString() + ' credits</div>'
+ (p.costWei ? '<div class="small muted">' + IAP.fmtPol(p.costWei) + ' POL now</div>' : '') + '</div>').join('');
}).catch(() => {});
+462 -35
View File
@@ -1,3 +1,8 @@
// member share links go out on the share domain (2026-10-20): https://ctbgo.com/<name> -> /join/<name> 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 () {
@@ -28,7 +33,51 @@
return r;
}
// holding tank activation hold (2026-10-27): no sponsor yet, so the activation waits for an adopter (24 hours at most)
let TANK_HOLD = null;
const holdLeft = ms => { const m = Math.max(1, Math.round(ms / 60000)); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; };
function tankHoldText(h) {
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
return t;
}
// one-tap switch on payouts (2026-10-27): the tank assignment chat + emails link to /my?activate=1#wallet. The intent
// survives the sign-in and the wallet link (memory + sessionStorage) and runs the Activate button's own flow once.
const ACT_KEY = 'iap.activateIntent';
let ACT_INTENT = /[?&]activate=1(&|#|$)/.test(location.search);
try { if (ACT_INTENT) sessionStorage.setItem(ACT_KEY, String(Date.now())); else { const t = Number(sessionStorage.getItem(ACT_KEY)) || 0; ACT_INTENT = t > 0 && Date.now() - t < 3600000; } } catch (e) {}
function clearActIntent() {
ACT_INTENT = false; try { sessionStorage.removeItem(ACT_KEY); } catch (e) {}
try { if (/[?&]activate=1/.test(location.search)) { const q = location.search.replace(/([?&])activate=1(&|$)/, (m, a, b) => b ? a : '').replace(/^&/, '?').replace(/[?&]$/, ''); history.replaceState(null, '', location.pathname + q + location.hash); } } catch (e) {}
}
function actNote(text) {
let n = $('actIntentNote');
if (!n && text) { n = document.createElement('p'); n.id = 'actIntentNote'; n.className = 'small'; n.style.cssText = 'margin:8px 0;color:#22c55e;font-weight:600'; }
if (!n) return null;
n.hidden = !text; n.textContent = text || '';
return n;
}
async function runActivateIntent(me) {
if (!ACT_INTENT || runActivateIntent.started || !me || !me.signedIn) return;
if (me.memberId) { clearActIntent(); IAP.status('Your payouts are already switched on.', 'ok'); return; }
// never auto-start while the tank hold applies, a sponsor is blocked, or no real sponsor resolves (it would bind the fallback)
if (TANK_HOLD || me.tankHold || me.sponsorBlocked || !me.sponsorId || me.sponsorFallback || me.sponsorRouted) { clearActIntent(); return; }
const who = me.sponsorName || ('member #' + me.sponsorId);
setPane('wallet');
if (!me.address) { // link the wallet first; render() after the link comes back here and carries on
const n = actNote('Step 1: link your wallet (one free signature). Then switching on payouts with ' + who + ' starts by itself.');
if (n && $('linkBtn') && !n.isConnected) $('linkBtn').insertAdjacentElement('beforebegin', n);
if ($('linkCard')) $('linkCard').scrollIntoView({ behavior: 'smooth', block: 'center' });
return;
}
runActivateIntent.started = true; clearActIntent();
const n = actNote('One free transaction switches on your payouts and locks ' + who + ' in as your sponsor. Confirm it in your wallet.');
if (n && !n.isConnected) $('activateBtn').insertAdjacentElement('beforebegin', n);
$('activateCard').scrollIntoView({ behavior: 'smooth', block: 'center' });
setTimeout(() => { if (!$('activateBtn').hidden && !$('activateBtn').disabled) $('activateBtn').click(); }, 400); // the Activate button's own flow (injected wallet, or the WalletConnect picker on a phone)
}
function nextMove(d) {
if (TANK_HOLD && d.address && !d.memberId) return tankHoldText(TANK_HOLD);
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.';
@@ -76,7 +125,13 @@
{ 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: '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 },
// Monthly Refuel badges (2026-10-24): final art, ribbon heights measured per image
{ key: 'refuelStart', label: 'Engine Started', sub: 'first monthly refuel', img: '/badges/badge-refuelstart.jpg?v=2', ribbonY: 0.735, earnedOnly: true },
{ key: 'refuel3', label: 'Refueled 3 months', sub: 'three monthly refuels in a row', img: '/badges/badge-refuel3.jpg?v=3', ribbonY: 0.783, earnedOnly: true },
{ key: 'refuel6', label: 'Refueled 6 months', sub: 'six monthly refuels in a row', img: '/badges/badge-refuel6.jpg?v=2', ribbonY: 0.716, earnedOnly: true },
{ key: 'refuel12', label: 'Refueled 12 months', sub: 'twelve monthly refuels in a row', img: '/badges/badge-refuel12.jpg?v=2', ribbonY: 0.744, earnedOnly: true }
];
let lastMilestones = [];
function renderBadges(d) {
@@ -85,7 +140,7 @@
const strip = $('badgeStrip');
if (!strip) return;
$('badgeCard').hidden = false;
strip.innerHTML = BADGES.map(b => {
strip.innerHTML = BADGES.filter(b => !b.earnedOnly || reached.includes(b.key)).map(b => { // earnedOnly: shown once earned (refuel badges)
const got = reached.includes(b.key);
return '<div class="badge-a' + (got ? '' : ' locked') + '">'
+ '<img class="badge-img" src="' + b.img + '" alt="' + b.label + ' badge" loading="lazy">'
@@ -104,7 +159,7 @@
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');
IAP.status('🏆 Achievement unlocked: ' + names + (total > 0 ? ': +' + total + ' bonus credits!' : '! See it in your badges.'), 'ok');
d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500));
}
}
@@ -407,7 +462,7 @@
}
bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({
v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6,
label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1),
label: e.type === 'AwardPaid' ? (e.override ? 'L4' : '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';
@@ -529,7 +584,7 @@
const media = isVid ? '<video src="' + esc(it.videoUrl) + '"' + (poster ? ' poster="' + esc(poster) + '"' : '') + ' preload="metadata" controls playsinline style="width:100%;max-width:640px;border-radius:12px;background:#000"></video>' : '';
const links = [];
if (it.videoUrl && !isVid) links.push('<a class="btn small sec" href="' + esc(it.videoUrl) + '" target="_blank" rel="noopener">Watch</a>');
if (it.docUrl) links.push('<a class="btn small sec" href="' + esc(it.docUrl) + '" target="_blank" rel="noopener">Open material</a>');
if (it.docUrl) links.push('<a class="btn small' + (it.docLabel ? '' : ' sec') + '" href="' + esc(it.docUrl) + '" target="_blank" rel="noopener">' + esc(it.docLabel || 'Open material') + '</a>');
return head + '<div class="card"><h3>' + esc(it.title || 'Lesson') + '</h3>'
+ (it.desc ? '<p class="muted small">' + esc(it.desc) + '</p>' : '')
+ (media ? '<p style="margin:10px 0">' + media + '</p>' : '')
@@ -631,8 +686,9 @@
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 = '<p><b>Next: ' + copy[0] + '</b>' + copy[1] + (cur.k === 'wallet' ? ' <a href="/wallets" target="_blank" rel="noopener" style="color:var(--mint)">Wallet guide</a>' : '') + '</p><button type="button" class="btn" id="gsGo">' + copy[2] + '</button>';
$('gsGo').addEventListener('click', copy[3]);
if (cur.k === 'payouts' && TANK_HOLD) { copy[0] = 'Matching you with a sponsor'; copy[1] = tankHoldText(TANK_HOLD); copy[2] = null; } // no activate button while held
$('gsNow').innerHTML = '<p><b>Next: ' + copy[0] + '</b>' + copy[1] + (cur.k === 'wallet' ? ' <a href="/wallets" target="_blank" rel="noopener" style="color:var(--mint)">Wallet guide</a>' : '') + '</p>' + (copy[2] ? '<button type="button" class="btn" id="gsGo">' + copy[2] + '</button>' : '');
if (copy[2]) $('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=<game>#buy.
@@ -651,7 +707,7 @@
box.innerHTML = v.eligible
? '<b>Welcome from ' + esc(v.game) + '!</b><br><span class="small">Your first package, $5 or more, comes with <b>+' + v.bonus + ' bonus ad credits</b>, and ' + esc(v.perk) + ' waiting for you in ' + esc(v.game) + '.</span>'
: '<b>You are a member.</b> <span class="small">' + (v.granted ? 'Your +' + v.bonus + ' welcome credits are in your balance. ' : '') + 'Your ' + esc(v.perk) + ' is waiting in ' + esc(v.game) + '.</span><br><a class="btn small" style="margin-top:8px;display:inline-block" href="' + esc(v.back) + '">Back to ' + esc(v.game) + ' to collect it</a>';
if (from) setPane('buy');
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);
@@ -680,6 +736,7 @@
$('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
@@ -728,7 +785,8 @@
}
} catch (e) {}
// ready-to-send share message + promo tools, personalized
const link = location.origin + '/join/' + (d.username || d.refCode || d.memberId || '');
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 {
@@ -745,7 +803,8 @@
tn.hidden = !(tw && tw.count);
if (tw && tw.count) tn.innerHTML = '<b>' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank</b> \u00b7 '
+ tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. <a href="#line">Adopt them from My line</a>'
+ (tw.eligible ? '.' : ' (you need your own $20 package first).');
+ (tw.eligible ? '.' : ' (you need your own $20 package first).')
+ (tw.ready ? ' <b style="color:#22c55e">' + tw.ready + ' of them ' + (tw.ready === 1 ? 'has' : 'have') + ' linked a wallet and ' + (tw.ready === 1 ? 'is' : 'are') + ' ready to switch on payouts.</b>' : '');
}
} catch (e) {}
// Share the presentation (2026-10-15): instantadpay.com/presentation?ref=<username> sets the same sponsor cookie as /join
@@ -783,11 +842,29 @@
}
// ── back-office menu: hash-routed panes ───────────────
const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', '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', games: 'Games',
const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile', 'engine']; // engine: the Engine Room (fuel.js, 2026-10-24)
const TITLES = { engine: 'Engine Room', 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' };
// wait for a card that loads late, then scroll to it and flash it once (deep links from the Engine Room)
function focusCard(id, inputId) {
const t0 = Date.now();
const tick = () => {
const el = $(id);
if (!el || el.hidden || !el.offsetParent) { if (Date.now() - t0 < 20000) setTimeout(tick, 300); return; }
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
el.style.transition = 'box-shadow .4s'; el.style.boxShadow = '0 0 0 3px #45e3c4';
setTimeout(() => { el.style.boxShadow = ''; }, 2600);
const inp = inputId && $(inputId); if (inp && !inp.closest('[hidden]')) setTimeout(() => { try { inp.focus({ preventScroll: true }); } catch (e) {} }, 500);
};
setTimeout(tick, 150);
}
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
// /my#conversions (2026-10-25): the Engine Room's "Set up conversion tracking" opens Campaigns and lands ON the
// Conversion tracking card (it unhides once the campaign list has loaded), highlighted, with the goal name box focused
if (name === 'conversions') { name = 'campaigns'; focusCard('convCard', 'convName'); }
if (!PANES.includes(name)) name = 'overview';
for (const p of PANES) {
const el = $('pane-' + p);
@@ -804,11 +881,13 @@
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') loadTraining();
if (name === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); }
if (name === 'pipeline') loadPipeline();
if (name === 'games') loadGames();
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
if (location.hash !== '#' + name) history.replaceState(null, '', '#' + name);
const keepQ = name === 'help' && paneQ ? '?' + paneQ : ''; // Help keeps ?t=<ref> 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)));
@@ -838,6 +917,7 @@
$('memberArea').hidden = !signedIn;
if ($('mcFinish')) $('mcFinish').hidden = !walletOnly;
if (!signedIn) return;
TANK_HOLD = (!me.memberId && me.tankHold) || null;
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
@@ -852,6 +932,9 @@
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 === 'polminer' && !render.toGame) { render.toGame = true; location.href = '/api/my/polminer'; return; } // POL Miner sent them here to sign in (2026-10-28)
if (me.returnTo === 'turkeydrop' && !render.toGame) { render.toGame = true; location.href = '/api/my/turkeydrop'; return; } // Turkey Drop sent them here to sign in (2026-10-28)
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
@@ -876,6 +959,7 @@
$('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);
@@ -891,6 +975,10 @@
loadPositions(me);
$('linkCard').hidden = !!me.address;
$('activateCard').hidden = !(me.address && !me.memberId);
{ let hn = $('tankHoldNote'); // held for an adopter: say so, and no activate button
if (!hn) { hn = document.createElement('p'); hn.id = 'tankHoldNote'; hn.className = 'small'; hn.style.cssText = 'margin:8px 0 0;color:#22c55e'; $('activateBtn').insertAdjacentElement('beforebegin', hn); }
hn.hidden = !TANK_HOLD; hn.textContent = TANK_HOLD ? tankHoldText(TANK_HOLD) : ''; $('activateBtn').hidden = !!TANK_HOLD; }
runActivateIntent(me).catch(() => {}); // arrived from the one-tap "Switch on payouts" link (tank assignment chat/email)
$('activityArea').hidden = !me.memberId;
$('campGate').hidden = true; // earned credits fund campaigns for everyone
$('campaignCard').hidden = false;
@@ -905,7 +993,8 @@
+ '<br>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) {
$('inviteLine').textContent = location.origin + '/join/' + (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.';
@@ -925,6 +1014,24 @@
}
}
// 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();
@@ -936,6 +1043,12 @@
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) {}
@@ -1024,11 +1137,109 @@
pageList('credits', box, 'tbody tr');
} catch (e) {}
}
// Campaigns > Conversion tracking (2026-10-23). Goals and counts come from LinkSpin through /api/my/conversions. Anything
// going wrong here only changes this card's own text: the campaign list never depends on it.
let convSel = null, convCamps = [];
const convFmt = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 1 });
function convSnips(host, g) {
const h = 'https://' + String(host || 'linkspin.app').replace(/^https?:\/\//, '').replace(/\/+$/, '');
const px = encodeURIComponent(g.px), goal = encodeURIComponent(g.name);
const val = Number(g.value) > 0 ? '&value=' + encodeURIComponent(g.value) : ''; // a goal with no default value (LinkSpin stores 0) adds nothing
return {
landing: '<script async src="' + h + '/t.js?px=' + px + '"></' + 'script>',
img: '<img src="' + h + '/cv.gif?px=' + px + '&goal=' + goal + val + '" width="1" height="1" alt="" style="display:none">',
js: '<script async src="' + h + '/cv.js?px=' + px + '&goal=' + goal + val + '"></' + 'script>'
};
}
const convBox = (id, label, text) => '<p class="small" style="margin:10px 0 4px"><b>' + label + '</b> <button class="btn small sec" type="button" data-convcopy="' + id + '">Copy</button></p>'
+ '<textarea id="' + id + '" readonly rows="2" style="width:100%;font-family:var(--mono);font-size:12px">' + esc(text) + '</textarea>';
function convCampLines(d) {
document.querySelectorAll('[data-convcamp]').forEach(el => { el.hidden = true; el.innerHTML = ''; });
if (!d || !d.ok || !(d.goals || []).length) return;
const by = d.byCampaign || {};
// cost per goal (30 days), 2026-10-26: goals are the last 30 days, so the spend is too. spend30 = credits each campaign
// spent in those days (credit activity log). A campaign started inside the window with no log rows uses its spend
// since it started (all of it is inside the window); otherwise no cost is shown rather than a lifetime figure.
const sp30 = d.spend30 || null, since = Number(d.spendSince) || (Date.now() - 30 * 86400000);
document.querySelectorAll('[data-convcamp]').forEach(el => {
const id = el.dataset.convcamp; const b = by[id]; const c = convCamps.find(x => String(x.id) === String(id)); if (!c) return;
let spent = null, basis = '';
if (sp30 && sp30[id] != null) { spent = Number(sp30[id]) || 0; basis = 'the credits it spent in the same 30 days'; }
else if (Number(c.created) >= since) { spent = Number(c.spent || 0); basis = 'the credits it spent since it started on ' + new Date(Number(c.created)).toLocaleDateString([], { month: 'short', day: 'numeric' }) + ', inside the 30 days'; }
const parts = d.goals.map(g => { const n = Number(b && b.conv && b.conv[g.px]) || 0;
return '<span>' + esc(g.name) + ' ' + n.toLocaleString() + (n > 0 && spent != null ? ' (' + convFmt(spent / n) + ' credits each)' : '') + '</span>'; });
el.innerHTML = '\u{1F3AF} <span class="muted">Goals and cost per goal (30 days):</span> ' + parts.join(' · ') + (spent == null ? ' <span class="muted">· no spend on record for these 30 days, so no cost per goal</span>' : '') + (b && b.clicks ? ' <span class="muted">· ' + Number(b.clicks).toLocaleString() + ' tracked clicks</span>' : '');
el.title = 'Goals counted for this campaign in the last 30 days. Cost per goal (30 days) = ' + (spent != null ? basis : 'the credits it spent in the same 30 days') + ', divided by those goals.';
el.hidden = false;
});
}
async function loadConv(fresh) {
const card = $('convCard'); if (!card) return;
card.hidden = false;
let d = null;
try { d = await (await fetch('/api/my/conversions' + (fresh ? '?fresh=1' : ''))).json(); } catch (e) { d = { ok: false, error: 'Could not reach InstantAdPay just now. Try again in a minute.' }; }
convCampLines(d);
const st = $('convStatus'), list = $('convGoals'), snips = $('convSnips'), add = $('convAddRow');
if (!d || !d.ok) { st.textContent = (d && d.error) || 'Conversion tracking is not available right now.'; list.innerHTML = ''; snips.innerHTML = ''; add.hidden = !!(d && d.reason === 'off'); return; }
add.hidden = false;
const goals = d.goals || [];
const m = d.methods || {}; const mt = ['url', 'stored', 'cookie', 'soft'].reduce((s, k) => s + (Number(m[k]) || 0), 0);
const selfN = Number(d.selfTests) || 0; // own clicks (ads here, spin links and Banner Spins on LinkSpin), kept as tests
st.textContent = goals.length ? (mt ? 'How your conversions were matched (30 days): ' + ['url', 'stored', 'cookie', 'soft'].map(k => k + ' ' + Number(m[k] || 0).toLocaleString()).join(', ') + '.' : 'No conversions counted yet in the last 30 days.')
+ (selfN ? ' ' + selfN.toLocaleString() + ' from your own clicks, kept as tests and left out.' : '') : 'No goals yet. Add your first one below.';
if (!goals.length) { list.innerHTML = ''; snips.innerHTML = ''; return; }
if (!convSel || !goals.some(g => g.px === convSel)) convSel = goals[0].px;
const when = ts => ts ? new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : 'never';
list.innerHTML = '<div class="tablewrap"><table class="camp-table"><thead><tr><th>Goal</th><th class="num">Default value</th><th>Pixel id</th><th class="num">Conversions (30 days)</th><th>Last test</th><th></th></tr></thead><tbody>'
+ goals.map(g => '<tr' + (g.px === convSel ? ' style="background:rgba(120,160,255,.08)"' : '') + '><td data-l="Goal"><b>' + esc(g.name) + '</b></td>'
+ '<td class="num" data-l="Default value">' + (Number(g.value) > 0 ? esc(g.value) : '<span class="muted">none</span>') + '</td>'
+ '<td data-l="Pixel id" class="mono small">' + esc(g.px) + '</td>'
+ '<td class="num" data-l="Conversions (30 days)">' + Number(g.conv || 0).toLocaleString() + (g.lastAt ? '<div class="muted small">last ' + when(g.lastAt) + '</div>' : '') + '</td>'
+ '<td data-l="Last test" class="small">' + when(g.lastTest) + '</td>'
+ '<td class="act"><button class="btn small sec" type="button" data-convpick="' + esc(g.px) + '">Snippets</button> <button class="btn small sec" type="button" data-convtest="' + esc(g.px) + '">Send a test conversion</button> <button class="btn small quiet" type="button" data-convdel="' + esc(g.px) + '" data-convname="' + esc(g.name) + '">Remove</button></td></tr>').join('')
+ '</tbody></table></div>';
const g = goals.find(x => x.px === convSel); const sn = convSnips(d.host, g);
snips.innerHTML = '<h4 style="margin:14px 0 0">Snippets for <b>' + esc(g.name) + '</b></h4>'
+ convBox('convLanding', '1. Landing tag (the page your ad points to)', sn.landing)
+ convBox('convImg', '2. Goal pixel (your thank-you page)', sn.img)
+ '<details style="margin-top:8px"><summary class="small">Prefer the JS version of the goal pixel?</summary>'
+ '<p class="small muted" style="margin:6px 0 0">Use it where your page allows scripts. It also sends the click id the landing tag stored, which makes the count surer.</p>'
+ convBox('convJs', 'Goal pixel, JS version', sn.js) + '</details>';
list.querySelectorAll('[data-convpick]').forEach(b => b.addEventListener('click', () => { convSel = b.dataset.convpick; loadConv(); }));
// Send a test conversion (2026-10-26): loads the member's REAL pixel in test mode from this browser, the same request a
// thank-you page makes (LinkSpin answers X-LS-Result: test). If the browser blocks it, the signed partner call records the test.
list.querySelectorAll('[data-convtest]').forEach(b => b.addEventListener('click', async () => {
b.disabled = true; const px = b.dataset.convtest; let via = '';
const base = 'https://' + String(d.host || 'linkspin.app').replace(/^https?:\/\//, '').replace(/\/+$/, '');
try { const r = await fetch(base + '/cv.gif?px=' + encodeURIComponent(px) + '&test=1&r=' + Date.now(), { cache: 'no-store', mode: 'cors', credentials: 'omit' }); if (r.ok && /^test/.test(r.headers.get('X-LS-Result') || '')) via = 'pixel'; } catch (e) {}
if (!via) { try { await api('/api/my/conversions/test', { px }); via = 'relay'; } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; return; } }
IAP.status(via === 'pixel' ? 'Test conversion received by your real pixel. It shows under Last test and never counts in your numbers.' : 'Test conversion recorded through InstantAdPay (this browser did not load the pixel itself). It shows under Last test and never counts in your numbers.', 'ok');
await loadConv(true);
}));
list.querySelectorAll('[data-convdel]').forEach(b => b.addEventListener('click', async () => {
const yes = await IAP.confirmBox('Remove the goal "' + b.dataset.convname + '"? Its pixel stops counting. Pages that still carry it will simply be ignored.', { title: 'Remove goal', ok: 'Remove', cancel: 'Keep it' });
if (!yes) return; b.disabled = true;
try { await api('/api/my/conversions/goal', { op: 'remove', px: b.dataset.convdel }); IAP.status('Goal removed.', 'ok'); await loadConv(true); }
catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
}));
snips.querySelectorAll('[data-convcopy]').forEach(b => b.addEventListener('click', async () => {
const ta = $(b.dataset.convcopy); try { await navigator.clipboard.writeText(ta.value); IAP.status('Copied. Paste it into your page.', 'ok'); } catch (e) { ta.select(); IAP.status('Selected. Press Ctrl+C (or long-press, Copy) to copy it.', 'ok'); }
}));
}
if ($('convAddBtn')) $('convAddBtn').addEventListener('click', async () => {
const b = $('convAddBtn'); const name = $('convName').value.trim(); const value = $('convValue').value.trim();
if (!name) { IAP.status('Give the goal a short name, like subscriber or sale.', 'bad'); return; }
b.disabled = true;
try { const r = await api('/api/my/conversions/goal', { op: 'create', name, value }); if (r.goal && r.goal.px) convSel = r.goal.px; $('convName').value = ''; $('convValue').value = ''; IAP.status('Goal added. Copy its two snippets below.', 'ok'); await loadConv(true); }
catch (e) { IAP.status(e.message, 'bad'); }
b.disabled = false;
});
async function loadCampaigns() {
try {
const r = await (await fetch('/api/my/campaigns')).json();
if (r.error) return;
lastRates = r.rates;
lastLoginLine = r.loginLine || null; loginLineHint();
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)
@@ -1042,42 +1253,52 @@
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 => '<span><b>' + x[0] + '</b> ' + x[1] + '</span>').join('');
$('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', Number(r.rates.loginSlotCredits || 1000).toLocaleString() + ' cr / ' + (r.rates.loginSlotDays || 30) + '-day slot'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].concat(Number(r.rates.synRateDivisor) > 1 ? [['Network', '1/' + Math.floor(Number(r.rates.synRateDivisor)) + ' of the rate']] : []).map(x => '<span><b>' + x[0] + '</b> ' + x[1] + '</span>').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 '
+ ' views, login ' + Number(r.rates.loginSlotCredits || 1000).toLocaleString() + 'cr per ' + (r.rates.loginSlotDays || 30) + '-day slot, solo '
+ (r.rates.soloCostPerRecipient || 5) + 'cr/delivery';
const el = $('campList');
el.innerHTML = '';
if (!r.campaigns.length) { el.innerHTML = '<p class="muted small">No campaigns yet. Launch your first below.</p>'; loadCreditActivity(el); return; }
convCamps = r.campaigns || [];
if (!r.campaigns.length) { el.innerHTML = '<p class="muted small">No campaigns yet. Launch your first below.</p>'; loadCreditActivity(el); loadConv(); return; }
const tbl = document.createElement('div');
tbl.className = 'tablewrap';
tbl.innerHTML = '<table class="camp-table"><thead><tr><th>Name</th><th>Type</th><th class="num">Views here</th><th class="num" title="Impressions delivered by Network Ad Space across the wider network (banner and text ads only)">Network views</th><th class="num">Clicks</th>'
// syndicated rate (Marty, 2026-10-27, 4:1): network views and partner visits cost 1/N of a view or visit here
const synN = Math.max(1, Math.floor(Number(r.rates && r.rates.synRateDivisor) || 1));
const netCell = c => ['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() + (synN > 1 && c.impsNas ? ' <span class="muted small">at 1/' + synN + '</span>' : '')
: (c.type === 'visits' && c.impsSyn) ? c.impsSyn.toLocaleString() + ' <span class="muted small">partner visits' + (synN > 1 ? ', ' + synN + ' = 1 visit' : '') + '</span>'
: '<span class="muted small" title="only banner and text ads syndicate to the network">n/a</span>';
if (synN > 1) { const n = document.createElement('p'); n.className = 'muted small'; n.textContent = 'Views and visits here on InstantAdPay use credits at the normal rate. Your ads also run on Network Ad Space and partner sites, and that delivery costs a ' + (synN === 4 ? 'quarter' : '1/' + synN) + ' of the rate: ' + synN + ' network views cost what 1 view here does, and ' + synN + ' partner visits use up 1 visit of your pack. Your budget goes further and every credit still buys real delivery.'; el.appendChild(n); }
tbl.innerHTML = '<table class="camp-table"><thead><tr><th>Name</th><th>Type</th><th class="num">Views here</th><th class="num" title="Impressions delivered by Network Ad Space across the wider network (banner and text ads), and visits from partner sites (visit packs)' + (synN > 1 ? ', at 1/' + synN + ' of the rate here' : '') + '">Network views</th><th class="num">Clicks</th>'
+ '<th class="num">Spent</th><th class="num">Budget</th><th>Status</th><th></th></tr></thead><tbody>'
+ r.campaigns.map(c => '<tr><td data-l="Campaign"><b>' + c.name + '</b>' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '</td>'
+ r.campaigns.map(c => '<tr><td data-l="Campaign"><b>' + c.name + '</b>' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '<div class="muted small conv-line" data-convcamp="' + c.id + '" hidden></div></td>'
+ '<td data-l="Type">' + c.type + (c.type === 'banner' && c.width ? ' <span class="muted small">' + c.width + '×' + c.height + '</span>' : '') + (c.dailyCap ? ' <span class="muted small" title="daily cap: ' + c.dailyCap + ' credits, ' + (c.daySpent || 0) + ' spent today">cap ' + c.dailyCap + '/day</span>' : '') + (c.geo ? ' <span class="muted small" title="shown only to viewers in these country tiers">tier ' + esc(c.geo.replace(/,/g, '+')) + '</span>' : '') + schedChips(c)
+ (c.type === 'visits' && (c.placement === 'golden' || c.placement === 'doors') ? ' <span class="badge' + (c.placement === 'golden' ? ' amber' : '') + '" title="' + (c.doorOnly ? 'runs only in Spooky Doors until the season ends, then any doors left run as normal visits' : 'the Spooky Doors season is over, so any doors left run as normal visits') + '">' + (c.placement === 'golden' ? 'Golden Door' : 'Spooky Doors') + '</span>' : '') + '</td>'
+ '<td class="num" data-l="Views here">' + c.imps.toLocaleString() + '</td>'
+ '<td class="num" data-l="Network views">' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : '<span class="muted small" title="only banner and text ads syndicate to the network">n/a</span>') + '</td>'
+ '<td class="num" data-l="Network views">' + netCell(c) + '</td>'
+ '<td class="num" data-l="Clicks">' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '<div class="muted small clk-src" title="where the clicks happened">' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '<span>' + esc(k) + ' ' + v + '</span>').join('') + (c.impsNas ? ' · network: see Network views' : '') + '</div>' : '') + '</td>'
+ (c.type === 'visits' ? '<td class="num" data-l="Spent"><span class="muted small" title="visit packs are paid in full when created; nothing more is charged as visits arrive">paid up front</span></td><td class="num" data-l="Delivered"><b>' + c.imps.toLocaleString() + '</b> 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 => '<div class="muted small" title="Spooky Doors: every door opened on this pack, and how many different players opened one">\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '</div>')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '</td>'
: c.type === 'featured' ? '<td class="num" data-l="Spent"><span class="muted small" title="featured runs are paid in full when booked (' + (r.rates.featuredPerDay || 40) + ' credits a day); nothing more is charged while the run is live">paid up front</span></td><td class="num" data-l="Run">' + featRun(c) + '</td>'
: '<td class="num" data-l="Spent">' + c.spent + '</td><td class="num" data-l="Budget">' + c.budget + '</td>')
+ '<td data-l="Status">' + (c.status === 'out' ? (c.type === 'visits' ? '<span class="badge">pack delivered</span>' : '<span class="badge amber">budget spent</span>') : c.status === 'done' ? '<span class="muted">' + (c.type === 'featured' ? 'run ended' : 'ended') + '</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
+ '<td data-l="Status">' + (c.status === 'queued' ? queuedCell(c) : c.status === 'cancelled' ? '<span class="muted" title="cancelled before it started; the full price came back to your balance">cancelled, refunded</span>' : c.status === 'out' ? (c.type === 'visits' ? '<span class="badge">pack delivered</span>' : '<span class="badge amber">budget spent</span>') : c.status === 'done' ? '<span class="muted">' + (c.type === 'featured' ? 'run ended' : 'ended') + '</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
+ '<td class="act">' + (c.status === 'active' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="pause">Pause</button>'
: c.status === 'paused' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="resume">Resume</button>' : '')
+ (['paused', 'out', 'done'].includes(c.status) ? ' <button class="btn small quiet" data-arch="' + c.id + '" data-archname="' + esc(c.name || ('#' + c.id)) + '" data-archleft="' + Math.max(0, (c.budget || 0) - (c.spent || 0)) + '" title="move it out of this list, keep its numbers">Archive</button>' : '')
: c.status === 'paused' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="resume">Resume</button>'
: c.status === 'queued' ? '<button class="btn small sec" data-qedit="' + c.id + '">Edit</button> <button class="btn small quiet" data-qcancel="' + c.id + '" data-qname="' + esc(c.name || ('#' + c.id)) + '" data-qpaid="' + Number(c.spent || 0) + '">Cancel and refund</button>' : '')
+ (['paused', 'out', 'done', 'cancelled'].includes(c.status) ? ' <button class="btn small quiet" data-arch="' + c.id + '" data-archname="' + esc(c.name || ('#' + c.id)) + '" data-archleft="' + Math.max(0, (c.budget || 0) - (c.spent || 0)) + '" title="move it out of this list, keep its numbers">Archive</button>' : '')
+ (c.type === 'featured' ? ' <button class="btn small sec" data-extend="' + c.id + '" title="book more days at the daily rate">Extend run</button>'
: c.type === 'visits' ? ' <button class="btn small sec" data-morevisits="' + c.id + '" data-vper="' + placeCost(c.doorOnly ? c.placement : 'all', r.rates) + '" data-vdoor="' + (c.doorOnly ? (c.placement === 'golden' ? 'golden' : 'doors') : '') + '">' + (c.doorOnly ? 'Buy more doors' : 'Buy more visits') + '</button>'
: c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up
: ' <button class="btn small sec" data-topup="' + c.id + '">Buy more views</button>')
+ '</td></tr>').join('') + '</tbody></table>';
el.appendChild(tbl);
pageList('camps', tbl, 'tbody tr');
loadConv();
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.';
@@ -1102,6 +1323,27 @@
await loadCampaigns(); loadDashboard();
} catch (e) { IAP.status(e.message, 'bad'); }
}));
// prepaid login-ad line (2026-10-23): a reservation can be edited for free and cancelled for the full price back until it starts
el.querySelectorAll('button[data-qcancel]').forEach(b => b.addEventListener('click', async () => {
const paid = Number(b.dataset.qpaid) || 0;
const ok = await IAP.confirmBox('You give up your place in line and the full ' + paid.toLocaleString() + ' credits come back to your balance right away, as purchased credits. You can reserve again later, at the back of the line.',
{ title: 'Cancel ' + b.dataset.qname + '?', ok: 'Cancel and refund', cancel: 'Keep my place' });
if (!ok) return;
b.disabled = true;
try { const x = await api('/api/my/campaigns/' + b.dataset.qcancel + '/cancel-reservation'); IAP.status('Reservation cancelled. ' + Number(x.refunded || 0).toLocaleString() + ' credits are back in your balance.', 'ok'); await loadCampaigns(); loadDashboard(); }
catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; await loadCampaigns(); }
}));
el.querySelectorAll('button[data-qedit]').forEach(b => b.addEventListener('click', async () => {
const c = r.campaigns.find(x => x.id === Number(b.dataset.qedit)); if (!c) return;
const target = await IAP.ask({ title: 'Edit your reserved login ad', text: 'Target URL: the page members see when they sign in. Editing is free until the ad starts.', value: c.targetUrl || '', placeholder: 'https://', ok: 'Next' });
if (target === null) return;
const image = await IAP.ask({ title: 'Image (optional)', text: 'A direct image link (.png or .jpg) shown as the clickable creative. Leave it empty for a plain link card.', value: c.imageUrl || '', placeholder: 'https://', ok: 'Next' });
if (image === null) return;
const title = await IAP.ask({ title: 'Headline (optional)', text: 'Shown on the link card when there is no image. Up to 60 characters.', value: c.title || '', placeholder: 'Visit today\'s sponsor', ok: 'Save changes' });
if (title === null) return;
try { await api('/api/my/campaigns/' + c.id + '/edit-reservation', { targetUrl: target.trim(), imageUrl: image.trim(), title: title.trim() }); IAP.status('Saved. Your place in line is unchanged.', 'ok'); await loadCampaigns(); }
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'); }
@@ -1138,6 +1380,28 @@
} catch (e) {}
}
let lastRates = null;
let lastLoginLine = null; // { max, used, queued, free, credits, days, nextPlace, nextEstStart, mine: [{ id, place, estStart }] }
// every date about the login-ad line is shown in Central time, Marty's clock
function ctWhen(ts) { return new Date(ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central'; }
function queuedCell(c) {
const m = lastLoginLine && (lastLoginLine.mine || []).find(x => x.id === c.id);
return '<span class="badge amber" title="paid in full; it starts on its own when a slot frees">In line' + (m ? ' #' + m.place : '') + '</span>'
+ '<div class="muted small">' + (m && m.estStart ? 'Estimated start ' + esc(ctWhen(m.estStart)) : 'Start date not known yet') + '</div>';
}
// the Login ad form: open slots, or the paid line with this buyer's place and estimated start
function loginLineHint() {
const el = $('cLoginLine'); const isLogin = $('cType') && $('cType').value === 'login';
if (el) el.hidden = !isLogin || !lastLoginLine;
if ($('createCampBtn')) $('createCampBtn').textContent = isLogin && lastLoginLine && !lastLoginLine.free ? 'Reserve the next slot' : 'Launch campaign';
if (!el || !isLogin || !lastLoginLine) return;
const L = lastLoginLine;
el.textContent = L.free
? L.free + ' of ' + L.max + ' login-ad slots open now. Yours goes live the moment you launch: ' + Number(L.credits).toLocaleString() + ' purchased credits for ' + L.days + ' days.'
: 'All ' + L.max + ' login-ad slots are taken' + (L.queued ? ' and ' + L.queued + ' paid ' + (L.queued === 1 ? 'reservation is' : 'reservations are') + ' in line' : '') + '. You can reserve the next slot: you pay the same '
+ Number(L.credits).toLocaleString() + ' purchased credits now and take place #' + L.nextPlace + ' in line. Your ' + L.days + ' days start when your turn comes, not before.'
+ (L.nextEstStart ? ' Estimated start: ' + ctWhen(L.nextEstStart) + '. That is an estimate: a slot can end early if its owner archives it, which moves the line forward.' : '')
+ ' Until it starts you can edit it for free, or cancel it for every credit back.';
}
function soloHint() {
if (!lastRates || $('cType').value !== 'solo') return;
const cost = lastRates.soloCostPerRecipient || 5;
@@ -1201,6 +1465,7 @@
// 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();
loginLineHint();
const t = $('cType').value;
$('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL
if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner';
@@ -1320,7 +1585,14 @@
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,
// login ad with every slot taken: pay now for a place in line (Marty, 2026-10-23), after one plain confirmation
const confirmReserve = async (place, est) => IAP.confirmBox('Every login-ad slot is taken right now. Reserving charges the full ' + Number((lastLoginLine && lastLoginLine.credits) || (lastRates && lastRates.loginSlotCredits) || 0).toLocaleString()
+ ' purchased credits now and puts you at place #' + place + ' in line. Your ad starts on its own when a slot frees, and runs its full ' + ((lastLoginLine && lastLoginLine.days) || 30) + ' days from then.'
+ (est ? '\n\nEstimated start: ' + ctWhen(est) + '. That is an estimate: a slot can end early if its owner archives it.' : '')
+ '\n\nUntil it starts you can edit it for free, or cancel it and get every credit back.', { title: 'Reserve the next login-ad slot?', ok: 'Pay now and reserve', cancel: 'Not now' });
let reserve = false;
if (t === 'login' && lastLoginLine && !lastLoginLine.free) { if (!(await confirmReserve(lastLoginLine.nextPlace, lastLoginLine.nextEstStart))) return; reserve = true; }
const sendCamp = extra => api('/api/my/campaigns', Object.assign({ 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,
@@ -1333,9 +1605,18 @@
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) });
budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) }, extra || {}));
let res;
try { res = await sendCamp({ reserve }); }
catch (e) { // the last slot went while the form was open: offer the line instead of a dead end
if (!(t === 'login' && e.data && e.data.full)) throw e;
if (!(await confirmReserve(e.data.place, e.data.estStart))) { await loadCampaigns(); return; }
res = await sendCamp({ reserve: true });
}
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');
if (res && res.queued) IAP.status('Reserved and paid. You are #' + res.place + ' in line' + (res.estStart ? ', estimated start ' + ctWhen(res.estStart) : '') + '. We will tell you on site and by email the moment it goes live.', 'ok');
else if (t === 'login' && reserve) IAP.status('A slot opened up while you were deciding, so your login ad is live now.', 'ok');
else 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']
@@ -1615,10 +1896,11 @@
} catch (e) {}
}
function renderTank(el, r) {
const rows = listApply('tank', r.waiting);
const rows = listApply('tank', r.waiting).sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0)); // ready to activate always on top (stable: the chosen order stays inside each group)
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 => '<div class="lin-row"><span class="nm">' + esc(w.name) + '</span>'
const readyBadge = w => w.ready ? ' <span class="badge" style="background:rgba(34,197,94,.15);border-color:#22c55e;color:#22c55e" title="Wallet linked. If nobody adopts them, the site assigns them to the next eligible adopter when the time runs out.">Ready to activate \u00b7 ' + (w.holdUntil > Date.now() ? holdLeft(w.holdUntil - Date.now()) + ' left' : 'assigning now') + '</span>' : '';
el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + readyBadge(w) + '</span>'
+ '<span class="em">joined ' + ago(w.joined) + '<span class="sp wrap">' + memberChips(w) + '</span></span>'
+ '<span class="dt">last sign-in: <b>' + ago(w.lastSeen) + '</b></span>'
+ (r.eligible ? '<button class="btn small" type="button" data-adopt="' + esc(w.username || w.email) + '" data-aname="' + esc(w.name) + '">Adopt</button>' : '') + '</div>').join('')
@@ -1681,6 +1963,147 @@
} catch (e) {}
}
loadWednesdayCard(); setInterval(loadWednesdayCard, 120000);
// ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across every network game. More game, never "earn more". ----
// (2026-10-28) the copy names no game count: seasonal games come and go (Spooky Doors ends Oct 31, Turkey Drop runs Nov 2 to 30)
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.
// 2026-10-22 (Dallas's structure): + Sovereign (monthly) and Legend (yearly). Names and what each includes come from the server
// (gamepass.js TIER_DEFS, row.perks); GP_TIER_PERKS is only the fallback for an older server answer.
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'],
};
// 2026-10-25 (Marty): every pass price equals a one-click package ($5, $20, $50, $100, $250), so the pass comes with exactly that
// package's ad credits (the base credits per package, same table as Buy packages; day bonuses can add more)
const GP_PKG_CREDITS = { 5: 500, 10: 1000, 20: 2000, 50: 5500, 100: 12000, 250: 32500, 500: 70000 };
const gpLen = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days';
function renderPassTiers(card, gp, highlight) {
const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier);
const state = top ? '<span class="badge" style="background:var(--gold,#e2b04a);color:#111">' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '</span>'
: '<span class="badge">No pass active</span>';
const caps = gp.caps || {};
const capsLine = caps.enforced ? 'Today: <b>' + gpPol(caps.used && caps.used.total) + '</b> 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 ? '<button class="btn small" type="button" data-gp-go="1">Buy a $' + r.package + ' package</button>'
: r.open ? '<button class="btn small" type="button" data-gp-tier="' + esc(r.tier) + '">' + (r.active ? 'Extend ' + gpLen(r.days) + ' more' : 'Get ' + esc(r.name)) + ' · ' + '$' + r.package + ' package</button>'
: '<span class="small muted">Not on sale right now. Your pass keeps running.</span>';
return '<div class="gp-tier' + (r.tier === gp.tier ? ' on' : '') + '"><h4>' + esc(r.name) + '</h4>'
+ '<p class="gp-price">$' + r.usd + ' <span class="small muted">for ' + gpLen(r.days) + '</span></p>'
+ '<p class="small muted" style="margin:0 0 6px">Comes with the $' + r.package + ' package and its ' + (GP_PKG_CREDITS[r.package] ? GP_PKG_CREDITS[r.package].toLocaleString('en-US') + ' ' : '') + 'ad credits.</p>'
+ '<ul>' + (r.perks || GP_TIER_PERKS[r.tier] || []).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul>'
+ '<p class="small" style="margin:6px 0">' + (r.active ? '<b>Active until ' + esc(gpCT(r.until)) + '</b>' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '</p>'
+ btn + '</div>';
};
card.hidden = false; card.classList.toggle('gp-hl', !!highlight);
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}️ Game Passes</h3><span class="sub">weekly, monthly or yearly · every game</span></div>'
+ '<p style="margin:0 0 8px">' + state + '</p>'
+ '<p>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. Each higher pass includes everything below it and adds more of Shards of Valor: weapons, gear, bonus islands, heroes and a higher level cap. <b>Paid passes add heroes, islands, a higher level cap and new looks.</b> Pass gear is never better than gear players can earn, and passes never pay more POL.</p>'
+ '<div class="gp-tiers">' + rows.map(box).join('') + '</div>'
+ (capsLine ? '<p class="small muted" style="margin-top:10px">' + capsLine + '</p>' : '')
+ '<p class="small muted" style="margin:10px 0 0">Every pass is paid by a new package purchase of at least its price, so your sponsor and team are paid; you keep the package credits for your ads. Credits you already hold 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.</p>';
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 ' + gpLen(r.days) : 'Get ' + r.name + ' for ' + gpLen(r.days)) + ' ($' + r.usd + ')? Every pass is paid by a new package purchase of $' + r.package + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the pass starts the moment it settles. Credits you already hold never buy a pass. The same POL caps as every pass: 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.', 'ok'); setPane('buy'); 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', 'spookydoors'],
['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'],
['POL Miner', 'daily crystal limit 1.5 POL instead of 0.5, plus one free supply crate every day'],
['Turkey Drop', 'one free \u201cback on the air\u201d extra life every day', 'turkeydrop'],
['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']
];
let gpShown = null; // slugs in the public games list (gamesLive, seasons applied): a row with a slug shows only while its game does
async function gpShownLoad() { if (gpShown) return gpShown; try { const d = await (await fetch('/api/public/games')).json(); gpShown = new Set((d.games || []).map(g => g.slug)); } catch (e) { gpShown = new Set(); } return gpShown; }
function gpPerksHtml() {
return '<div class="gp-perks"><p style="margin:10px 0 6px"><b>What you get</b></p>'
+ '<table class="gp-tbl"><tr><td>Every game</td><td>Daily 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 the games</td></tr>'
+ '<tr><td>Weekly</td><td>A seat in the Pass Tournament, POL prizes from 5% of pass sales, paid Mondays</td></tr>'
+ '<tr><td>Badge</td><td>The gold Game Pass badge with your name, to share or post</td></tr></table>'
+ '<p style="margin:10px 0 6px"><b>In each game</b></p><table class="gp-tbl">'
+ GP_PERKS.filter(p => !p[2] || (gpShown && gpShown.has(p[2]))).map(p => '<tr><td>' + p[0] + '</td><td>' + p[1] + '</td></tr>').join('') + '</table>'
+ '<p class="small muted" style="margin:6px 0 0">The Pass never changes how much a reward pays: it lets you play and collect more each day.</p></div>';
}
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; }
await gpShownLoad();
if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight);
// Five Dollar Friday + the pass (Marty 2026-10-23): the package that starts the pass also gets the Friday bonus, so say so on Fridays
let fdf = ''; try { const f = await (await fetch('/api/friday')).json(); if (f && f.on && f.live) { const base = gp.price || 500, got = Math.round(base * (1 + (Number(f.pct) || 20) / 100));
fdf = '<p style="margin:0 0 10px;padding:8px 10px;border-radius:8px;background:rgba(226,176,74,.12);border:1px solid rgba(226,176,74,.35)">\u{1F383} <b>It\u2019s Five Dollar Friday.</b> The $' + (gp.usd || 5) + ' package that starts your pass gets +' + (Number(f.pct) || 20) + '% too, so you get the ' + (gp.days || 7) + '-day pass <b>and keep ' + got.toLocaleString() + ' ad credits</b>. Tap Get the Pass first, then buy the package.</p>'; } } catch (e) {} // the tier boxes above show only when a tier above weekly is on sale or the member holds one (never an admin-only view: tier tests live in Admin > Game Pass)
const caps = gp.caps || {}; const price = gp.price || 500;
const state = gp.active ? '<span class="badge" style="background:var(--gold,#e2b04a);color:#111">Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '</span>'
: gp.waiting ? '<span class="badge amber">Waiting for a $' + (gp.usd || 5) + ' package</span>' : '<span class="badge">Not active</span>';
const capsLine = caps.enforced
? 'Today: <b>' + gpPol(caps.used && caps.used.total) + '</b> 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 = '<div class="card-head"><h3>\u{1F39F}\uFE0F Game Pass</h3><span class="sub">$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 every game</span></div>'
+ '<p style="margin:0 0 8px">' + state + '</p>'
+ fdf
+ '<p>Free play pays real POL every day. The Pass plays <b>more</b>: 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 <b>Pass Tournament</b> 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.</p>'
+ gpPerksHtml()
+ '<p class="small muted">' + capsLine + '</p>'
+ (gp.waiting ? '<p class="small">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.</p>' : '')
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:10px 0 0">'
+ (gp.waiting ? '<button class="btn" type="button" id="gpGoBuy">Buy a $' + (gp.usd || 5) + ' package</button>' : '<button class="btn" type="button" id="gpBuy">' + (gp.active ? 'Extend ' + (gp.days || 7) + ' more days' : 'Get the Pass') + ' \u00b7 buy a $' + (gp.usd || 5) + ' package</button>')
+ '<span class="small muted">Paid by a new $' + (gp.usd || 5) + ' or bigger package, so your sponsor and team are paid. You keep the package credits for your ads; credits you already hold never buy a pass.</span></p>';
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') + '? The Pass is paid by a new package purchase of $' + (gp.usd || 5) + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the Pass starts the moment it settles. Credits you already hold never buy a pass.', { 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.', 'ok'); setPane('buy'); return; }
IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok');
await loadGamePassCard(true);
try { await loadDashboard(); } catch (e) {} // unlocks the Game Pass badge at once (toast + team post)
} 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', polminer: 'POL Miner', turkeydrop: 'Turkey Drop', driprunner: 'Drip Runner', roadagent: 'Road Agent' };
card.hidden = false;
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '</h3><span class="sub">free play keeps paying; the Pass plays more</span></div>'
+ '<p>Every member earns real POL in the games up to the daily cap. The <b>Game Pass</b> raises the caps across all the games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with a new package), adds the weekly Pass Tournament and a perk in every game.</p>'
+ '<button class="btn" type="button" id="gpNudgeGo">See the Game Pass</button>';
$('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;
@@ -1712,8 +2135,9 @@
if (!j || !j.show) { card.hidden = true; return; }
card.hidden = false; $('pdPre').hidden = !j.preview; $('pdLine').textContent = j.line || '';
}
async function loadGames() {
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 = '<p class="muted small">No games are open yet. Check back soon.</p>'; return; }
@@ -1941,7 +2365,7 @@
// ── 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 };
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);
@@ -2439,7 +2863,7 @@
}));
// ── in-dashboard package buying ──
const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
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.
@@ -2525,6 +2949,7 @@
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');
@@ -2570,7 +2995,7 @@
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.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), spNow.sponsorBlocked === 'tankHold' ? 'ok' : '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
@@ -2820,10 +3245,12 @@
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.';
if (sp.sponsorBlocked === 'tankHold') return tankHoldText(sp.tankHold);
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.tankHold || me.sponsorBlocked === 'tankHold') { TANK_HOLD = me.tankHold || {}; IAP.status(tankHoldText(me.tankHold), 'ok'); await render(); return; } // never bound under the company
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);
+21 -9
View File
@@ -29,8 +29,8 @@ window.IAPPromo = (function () {
{ net: 'X', label: 'X · advertiser', text: 'Marketers: you were buying traffic anyway. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Packages from $5. Join free: {{LINK:adspend}}' },
{ net: 'X', label: 'X · free join', text: 'Join free. View a few ads, earn credits, run your first campaign for zero dollars. Seven ad formats, real dwell-timed attention, every payout public on Polygon. {{LINK:free}}' },
{ net: 'Facebook', label: 'Facebook · story post', text: 'I got tired of "your commission is pending." So I joined a platform where there is no pending. A smart contract on the Polygon blockchain splits every ad package the moment it sells: half to the sponsor, then levels two and three, then the platform. It lands in your own wallet in seconds. No approval queue, no withdrawal button, no 15th of the month.\n\nYou are buying real advertising: banners, text ads, login ads, solo ads to member inboxes, video ads, featured links and verified visits. Members earn credits for their attention, so the ads actually get seen.\n\nJoin free, look around, and check the public ledger before you spend a dollar: {{LINK:instant}}\n\nNo income promises. It is advertising, not investing, and crypto carries risk.' },
{ net: 'Facebook', label: 'Facebook · skeptic angle', text: 'Every online program I ever joined asked me to trust a back office. This one does not. Every payout is a public transaction on Polygon you can look up yourself, with the wallet addresses and amounts right there. The split is written in a verified smart contract nobody can quietly edit.\n\nFree to join with just an email. The wallet comes out only if you buy a package or switch on payouts. Packages run $5 to $250, and every one of them is ad delivery you can watch running.\n\nTake the tour: {{LINK:ledger}}' },
{ net: 'LinkedIn', label: 'LinkedIn · professional', text: 'An experiment in transparent affiliate payouts: InstantAdPay sells advertising packages ($5 to $250) whose sponsor commissions are settled by a verified smart contract on Polygon in the same transaction as the purchase. 50 / 20 / 10 across three levels, 20 percent to the platform, every payment public on the chain.\n\nWhat I find interesting is not the commission. It is that "pending payout" stops being a concept. If you buy traffic for a living and want to see how same-transaction settlement works in practice, the tour is free: {{LINK:adspend}}' },
{ net: 'Facebook', label: 'Facebook · skeptic angle', text: 'Every online program I ever joined asked me to trust a back office. This one does not. Every payout is a public transaction on Polygon you can look up yourself, with the wallet addresses and amounts right there. The split is written in a verified smart contract nobody can quietly edit.\n\nFree to join with just an email. The wallet comes out only if you buy a package or switch on payouts. Packages run $5 to $500, and every one of them is ad delivery you can watch running.\n\nTake the tour: {{LINK:ledger}}' },
{ net: 'LinkedIn', label: 'LinkedIn · professional', text: 'An experiment in transparent affiliate payouts: InstantAdPay sells advertising packages ($5 to $500) whose sponsor commissions are settled by a verified smart contract on Polygon in the same transaction as the purchase. 50 / 20 / 10 across three levels, 20 percent to the platform, every payment public on the chain.\n\nWhat I find interesting is not the commission. It is that "pending payout" stops being a concept. If you buy traffic for a living and want to see how same-transaction settlement works in practice, the tour is free: {{LINK:adspend}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp group', text: 'Quick one for the group. Ad platform on Polygon where every package splits to sponsor wallets the second it sells. No withdrawals, no pending. Free to join by email, packages from $5, seven ad formats, and you earn credits for viewing. Tour here: {{LINK:instant}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp group · free angle', text: 'If you want to test an ad network without spending anything: join free, view a handful of ads, earn credits, run your first campaign on the house. Payouts are on the public Polygon ledger. {{LINK:free}}' }
];
@@ -51,8 +51,8 @@ window.IAPPromo = (function () {
{ tier: 'Five Dollar Friday', subject: 'Tomorrow is Five Dollar Friday', body: 'Quick heads-up.\n\nTomorrow is Five Dollar Friday on InstantAdPay. Any ad package from $5 up, bought on Friday (Central time), earns +20% bonus credits the moment it settles.\n\nHere is why it matters: every pack pays its sponsor line in the same transaction, on the Polygon blockchain. When the whole network buys on the same day, every line gets paid at once, and you can watch it happen on the public ledger.\n\nIt is free to join. Line up your pack tonight so you are ready when Friday starts:\n{{LINK}}\n\nAdvertising with a referral program. Not an investment, no income guaranteed.' },
{ tier: 'Wired Wednesday', subject: 'Tomorrow is Wired Wednesday', body: 'Quick heads-up.\n\nTomorrow is Wired Wednesday on InstantAdPay. Any ad package from $20 up, bought on Wednesday (Central time), 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. Nothing to set up, nothing to claim.\n\nAnd like every pack, it pays the sponsor line in the same transaction on the Polygon blockchain, public on the ledger.\n\nIf you have been meaning to get a pack, tomorrow is the day: {{WEDNESDAY}}\n\nNo income promises. Advertising, not investing.' },
{ tier: 'Short', subject: 'Paid the second it sells', body: 'Quick one.\n\nI joined an ad platform where every package splits to sponsor wallets in the same transaction as the sale. No pending payouts, no withdraw button. It is on the Polygon blockchain, and every payment is public.\n\nJoin free, look at the ledger, decide later: {{LINK:instant}}\n\nNo income promises. Advertising, not investing.' },
{ tier: 'Standard', subject: 'Your wallet gets paid instantly', body: 'You know the usual drill. Someone buys on your link, you wait for a payout. Maybe days. Maybe an approval hold. Maybe a "your account is under review."\n\nInstantAdPay does not work like that.\n\nA smart contract on the Polygon blockchain handles every purchase the second it happens. 50% to the sponsor. 20% to the next level. 10% to the one after that. 20% to the platform. Each split lands directly in your own wallet. No withdrawal button. No "request payout." No approval queue.\n\nThe money just shows up.\n\nYou can watch every transaction on the public ledger. Real time. Anyone can verify it.\n\nFree to join. Packages from $5 to $250. No income promises. It is advertising, not investing.\n\n{{LINK}}' },
{ tier: 'Long', subject: 'The ad network with no pending payouts', body: 'Let me tell you what you are actually looking at, because "crypto ad platform" can mean anything.\n\nInstantAdPay sells advertising. Five packages, $5 to $250. A package mints ad credits, and one credit is one cent of delivery across seven formats: display banners, text ads, full-screen login ads, solo ads delivered into member inboxes, video ads, featured links, and verified visits. Members earn credits for their attention, with a timer that pauses when they look away, so your ad is seen by a person, not a script.\n\nNow the part that made me join.\n\nWhen anyone in your line buys a package, a verified smart contract on Polygon splits the payment in that same transaction: 50 percent to their direct sponsor, 20 percent to level two, 10 percent to level three, 20 percent to the platform. It lands in real wallets in seconds. There is no balance to withdraw because nothing is ever held.\n\nEvery one of those payments is public. Open the ledger, click a transaction, read it on Polygonscan.\n\nJoining is free and only needs an email. Your wallet comes out when you buy a package or switch on payouts. If you never spend a dollar, you can still view ads, earn credits, and run a small campaign on those.\n\nHave a look: {{LINK:instant}}\n\nOne honest line: nobody is promising you an income. Results depend on your effort, and crypto carries risk of loss.' },
{ tier: 'Standard', subject: 'Your wallet gets paid instantly', body: 'You know the usual drill. Someone buys on your link, you wait for a payout. Maybe days. Maybe an approval hold. Maybe a "your account is under review."\n\nInstantAdPay does not work like that.\n\nA smart contract on the Polygon blockchain handles every purchase the second it happens. 50% to the sponsor. 20% to the next level. 10% to the one after that. 20% to the platform. Each split lands directly in your own wallet. No withdrawal button. No "request payout." No approval queue.\n\nThe money just shows up.\n\nYou can watch every transaction on the public ledger. Real time. Anyone can verify it.\n\nFree to join. Packages from $5 to $500. No income promises. It is advertising, not investing.\n\n{{LINK}}' },
{ tier: 'Long', subject: 'The ad network with no pending payouts', body: 'Let me tell you what you are actually looking at, because "crypto ad platform" can mean anything.\n\nInstantAdPay sells advertising. Seven packages, $5 to $500. A package mints ad credits, and one credit is one cent of delivery across seven formats: display banners, text ads, full-screen login ads, solo ads delivered into member inboxes, video ads, featured links, and verified visits. Members earn credits for their attention, with a timer that pauses when they look away, so your ad is seen by a person, not a script.\n\nNow the part that made me join.\n\nWhen anyone in your line buys a package, a verified smart contract on Polygon splits the payment in that same transaction: 50 percent to their direct sponsor, 20 percent to level two, 10 percent to level three, 20 percent to the platform. It lands in real wallets in seconds. There is no balance to withdraw because nothing is ever held.\n\nEvery one of those payments is public. Open the ledger, click a transaction, read it on Polygonscan.\n\nJoining is free and only needs an email. Your wallet comes out when you buy a package or switch on payouts. If you never spend a dollar, you can still view ads, earn credits, and run a small campaign on those.\n\nHave a look: {{LINK:instant}}\n\nOne honest line: nobody is promising you an income. Results depend on your effort, and crypto carries risk of loss.' },
{ tier: 'Follow-up', subject: 'Did you see the ledger?', body: 'Following up on the ad platform I sent over.\n\nIf you only look at one thing, look at the live ledger. Every purchase and every payout, with real wallet addresses, in the order they happened. That is the whole pitch: nothing to take on faith.\n\n{{LINK:ledger}}\n\nIf it is not for you, no worries at all.' }
];
@@ -61,7 +61,7 @@ window.IAPPromo = (function () {
{ q: 'Which crypto do I get paid in?', truth: 'One coin, one network: POL, the native coin of Polygon. Packages are dollar-priced and settled in POL at the live Chainlink rate; every payout is sent as POL to the recipient\'s own Polygon wallet in the same transaction. No tokens, no other chains, no stablecoins.', say: 'You get paid in POL, which is Polygon\'s own coin, straight into your wallet the moment a package in your line sells. Any Polygon wallet works, MetaMask, SafePal, Phantom, and if you have never held crypto you can buy POL with a card inside the member area. {{LINK}}' },
{ q: 'Is this a pyramid scheme?', truth: 'You are buying advertising that actually runs: a credit is one cent of delivery across seven live formats, and members earn credits for dwell-timed attention. Sponsor payments are referral commissions written as constants in a verified contract, paid only when a real package sells. Nobody has to recruit to use the ads, and joining costs nothing.', say: 'Fair question. Here is the test I use: is there a real product that people would buy with no referral involved? Here the product is ad delivery, seven formats, one cent per credit, and you can watch your campaign serving. The sponsor split is a referral commission on those sales, fixed in a public contract. Join free and run the ads with zero referrals if you like. {{LINK:free}}' },
{ q: 'I do not have a crypto wallet. I am not technical.', truth: 'Joining needs only an email and a 6-digit code. The wallet comes out only when someone buys a package or switches on payouts, and the site walks them through it. A card on-ramp (MoonPay) delivers POL straight to their own wallet. Email first, wallet second.', say: 'You do not need one to join. It is email only, no password even. The wallet shows up later, only if you decide to buy a package or want payouts, and the site walks you through it step by step. Start here and look around first: {{LINK}}' },
{ q: 'What am I actually buying?', truth: 'Ad credits minted on-chain the moment a package is bought: $5 = 500, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500. Credits spend on banners, text ads, login ads, solo ads to member inboxes, video ads, featured links and verified visits, with live stats per campaign. Only the buyer\'s campaigns can spend them.', say: 'Advertising. A package mints credits, one credit is one cent of delivery, and you spend them on seven ad formats from your own dashboard with live stats. The $5 package is 500 credits, the $250 package is 32,500. You can see the formats before you spend anything: {{LINK:adspend}}' },
{ q: 'What am I actually buying?', truth: 'Ad credits minted on-chain the moment a package is bought: $5 = 500, $10 = 1,000, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500, $500 = 70,000. Credits spend on banners, text ads, login ads, solo ads to member inboxes, video ads, featured links and verified visits, with live stats per campaign. Only the buyer\'s campaigns can spend them.', say: 'Advertising. A package mints credits, one credit is one cent of delivery, and you spend them on seven ad formats from your own dashboard with live stats. The $5 package is 500 credits, the $500 package is 70,000. You can see the formats before you spend anything: {{LINK:adspend}}' },
{ q: 'Who holds my money?', truth: 'Nobody. A purchase is one Polygon transaction that splits to the sponsor line and the platform wallets immediately. The site never holds balances, and the contract source is verified on Polygonscan and Sourcify. Overpayment refunds itself in the same transaction.', say: 'That is the part I like most: nobody holds it. The purchase is a single blockchain transaction that pays the sponsor line and the platform in the same moment. There is no balance sitting anywhere waiting for a withdrawal. The contract code is public and verified, and every payment is on the ledger: {{LINK:ledger}}' },
{ q: 'What if POL drops?', truth: 'Packages are priced in dollars and settled in POL at the live Chainlink rate at the moment of purchase. Payouts arrive as POL in the recipient\'s own wallet immediately, so what they do with it is their call. This is advertising, not an investment, and POL is volatile like any crypto asset.', say: 'Packages are dollar priced, so $20 is $20 worth of POL at that moment. Payouts land in your wallet right away, and it is your money from that second. Crypto does move, so treat it as advertising you bought, not an investment. {{LINK}}' },
{ q: 'Why would anyone buy ads here?', truth: 'The members are marketers who already buy traffic. Viewers earn credits only after a server-timed dwell, so impressions are real people. Solo ads reach member inboxes with a guaranteed delivery count, verified visits are one unique member per visit, and banner and text ads also syndicate to a partner ad network.', say: 'Because the people on it are marketers, and they get paid to actually look. Every view is dwell-timed on the server, solo ads land in real inboxes with a guaranteed count, and verified visits are one real person each. You can watch your own campaign serve: {{LINK:adspend}}' },
@@ -292,9 +292,21 @@ window.IAPPromo = (function () {
// the public games page (2026-10-10, Marty: "make sure that's in the promo tools for everyone"): every game on one page, with the member's referral on the Join button
{ slug: 'allgames', name: 'All games (one page)', link: 'https://instantadpay.com/games?ref=', img: 'https://instantadpay.com/banners/iap-games-1200x630.jpg', sub: 'every game in the network on one public page, open now and opening next',
posts: [
{ name: 'Short post', text: 'Every game in the InstantAdPay network on one page: a word puzzle, a hidden-object hunt, a match-3, a runner, a scavenger hunt, a cyberpunk battler. Free to play, and they pay POL to the wallet on your account. {L}' },
{ name: 'Friendly post', text: 'If you like small games that actually pay something, this is the page I send people. Eight games, all free, all paying POL on Polygon for first clears, levels and daily puzzles. Pick one: {L}' },
{ name: 'Short post', text: 'Every game in the InstantAdPay network on one page: a word puzzle, a hidden-object hunt, a match-3, a runner, a scavenger hunt, a cyberpunk battler, a brick breaker, a mining game. Free to play, and they pay POL to the wallet on your account. {L}' },
{ name: 'Friendly post', text: 'If you like small games that actually pay something, this is the page I send people. Every one is free, and they all pay POL on Polygon for first clears, levels, bosses and daily puzzles. Pick one: {L}' },
{ name: 'Telegram or WhatsApp line', text: 'All the games that pay POL, one page, free to play: {L}' }] },
// Turkey Drop (2026-10-28, the Thanksgiving season game): shows only while it is in the public games list (gamesLive, through Nov 30) and from Nov 2
{ slug: 'turkeydrop', name: 'Turkey Drop', link: 'https://turkeydropgame.com/?ref=', img: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/turkeydrop/og-turkeydrop.jpg', sub: 'Thanksgiving game that pays Polygon, through Nov 30',
posts: [
{ name: 'Short post', text: 'Turkey Drop is a free Thanksgiving game. The radio station helicopter is dropping turkeys over the mall, and you swing the net to catch them before they splat. Score milestones pay Polygon the first time you reach them, and the top 3 each week win a Polygon prize. Here through Nov 30: {L}' },
{ name: 'Telegram or WhatsApp line', text: 'Thanksgiving game in the network: Turkey Drop. Catch the turkeys before they splat, score milestones pay Polygon. Free, through Nov 30: {L}' }] },
// POL Miner (2026-10-28): shows once 'polminer' is in gamesLive (the public games list), like PolyBreak
{ slug: 'polminer', name: 'POL Miner', link: 'https://polminer.com/?ref=', img: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polminer/og-polminer.jpg', sub: 'mining game that pays Polygon',
posts: [
{ name: 'Short post', text: 'POL Miner is a free mining game. Dig down through the layers, haul ore up to sell, upgrade your pick, lamp and cart, and beat a drill boss every 30 m. The rare pink Polygon crystals pay Polygon to the wallet on your InstantAdPay account. {L}' },
{ name: 'Friendly post', text: 'This one is easy to lose an hour in. POL Miner is free, it plays fine on a phone, and you sign in with your InstantAdPay account. Each pink Polygon crystal you dig out pays Polygon, and so does each drill boss the first time you beat it. Give it a dig: {L}' },
{ name: 'Crystal angle', text: 'Somewhere under the gravel there is a pink glow. In POL Miner the rare Polygon crystals pay Polygon when you dig them out. Free to play: {L}' },
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: POL Miner. Free mining game, the pink Polygon crystals pay Polygon: {L}' }] },
{ slug: 'polybreak', name: 'PolyBreak', link: 'https://polybreak.app/?ref=', img: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polybreak/og-polybreak.jpg', sub: 'brick breaker that pays Polygon',
posts: [
{ name: 'Short post', text: 'PolyBreak is a free brick breaker in the old Amiga arcade style. Smash a wall of glass jewel bricks, grab the capsules, and catch the purple Polygon gem when it drops. Your first clear of each round pays Polygon to the wallet on your InstantAdPay account. {L}' },
@@ -333,7 +345,7 @@ window.IAPPromo = (function () {
{ slug: 'spookydoors', name: 'Spooky Doors', link: 'https://spookydoors.com/?ref=', kit: 'promo-spookydoors', seasonal: true },
{ slug: 'polhunter', name: 'PolHunter', link: 'https://polhunter.com/?r=', kit: 'promo-polhunter' }];
const SIZES = [['728x90', 'Leaderboard'], ['468x60', 'Banner'], ['320x50', 'Mobile banner'], ['300x250', 'Medium rectangle'], ['336x280', 'Large rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Wide skyscraper'], ['120x600', 'Skyscraper'], ['300x600', 'Half page'], ['600x300', 'Traffic exchange / splash page']];
const avail = { spookydoors: false, roadagent: !preLaunch(2026, 10, 15), polybreak: false }; // PolyBreak joins once it is in gamesLive (public games list) // seasonal: the Spooky Doors kit says whether its season is showing; Road Agent joins the list on its launch day
const avail = { spookydoors: false, roadagent: !preLaunch(2026, 10, 15), polybreak: false, polminer: false, turkeydrop: false }; // Turkey Drop: in the public games list AND from Nov 2 (its season start) // PolyBreak joins once it is in gamesLive (public games list) // seasonal: the Spooky Doors kit says whether its season is showing; Road Agent joins the list on its launch day
const list = () => GAMES.filter(g => avail[g.slug] !== false);
let cur = null; try { cur = localStorage.getItem('iap.gmGame'); } catch (e) {}
const draw = () => {
@@ -369,7 +381,7 @@ window.IAPPromo = (function () {
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(copyBtn(src, 'Copy image URL')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); grid.appendChild(d); }
};
window.__gmAvail = (slug, on) => { avail[slug] = !!on; draw(); };
fetch('/api/public/games').then(r => r.json()).then(d => { if ((d.games || []).some(g => g.slug === 'polybreak')) window.__gmAvail('polybreak', true); }).catch(() => {});
fetch('/api/public/games').then(r => r.json()).then(d => { for (const sl of ['polybreak', 'polminer', 'turkeydrop']) if ((d.games || []).some(g => g.slug === sl) && !(sl === 'turkeydrop' && preLaunch(2026, 11, 2))) window.__gmAvail(sl, true); }).catch(() => {});
$('gmPick').addEventListener('click', e => { const b = e.target.closest('[data-gm]'); if (!b) return; cur = b.dataset.gm; draw(); });
draw();
}
+3 -3
View File
@@ -32,10 +32,10 @@
function answer(i) {
api('/api/refuel/done', { n: nonce, answer: i }).then(function (r) {
if (r.error) { if (r.retry) return challenge(); $('rfHint').textContent = r.error; $('rfCheck').hidden = true; return; }
done = true; $('rfCheck').hidden = true; var gk = GAME === 'Gem Kingdom', ch = GAME === 'ClutterHunt', sw = GAME === 'SpellWheel';
$('rfHint').textContent = gk ? 'Visit counted. Your heroes are back on their feet.' : (ch || sw) ? 'Visit counted. Your hint is ready.' : 'Visit counted. Your tank is full.';
done = true; $('rfCheck').hidden = true; var gk = GAME === 'Gem Kingdom', ch = GAME === 'ClutterHunt', sw = GAME === 'SpellWheel', td = GAME === 'Turkey Drop';
$('rfHint').textContent = gk ? 'Visit counted. Your heroes are back on their feet.' : (ch || sw) ? 'Visit counted. Your hint is ready.' : td ? 'Visit counted. WFWL is back on the air.' : 'Visit counted. Your tank is full.';
if (gk && inGame) { try { window.parent.postMessage({ gkContinue: nonce, ok: true }, '*'); } catch (e) {} }
var b = $('rfDone'); b.disabled = false; b.textContent = gk ? 'Back to the battle' : ch ? 'Back to the room' : sw ? 'Back to the puzzle' : 'Back to the run'; b.onclick = function () { location.href = r.ret; };
var b = $('rfDone'); b.disabled = false; b.textContent = gk ? 'Back to the battle' : ch ? 'Back to the room' : sw ? 'Back to the puzzle' : td ? 'Back on the air' : 'Back to the run'; b.onclick = function () { location.href = r.ret; };
setTimeout(function () { location.href = r.ret; }, 1200);
});
}
+194
View File
@@ -0,0 +1,194 @@
// Help desk front end (2026-10-16): the public /support form, the private ticket link page (/support/t/<token>)
// and the member Help pane (/my#help). Server side: tickets.js + the /api/support, /api/my/support routes.
// Times show in US Central, like the rest of the site's support copy.
window.IAPSupport = (function () {
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const CATS = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other'];
const STATUS = { open: 'Open', waiting_on_member: 'Waiting on you', closed: 'Closed' };
const when = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
const linkify = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '<a href="$1" target="_blank" rel="noopener nofollow">$1</a>');
async function call(path, body, method) {
const o = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
if (body !== undefined) { o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(body); }
const r = await (await fetch(path, o)).json();
if (r.error && !r.challenge) { const e = new Error(r.error); e.data = r; throw e; }
return r;
}
(function css() {
if (document.getElementById('supCss')) return;
const st = document.createElement('style'); st.id = 'supCss';
st.textContent = '.sup-form label{display:block;font-size:13px;color:var(--muted);margin:12px 0 4px}.sup-form input,.sup-form select,.sup-form textarea{width:100%;box-sizing:border-box}'
+ '.sup-row{display:flex;gap:10px;align-items:center;justify-content:space-between;padding:12px 4px;border-bottom:1px solid var(--line);cursor:pointer}.sup-row:last-child{border-bottom:0}.sup-row:hover{background:rgba(67,232,195,.04)}'
+ '.sup-row .sr-main{min-width:0;flex:1}.sup-row .sr-sub{font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sup-row .sr-meta{font-size:12px;color:var(--muted)}'
+ '.sup-st{font-size:11.5px;font-weight:700;border-radius:999px;padding:2px 10px;border:1px solid var(--line-strong);white-space:nowrap}.sup-st.open{color:var(--mint);border-color:rgba(67,232,195,.5)}.sup-st.waiting_on_member{color:#f2c94c;border-color:rgba(242,201,76,.5)}.sup-st.closed{color:var(--muted)}'
+ '.sup-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--amber,#ffb238);margin-right:6px;vertical-align:1px}'
+ '.sup-msg{border:1px solid var(--line);border-radius:12px;padding:12px 14px;margin:10px 0;background:rgba(4,8,7,.35)}.sup-msg.admin{border-color:rgba(67,232,195,.45);background:rgba(67,232,195,.06)}.sup-msg.system{opacity:.8}'
+ '.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}.sup-msg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:15px;line-height:1.5}'
+ '.sup-att{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}.sup-att img{max-width:160px;max-height:120px;border-radius:8px;border:1px solid var(--line)}'
+ '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}';
document.head.appendChild(st);
})();
const catOptions = sel => CATS.map(c => '<option' + (c === sel ? ' selected' : '') + '>' + esc(c) + '</option>').join('');
const AUTHOR = { member: 'You', admin: 'Marty, InstantAdPay support', system: 'InstantAdPay' };
function threadHtml(v) {
const t = v.ticket;
return '<div class="card-head" style="flex-wrap:wrap;gap:8px"><h3 style="margin:0">' + esc(t.subject) + '</h3><span class="sup-st ' + esc(t.status) + '">' + esc(STATUS[t.status] || t.status) + '</span></div>'
+ '<p class="small muted" style="margin:4px 0 6px">' + esc(t.ref) + ' · ' + esc(t.category) + ' · opened ' + esc(when(t.created)) + '</p>'
+ v.messages.map(m => '<div class="sup-msg ' + esc(m.author) + '"><div class="sm-head"><b>' + esc(AUTHOR[m.author] || m.author) + '</b><span>' + esc(when(m.created)) + '</span></div>'
+ '<div class="sm-body">' + linkify(m.body) + '</div>'
+ ((m.attachments || []).length ? '<div class="sup-att">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment"></a>').join('') + '</div>' : '') + '</div>').join('')
+ (t.status === 'closed' ? '<p class="small muted" style="margin:14px 0 0">This ticket is closed. Write below and it opens again.</p>' : '');
}
function replyBox(id, withAttach) {
return '<div class="sup-form"><label for="' + id + 'Body">Your reply</label><textarea id="' + id + 'Body" rows="4" maxlength="5000" placeholder="Add more detail or answer Marty here"></textarea>'
+ (withAttach ? attachRow(id) : '')
+ '<div class="sup-actions"><button class="btn small" type="button" id="' + id + 'Send">Send reply</button><span class="small muted" id="' + id + 'Msg"></span></div></div>';
}
// up to 2 screenshots per message, through the member upload path (signed-in only)
const attachRow = id => '<label for="' + id + 'File">Screenshots (optional, up to 2 images)</label><input type="file" id="' + id + 'File" accept="image/png,image/jpeg,image/webp,image/gif" multiple><div class="sup-att" id="' + id + 'Att"></div>';
function wireAttach(id) {
const list = []; const inp = document.getElementById(id + 'File'); if (!inp) return () => [];
const draw = () => { document.getElementById(id + 'Att').innerHTML = list.map(u => '<img src="' + esc(u) + '" alt="screenshot">').join(''); };
inp.addEventListener('change', async () => {
for (const f of [...inp.files]) {
if (list.length >= 2) { IAP.status('Two images per message at most.', 'bad'); break; }
try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); if (r.type !== 'image') throw new Error('Images only, please.'); list.push(r.url); draw(); }
catch (e) { IAP.status(e.message || 'Upload failed.', 'bad'); }
}
inp.value = '';
});
return () => list.slice(); // read at send time
}
// ── member Help pane ──
let helpState = { open: null };
async function badge() {
try { const r = await call('/api/my/support'); const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; } return r; } catch (e) { return null; }
}
async function help(paneQ) {
const host = document.getElementById('helpBody'); if (!host) return;
const want = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(paneQ || '') || [])[1];
if (want) return openMine(want);
helpState.open = null;
host.innerHTML = '<div class="card"><p class="muted small">Loading your tickets…</p></div>';
let r; try { r = await call('/api/my/support'); } catch (e) { host.innerHTML = '<div class="card"><p class="small">Could not load your tickets. ' + esc(e.message) + '</p></div>'; return; }
const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; }
host.innerHTML = '<div class="card"><div class="card-head"><h3>Help and support</h3><button class="btn small" type="button" id="helpNewBtn">New ticket</button></div>'
+ '<p class="muted small" style="margin:6px 0 0">Stuck on something? Send Marty a ticket. He reads every one and replies here, and you get an email when he does. The quickest answers to common questions are in Training and the chat bubble.</p></div>'
+ '<div class="card" id="helpNew" hidden></div>'
+ '<div class="card"><div class="card-head"><h3>Your tickets</h3><span class="sub">' + r.tickets.length + '</span></div>'
+ (r.tickets.length ? r.tickets.map(t => '<div class="sup-row" data-ref="' + esc(t.ref) + '"><div class="sr-main"><div class="sr-sub">' + (t.unread ? '<span class="sup-dot" title="New reply"></span>' : '') + esc(t.subject) + '</div>'
+ '<div class="sr-meta">' + esc(t.ref) + ' · ' + esc(t.category) + ' · updated ' + esc(when(t.updated)) + '</div></div><span class="sup-st ' + esc(t.status) + '">' + esc(STATUS[t.status] || t.status) + '</span></div>').join('')
: '<p class="muted small" id="helpEmpty">No tickets yet. When you send one, it shows up here with Marty\'s replies.</p>') + '</div>';
host.querySelectorAll('.sup-row').forEach(el => el.addEventListener('click', () => { history.replaceState(null, '', '#help?t=' + el.dataset.ref); openMine(el.dataset.ref); }));
document.getElementById('helpNewBtn').addEventListener('click', () => newForm());
if (/(?:^|&)new=1/.test(paneQ || '')) newForm();
}
function newForm() {
const box = document.getElementById('helpNew'); if (!box) return;
box.hidden = false;
box.innerHTML = '<h3 style="margin:0 0 4px">New ticket</h3><div class="sup-form">'
+ '<label for="hnCat">What is it about?</label><select id="hnCat">' + catOptions('') + '</select>'
+ '<label for="hnSubject">Subject</label><input id="hnSubject" maxlength="140" placeholder="A few words, like: my payout did not arrive">'
+ '<label for="hnBody">Message</label><textarea id="hnBody" rows="6" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
+ attachRow('hn')
+ '<div class="sup-actions"><button class="btn small" type="button" id="hnSend">Send to support</button><button class="btn small sec" type="button" id="hnCancel">Cancel</button><span class="small muted" id="hnMsg"></span></div></div>';
const atts = wireAttach('hn');
document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
const send = document.getElementById('hnSend');
send.addEventListener('click', async () => {
if (send.disabled) return; send.disabled = true;
try {
const r = await call('/api/my/support', { category: document.getElementById('hnCat').value, subject: document.getElementById('hnSubject').value, body: document.getElementById('hnBody').value, attachments: atts() });
IAP.status('Sent. Your ticket is ' + r.ref + '. Marty will reply here and by email.', 'ok');
history.replaceState(null, '', '#help?t=' + r.ref); openMine(r.ref);
} catch (e) { document.getElementById('hnMsg').textContent = e.message; }
finally { send.disabled = false; }
});
document.getElementById('hnSubject').focus();
}
async function openMine(ref) {
const host = document.getElementById('helpBody'); if (!host) return;
helpState.open = ref;
host.innerHTML = '<div class="card"><p class="muted small">Loading…</p></div>';
let v; try { v = await call('/api/my/support/' + encodeURIComponent(ref)); } catch (e) { host.innerHTML = '<div class="card"><p class="small">' + esc(e.message) + '</p><p><a href="#help" id="helpBack">Back to your tickets</a></p></div>'; wireBack(); return; }
drawMine(v);
badge();
}
const wireBack = () => { const a = document.getElementById('helpBack'); if (a) a.addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#help'); help(''); }); };
function drawMine(v) {
const host = document.getElementById('helpBody');
host.innerHTML = '<p style="margin:0 0 10px"><a href="#help" id="helpBack">‹ All your tickets</a></p><div class="card">' + threadHtml(v) + '</div><div class="card">' + replyBox('hr', true) + '</div>';
wireBack();
const atts = wireAttach('hr');
const btn = document.getElementById('hrSend');
btn.addEventListener('click', async () => {
if (btn.disabled) return; btn.disabled = true;
try { const nv = await call('/api/my/support/' + encodeURIComponent(v.ticket.ref) + '/reply', { body: document.getElementById('hrBody').value, attachments: atts() }); drawMine(nv); IAP.status('Reply sent.', 'ok'); }
catch (e) { document.getElementById('hrMsg').textContent = e.message; }
finally { btn.disabled = false; }
});
}
// ── public /support page and the private ticket link ──
async function page() {
const host = document.getElementById('supMain'); if (!host) return;
const m = /^\/support\/t\/([A-Za-z0-9_.-]{20,80})$/.exec(location.pathname);
if (m) return tokenPage(host, m[1]);
let me = null; try { me = await (await fetch('/api/me')).json(); } catch (e) {}
const signedIn = !!(me && me.signedIn && me.email);
host.innerHTML = (signedIn ? '<div class="card" style="border-color:rgba(67,232,195,.45)"><p class="small" style="margin:0">You are signed in as <b>' + esc(me.username ? '@' + me.username : me.email) + '</b>. Your tickets and Marty\'s replies live in <a href="/my#help">Help in your dashboard</a>, which is the easiest place to follow up. This form works too and files the ticket under your account.</p></div>' : '')
+ '<div class="card"><form class="sup-form" id="supForm" novalidate autocomplete="on">'
+ '<input class="hp-field" type="text" name="website_url" id="supHp" tabindex="-1" aria-hidden="true" autocomplete="off">'
+ (signedIn ? '' : '<label for="supName">Your name</label><input id="supName" maxlength="80" autocomplete="name">'
+ '<label for="supEmail">Your email (replies go here)</label><input id="supEmail" type="email" maxlength="190" autocomplete="email" required>')
+ '<label for="supCat">What is it about?</label><select id="supCat">' + catOptions('') + '</select>'
+ '<label for="supSubject">Subject</label><input id="supSubject" maxlength="140" placeholder="A few words, like: my sign-in code does not arrive">'
+ '<label for="supBody">Message</label><textarea id="supBody" rows="7" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
+ '<div id="supCheck" hidden style="margin-top:12px"></div>'
+ '<div class="sup-actions"><button class="btn" type="submit" id="supSend">Send to support</button><span class="small muted" id="supMsg"></span></div>'
+ '</form></div>';
const f = document.getElementById('supForm');
f.addEventListener('submit', async e => {
e.preventDefault();
const btn = document.getElementById('supSend'); if (btn.disabled) return; btn.disabled = true;
const msg = document.getElementById('supMsg'); msg.textContent = 'Sending…';
const val = id => { const el = document.getElementById(id); return el ? el.value : ''; };
try {
const g = IAP.guard; await g.formSettled();
let pick = null, r = null;
for (let i = 0; i < 4; i++) {
r = await call('/api/support', { name: val('supName'), email: val('supEmail'), category: val('supCat'), subject: val('supSubject'), body: val('supBody'),
fts: g.FORM_TS, fage: Date.now() - g.FORM_TS, hp_field_x9: g.hpValue(document.getElementById('supHp')), pick });
if (r.challenge) { msg.textContent = ''; pick = await g.iconCheck(document.getElementById('supCheck'), r.challenge, r.error); continue; }
break;
}
if (!r || !r.ok) throw new Error('Could not verify. Refresh the page and try again.');
host.innerHTML = '<div class="card"><h3 style="margin:0 0 6px">Got it. Your ticket is ' + esc(r.ref) + '.</h3>'
+ '<p class="muted small">Marty reads every ticket and replies as soon as he can. ' + (r.member ? 'His reply shows up in Help in your dashboard and in your email.' : 'We just emailed you a private link to this ticket, so you can check on it or add more detail without signing in. If it does not arrive, look in spam or promotions.') + '</p>'
+ '<p class="sup-actions">' + (r.member ? '<a class="btn small" href="/my#help?t=' + esc(r.ref) + '">Open it in Help</a>' : '<a class="btn small" href="/support/t/' + esc(r.token) + '">View your ticket</a>') + '<a class="btn small sec" href="/">Back to InstantAdPay</a></p></div>';
window.scrollTo(0, 0);
} catch (err) { msg.textContent = err.message; }
finally { btn.disabled = false; }
});
}
async function tokenPage(host, tok) {
const h = document.querySelector('.sectionhead h2'); if (h) h.innerHTML = 'Your support <em>ticket</em>';
host.innerHTML = '<div class="card"><p class="muted small">Loading your ticket…</p></div>';
let v; try { v = await call('/api/support/t/' + encodeURIComponent(tok)); } catch (e) { host.innerHTML = '<div class="card"><p>' + esc(e.message) + '</p><p><a class="btn small" href="/support">Send a new ticket</a></p></div>'; return; }
const draw = v2 => {
host.innerHTML = '<div class="card">' + threadHtml(v2) + '</div><div class="card">' + replyBox('tk', false)
+ '<p class="small muted" style="margin:10px 0 0">Keep this link private: anyone with it can read and answer this ticket. Members can also follow up from <a href="/my#help">Help in the dashboard</a>, where screenshots can be attached.</p></div>';
const btn = document.getElementById('tkSend');
btn.addEventListener('click', async () => {
if (btn.disabled) return; btn.disabled = true;
try { const nv = await call('/api/support/t/' + encodeURIComponent(tok) + '/reply', { body: document.getElementById('tkBody').value }); draw(nv); IAP.status('Reply sent. Marty will see it.', 'ok'); }
catch (e) { document.getElementById('tkMsg').textContent = e.message; }
finally { btn.disabled = false; }
});
};
draw(v);
}
return { help, badge, page, CATS, STATUS, when, esc, linkify };
})();
if (document.getElementById('supMain')) IAPSupport.page();
Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

+55 -55
View File
@@ -200,254 +200,254 @@ dieser Käufer an den nächsten Sponsor über
dir, für immer.
43
00:02:38.550 --> 00:02:41.586
Die Pakete reichen von $5 bis $250.
00:02:38.550 --> 00:02:41.517
Die Pakete reichen von $5 bis $500.
44
00:02:41.940 --> 00:02:46.219
00:02:41.963 --> 00:02:46.823
Ab $20 wird jemand zum qualifizierenden
Käufer, und das ist wichtig für das,
45
00:02:46.259 --> 00:02:48.134
00:02:46.863 --> 00:02:48.877
was jetzt kommt.
46
00:02:49.380 --> 00:02:51.662
00:02:50.130 --> 00:02:52.412
Das ist das Herz der Strategie.
47
00:02:51.853 --> 00:02:54.274
00:02:52.603 --> 00:02:55.024
Ebene 1 ist ab dem ersten Tag offen.
48
00:02:54.407 --> 00:02:57.467
00:02:55.157 --> 00:02:58.217
Ebene 2 öffnet sich, wenn zwei deiner
direkt Geworbenen jeweils für $20
49
00:02:57.507 --> 00:02:59.359
00:02:58.257 --> 00:03:00.109
oder mehr gekauft haben.
50
00:02:59.492 --> 00:03:01.484
00:03:00.242 --> 00:03:02.234
Ebene 3 öffnet sich bei fünf.
51
00:03:01.617 --> 00:03:03.725
00:03:02.367 --> 00:03:04.475
Breite ersetzt also nicht die Tiefe.
52
00:03:03.765 --> 00:03:06.627
00:03:04.515 --> 00:03:07.377
Breite ist das, was die Tiefe
freischaltet.
53
00:03:14.480 --> 00:03:17.644
00:03:15.230 --> 00:03:18.394
Das passiert, wenn du in die Tiefe baust,
ohne in die Breite zu bauen.
54
00:03:17.835 --> 00:03:21.023
00:03:18.585 --> 00:03:21.773
Angenommen, du hast zwei Käufer und ein
tiefes Team darunter.
55
00:03:21.063 --> 00:03:24.668
00:03:21.813 --> 00:03:25.418
Wenn jemand in deiner Ebene 3 kauft,
wartet dieser Anteil nicht auf dich.
56
00:03:24.859 --> 00:03:28.523
00:03:25.609 --> 00:03:29.273
Er geht an die nächste Person über dir,
die fünf Käufer hat.
57
00:03:29.770 --> 00:03:34.316
00:03:30.520 --> 00:03:35.066
Stell dir zwei Leader vor, und jeder macht
einen Kauf für $20.
58
00:03:34.391 --> 00:03:38.774
00:03:35.141 --> 00:03:39.524
Leader A sponsert zehn, jeder davon
sponsert fünf, und jeder
59
00:03:38.814 --> 00:03:40.411
00:03:39.564 --> 00:03:41.161
von denen sponsert fünf.
60
00:03:40.672 --> 00:03:43.616
00:03:41.422 --> 00:03:44.366
Das sind $800 aus einem einzigen Kauf pro
Person.
61
00:03:43.807 --> 00:03:47.307
00:03:44.557 --> 00:03:48.057
Leader B sponsert zwei, und jeder davon
sponsert zwei.
62
00:03:47.870 --> 00:03:51.116
00:03:48.620 --> 00:03:51.866
$36, und B's Ebene 3 wird nach oben
weitergegeben.
63
00:03:51.307 --> 00:03:54.413
00:03:52.057 --> 00:03:55.163
Das ist ein Beispiel, kein
Einkommensversprechen.
64
00:03:54.604 --> 00:03:58.163
00:03:55.354 --> 00:03:58.913
Ob jemand kauft, ist seine eigene
Entscheidung.
65
00:03:59.410 --> 00:04:01.460
00:04:00.160 --> 00:04:02.210
Du willst nicht auf deine ersten
Geworbenen warten?
66
00:04:01.488 --> 00:04:05.651
00:04:02.238 --> 00:04:06.401
Qualified Start lässt dich bis zu fünf
eigene Wallets als Positionen verknüpfen.
67
00:04:05.784 --> 00:04:10.074
00:04:06.534 --> 00:04:10.824
Jeder $20-Kauf einer Position zählt als
qualifizierender Käufer, und die Hälfte
68
00:04:10.114 --> 00:04:12.187
00:04:10.864 --> 00:04:12.937
geht direkt zurück an deine Haupt-Wallet.
69
00:04:12.320 --> 00:04:16.332
00:04:13.070 --> 00:04:17.082
Fünf Positionen: Du gibst $100 aus, $50
kommen zurück, du hast 10.000
70
00:04:16.372 --> 00:04:20.186
00:04:17.122 --> 00:04:20.936
Werbe-Credits, und die Ebenen 2 und 3 sind
offen.
71
00:04:21.440 --> 00:04:23.536
00:04:22.190 --> 00:04:24.286
Du hast echte Werkzeuge zum Aufbauen.
72
00:04:24.238 --> 00:04:28.900
00:04:24.988 --> 00:04:29.650
Die Pipeline ist dein Follow-up-Board:
alle, mit denen du arbeitest, in Spalten,
die sich von selbst
73
00:04:28.940 --> 00:04:33.161
00:04:29.690 --> 00:04:33.911
bewegen, wenn Leute den nächsten Schritt
machen, damit du immer weißt, mit wem du
74
00:04:33.201 --> 00:04:34.451
00:04:33.951 --> 00:04:35.201
als Nächstes sprichst.
75
00:04:34.698 --> 00:04:38.211
00:04:35.448 --> 00:04:38.961
Dazu bekommst du Coaching für dein Team,
und Promo-Tools mit
76
00:04:38.251 --> 00:04:39.662
00:04:39.001 --> 00:04:40.412
deinem Link schon eingetragen.
77
00:04:41.910 --> 00:04:44.540
00:04:42.660 --> 00:04:45.290
Es gibt eine zweite Einkommensquelle auf
derselben Wallet.
78
00:04:44.673 --> 00:04:50.543
00:04:45.423 --> 00:04:51.293
LinkSpin gibt deinem Team Werkzeuge, um
alles zu bewerben: rotierende Links,
echtes Tracking,
79
00:04:50.583 --> 00:04:52.203
00:04:51.333 --> 00:04:52.953
Seiten und Werbezonen.
80
00:04:52.336 --> 00:04:57.555
00:04:53.086 --> 00:04:58.305
Es zahlt dieselben 50, 20, 10, mit
denselben Freischaltungen.
81
00:04:57.583 --> 00:04:59.668
00:04:58.333 --> 00:05:00.418
Der Pre-Launch öffnet am 1. November.
82
00:05:00.920 --> 00:05:02.668
00:05:01.670 --> 00:05:03.418
Deine Wallet ist dein Schlüssel.
83
00:05:03.114 --> 00:05:07.184
00:05:03.864 --> 00:05:07.934
Jede Plattform im Netzwerk erkennt dich
daran, und dein Team folgt dir.
84
00:05:07.445 --> 00:05:10.714
00:05:08.195 --> 00:05:11.464
Wenn eine neue Plattform startet, sind
deine Leute schon unter dir platziert.
85
00:05:10.754 --> 00:05:16.913
00:05:11.504 --> 00:05:17.663
Ein Sponsor wird nie übergangen, weil er
ruhig ist, und ein Kauf wird nie
aufgehalten.
86
00:05:18.160 --> 00:05:20.639
00:05:18.910 --> 00:05:21.389
Deine erste Woche: Schalte die
Auszahlungen ein.
87
00:05:20.830 --> 00:05:22.265
00:05:21.580 --> 00:05:23.015
Finde deine ersten zwei Käufer.
88
00:05:22.305 --> 00:05:23.147
00:05:23.055 --> 00:05:23.897
Komm auf fünf.
89
00:05:23.187 --> 00:05:24.494
00:05:23.937 --> 00:05:25.244
Bau weiter in die Breite.
90
00:05:24.627 --> 00:05:28.162
00:05:25.377 --> 00:05:28.912
Und bring jeder Person, die du dazuholst,
denselben Plan bei.
91
00:05:36.010 --> 00:05:37.386
00:05:36.760 --> 00:05:38.136
Das Ziel ist fünf.
92
00:05:37.647 --> 00:05:42.297
00:05:38.397 --> 00:05:43.047
Fünf starke Käufer schalten jede Ebene,
jeden Meilenstein und jedes Werkzeug frei.
93
00:05:42.651 --> 00:05:43.901
00:05:43.401 --> 00:05:44.651
Bereit zu starten?
94
00:05:44.857 --> 00:05:47.394
00:05:45.607 --> 00:05:48.144
Melde dich bei der Person, die dir das
geteilt hat.
95
00:05:47.434 --> 00:05:50.865
00:05:48.184 --> 00:05:51.615
Sie hilft dir, in wenigen Minuten
startklar zu sein, und sie wird dein
Sponsor
96
00:05:50.905 --> 00:05:52.792
00:05:51.655 --> 00:05:53.542
auf jeder Plattform im Netzwerk.
+56 -56
View File
@@ -190,249 +190,249 @@ buyer move to the next sponsor above you,
for good.
43
00:02:38.550 --> 00:02:41.586
Packages run from five dollars to two
hundred fifty.
00:02:38.550 --> 00:02:41.517
Packages run from five dollars to five
hundred.
44
00:02:41.940 --> 00:02:46.219
00:02:41.963 --> 00:02:46.823
Twenty dollars or more makes someone a
qualifying buyer, and that matters for
45
00:02:46.259 --> 00:02:48.134
00:02:46.863 --> 00:02:48.877
what comes next.
46
00:02:49.380 --> 00:02:51.662
00:02:50.130 --> 00:02:52.412
This is the heart of the strategy.
47
00:02:51.853 --> 00:02:54.274
00:02:52.603 --> 00:02:55.024
Level one is open from day one.
48
00:02:54.407 --> 00:02:57.467
00:02:55.157 --> 00:02:58.217
Level two opens when two of your personal
referrals have each bought
49
00:02:57.507 --> 00:02:59.359
00:02:58.257 --> 00:03:00.109
twenty dollars or more.
50
00:02:59.492 --> 00:03:01.484
00:03:00.242 --> 00:03:02.234
Level three opens at five.
51
00:03:01.617 --> 00:03:03.725
00:03:02.367 --> 00:03:04.475
So width isn't instead of depth.
52
00:03:03.765 --> 00:03:06.627
00:03:04.515 --> 00:03:07.377
Width is what unlocks depth.
53
00:03:14.480 --> 00:03:17.644
00:03:15.230 --> 00:03:18.394
Here's what happens if you build deep
without building wide.
54
00:03:17.835 --> 00:03:21.023
00:03:18.585 --> 00:03:21.773
Say you have two buyers and a deep team
below them.
55
00:03:21.063 --> 00:03:24.668
00:03:21.813 --> 00:03:25.418
When someone in your level three buys,
that share doesn't wait for you.
56
00:03:24.859 --> 00:03:28.523
00:03:25.609 --> 00:03:29.273
It passes to the next person above you who
has five buyers.
57
00:03:29.770 --> 00:03:34.316
00:03:30.520 --> 00:03:35.066
Picture two leaders, and everyone makes
one twenty-dollar purchase.
58
00:03:34.391 --> 00:03:38.774
00:03:35.141 --> 00:03:39.524
Leader A sponsors ten, each of them
sponsors five, and each
59
00:03:38.814 --> 00:03:40.411
00:03:39.564 --> 00:03:41.161
of those sponsors five.
60
00:03:40.672 --> 00:03:43.616
00:03:41.422 --> 00:03:44.366
That's eight hundred dollars from one
purchase each.
61
00:03:43.807 --> 00:03:47.307
00:03:44.557 --> 00:03:48.057
Leader B sponsors two, and each of them
sponsors two.
62
00:03:47.870 --> 00:03:51.116
00:03:48.620 --> 00:03:51.866
Thirty-six dollars, and B's level three
passes up.
63
00:03:51.307 --> 00:03:54.413
00:03:52.057 --> 00:03:55.163
This is an illustration, not a promise of
income.
64
00:03:54.604 --> 00:03:58.163
00:03:55.354 --> 00:03:58.913
Whether anyone buys is their own choice.
65
00:03:59.410 --> 00:04:01.460
00:04:00.160 --> 00:04:02.210
Don't want to wait for your first
referrals?
66
00:04:01.488 --> 00:04:05.651
00:04:02.238 --> 00:04:06.401
Qualified Start lets you link up to five
wallets of your own as positions.
67
00:04:05.784 --> 00:04:10.074
00:04:06.534 --> 00:04:10.824
Each twenty-dollar position purchase
counts as a qualifying buyer, and half of
68
00:04:10.114 --> 00:04:12.187
00:04:10.864 --> 00:04:12.937
it comes straight back to your main
wallet.
69
00:04:12.320 --> 00:04:16.332
00:04:13.070 --> 00:04:17.082
Five positions: you spend a hundred
dollars, fifty comes back, you hold ten
70
00:04:16.372 --> 00:04:20.186
00:04:17.122 --> 00:04:20.936
thousand ad credits, and levels two and
three are open.
71
00:04:21.440 --> 00:04:23.536
00:04:22.190 --> 00:04:24.286
You'll have real tools to build with.
72
00:04:24.238 --> 00:04:28.900
00:04:24.988 --> 00:04:29.650
The Pipeline is your follow-up board:
everyone you're working with, in columns
73
00:04:28.940 --> 00:04:33.161
00:04:29.690 --> 00:04:33.911
that move on their own as people take each
step, so you always know who
74
00:04:33.201 --> 00:04:34.451
00:04:33.951 --> 00:04:35.201
to talk to next.
75
00:04:34.698 --> 00:04:38.211
00:04:35.448 --> 00:04:38.961
You also get coaching for your team, and
promo tools with your
76
00:04:38.251 --> 00:04:39.662
00:04:39.001 --> 00:04:40.412
link already filled in.
77
00:04:41.910 --> 00:04:44.540
00:04:42.660 --> 00:04:45.290
There's a second income stream on the same
wallet.
78
00:04:44.673 --> 00:04:50.543
00:04:45.423 --> 00:04:51.293
LinkSpin gives your team tools to promote
anything: rotating links, real tracking,
79
00:04:50.583 --> 00:04:52.203
00:04:51.333 --> 00:04:52.953
pages and ad zones.
80
00:04:52.336 --> 00:04:57.555
00:04:53.086 --> 00:04:58.305
It pays the same fifty, twenty, ten, with
the same unlocks.
81
00:04:57.583 --> 00:04:59.668
00:04:58.333 --> 00:05:00.418
Pre-launch opens November first.
82
00:05:00.920 --> 00:05:02.668
00:05:01.670 --> 00:05:03.418
Your wallet is your key.
83
00:05:03.114 --> 00:05:07.184
00:05:03.864 --> 00:05:07.934
Every platform in the network knows you by
it, and your team follows you.
84
00:05:07.445 --> 00:05:10.714
00:05:08.195 --> 00:05:11.464
When a new platform launches, your people
are already placed under you.
85
00:05:10.754 --> 00:05:16.913
00:05:11.504 --> 00:05:17.663
A sponsor is never passed over for being
quiet, and a purchase is never held up.
86
00:05:18.160 --> 00:05:20.639
00:05:18.910 --> 00:05:21.389
Your first week: switch on payouts.
87
00:05:20.830 --> 00:05:22.265
00:05:21.580 --> 00:05:23.015
Find your first two buyers.
88
00:05:22.305 --> 00:05:23.147
00:05:23.055 --> 00:05:23.897
Get to five.
89
00:05:23.187 --> 00:05:24.494
00:05:23.937 --> 00:05:25.244
Keep going wide.
90
00:05:24.627 --> 00:05:28.162
00:05:25.377 --> 00:05:28.912
And teach the same plan to every person
you bring in.
91
00:05:36.010 --> 00:05:37.386
00:05:36.760 --> 00:05:38.136
The target is five.
92
00:05:37.647 --> 00:05:42.297
00:05:38.397 --> 00:05:43.047
Five strong buyers unlock every level,
every milestone and every tool.
93
00:05:42.651 --> 00:05:43.901
00:05:43.401 --> 00:05:44.651
Ready to start?
94
00:05:44.857 --> 00:05:47.394
00:05:45.607 --> 00:05:48.144
Reach out to the person who shared this
with you.
95
00:05:47.434 --> 00:05:50.865
00:05:48.184 --> 00:05:51.615
They'll help you get set up in a few
minutes, and they'll be your sponsor on
96
00:05:50.905 --> 00:05:52.792
00:05:51.655 --> 00:05:53.542
every platform in the network.
+55 -55
View File
@@ -196,252 +196,252 @@ comprador pasan al siguiente patrocinador
por encima de ti, para siempre.
43
00:02:38.550 --> 00:02:41.586
Los paquetes van de $5 a $250.
00:02:38.550 --> 00:02:41.517
Los paquetes van de $5 a $500.
44
00:02:41.940 --> 00:02:46.219
00:02:41.963 --> 00:02:46.823
Con $20 o más alguien se convierte en
comprador calificado, y eso importa para
45
00:02:46.259 --> 00:02:48.134
00:02:46.863 --> 00:02:48.877
lo que viene.
46
00:02:49.380 --> 00:02:51.662
00:02:50.130 --> 00:02:52.412
Este es el corazón de la estrategia.
47
00:02:51.853 --> 00:02:54.274
00:02:52.603 --> 00:02:55.024
El nivel 1 está abierto desde el primer
día.
48
00:02:54.407 --> 00:02:57.467
00:02:55.157 --> 00:02:58.217
El nivel 2 se abre cuando dos de tus
referidos directos han comprado
49
00:02:57.507 --> 00:02:59.359
00:02:58.257 --> 00:03:00.109
cada uno $20 o más.
50
00:02:59.492 --> 00:03:01.484
00:03:00.242 --> 00:03:02.234
El nivel 3 se abre con cinco.
51
00:03:01.617 --> 00:03:03.725
00:03:02.367 --> 00:03:04.475
Así que el ancho no reemplaza a la
profundidad.
52
00:03:03.765 --> 00:03:06.627
00:03:04.515 --> 00:03:07.377
El ancho es lo que desbloquea la
profundidad.
53
00:03:14.480 --> 00:03:17.644
00:03:15.230 --> 00:03:18.394
Esto es lo que pasa si construyes en
profundidad sin construir a lo ancho.
54
00:03:17.835 --> 00:03:21.023
00:03:18.585 --> 00:03:21.773
Digamos que tienes dos compradores y un
equipo profundo debajo de ellos.
55
00:03:21.063 --> 00:03:24.668
00:03:21.813 --> 00:03:25.418
Cuando alguien de tu nivel 3 compra, esa
parte no te espera.
56
00:03:24.859 --> 00:03:28.523
00:03:25.609 --> 00:03:29.273
Pasa a la siguiente persona por encima de
ti que tiene cinco compradores.
57
00:03:29.770 --> 00:03:34.316
00:03:30.520 --> 00:03:35.066
Imagina dos líderes, y cada persona hace
una compra de $20.
58
00:03:34.391 --> 00:03:38.774
00:03:35.141 --> 00:03:39.524
El líder A patrocina a diez, cada uno
patrocina a cinco, y cada uno
59
00:03:38.814 --> 00:03:40.411
00:03:39.564 --> 00:03:41.161
de esos patrocina a cinco.
60
00:03:40.672 --> 00:03:43.616
00:03:41.422 --> 00:03:44.366
Son $800 de una sola compra por persona.
61
00:03:43.807 --> 00:03:47.307
00:03:44.557 --> 00:03:48.057
El líder B patrocina a dos, y cada uno
patrocina a dos.
62
00:03:47.870 --> 00:03:51.116
00:03:48.620 --> 00:03:51.866
$36, y el nivel 3 de B pasa hacia arriba.
63
00:03:51.307 --> 00:03:54.413
00:03:52.057 --> 00:03:55.163
Esto es una ilustración, no una promesa de
ingresos.
64
00:03:54.604 --> 00:03:58.163
00:03:55.354 --> 00:03:58.913
Comprar o no es decisión de cada persona.
65
00:03:59.410 --> 00:04:01.460
00:04:00.160 --> 00:04:02.210
¿No quieres esperar a tus primeros
referidos?
66
00:04:01.488 --> 00:04:05.651
00:04:02.238 --> 00:04:06.401
Qualified Start te permite vincular hasta
cinco wallets propios como posiciones.
67
00:04:05.784 --> 00:04:10.074
00:04:06.534 --> 00:04:10.824
Cada compra de $20 de una posición cuenta
como comprador calificado, y la
68
00:04:10.114 --> 00:04:12.187
00:04:10.864 --> 00:04:12.937
mitad vuelve directo a tu wallet
principal.
69
00:04:12.320 --> 00:04:16.332
00:04:13.070 --> 00:04:17.082
Cinco posiciones: gastas $100, te vuelven
$50, tienes 10.000 créditos publicitarios,
70
00:04:16.372 --> 00:04:20.186
00:04:17.122 --> 00:04:20.936
y los niveles 2 y 3 quedan abiertos.
71
00:04:21.440 --> 00:04:23.536
00:04:22.190 --> 00:04:24.286
Tendrás herramientas reales para
construir.
72
00:04:24.238 --> 00:04:28.900
00:04:24.988 --> 00:04:29.650
El Pipeline es tu tablero de seguimiento:
todas las personas con las que trabajas,
en columnas que
73
00:04:28.940 --> 00:04:33.161
00:04:29.690 --> 00:04:33.911
avanzan solas a medida que cada uno da su
paso, para que siempre sepas con
74
00:04:33.201 --> 00:04:34.451
00:04:33.951 --> 00:04:35.201
quién hablar después.
75
00:04:34.698 --> 00:04:38.211
00:04:35.448 --> 00:04:38.961
También tienes coaching para tu equipo, y
herramientas promocionales con
76
00:04:38.251 --> 00:04:39.662
00:04:39.001 --> 00:04:40.412
tu enlace ya incluido.
77
00:04:41.910 --> 00:04:44.540
00:04:42.660 --> 00:04:45.290
Hay una segunda fuente de ingresos en el
mismo wallet.
78
00:04:44.673 --> 00:04:50.543
00:04:45.423 --> 00:04:51.293
LinkSpin le da a tu equipo herramientas
para promocionar cualquier cosa: enlaces
rotativos, seguimiento real, páginas
79
00:04:50.583 --> 00:04:52.203
00:04:51.333 --> 00:04:52.953
y zonas de anuncios.
80
00:04:52.336 --> 00:04:57.555
00:04:53.086 --> 00:04:58.305
Paga el mismo 50, 20, 10, con los mismos
desbloqueos.
81
00:04:57.583 --> 00:04:59.668
00:04:58.333 --> 00:05:00.418
El prelanzamiento abre el 1 de noviembre.
82
00:05:00.920 --> 00:05:02.668
00:05:01.670 --> 00:05:03.418
Tu wallet es tu llave.
83
00:05:03.114 --> 00:05:07.184
00:05:03.864 --> 00:05:07.934
Cada plataforma de la red te reconoce por
él, y tu equipo te sigue.
84
00:05:07.445 --> 00:05:10.714
00:05:08.195 --> 00:05:11.464
Cuando se lanza una nueva plataforma, tu
gente ya está colocada debajo de ti.
85
00:05:10.754 --> 00:05:16.913
00:05:11.504 --> 00:05:17.663
A un patrocinador nunca se le salta por
estar callado, y una compra nunca se
detiene.
86
00:05:18.160 --> 00:05:20.639
00:05:18.910 --> 00:05:21.389
Tu primera semana: activa los pagos.
87
00:05:20.830 --> 00:05:22.265
00:05:21.580 --> 00:05:23.015
Encuentra a tus dos primeros compradores.
88
00:05:22.305 --> 00:05:23.147
00:05:23.055 --> 00:05:23.897
Llega a cinco.
89
00:05:23.187 --> 00:05:24.494
00:05:23.937 --> 00:05:25.244
Sigue construyendo a lo ancho.
90
00:05:24.627 --> 00:05:28.162
00:05:25.377 --> 00:05:28.912
Y enseña el mismo plan a cada persona que
traigas.
91
00:05:36.010 --> 00:05:37.386
00:05:36.760 --> 00:05:38.136
La meta es cinco.
92
00:05:37.647 --> 00:05:42.297
00:05:38.397 --> 00:05:43.047
Cinco compradores sólidos desbloquean cada
nivel, cada hito y cada herramienta.
93
00:05:42.651 --> 00:05:43.901
00:05:43.401 --> 00:05:44.651
¿Listo para empezar?
94
00:05:44.857 --> 00:05:47.394
00:05:45.607 --> 00:05:48.144
Contacta a la persona que te compartió
este video.
95
00:05:47.434 --> 00:05:50.865
00:05:48.184 --> 00:05:51.615
Te ayudará a empezar en pocos minutos, y
será tu patrocinador en
96
00:05:50.905 --> 00:05:52.792
00:05:51.655 --> 00:05:53.542
cada plataforma de la red.
+55 -55
View File
@@ -202,258 +202,258 @@ cet acheteur passent au parrain suivant
au-dessus de vous, définitivement.
43
00:02:38.550 --> 00:02:41.586
Les packs vont de $5 à $250.
00:02:38.550 --> 00:02:41.517
Les packs vont de $5 à $500.
44
00:02:41.940 --> 00:02:46.219
00:02:41.963 --> 00:02:46.823
À partir de $20, on devient acheteur
qualifiant, et c'est important pour
45
00:02:46.259 --> 00:02:48.134
00:02:46.863 --> 00:02:48.877
la suite.
46
00:02:49.380 --> 00:02:51.662
00:02:50.130 --> 00:02:52.412
C'est le cœur de la stratégie.
47
00:02:51.853 --> 00:02:54.274
00:02:52.603 --> 00:02:55.024
Le niveau 1 est ouvert dès le premier
jour.
48
00:02:54.407 --> 00:02:57.467
00:02:55.157 --> 00:02:58.217
Le niveau 2 s'ouvre quand deux de vos
filleuls directs ont chacun acheté
49
00:02:57.507 --> 00:02:59.359
00:02:58.257 --> 00:03:00.109
pour $20 ou plus.
50
00:02:59.492 --> 00:03:01.484
00:03:00.242 --> 00:03:02.234
Le niveau 3 s'ouvre à cinq.
51
00:03:01.617 --> 00:03:03.725
00:03:02.367 --> 00:03:04.475
La largeur ne remplace donc pas la
profondeur.
52
00:03:03.765 --> 00:03:06.627
00:03:04.515 --> 00:03:07.377
C'est la largeur qui débloque la
profondeur.
53
00:03:14.480 --> 00:03:17.644
00:03:15.230 --> 00:03:18.394
Voici ce qui arrive si vous construisez en
profondeur sans construire en largeur.
54
00:03:17.835 --> 00:03:21.023
00:03:18.585 --> 00:03:21.773
Disons que vous avez deux acheteurs et une
équipe profonde en dessous.
55
00:03:21.063 --> 00:03:24.668
00:03:21.813 --> 00:03:25.418
Quand quelqu'un de votre niveau 3 achète,
cette part ne vous attend pas.
56
00:03:24.859 --> 00:03:28.523
00:03:25.609 --> 00:03:29.273
Elle passe à la prochaine personne
au-dessus de vous qui a cinq acheteurs.
57
00:03:29.770 --> 00:03:34.316
00:03:30.520 --> 00:03:35.066
Imaginez deux leaders, et chacun fait un
achat de $20.
58
00:03:34.391 --> 00:03:38.774
00:03:35.141 --> 00:03:39.524
Le leader A parraine dix personnes,
chacune en parraine cinq, et chacune
59
00:03:38.814 --> 00:03:40.411
00:03:39.564 --> 00:03:41.161
de celles-ci en parraine cinq.
60
00:03:40.672 --> 00:03:43.616
00:03:41.422 --> 00:03:44.366
Cela fait $800 pour un seul achat chacun.
61
00:03:43.807 --> 00:03:47.307
00:03:44.557 --> 00:03:48.057
Le leader B en parraine deux, et chacun
d'eux en parraine deux.
62
00:03:47.870 --> 00:03:51.116
00:03:48.620 --> 00:03:51.866
$36, et le niveau 3 de B remonte
au-dessus.
63
00:03:51.307 --> 00:03:54.413
00:03:52.057 --> 00:03:55.163
Ceci est une illustration, pas une
promesse de revenus.
64
00:03:54.604 --> 00:03:58.163
00:03:55.354 --> 00:03:58.913
Acheter ou non reste le libre choix de
chacun.
65
00:03:59.410 --> 00:04:01.460
00:04:00.160 --> 00:04:02.210
Vous ne voulez pas attendre vos premiers
filleuls ?
66
00:04:01.488 --> 00:04:05.651
00:04:02.238 --> 00:04:06.401
Qualified Start vous permet de lier
jusqu'à cinq de vos propres wallets comme
positions.
67
00:04:05.784 --> 00:04:10.074
00:04:06.534 --> 00:04:10.824
Chaque achat de $20 d'une position compte
comme un acheteur qualifiant, et la
68
00:04:10.114 --> 00:04:12.187
00:04:10.864 --> 00:04:12.937
moitié revient directement sur votre
wallet principal.
69
00:04:12.320 --> 00:04:16.332
00:04:13.070 --> 00:04:17.082
Cinq positions : vous dépensez $100, $50
vous reviennent, vous détenez 10 000
70
00:04:16.372 --> 00:04:20.186
00:04:17.122 --> 00:04:20.936
crédits publicitaires, et les niveaux 2 et
3 sont ouverts.
71
00:04:21.440 --> 00:04:23.536
00:04:22.190 --> 00:04:24.286
Vous aurez de vrais outils pour
construire.
72
00:04:24.238 --> 00:04:28.900
00:04:24.988 --> 00:04:29.650
La Pipeline est votre tableau de suivi :
toutes les personnes avec qui vous
travaillez, dans
73
00:04:28.940 --> 00:04:33.161
00:04:29.690 --> 00:04:33.911
des colonnes qui avancent d'elles-mêmes à
chaque étape franchie, pour que vous
sachiez toujours à
74
00:04:33.201 --> 00:04:34.451
00:04:33.951 --> 00:04:35.201
qui parler ensuite.
75
00:04:34.698 --> 00:04:38.211
00:04:35.448 --> 00:04:38.961
Vous avez aussi du coaching pour votre
équipe, et des outils promo
76
00:04:38.251 --> 00:04:39.662
00:04:39.001 --> 00:04:40.412
avec votre lien déjà intégré.
77
00:04:41.910 --> 00:04:44.540
00:04:42.660 --> 00:04:45.290
Il y a une deuxième source de revenus sur
le même wallet.
78
00:04:44.673 --> 00:04:50.543
00:04:45.423 --> 00:04:51.293
LinkSpin donne à votre équipe des outils
pour promouvoir n'importe quoi : liens
rotatifs, vrai suivi,
79
00:04:50.583 --> 00:04:52.203
00:04:51.333 --> 00:04:52.953
pages et zones publicitaires.
80
00:04:52.336 --> 00:04:57.555
00:04:53.086 --> 00:04:58.305
Il paie les mêmes 50, 20, 10, avec les
mêmes déblocages.
81
00:04:57.583 --> 00:04:59.668
00:04:58.333 --> 00:05:00.418
La pré-ouverture démarre le 1er novembre.
82
00:05:00.920 --> 00:05:02.668
00:05:01.670 --> 00:05:03.418
Votre wallet est votre clé.
83
00:05:03.114 --> 00:05:07.184
00:05:03.864 --> 00:05:07.934
Chaque plateforme du réseau vous reconnaît
grâce à lui, et votre équipe vous suit.
84
00:05:07.445 --> 00:05:10.714
00:05:08.195 --> 00:05:11.464
Quand une nouvelle plateforme est lancée,
vos personnes sont déjà placées sous vous.
85
00:05:10.754 --> 00:05:16.913
00:05:11.504 --> 00:05:17.663
Un parrain n'est jamais écarté parce qu'il
est discret, et un achat n'est jamais
bloqué.
86
00:05:18.160 --> 00:05:20.639
00:05:18.910 --> 00:05:21.389
Votre première semaine : activez les
paiements.
87
00:05:20.830 --> 00:05:22.265
00:05:21.580 --> 00:05:23.015
Trouvez vos deux premiers acheteurs.
88
00:05:22.305 --> 00:05:23.147
00:05:23.055 --> 00:05:23.897
Atteignez cinq.
89
00:05:23.187 --> 00:05:24.494
00:05:23.937 --> 00:05:25.244
Continuez à construire en largeur.
90
00:05:24.627 --> 00:05:28.162
00:05:25.377 --> 00:05:28.912
Et enseignez le même plan à chaque
personne que vous faites entrer.
91
00:05:36.010 --> 00:05:37.386
00:05:36.760 --> 00:05:38.136
L'objectif, c'est cinq.
92
00:05:37.647 --> 00:05:42.297
00:05:38.397 --> 00:05:43.047
Cinq acheteurs solides débloquent chaque
niveau, chaque palier et chaque outil.
93
00:05:42.651 --> 00:05:43.901
00:05:43.401 --> 00:05:44.651
Prêt à commencer ?
94
00:05:44.857 --> 00:05:47.394
00:05:45.607 --> 00:05:48.144
Contactez la personne qui vous a partagé
cette vidéo.
95
00:05:47.434 --> 00:05:50.865
00:05:48.184 --> 00:05:51.615
Elle vous aidera à démarrer en quelques
minutes, et elle sera votre parrain
96
00:05:50.905 --> 00:05:52.792
00:05:51.655 --> 00:05:53.542
sur chaque plateforme du réseau.
+55 -55
View File
@@ -198,252 +198,252 @@ e quell'acquirente passano allo sponsor
successivo sopra di te, per sempre.
43
00:02:38.550 --> 00:02:41.586
I pacchetti vanno da $5 a $250.
00:02:38.550 --> 00:02:41.517
I pacchetti vanno da $5 a $500.
44
00:02:41.940 --> 00:02:46.219
00:02:41.963 --> 00:02:46.823
Da $20 in su si diventa acquirente
qualificante, e questo conta per quello
45
00:02:46.259 --> 00:02:48.134
00:02:46.863 --> 00:02:48.877
che viene dopo.
46
00:02:49.380 --> 00:02:51.662
00:02:50.130 --> 00:02:52.412
Questo è il cuore della strategia.
47
00:02:51.853 --> 00:02:54.274
00:02:52.603 --> 00:02:55.024
Il livello 1 è aperto dal primo giorno.
48
00:02:54.407 --> 00:02:57.467
00:02:55.157 --> 00:02:58.217
Il livello 2 si apre quando due tuoi
invitati diretti hanno acquistato
49
00:02:57.507 --> 00:02:59.359
00:02:58.257 --> 00:03:00.109
ciascuno $20 o più.
50
00:02:59.492 --> 00:03:01.484
00:03:00.242 --> 00:03:02.234
Il livello 3 si apre a cinque.
51
00:03:01.617 --> 00:03:03.725
00:03:02.367 --> 00:03:04.475
Quindi la larghezza non sostituisce la
profondità.
52
00:03:03.765 --> 00:03:06.627
00:03:04.515 --> 00:03:07.377
È la larghezza che sblocca la profondità.
53
00:03:14.480 --> 00:03:17.644
00:03:15.230 --> 00:03:18.394
Ecco cosa succede se costruisci in
profondità senza costruire in larghezza.
54
00:03:17.835 --> 00:03:21.023
00:03:18.585 --> 00:03:21.773
Diciamo che hai due acquirenti e un team
profondo sotto di loro.
55
00:03:21.063 --> 00:03:24.668
00:03:21.813 --> 00:03:25.418
Quando qualcuno nel tuo livello 3
acquista, quella quota non ti aspetta.
56
00:03:24.859 --> 00:03:28.523
00:03:25.609 --> 00:03:29.273
Passa alla prossima persona sopra di te
che ha cinque acquirenti.
57
00:03:29.770 --> 00:03:34.316
00:03:30.520 --> 00:03:35.066
Immagina due leader, e ognuno fa un
acquisto da $20.
58
00:03:34.391 --> 00:03:38.774
00:03:35.141 --> 00:03:39.524
Il leader A sponsorizza dieci persone,
ognuna ne sponsorizza cinque, e ognuna
59
00:03:38.814 --> 00:03:40.411
00:03:39.564 --> 00:03:41.161
di quelle ne sponsorizza cinque.
60
00:03:40.672 --> 00:03:43.616
00:03:41.422 --> 00:03:44.366
Sono $800 da un solo acquisto a testa.
61
00:03:43.807 --> 00:03:47.307
00:03:44.557 --> 00:03:48.057
Il leader B ne sponsorizza due, e ognuno
di loro ne sponsorizza due.
62
00:03:47.870 --> 00:03:51.116
00:03:48.620 --> 00:03:51.866
$36, e il livello 3 di B passa sopra.
63
00:03:51.307 --> 00:03:54.413
00:03:52.057 --> 00:03:55.163
Questo è un esempio, non una promessa di
guadagno.
64
00:03:54.604 --> 00:03:58.163
00:03:55.354 --> 00:03:58.913
Se qualcuno acquista è una sua libera
scelta.
65
00:03:59.410 --> 00:04:01.460
00:04:00.160 --> 00:04:02.210
Non vuoi aspettare i tuoi primi invitati?
66
00:04:01.488 --> 00:04:05.651
00:04:02.238 --> 00:04:06.401
Qualified Start ti permette di collegare
fino a cinque wallet tuoi come posizioni.
67
00:04:05.784 --> 00:04:10.074
00:04:06.534 --> 00:04:10.824
Ogni acquisto da $20 di una posizione
conta come acquirente qualificante, e
68
00:04:10.114 --> 00:04:12.187
00:04:10.864 --> 00:04:12.937
metà torna direttamente al tuo wallet
principale.
69
00:04:12.320 --> 00:04:16.332
00:04:13.070 --> 00:04:17.082
Cinque posizioni: spendi $100, te ne
tornano $50, hai 10.000 crediti
pubblicitari,
70
00:04:16.372 --> 00:04:20.186
00:04:17.122 --> 00:04:20.936
e i livelli 2 e 3 sono aperti.
71
00:04:21.440 --> 00:04:23.536
00:04:22.190 --> 00:04:24.286
Avrai strumenti veri con cui costruire.
72
00:04:24.238 --> 00:04:28.900
00:04:24.988 --> 00:04:29.650
La Pipeline è la tua bacheca di follow-up:
tutte le persone con cui stai lavorando,
in colonne
73
00:04:28.940 --> 00:04:33.161
00:04:29.690 --> 00:04:33.911
che si aggiornano da sole man mano che
ognuno fa il passo successivo, così sai
74
00:04:33.201 --> 00:04:34.451
00:04:33.951 --> 00:04:35.201
sempre con chi parlare.
75
00:04:34.698 --> 00:04:38.211
00:04:35.448 --> 00:04:38.961
Hai anche il coaching per il tuo team, e
strumenti promozionali con
76
00:04:38.251 --> 00:04:39.662
00:04:39.001 --> 00:04:40.412
il tuo link già inserito.
77
00:04:41.910 --> 00:04:44.540
00:04:42.660 --> 00:04:45.290
C'è una seconda fonte di reddito sullo
stesso wallet.
78
00:04:44.673 --> 00:04:50.543
00:04:45.423 --> 00:04:51.293
LinkSpin dà al tuo team gli strumenti per
promuovere qualsiasi cosa: link a
rotazione, tracciamento reale,
79
00:04:50.583 --> 00:04:52.203
00:04:51.333 --> 00:04:52.953
pagine e zone pubblicitarie.
80
00:04:52.336 --> 00:04:57.555
00:04:53.086 --> 00:04:58.305
Paga lo stesso 50, 20, 10, con gli stessi
sblocchi.
81
00:04:57.583 --> 00:04:59.668
00:04:58.333 --> 00:05:00.418
Il pre-lancio apre il primo novembre.
82
00:05:00.920 --> 00:05:02.668
00:05:01.670 --> 00:05:03.418
Il tuo wallet è la tua chiave.
83
00:05:03.114 --> 00:05:07.184
00:05:03.864 --> 00:05:07.934
Ogni piattaforma del network ti riconosce
da esso, e il tuo team ti segue.
84
00:05:07.445 --> 00:05:10.714
00:05:08.195 --> 00:05:11.464
Quando lancia una nuova piattaforma, le
tue persone sono già posizionate sotto di
te.
85
00:05:10.754 --> 00:05:16.913
00:05:11.504 --> 00:05:17.663
Uno sponsor non viene mai scavalcato
perché è silenzioso, e un acquisto non
viene mai bloccato.
86
00:05:18.160 --> 00:05:20.639
00:05:18.910 --> 00:05:21.389
La tua prima settimana: attiva i
pagamenti.
87
00:05:20.830 --> 00:05:22.265
00:05:21.580 --> 00:05:23.015
Trova i tuoi primi due acquirenti.
88
00:05:22.305 --> 00:05:23.147
00:05:23.055 --> 00:05:23.897
Arriva a cinque.
89
00:05:23.187 --> 00:05:24.494
00:05:23.937 --> 00:05:25.244
Continua a costruire in larghezza.
90
00:05:24.627 --> 00:05:28.162
00:05:25.377 --> 00:05:28.912
E insegna lo stesso piano a ogni persona
che porti dentro.
91
00:05:36.010 --> 00:05:37.386
00:05:36.760 --> 00:05:38.136
L'obiettivo è cinque.
92
00:05:37.647 --> 00:05:42.297
00:05:38.397 --> 00:05:43.047
Cinque acquirenti solidi sbloccano ogni
livello, ogni traguardo e ogni strumento.
93
00:05:42.651 --> 00:05:43.901
00:05:43.401 --> 00:05:44.651
Pronto a iniziare?
94
00:05:44.857 --> 00:05:47.394
00:05:45.607 --> 00:05:48.144
Contatta la persona che ti ha condiviso
questo video.
95
00:05:47.434 --> 00:05:50.865
00:05:48.184 --> 00:05:51.615
Ti aiuterà a partire in pochi minuti, e
sarà il tuo sponsor
96
00:05:50.905 --> 00:05:52.792
00:05:51.655 --> 00:05:53.542
su ogni piattaforma del network.
+55 -55
View File
@@ -195,252 +195,252 @@ comprador passam para o próximo
patrocinador acima de você, para sempre.
43
00:02:38.550 --> 00:02:41.586
Os pacotes vão de $5 a $250.
00:02:38.550 --> 00:02:41.517
Os pacotes vão de $5 a $500.
44
00:02:41.940 --> 00:02:46.219
00:02:41.963 --> 00:02:46.823
Com $20 ou mais a pessoa vira compradora
qualificada, e isso importa para o que
45
00:02:46.259 --> 00:02:48.134
00:02:46.863 --> 00:02:48.877
vem a seguir.
46
00:02:49.380 --> 00:02:51.662
00:02:50.130 --> 00:02:52.412
Este é o coração da estratégia.
47
00:02:51.853 --> 00:02:54.274
00:02:52.603 --> 00:02:55.024
O nível 1 está aberto desde o primeiro
dia.
48
00:02:54.407 --> 00:02:57.467
00:02:55.157 --> 00:02:58.217
O nível 2 abre quando dois dos seus
indicados diretos compraram, cada
49
00:02:57.507 --> 00:02:59.359
00:02:58.257 --> 00:03:00.109
um, $20 ou mais.
50
00:02:59.492 --> 00:03:01.484
00:03:00.242 --> 00:03:02.234
O nível 3 abre com cinco.
51
00:03:01.617 --> 00:03:03.725
00:03:02.367 --> 00:03:04.475
Então a largura não substitui a
profundidade.
52
00:03:03.765 --> 00:03:06.627
00:03:04.515 --> 00:03:07.377
É a largura que desbloqueia a
profundidade.
53
00:03:14.480 --> 00:03:17.644
00:03:15.230 --> 00:03:18.394
Veja o que acontece se você construir em
profundidade sem construir na largura.
54
00:03:17.835 --> 00:03:21.023
00:03:18.585 --> 00:03:21.773
Digamos que você tem dois compradores e
uma equipe profunda abaixo deles.
55
00:03:21.063 --> 00:03:24.668
00:03:21.813 --> 00:03:25.418
Quando alguém do seu nível 3 compra, essa
parte não espera por você.
56
00:03:24.859 --> 00:03:28.523
00:03:25.609 --> 00:03:29.273
Ela passa para a próxima pessoa acima de
você que tem cinco compradores.
57
00:03:29.770 --> 00:03:34.316
00:03:30.520 --> 00:03:35.066
Imagine dois líderes, e cada pessoa faz
uma compra de $20.
58
00:03:34.391 --> 00:03:38.774
00:03:35.141 --> 00:03:39.524
O líder A patrocina dez, cada um deles
patrocina cinco, e cada
59
00:03:38.814 --> 00:03:40.411
00:03:39.564 --> 00:03:41.161
um desses patrocina cinco.
60
00:03:40.672 --> 00:03:43.616
00:03:41.422 --> 00:03:44.366
São $800 de uma única compra por pessoa.
61
00:03:43.807 --> 00:03:47.307
00:03:44.557 --> 00:03:48.057
O líder B patrocina dois, e cada um deles
patrocina dois.
62
00:03:47.870 --> 00:03:51.116
00:03:48.620 --> 00:03:51.866
$36, e o nível 3 de B passa para cima.
63
00:03:51.307 --> 00:03:54.413
00:03:52.057 --> 00:03:55.163
Isto é uma ilustração, não uma promessa de
renda.
64
00:03:54.604 --> 00:03:58.163
00:03:55.354 --> 00:03:58.913
Comprar ou não é escolha de cada um.
65
00:03:59.410 --> 00:04:01.460
00:04:00.160 --> 00:04:02.210
Não quer esperar pelos seus primeiros
indicados?
66
00:04:01.488 --> 00:04:05.651
00:04:02.238 --> 00:04:06.401
O Qualified Start permite vincular até
cinco wallets suas como posições.
67
00:04:05.784 --> 00:04:10.074
00:04:06.534 --> 00:04:10.824
Cada compra de $20 de uma posição conta
como compradora qualificada, e metade
68
00:04:10.114 --> 00:04:12.187
00:04:10.864 --> 00:04:12.937
volta direto para a sua wallet principal.
69
00:04:12.320 --> 00:04:16.332
00:04:13.070 --> 00:04:17.082
Cinco posições: você gasta $100, $50
voltam, você fica com 10.000 créditos de
70
00:04:16.372 --> 00:04:20.186
00:04:17.122 --> 00:04:20.936
anúncio, e os níveis 2 e 3 ficam abertos.
71
00:04:21.440 --> 00:04:23.536
00:04:22.190 --> 00:04:24.286
Você terá ferramentas de verdade para
construir.
72
00:04:24.238 --> 00:04:28.900
00:04:24.988 --> 00:04:29.650
O Pipeline é o seu quadro de
acompanhamento: todas as pessoas com quem
você está trabalhando, em
73
00:04:28.940 --> 00:04:33.161
00:04:29.690 --> 00:04:33.911
colunas que avançam sozinhas conforme cada
um dá o próximo passo, para você sempre
saber com
74
00:04:33.201 --> 00:04:34.451
00:04:33.951 --> 00:04:35.201
quem falar a seguir.
75
00:04:34.698 --> 00:04:38.211
00:04:35.448 --> 00:04:38.961
Você também tem coaching para a sua
equipe, e ferramentas de divulgação com
76
00:04:38.251 --> 00:04:39.662
00:04:39.001 --> 00:04:40.412
o seu link já preenchido.
77
00:04:41.910 --> 00:04:44.540
00:04:42.660 --> 00:04:45.290
Existe uma segunda fonte de renda na mesma
wallet.
78
00:04:44.673 --> 00:04:50.543
00:04:45.423 --> 00:04:51.293
O LinkSpin dá à sua equipe ferramentas
para divulgar qualquer coisa: links
rotativos, rastreamento real, páginas
79
00:04:50.583 --> 00:04:52.203
00:04:51.333 --> 00:04:52.953
e zonas de anúncio.
80
00:04:52.336 --> 00:04:57.555
00:04:53.086 --> 00:04:58.305
Ele paga os mesmos 50, 20, 10, com os
mesmos desbloqueios.
81
00:04:57.583 --> 00:04:59.668
00:04:58.333 --> 00:05:00.418
O pré-lançamento abre em 1º de novembro.
82
00:05:00.920 --> 00:05:02.668
00:05:01.670 --> 00:05:03.418
Sua wallet é a sua chave.
83
00:05:03.114 --> 00:05:07.184
00:05:03.864 --> 00:05:07.934
Cada plataforma da rede reconhece você por
ela, e a sua equipe segue você.
84
00:05:07.445 --> 00:05:10.714
00:05:08.195 --> 00:05:11.464
Quando uma nova plataforma é lançada, o
seu pessoal já está posicionado abaixo de
você.
85
00:05:10.754 --> 00:05:16.913
00:05:11.504 --> 00:05:17.663
Um patrocinador nunca é pulado por estar
quieto, e uma compra nunca fica parada.
86
00:05:18.160 --> 00:05:20.639
00:05:18.910 --> 00:05:21.389
Sua primeira semana: ative os pagamentos.
87
00:05:20.830 --> 00:05:22.265
00:05:21.580 --> 00:05:23.015
Encontre seus dois primeiros compradores.
88
00:05:22.305 --> 00:05:23.147
00:05:23.055 --> 00:05:23.897
Chegue a cinco.
89
00:05:23.187 --> 00:05:24.494
00:05:23.937 --> 00:05:25.244
Continue construindo na largura.
90
00:05:24.627 --> 00:05:28.162
00:05:25.377 --> 00:05:28.912
E ensine o mesmo plano a cada pessoa que
você trouxer.
91
00:05:36.010 --> 00:05:37.386
00:05:36.760 --> 00:05:38.136
A meta é cinco.
92
00:05:37.647 --> 00:05:42.297
00:05:38.397 --> 00:05:43.047
Cinco compradores fortes desbloqueiam cada
nível, cada marco e cada ferramenta.
93
00:05:42.651 --> 00:05:43.901
00:05:43.401 --> 00:05:44.651
Pronto para começar?
94
00:05:44.857 --> 00:05:47.394
00:05:45.607 --> 00:05:48.144
Fale com a pessoa que compartilhou isto
com você.
95
00:05:47.434 --> 00:05:50.865
00:05:48.184 --> 00:05:51.615
Ela vai te ajudar a começar em poucos
minutos, e será seu patrocinador em
96
00:05:50.905 --> 00:05:52.792
00:05:51.655 --> 00:05:53.542
todas as plataformas da rede.
+2 -2
View File
@@ -142,8 +142,8 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/contract.js?v=20260908p"></script>
<script src="/assets/chat.js?v=20260906m"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+268
View File
@@ -0,0 +1,268 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Conversion tracking: see which ad brings sign-ups and sales | InstantAdPay</title>
<meta name="description" content="How to set up conversion tracking on InstantAdPay: create a goal, put the landing tag on the page your ad points to and the goal pixel on your thank-you page, then read conversions and cost per goal in credits for every campaign. Copy-paste examples for HTML, WordPress, page builders, Aweber and GetResponse.">
<meta name="theme-color" content="#043b2f">
<link rel="canonical" href="https://instantadpay.com/conversion-tracking">
<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay">
<meta property="og:title" content="Conversion tracking: see which ad brings sign-ups and sales">
<meta property="og:description" content="Clicks tell you who looked. Conversion tracking tells you which ad, page and source actually brought a subscriber or a sale, with a cost per goal in credits. Free for every member. Set it up in four steps.">
<meta property="og:url" content="https://instantadpay.com/conversion-tracking">
<meta name="twitter:card" content="summary">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
<link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="/assets/site.css?v=20260912b">
<style>
.rg{max-width:900px}
.rg .hero{padding:44px 0 10px}
.rg h2{font-size:26px;margin:38px 0 6px}
.rg h3{font-size:17px;margin:0 0 6px}
.rg-eye{font-family:var(--mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--amber);font-weight:700;margin:38px 0 0}
.rg-eye + h2{margin-top:6px}
.rg-cta{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin:6px 0 10px}
.rg-cta .btn.big{font-size:17px;padding:14px 22px}
.rg-two{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:14px;margin:14px 0 0}
.rg-box{border:1px solid var(--line);border-radius:14px;padding:16px 18px;background:rgba(255,255,255,.02);min-width:0}
.rg-box p{margin:0;font-size:14.5px;color:var(--muted)}
.rg-box p + p{margin-top:8px}
.rg-note{font-size:14.5px;color:var(--muted);margin:8px 0 0}
/* the flow: across on a wide screen, down on a phone */
.cg-flow{list-style:none;margin:16px 0 8px;padding:0;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:26px}
.cg-flow li{position:relative;border:1px solid var(--line-strong);border-radius:12px;padding:12px 13px;background:rgba(255,255,255,.02);font-size:13.5px;line-height:1.45;color:var(--muted);min-width:0}
.cg-flow li b{display:block;font-family:var(--disp);font-size:14.5px;color:var(--ink);margin-bottom:4px}
.cg-flow li .k{display:inline-grid;place-items:center;width:24px;height:24px;border-radius:50%;font-family:var(--mono);font-size:12px;font-weight:700;margin-bottom:6px;background:var(--ink);color:#04120e}
.cg-flow li code{font-family:var(--mono);font-size:12px;color:var(--mint);overflow-wrap:anywhere}
.cg-flow li.f-ad{border-color:rgba(84,204,255,.55);background:rgba(84,204,255,.07)}
.cg-flow li.f-tag{border-color:rgba(67,232,195,.6);background:rgba(67,232,195,.08)}
.cg-flow li.f-px{border-color:rgba(255,178,56,.7);background:rgba(255,178,56,.09)}
.cg-flow li.f-win{border-color:var(--mint);background:var(--mint-soft)}
.cg-flow li:not(:last-child)::after{content:"";position:absolute;right:-20px;top:50%;margin-top:-7px;border:7px solid transparent;border-left:9px solid var(--line-strong);border-right:0}
@media (max-width:820px){
.cg-flow{grid-template-columns:1fr;gap:24px}
.cg-flow li:not(:last-child)::after{right:auto;left:26px;top:auto;bottom:-19px;margin-top:0;border:7px solid transparent;border-top:9px solid var(--line-strong);border-bottom:0}
}
/* steps */
.rg-route{list-style:none;counter-reset:s;margin:12px 0 0;padding:0;display:grid;gap:14px}
.rg-route > li{counter-increment:s;display:grid;grid-template-columns:42px minmax(0,1fr);gap:14px;align-items:start;border:1px solid var(--line);border-radius:14px;padding:14px 16px;background:rgba(255,255,255,.02);min-width:0}
.rg-route > li::before{content:counter(s);font-family:var(--disp);font-weight:800;font-size:20px;width:42px;height:42px;border-radius:50%;display:grid;place-items:center;background:var(--amber);color:#1b1203}
.rg-route > li > div{min-width:0}
.rg-route p{margin:0 0 8px;font-size:14.5px;color:var(--muted)}
.rg-where{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px}
.rg-chip{font-size:12.5px;font-weight:600;padding:3px 10px;border-radius:999px;background:var(--mint-soft);color:var(--mint);border:1px solid rgba(67,232,195,.35)}
.rg-chip.ls{background:rgba(84,204,255,.08);color:var(--cyan);border-color:rgba(84,204,255,.35)}
/* code */
.cg-code{position:relative;margin:8px 0 10px;border:1px solid var(--line-strong);border-radius:10px;background:#02100b;padding:12px 14px 12px;min-width:0}
.cg-code pre{margin:0;font-family:var(--mono);font-size:12.5px;line-height:1.6;color:var(--mint-hi);white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
.cg-code .cg-lbl{display:flex;justify-content:space-between;align-items:center;gap:8px;font-family:var(--mono);font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin:0 0 6px}
.cg-copy{font:600 12px var(--disp);background:transparent;color:var(--mint);border:1px solid rgba(67,232,195,.5);border-radius:999px;padding:3px 12px;cursor:pointer}
.cg-copy:hover{background:rgba(67,232,195,.1)}
.cg-ph{color:var(--amber);font-weight:700}
.cg-ex{border:1px solid var(--line);border-radius:14px;padding:16px 18px;background:rgba(255,255,255,.02);margin:14px 0 0;min-width:0}
.cg-ex > p,.cg-ex li{font-size:14.5px;color:var(--muted)}
.cg-ex > p{margin:0 0 8px}
.cg-ex ol,.cg-ex ul{margin:0 0 8px;padding-left:20px;display:grid;gap:4px}
.rg code.i{font-family:var(--mono);font-size:13px;color:var(--mint);background:rgba(67,232,195,.08);padding:1px 5px;border-radius:4px;overflow-wrap:anywhere}
/* report table */
.rg-tbl{border:1px solid var(--line);border-radius:14px;overflow:hidden;margin:10px 0 8px}
.rg-tbl table{width:100%;border-collapse:collapse;font-size:14.5px;table-layout:fixed}
.rg-tbl th,.rg-tbl td{padding:10px 12px;text-align:left;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}
.rg-tbl th{font-family:var(--mono);font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);font-weight:600}
.rg-tbl td:first-child{width:34%;font-weight:700}
.rg-tbl td .muted{font-weight:400;font-size:12.5px}
.rg-tbl tr:last-child td{border-bottom:0}
/* checklist */
.cg-check{list-style:none;margin:12px 0 0;padding:0;display:grid;gap:10px}
.cg-check li{position:relative;padding:12px 14px 12px 44px;border:1px solid var(--line);border-radius:12px;background:rgba(255,255,255,.02);font-size:14.5px;color:var(--muted)}
.cg-check li::before{content:"";position:absolute;left:14px;top:14px;width:16px;height:16px;border-radius:4px;border:2px solid var(--mint)}
.cg-check li b{color:var(--ink)}
.rg-faq{display:grid;gap:14px;margin:12px 0 0}
.rg-faq dt{font-family:var(--disp);font-weight:700}
.rg-faq dd{margin:4px 0 0;color:var(--muted);font-size:14.5px}
.rg-rule{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:14px 18px;border-radius:0 12px 12px 0;margin:30px 0 22px;font-size:14.5px}
.rg-warn{border-left:4px solid var(--amber);background:rgba(255,178,56,.07);padding:12px 16px;border-radius:0 12px 12px 0;margin:12px 0 0;font-size:14.5px}
@media (max-width:640px){.rg .hero h1{font-size:30px}.cg-ex,.rg-box{padding:14px}.rg-route > li{grid-template-columns:34px minmax(0,1fr);gap:10px;padding:12px}.rg-route > li::before{width:34px;height:34px;font-size:17px}}
</style>
</head>
<body>
<div class="wrap rg">
<section class="hero">
<p class="eyebrow">InstantAdPay + LinkSpin · free for every member</p>
<h1>Conversion tracking: <em>see which ad</em> actually brings sign-ups and sales.</h1>
<p class="lead">Clicks tell you who looked. Conversion tracking tells you which ad, which page and which traffic source brought a subscriber or a sale, and what each one cost you in credits. You paste two small tags on your own site, one time. After that, every campaign in your dashboard shows its goals next to its clicks.</p>
</section>
<video src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/conversion-tracking-iap.mp4?v=20261026" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/conversion-tracking-iap.jpg?v=20261026" controls playsinline preload="metadata" width="1200" height="675" style="display:block;width:100%;height:auto;max-width:860px;background:#000;border-radius:16px;border:1px solid var(--line);margin:18px 0 14px" aria-label="Video: Marty walks through setting up conversion tracking, about 3 minutes"></video>
<div class="rg-cta">
<a class="btn big" href="/my#campaigns">Open Conversion tracking</a>
<a class="btn sec" href="/join">Not a member yet? Join free by email</a>
</div>
<p class="rg-note">In your dashboard it lives under <b>Campaigns</b>, in the <b>Conversion tracking</b> card below your campaign list. The counting is done by LinkSpin, our sister site, under the same email, so the same goals also show in your LinkSpin Control Room under <b>Conversions</b>.</p>
<p class="rg-eye">Why it matters</p>
<h2>Why track conversions</h2>
<div class="rg-two">
<div class="rg-box"><h3>Clicks are not sign-ups</h3><p>One ad can get lots of clicks from people who never sign up. Another gets fewer clicks and brings you subscribers. Without tracking, both look the same, or the wrong one looks better.</p></div>
<div class="rg-box"><h3>Find the winner</h3><p>Every goal is counted against the ad that sent the visitor. You see which campaign, which landing page and which traffic source produced the sign-up or the sale.</p></div>
<div class="rg-box"><h3>A cost per goal, in credits</h3><p>Each campaign shows its goals and what each one cost: the credits the campaign spent in the last 30 days, divided by its goals in those 30 days. Lower is better. Compare two ads on the same offer and you know which to keep.</p></div>
<div class="rg-box"><h3>Put next month's fuel behind it</h3><p>This is the "your numbers get useful" part of <a href="/refuel">Fuel Your Offers</a>. Run your ads all month, let the goals come in, then put next month's refuel behind the ad and the page that convert, instead of guessing.</p></div>
</div>
<p class="rg-eye">The flow</p>
<h2>How a conversion gets counted</h2>
<ol class="cg-flow" aria-label="How a conversion gets counted, step by step">
<li class="f-ad"><span class="k">1</span><b>Someone clicks your ad</b>The click gets a random id, added to your page's address as <code>?lsclk=i2f9…</code></li>
<li class="f-tag"><span class="k">2</span><b>They land on your page</b>The landing tag keeps that id on your own site for 30 days.</li>
<li><span class="k">3</span><b>They sign up or buy</b>On your page, through your form or your checkout. Nothing changes for them.</li>
<li class="f-px"><span class="k">4</span><b>Your thank-you page loads</b>The goal pixel there reads the kept id and sends it to LinkSpin.</li>
<li class="f-win"><span class="k">5</span><b>Counted on your campaign</b>The goal shows on the ad that sent them, with its cost per goal in credits.</li>
</ol>
<p class="rg-note">The id is random. It identifies the click, not the person. Nothing personal is read from your page or sent anywhere.</p>
<p class="rg-eye">Set it up</p>
<h2>Four steps, one time</h2>
<ol class="rg-route">
<li><div>
<h3>Create a goal</h3>
<p>A goal is one thing you want counted: <b>subscriber</b>, <b>sale</b>, <b>signup</b>. Type a short name (letters, numbers and dashes) and press Add goal. The default value is optional: put what a sale is worth, like 19.95, and it is recorded with each conversion. You can have up to 20 goals.</p>
<p>Each goal gets its own pixel id: <b>px</b> plus 10 letters and numbers. It is not a secret. It can only ever count clicks on your own ads, so it is safe to paste on any page.</p>
<div class="rg-where"><span class="rg-chip">InstantAdPay: Campaigns, Conversion tracking</span><span class="rg-chip ls">LinkSpin: Control Room, Conversions</span></div>
</div></li>
<li><div>
<h3>Put the landing tag on the page your ad points to</h3>
<p>Press <b>Snippets</b> on your goal and copy <b>1. Landing tag</b>. Paste it once on your landing page (the address your ad sends people to), just before <code class="i">&lt;/body&gt;</code>. It keeps the click id on your site, fills any hidden form field named <code class="i">lsclk</code>, and adds the id to links that stay on your site.</p>
<div class="cg-code"><div class="cg-lbl"><span>Landing tag</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre>&lt;script async src="https://linkspin.app/t.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>"&gt;&lt;/script&gt;</pre></div>
<p>It is fine to put it on every page of your site (in a site-wide footer). It never slows or breaks the page, even if LinkSpin cannot be reached.</p>
</div></li>
<li><div>
<h3>Put the goal pixel on your thank-you page</h3>
<p>Copy <b>2. Goal pixel</b> and paste it on the page people see only after they sign up or buy. Use the script version wherever your page allows scripts: it reads the id the landing tag kept, which is the surest match. Use the image version where scripts are not allowed.</p>
<div class="cg-code"><div class="cg-lbl"><span>Goal pixel, script version (surest)</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre>&lt;script async src="https://linkspin.app/cv.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>&amp;goal=<span class="cg-ph">subscriber</span>"&gt;&lt;/script&gt;</pre></div>
<div class="cg-code"><div class="cg-lbl"><span>Goal pixel, image version</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre>&lt;img src="https://linkspin.app/cv.gif?px=<span class="cg-ph">YOUR_PIXEL_ID</span>&amp;goal=<span class="cg-ph">subscriber</span>" width="1" height="1" alt="" style="display:none"&gt;</pre></div>
<p>Recording a sale amount? Add <code class="i">&amp;value=19.95</code> to the end of the pixel address. Without it, the goal's default value is used.</p>
<div class="rg-warn"><b>Only on the thank-you page.</b> Never put the goal pixel on your landing page. Everyone who lands would count as a goal.</div>
</div></li>
<li><div>
<h3>Send a test conversion</h3>
<p>Press <b>Send a test conversion</b> on your goal. It loads your real pixel in test mode, the same request your thank-you page makes. It shows under <b>Last test</b> and never counts in your numbers. That proves your pixel id is live.</p>
<p>To check the pixel on your real thank-you page, add <code class="i">&amp;test=1</code> to the end of the pixel address, open your thank-you page once, and reload your dashboard a minute later: Last test updates. Then take <code class="i">&amp;test=1</code> back out. Last, click one of your own ads and look at the address bar on your landing page: you should see <code class="i">lsclk=</code> in it. That click is yours, so anything you finish after it is kept as a test, never counted.</p>
</div></li>
</ol>
<p class="rg-note">Your own clicks are kept as tests: on your ads here, and on your spin links and Banner Spins on LinkSpin, whether you are signed in on that browser or it is one you sign in from. They never show in your numbers, so a full run-through of your own funnel will not inflate anything. The card says how many of your own clicks were kept as tests.</p>
<p class="rg-eye">Copy and paste</p>
<h2>Where the code goes, by platform</h2>
<p class="rg-note">In every example, replace <span class="cg-ph" style="font-family:var(--mono)">YOUR_PIXEL_ID</span> with your goal's pixel id and <span class="cg-ph" style="font-family:var(--mono)">subscriber</span> with your goal's name. The Snippets button in your dashboard gives you both lines with these already filled in.</p>
<div class="cg-ex">
<h3>A plain HTML page</h3>
<p>Landing page: paste the landing tag right before the closing body tag.</p>
<div class="cg-code"><div class="cg-lbl"><span>landing.html</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre> ...your page...
&lt;script async src="https://linkspin.app/t.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>"&gt;&lt;/script&gt;
&lt;/body&gt;</pre></div>
<p>Thank-you page: the landing tag (optional, harmless) and the goal pixel.</p>
<div class="cg-code"><div class="cg-lbl"><span>thank-you.html</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre> ...your thank-you message...
&lt;script async src="https://linkspin.app/cv.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>&amp;goal=<span class="cg-ph">subscriber</span>"&gt;&lt;/script&gt;
&lt;/body&gt;</pre></div>
<p>Have your own form on the landing page? Add a hidden field and the landing tag fills it with the click id, so your own system can keep it with the lead:</p>
<div class="cg-code"><div class="cg-lbl"><span>hidden field</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre>&lt;input type="hidden" name="lsclk" value=""&gt;</pre></div>
</div>
<div class="cg-ex">
<h3>WordPress</h3>
<ol>
<li><b>Landing tag, site-wide:</b> with a header and footer plugin (WPCode, for example), paste the landing tag into the <b>footer</b> box and save. It now runs on every page, landing page included.</li>
<li><b>Goal pixel, thank-you page only:</b> edit your thank-you page, add a <b>Custom HTML</b> block, paste the goal pixel into it, and update the page. Do not put the goal pixel in the site-wide footer.</li>
<li>If your WordPress plan or theme strips scripts out of blocks (some hosted plans do), use the image version of the goal pixel in the Custom HTML block instead.</li>
</ol>
</div>
<div class="cg-ex">
<h3>Funnel and page builders</h3>
<p>Most builders that allow custom code give you one of two places, and either works:</p>
<ul>
<li>A <b>tracking code</b> or <b>footer code</b> box in the page or funnel settings. Put the landing tag in your landing page's box, and the goal pixel in your thank-you page's box.</li>
<li>A <b>custom HTML</b> or <b>code</b> element you drop onto the page. Drop one on each page and paste the matching line.</li>
</ul>
<p>If the builder only accepts images and no scripts on a page, use the image version of the goal pixel there. Keep the landing page and the thank-you page on the same domain (see the checklist below).</p>
</div>
<div class="cg-ex">
<h3>Autoresponders: Aweber, GetResponse and others</h3>
<p>If your list provider shows its own thank-you page after someone subscribes, you cannot paste the pixel there. Point the provider at a thank-you page on <b>your</b> site instead, and put the goal pixel on that page.</p>
<ul>
<li><b>Aweber:</b> open your sign-up form's settings, set <b>Thank You Page</b> to a custom page, and paste your own page's address.</li>
<li><b>GetResponse:</b> in the form or landing page settings, set the <b>thank-you page</b> to a custom URL, and paste your own page's address.</li>
<li><b>Any other provider:</b> look for "thank-you page", "success page" or "redirect after sign-up" and give it your own page's address.</li>
</ul>
<p>Your own thank-you page needs only your message and the goal pixel. Put the form on your landing page (where the landing tag runs), and use the same domain for both pages.</p>
</div>
<div class="cg-ex">
<h3>What if I can't put code on the thank-you page?</h3>
<p>Best fix: send people to a thank-you page you control, as above. If that is not possible:</p>
<ul>
<li><b>The pixel can go on the thank-you page, but it is on another domain, or only images are allowed there.</b> Use the image version. It cannot read the id your landing tag kept, so it counts through LinkSpin's cookie or the 24-hour match (the same network and browser within a day of the click). Both work, just less surely, and your report labels them so you can tell.</li>
<li><b>No code of any kind after the sign-up.</b> Then nothing can tell LinkSpin the sign-up happened. You can still keep the click id with each lead: add the hidden <code class="i">lsclk</code> field to your form, and if your provider keeps custom fields, the id is stored with the subscriber.</li>
<li><b>Your page signs people up without leaving the page</b> (a pop-up form). With the landing tag on that page, your page's own code can count the goal with one line after a successful sign-up: <code class="i">if (window.LinkSpin) LinkSpin.goal('YOUR_PIXEL_ID', 'subscriber');</code></li>
</ul>
</div>
<p class="rg-eye">Your numbers</p>
<h2>How to read the report</h2>
<p class="rg-note">On InstantAdPay, each campaign row under Campaigns gets a goal line, for example <b>subscriber 4 (35 credits each) · 61 tracked clicks</b>. The Conversion tracking card lists your goals with their conversions in the last 30 days, the last test, and how your conversions were matched. Numbers refresh about once a minute.</p>
<div class="rg-tbl">
<table>
<thead><tr><th>You see</th><th>What it means</th></tr></thead>
<tbody>
<tr><td>Conversions (30 days)</td><td>Goals counted for this goal in the last 30 days, tests and your own clicks left out.</td></tr>
<tr><td>Cost per goal (30 days), in credits</td><td>The credits the campaign spent in the last 30 days, divided by its goals in the same 30 days, so an older campaign reads the same way as a new one. Spend comes from your credit activity (Campaigns, Credit activity). It is in ad credits, never dollars.</td></tr>
<tr><td>url <span class="muted">(LinkSpin: Address)</span></td><td>Surest. The thank-you page's own address still carried the click id.</td></tr>
<tr><td>stored <span class="muted">(LinkSpin: Kept)</span></td><td>Very sure. The landing tag kept the click id on your site and the goal pixel read it back.</td></tr>
<tr><td>cookie <span class="muted">(LinkSpin: Cookie)</span></td><td>Fairly sure. Matched through LinkSpin's own cookie in the visitor's browser. Some browsers block it.</td></tr>
<tr><td>soft <span class="muted">(LinkSpin: 24 h match)</span></td><td>Least sure. The same network and browser within 24 hours of a click on your ad. A good guess, not proof.</td></tr>
<tr><td>Last test</td><td>When your last test conversion arrived. Tests are recorded apart and never counted.</td></tr>
</tbody>
</table>
</div>
<div class="rg-two">
<div class="rg-box"><h3>The counting rules</h3><p>Each goal counts once per click, so one person signing up twice from one click is one goal. A goal counts only within 30 days of a real click, and only for clicks on your own ads. Your own clicks are kept as tests, never counted.</p></div>
<div class="rg-box"><h3>More detail on LinkSpin</h3><p>Sign in to LinkSpin with the same email and open <b>Conversions</b> in the Control Room for the full breakdown: by ad campaign (both sites), by destination page and by traffic source, a 7, 30 or 90 day range, and a CSV download.</p></div>
</div>
<p class="rg-eye">Not counting?</p>
<h2>Troubleshooting checklist</h2>
<ul class="cg-check">
<li><b>Is the pixel id right?</b> It is <code class="i">px</code> plus 10 letters and numbers, copied from Snippets. A removed goal's pixel stops counting.</li>
<li><b>Did the test arrive?</b> Press Send a test conversion. If Last test updates, the goal is live. If the <code class="i">&amp;test=1</code> check on your real page does not update it, the pixel is not on that page or the page strips it.</li>
<li><b>Does the click id reach your page?</b> Click your own ad: your landing page's address should show <code class="i">lsclk=</code>. If it does not, something between the ad and your page (a redirect or a link shortener) is dropping it. Point the ad straight at the page with the landing tag.</li>
<li><b>Is the landing tag on the page the ad points to?</b> Exactly that address, not another page of your site.</li>
<li><b>Same domain for both pages?</b> The landing tag keeps the id on one domain. If the landing page is on <code class="i">www.yoursite.com</code> and the thank-you page on <code class="i">yoursite.com</code> (or another site), the script pixel cannot read it and only the cookie or 24-hour match is left.</li>
<li><b>Goal pixel only on the thank-you page?</b> Not in a site-wide footer, not on the landing page.</li>
<li><b>Scripts stripped?</b> Some builders and hosted blogs remove scripts. Use the image version of the goal pixel there.</li>
<li><b>Testing with your own clicks?</b> Your own clicks on your ads (and on your LinkSpin spin links and Banner Spins) are kept as tests and never show in the counts. Use Send a test conversion and the <code class="i">&amp;test=1</code> check above instead.</li>
<li><b>Older than 30 days, or the same click twice?</b> A sign-up more than 30 days after the click does not count, and each click counts once per goal.</li>
</ul>
<p class="rg-eye">Quick answers</p>
<h2>Questions members ask</h2>
<dl class="rg-faq">
<div><dt>Does it cost anything?</dt><dd>No. Conversion tracking is free for every member. It does not use credits.</dd></div>
<div><dt>Will the tags slow down or break my page?</dt><dd>No. Both load in the background, never stop your page from showing, and do nothing visible. If LinkSpin cannot be reached, your page works exactly as before.</dd></div>
<div><dt>Do I need a separate goal for each ad?</dt><dd>No. One goal covers all your ads. Each conversion is counted against whichever ad sent that visitor.</dd></div>
<div><dt>Do my ads get the click id automatically?</dt><dd>Yes. Every click through your InstantAdPay ads carries one. Your page address keeps all its own parameters; the click id is added to the end.</dd></div>
<div><dt>Is any personal data sent?</dt><dd>No. The click id is random. No name or email from your page is read or sent.</dd></div>
</dl>
<div class="rg-rule"><b>What a credit is.</b> One credit is one cent of ad delivery across the network. Credits are not money and cannot be withdrawn. Cost per goal is shown in credits for that reason.</div>
<p class="muted small" style="margin-top:10px">Conversion tracking shows what your own ads and pages produce. It does not promise any number of sign-ups or sales. No income is guaranteed; any commissions depend on real purchases in your line and on your own effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.</p>
<footer>
<div>InstantAdPay · <a href="/">Home</a> · <a href="/refuel">Fuel Your Offers</a> · <a href="/earning">How earning works</a> · <a href="https://linkspin.app/conversion-tracking">The LinkSpin side</a></div>
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
</body>
</html>
+1 -1
View File
@@ -26,7 +26,7 @@
<p class="muted small">You decide whether, and how much, to spend. Never spend more than you can afford to lose.</p>
</div>
</div></section>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+13 -1
View File
@@ -72,6 +72,18 @@
<li><b>Level 2 opens at two qualifying buyers, level 3 at five.</b> A qualifying buyer is a direct referral who bought a package of $20 or more. Qualification never expires and cannot be bought. It is counted at the block the purchase happens in, so a buy that lands forty minutes before you qualify is passed up, not held.</li>
<li><b>Passed-up shares go to the next qualified person above.</b> That is why the people who qualify early collect what the people below them are not yet set up to receive.</li>
</ul>
<div data-when="override-live" hidden><!-- Level 4 override: shown only when overrideMode is live (common.js) -->
<h3>The Level 4 override: 3% from deeper in your line</h3>
<p>On top of the three levels the contract pays in the same transaction, the company pays a <b>3% override</b> on every package bought four levels below you. It goes to the 4th sponsor up from the buyer, as long as that member has <b>5 or more qualifying buyers</b>, the same bar that opens level 3.</p>
<ul>
<li><b>It hunts upward.</b> If the 4th sponsor up does not have 5 qualifying buyers yet, the override moves up the line to the next member who does, up to 25 steps. Each purchase pays one override to one person, never more.</li>
<li><b>Paid weekly in POL.</b> Every Monday after 9 AM Central, the company wallet sends the override for the Monday to Sunday week before through the contract's award function, so every payment has its own Polygon link. It shows in your Earnings as "Level 4 override".</li>
<li><b>Small amounts wait.</b> A weekly total under 0.01 POL carries over to the next week.</li>
<li><b>From the start date on.</b> It counts purchases made from <span data-ov-start>the start date</span> forward. Earlier purchases are not paid.</li>
<li><b>The company pays it, not the contract.</b> It comes out of the platform's 20% share, so the 50/20/10 split does not change for anyone.</li>
</ul>
<p>What it rewards: building wide, and bringing in people who actually want traffic. Five qualifying buyers of your own opens it. Members who advertise again and again are what keep it coming.</p>
</div>
<h3>Who is your sponsor</h3>
<p>The invite link you opened most recently before creating your account sets your sponsor, and it locks the moment the account exists. Linked positions from Qualified Start count toward your badges, and their purchases pay your main position at level 1.</p>
<h3>Where to see it</h3>
@@ -84,6 +96,6 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
</body>
</html>
+7 -2
View File
@@ -70,7 +70,7 @@
<h3>3. Pricing and ad credits</h3>
<ul class="muted small">
<li><b>Prices are set in US dollars and paid in POL.</b> The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers.</li>
<li><b>Base rate: 1 credit = $0.01.</b> Current packages: $5 = 500 credits, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500 (larger packages include bonus credits). Package prices are bounded in the contract between $1 and $500, and any price change waits 24 hours before it takes effect.</li>
<li><b>Base rate: 1 credit = $0.01.</b> Current packages: $5 = 500 credits, $10 = 1,000, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500, $500 = 70,000 (larger packages include bonus credits). Package prices are bounded in the contract between $1 and $500, and any price change waits 24 hours before it takes effect.</li>
<li><b>Purchased credits are recorded on-chain.</b> A purchase adds credits to the member's balance inside the contract. As campaigns run, the platform's engine wallet burns the spent credits on-chain in batches, each burn tagged with its campaign reference, so the public ledger shows credits in and credits used. Only the engine wallet can reduce a balance, and only by burning.</li>
<li><b>Earned credits are kept by the site, not on-chain.</b> Welcome credits, surfing and viewing rewards, promo codes and other bonuses are tracked in the site's database and labeled separately from purchased credits.</li>
<li><b>Credits are advertising credit, not currency.</b> They cannot be transferred between members and cannot be exchanged back into POL or cash.</li>
@@ -112,6 +112,11 @@
</table></div>
</div>
<div class="card" data-when="override-live" hidden><!-- shown only when overrideMode is live (common.js) -->
<h3>Level 4 override (company paid)</h3>
<p class="muted small">Since <span data-ov-start>the start date</span> the company pays a weekly override of 3% of every package purchase to the buyer's 4th upline on the contract's sponsor line, if that member has 5 or more qualifying buyers. If not, it goes to the next qualified upline, up to 25 steps; if none is found, or the company account is reached first, the company keeps it. One override per purchase. It is paid in POL every Monday after 9 AM Central for the previous Monday to Sunday week, from a company wallet through the contract's public award function, and amounts under 0.01 POL carry to the next week. It is funded from the platform's 20% share; the contract split is unchanged. Purchases before the start date are not included.</p>
</div>
<div class="card">
<h3>What InstantAdPay is not</h3>
<ul class="muted small">
@@ -121,7 +126,7 @@
</ul>
</div>
</div></section>
<script src="/assets/common.js?v=20261015a"></script>
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+2 -2
View File
@@ -55,7 +55,7 @@
<div class="fr-steps">
<div class="fr-step"><div class="n">Step 1</div><h3>Join free, by email.</h3><p>Email first, wallet later, inside your account. Nothing to install to look around.</p></div>
<div class="fr-step"><div class="n">Step 2</div><h3>Buy any pack from $5 on a Friday.</h3><p>Central time, midnight to midnight. The 20% bonus is added to your credits the moment the purchase settles, and labelled in your credit log.</p></div>
<div class="fr-step"><div class="n">Step 2</div><h3>Buy any pack from $5 on a Friday.</h3><p>Central time, midnight to midnight. The 20% bonus is added to your credits the moment the purchase settles, and labelled in your credit log. You also get a free 7-day Game Pass for all the games.</p></div>
<div class="fr-step"><div class="n">Step 3</div><h3>Your pack pays the line above you. Theirs pays you.</h3><p>Every package is one Polygon transaction that splits to the sponsor line instantly. Public ledger, nothing held, nothing pending.</p></div>
</div>
@@ -71,6 +71,6 @@
</footer>
</div>
<script src="/assets/friday.js?v=20260925a"></script>
<script src="/assets/common.js?v=20261015a"></script>
<script src="/assets/common.js?v=20261023ov"></script>
</body>
</html>
+1 -1
View File
@@ -78,6 +78,6 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/games-page.js?v=20261012b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/games-page.js?v=20261012b"></script>
</body>
</html>
+14 -7
View File
@@ -52,7 +52,7 @@
<span class="streak" style="left:86%;animation-delay:5.6s"></span>
<div class="wrap">
<h1>Advertise and earn instantly.<br><em>Locked in code, not promises.</em></h1>
<p class="lead">Buy real ad packages from 5 to 250 dollars. Every purchase settles through
<p class="lead">Buy real ad packages from 5 to 500 dollars. Every purchase settles through
a smart contract you can read yourself, and your earnings land in
<b>your own wallet</b> before the page even refreshes.</p>
<p class="small muted" style="margin:-14px auto 26px;max-width:620px">One crypto, one network: packages are paid in <b style="color:var(--ink)">POL on Polygon</b> and every payout arrives as POL in your wallet. Buy POL with a card inside if you have never held any.</p>
@@ -83,7 +83,7 @@
<p>What it is, what you get free, how the ads run, how the money moves, and how a line gets built. Watch this first.</p>
</div>
<div style="max-width:960px;margin:0 auto;border-radius:14px;overflow:hidden;box-shadow:0 12px 48px rgba(0,0,0,.45);background:#000">
<video controls preload="metadata" playsinline style="display:block;width:100%;aspect-ratio:16/9" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/platform-overview.jpg?v=20260916a" src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/platform-overview.mp4?v=20260928a"></video>
<video controls preload="metadata" playsinline style="display:block;width:100%;aspect-ratio:16/9" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/platform-overview.jpg?v=20261016p" src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/platform-overview.mp4?v=20261016p"></video>
</div>
<p class="small muted" style="text-align:center;margin-top:12px">No income is promised. Every figure in the video is a rule of the contract.</p>
</div>
@@ -401,10 +401,12 @@
<p class="small muted" style="margin-bottom:4px">The package they buy</p>
<p><select id="dcPkg" style="width:100%">
<option value="5">Micro, $5</option>
<option value="10">Starter, $10</option>
<option value="20" selected>Activation, $20</option>
<option value="50">Builder, $50</option>
<option value="100">Growth, $100</option>
<option value="250">Leader, $250</option>
<option value="500">Elite, $500</option>
</select></p>
<p class="small muted" style="margin-bottom:4px">Referrals each of them brings who also buy</p>
<p><input type="range" id="dcSpread" min="0" max="10" value="2" style="width:100%">
@@ -468,8 +470,13 @@
<details><summary>What am I actually buying?</summary>
<p>You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy.
The 5 dollar package mints 500 credits, and the bigger packages mint bonus credits on top, up to
32,500 on the 250 dollar package. That is the product, plain and simple. Your earnings come from
70,000 on the 500 dollar package. That is the product, plain and simple. Your earnings come from
referring people who also buy real ad delivery, and the contract splits every purchase automatically.</p></details>
<details><summary>Can I see which ads bring me subscribers or sales?</summary>
<p>Yes. Campaigns &gt; Conversion tracking in your dashboard gives you two small tags for your own site:
a landing tag for the page your ad points to and a goal pixel for your thank-you page. Each subscriber
or sale is counted against the ad that sent the visitor, once per click, within 30 days, and every
campaign shows its cost per goal in credits.</p></details>
<div class="closer">
<div>
@@ -490,7 +497,7 @@
</div>
<footer>
<div>InstantAdPay · every payment verifiable on-chain · <a href="/ledger">live ledger</a> · <a id="contractLink" href="#" target="_blank" rel="noopener">view the contract ↗</a></div>
<div>InstantAdPay · every payment verifiable on-chain · <a href="/ledger">live ledger</a> · <a id="contractLink" href="#" target="_blank" rel="noopener">view the contract ↗</a> · <a href="/support">support</a></div>
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
<div class="ghost" aria-hidden="true">InstantAdPay</div>
@@ -498,9 +505,9 @@
</div>
</section>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/wallet.js?v=20260909c"></script>
<script src="/assets/home.js?v=20260929b"></script>
<script src="/assets/chat.js?v=20260906m"></script>
<script src="/assets/home.js?v=20261027tb"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+2 -2
View File
@@ -157,7 +157,7 @@
InstantAdPay · <a href="/contract">Contract</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a> · <a href="/disclaimer">Disclaimer</a>
</div>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/join.js?v=20261015a"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/join.js?v=20261016p"></script>
</body>
</html>
+2
View File
@@ -116,10 +116,12 @@ footer{color:var(--muted);font-size:14.5px;border-top:1px solid var(--line);padd
<thead><tr><th>Package</th><th>Price</th><th>Credits</th><th>You get as direct sponsor</th></tr></thead>
<tbody>
<tr><td>Micro</td><td>$5</td><td>500</td><td>$2.50</td></tr>
<tr><td>Starter</td><td>$10</td><td>1,000</td><td>$5</td></tr>
<tr><td>Activation (the qualifying buy)</td><td>$20</td><td>2,000</td><td>$10</td></tr>
<tr><td>Builder</td><td>$50</td><td>5,500</td><td>$25</td></tr>
<tr><td>Growth</td><td>$100</td><td>12,000</td><td>$50</td></tr>
<tr><td>Leader</td><td>$250</td><td>32,500</td><td>$125</td></tr>
<tr><td>Elite</td><td>$500</td><td>70,000</td><td>$250</td></tr>
</tbody>
</table>
</div>
+1 -1
View File
@@ -105,7 +105,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/launch.js?v=20260915b"></script>
</body>
</html>
+3 -3
View File
@@ -32,7 +32,7 @@
<div class="card" style="padding:0">
<div data-ph-slot="0" style="margin:0 0 10px"></div>
<div class="feed" id="feed"><div class="row muted">Loading recent history…</div></div>
<div class="nas-zone" style="max-width:728px;margin:22px auto 0;overflow:hidden;text-align:center"><!-- nas-ledger --><script src="https://www.networkadspace.com/showadss.php?w=728&h=90&n=1&bw=728&bh=90&c=999"></script></div>
<div class="nas-zone" style="max-width:728px;margin:22px auto 0;overflow:hidden;text-align:center"><!-- nas-ledger --><iframe title="Advertisement" width="728" height="90" scrolling="no" loading="lazy" style="border:0;max-width:100%;display:block;margin:0 auto;background:transparent" srcdoc="&lt;!doctype html&gt;&lt;base target=&quot;_blank&quot;&gt;&lt;style&gt;html,body{margin:0;padding:0;overflow:hidden;background:transparent}&lt;/style&gt;&lt;script src=&quot;https://www.networkadspace.com/showadss.php?w=728&amp;h=90&amp;n=1&amp;bw=728&amp;bh=90&amp;c=999&quot;&gt;&lt;/script&gt;"></iframe><!-- framed 2026-10-24: a dead ad server must never block the page --></div>
</div>
<div class="card small" id="adSlotText" hidden></div>
<footer>
@@ -40,9 +40,9 @@
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/ledger.js?v=20260906m"></script>
<script src="https://polhunter.com/embed.js" data-slots="1" async></script>
<script src="/assets/chat.js?v=20260906m"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+1 -1
View File
@@ -21,7 +21,7 @@
## Pricing and ad credits
- Prices are set in US dollars and paid in POL, converted at purchase time with the Chainlink POL/USD feed on Polygon. If the feed is stale, the last fresh price is used for up to 24 hours, then new sales pause until the feed recovers.
- Base rate: 1 credit = $0.01. Packages: $5 = 500 credits, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500 (larger packages include bonus credits).
- Base rate: 1 credit = $0.01. Packages: $5 = 500 credits, $10 = 1,000, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500, $500 = 70,000 (larger packages include bonus credits).
- Package prices are bounded in the contract between $1 and $500; a price change waits 24 hours before taking effect.
- Purchased credits are recorded in the contract. As campaigns run, the platform's engine wallet burns spent credits on-chain in batches, each tagged with a campaign reference. Only the engine wallet can reduce a balance, and only by burning.
- Earned credits (welcome credits, viewing and surfing rewards, promo codes, bonuses) are tracked in the site database, not on-chain, and are labeled separately from purchased credits.
+76 -7
View File
@@ -139,10 +139,12 @@
<button data-pane="pipeline" type="button"><svg viewBox="0 0 24 24"><rect x="3" y="4" width="5" height="16" rx="1.2"/><rect x="9.5" y="4" width="5" height="11" rx="1.2"/><rect x="16" y="4" width="5" height="7" rx="1.2"/></svg>Pipeline<span class="pill" id="pipeBadge" hidden></span></button>
<button data-pane="buy" type="button"><svg viewBox="0 0 24 24"><circle cx="9" cy="20" r="1.6"/><circle cx="17" cy="20" r="1.6"/><path d="M3 4h2l2.4 11.2A2 2 0 0 0 9.4 17h8.2a2 2 0 0 0 2-1.6L21 8H6"/></svg>Buy packages</button>
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8M7 13v5a2 2 0 0 0 4 0v-3"/></svg>Campaigns</button>
<button data-pane="engine" id="engineNav" type="button" hidden><svg viewBox="0 0 24 24"><path d="M4 16a8 8 0 1 1 16 0"/><path d="M12 16l4-5"/><circle cx="12" cy="16" r="1.4"/></svg>Engine Room</button>
<button data-pane="earn" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v9M9 10c0-1.1 1.3-1.8 3-1.8s3 .7 3 1.8-1.3 1.6-3 1.8-3 .7-3 1.8 1.3 1.8 3 1.8 3-.7 3-1.8"/></svg>Earn credits<span class="pill" id="inboxBadge" hidden></span></button>
<button data-pane="earnings" type="button"><svg viewBox="0 0 24 24"><path d="M4 17l5-5 4 3 7-8"/><path d="M14 7h6v6"/></svg>Earnings</button>
<button data-pane="promo" type="button"><svg viewBox="0 0 24 24"><path d="M7 10s5-1 9-5v14c-4-4-9-5-9-5H5a2 2 0 0 1-2-2v0a2 2 0 0 1 2-2h2z"/><path d="M8 15l1 5h2l-1-5"/></svg>Promo tools</button>
<button data-pane="training" type="button"><svg viewBox="0 0 24 24"><path d="M3 5l9-2 9 2v11l-9 2-9-2z"/><path d="M12 3v13"/><path d="M9 11l3 2 3-2"/></svg>Training</button>
<button data-pane="help" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.1-2.4 3.7"/><path d="M12 17v.5"/></svg>Help<span class="pill" id="helpBadge" hidden></span></button>
<button data-pane="games" id="gamesNav" type="button" hidden><svg viewBox="0 0 24 24"><rect x="2.5" y="7" width="19" height="11" rx="5.5"/><path d="M7 11v3M5.5 12.5h3"/><circle cx="15.5" cy="11.5" r="1.1"/><circle cx="18" cy="13.5" r="1.1"/></svg>Games</button>
<button data-pane="wallet" type="button"><svg viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><circle cx="16.5" cy="14.5" r="1.4"/></svg>Wallet</button>
<button data-pane="profile" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.6"/><path d="M4.5 20c1.6-3.6 4.2-5.2 7.5-5.2s5.9 1.6 7.5 5.2"/></svg>Profile</button>
@@ -182,6 +184,8 @@
<div class="card" id="phLaunch" hidden></div>
<div class="card" id="fdfCard" hidden></div>
<div class="card" id="wwCard" hidden></div>
<div class="card" id="rfCard" hidden aria-live="polite"></div>
<div class="card" id="gpNudge" hidden></div>
<div class="card gs" id="gsCard" hidden>
<div class="card-head"><h3>Getting started</h3><span class="sub" id="gsSub"></span></div>
<div class="gs-steps" id="gsSteps"></div>
@@ -194,7 +198,7 @@
</div>
<div class="statx c-cyan">
<div class="pl"><svg viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><circle cx="16.5" cy="14.5" r="1.4"/></svg></div>
<div><div class="nv mono" id="dbEarned">0</div><div class="lb">POL earned</div><span class="chip" id="dbEarnedChip" hidden></span></div>
<div><div class="nv mono" id="dbEarned">0</div><div class="lb">POL earned <span class="muted" id="dbEarnedUsd"></span></div><span class="chip" id="dbEarnedChip" hidden></span></div>
</div>
<div class="statx c-violet">
<div class="pl"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg></div>
@@ -391,6 +395,12 @@
<h3>Messages from your upline</h3>
<div id="upList"></div>
</div>
<div class="card" id="leaderToolsLine" data-jump="Leader tools">
<h3>Leader tools: build wide</h3>
<p class="muted small">The Leader's Guide shows how width unlocks levels 2 and 3, how far your ads reach, Qualified Start, LinkSpin and your first week, with diagrams you can present from. The presentation and the build-wide video sit beside it in Training.</p>
<p><a class="btn small" href="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-leaders-guide.pdf?v=20261016p" target="_blank" rel="noopener">Download the Leader's Guide (PDF)</a>
<a class="btn small sec" href="#training?g=leader">Open Leader tools</a></p>
</div>
<div class="card ad-foot" id="adSlotPane-line" hidden></div>
</div>
@@ -428,6 +438,12 @@
<p style="margin:10px 0 0"><button class="btn small" type="button" id="pipeSave">Save</button> <span class="muted small" id="pipeSaved"></span></p>
</div>
</div>
<div class="card" id="leaderToolsPipe">
<h3>Leader tools</h3>
<p class="muted small">Working someone through a decision? Share the presentation from Leader tools, and keep the Leader's Guide handy for the questions about levels, packages and payouts.</p>
<p><a class="btn small" href="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-leaders-guide.pdf?v=20261016p" target="_blank" rel="noopener">Download the Leader's Guide (PDF)</a>
<a class="btn small sec" href="#training?g=leader">Open Leader tools</a></p>
</div>
<div class="card ad-foot" id="adSlotPane-pipeline" hidden></div>
</div>
<div class="pane" id="pane-buy" hidden>
@@ -464,7 +480,7 @@
<p class="muted small">What it costs to open each level with your own positions, what comes straight back to your main wallet, and the ad credits you end up holding.</p>
<p style="display:flex;gap:12px;flex-wrap:wrap;align-items:center">
<label class="small">Positions <input type="number" id="qcN" min="1" max="10" value="2" style="width:80px;margin-left:6px"></label>
<label class="small">Package each <select id="qcPkg" style="margin-left:6px"><option value="20">$20 · 2,000 credits</option><option value="50">$50 · 5,500 credits</option><option value="100">$100 · 12,000 credits</option><option value="250">$250 · 32,500 credits</option></select></label>
<label class="small">Package each <select id="qcPkg" style="margin-left:6px"><option value="20">$20 · 2,000 credits</option><option value="50">$50 · 5,500 credits</option><option value="100">$100 · 12,000 credits</option><option value="250">$250 · 32,500 credits</option><option value="500">$500 · 70,000 credits</option></select></label>
</p>
<div id="qcOut" class="small"></div>
</div>
@@ -514,6 +530,7 @@
<option value="visits">Verified visits (guaranteed unique)</option>
</select></p>
<p class="small muted" id="cWhere" style="margin:-4px 0 10px"></p>
<p class="small" id="cLoginLine" hidden style="grid-column:1/-1;margin:-4px 0 10px"></p>
<p><input id="cName" placeholder="Campaign name" style="width:100%"></p>
<p id="cBudgetRow"><input id="cBudget" type="number" placeholder="Budget (credits)" min="10" style="width:100%"></p>
<p id="cCapRow" style="grid-column:1/-1"><input id="cDailyCap" type="number" placeholder="Daily cap in credits (optional) — paces the budget across days" min="10" style="width:100%">
@@ -603,6 +620,34 @@
</div>
<button class="btn" id="createCampBtn">Launch campaign</button>
</div>
<div class="card" id="convCard" hidden>
<h3>Conversion tracking</h3>
<p class="small" style="margin:0 0 6px"><a href="/conversion-tracking" target="_blank" rel="noopener">How to set it up: the step-by-step guide with copy-paste examples</a></p>
<p class="muted small">See which of your ads bring subscribers and sales, not just clicks. Every click on your ad carries a click id. Put two small tags on your own site and each goal is counted against the ad that sent the visitor, with a cost per goal in credits on each campaign above. The counting is done by LinkSpin, our sister site, under this same email.</p>
<ol class="small" style="margin:6px 0 10px 18px;padding:0">
<li>Add a goal below, for example <b>subscriber</b> or <b>sale</b>.</li>
<li>Put the <b>landing tag</b> on the page your ad sends people to (once per page, just before &lt;/body&gt;).</li>
<li>Put the <b>goal pixel</b> on your thank-you page, the page people see after they sign up or buy.</li>
</ol>
<p class="small" id="convStatus"></p>
<div id="convGoals"></div>
<div id="convAddRow" class="grid c3" style="margin-top:10px">
<p><input id="convName" maxlength="32" placeholder="Goal name, like subscriber or sale" style="width:100%"></p>
<p><input id="convValue" type="number" min="0" step="0.01" placeholder="Default value (optional), like 19.95" style="width:100%"></p>
<p><button class="btn small" id="convAddBtn" type="button">Add goal</button></p>
</div>
<div id="convSnips"></div>
<h4 style="margin:14px 0 4px">Your autoresponder's thank-you page</h4>
<p class="small muted" style="margin:0">Set your autoresponder's thank-you (success) page to a page on YOUR site that carries the goal pixel. Aweber: in your sign-up form settings, choose 'Thank You Page: custom page' and paste your page's address. GetResponse: in the form or landing page settings, pick 'Thank-you page: custom URL' and paste your page's address. If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely.</p>
<h4 style="margin:14px 0 4px">How sure is each count</h4>
<ul class="small muted" id="convLegend" style="margin:0 0 0 18px;padding:0">
<li><b>Click id in the address</b> (url): surest. The thank-you page address still carried the click id from your ad.</li>
<li><b>Stored by the landing tag</b> (stored): very sure. The landing tag kept the click id on your site and the goal pixel read it back.</li>
<li><b>LinkSpin cookie</b> (cookie): fairly sure. Matched through LinkSpin's own cookie in the visitor's browser. Some browsers block it.</li>
<li><b>24-hour match</b> (soft): least sure. Same connection and browser within 24 hours of a click. A good guess, not a proof.</li>
</ul>
<p class="small muted" style="margin:8px 0 0">Each goal counts once per click, only within 30 days of a real click on one of your ads. Your own clicks (on your ads here, and on your LinkSpin spin links and Banner Spins) and the test button count as tests, never in your numbers. Send a test conversion loads your real pixel in test mode. Cost per goal (30 days) = the credits a campaign spent in the same 30 days, divided by its goals.</p>
</div>
<div class="card ad-foot" id="adSlotPane-campaigns" hidden></div>
</div>
@@ -731,6 +776,7 @@
<div class="card">
<h3>Earnings</h3>
<p class="muted small">Every payout the contract has sent to your wallet. Each line links to the transaction.</p>
<p class="muted small" id="earnUsdNote" style="margin-top:-4px"></p>
<div class="feed" id="earnFeed"><div class="row muted">Nothing yet.</div></div>
</div>
<div class="card">
@@ -753,7 +799,11 @@
<div class="card ad-foot" id="adSlotPane-earnings" hidden></div>
</div>
<div class="pane" id="pane-engine" hidden>
<div class="card"><div class="card-head"><h3>Engine Room</h3><span class="sub">InstantAdPay and LinkSpin at a glance</span></div><div id="erRoot" data-host="engineNav" aria-live="polite"></div></div>
</div>
<div class="pane" id="pane-promo" hidden>
<div class="card" id="rkCard" hidden aria-live="polite"></div>
<div class="card" id="promoLinks">
<div class="card-head"><h3>Your links</h3><span class="sub">one invite link, eight front doors</span></div>
<div class="promo-strip" style="padding:0 0 12px">
@@ -772,7 +822,7 @@
<span><button class="btn small sec" id="promoWallCopy" type="button">Copy wall link</button> <a class="btn small sec" id="promoWallOpen" href="#" target="_blank" rel="noopener">Open</a></span>
</div>
<div class="chips promo-pills" role="tablist" aria-label="Promo tools sections">
<button class="chip-t" data-promo="toolkit" type="button" role="tab">✨ AI Copy Engine</button>
<button class="chip-t" data-promo="toolkit" type="button" role="tab">✨ Your toolkit</button>
<button class="chip-t on" data-promo="posts" type="button" role="tab">Social posts</button>
<button class="chip-t" data-promo="text" type="button" role="tab">Text a friend</button>
<button class="chip-t" data-promo="swipe" type="button" role="tab">Email swipes</button>
@@ -1059,8 +1109,14 @@
<div class="card ad-foot" id="adSlotPane-training" hidden></div>
</div>
<div class="pane" id="pane-help" hidden>
<div id="helpBody"><div class="card"><p class="muted small">Loading your tickets…</p></div></div>
<div class="card ad-foot" id="adSlotPane-help" hidden></div>
</div>
<div class="pane" id="pane-games" hidden>
<div class="card"><h3>Games</h3><p class="muted small">Games in the InstantAdPay network, the Polygon wing of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>. They pay in POL to the wallet on your InstantAdPay account, and one tap signs you in.</p></div>
<div class="card" id="gpCard" hidden></div>
<div class="games-grid" id="gamesGrid"><p class="muted small">Loading games…</p></div>
<style>.games-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:16px;margin-top:4px}
.game-card{background:var(--panel-solid);border:1px solid var(--line-strong);border-radius:var(--radius);overflow:hidden;display:flex;flex-direction:column}
@@ -1072,6 +1128,15 @@
.game-card .gc-pre{display:inline-block;font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;padding:2px 6px;border-radius:5px;background:#fde68a;color:#7c2d12;margin-left:6px}
.game-card .btn{margin-top:auto;text-align:center}
.game-card{position:relative}
#gpCard.gp-hl{outline:2px solid var(--gold,#e2b04a);outline-offset:2px}
.gp-tbl{width:100%;border-collapse:collapse;font-size:13px}.gp-tbl td{padding:5px 8px;border-top:1px solid var(--line,#e5e7eb);vertical-align:top}.gp-tbl td:first-child{font-weight:700;white-space:nowrap;width:1%}
.gp-tiers{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px;margin-top:10px}
.gp-tier{border:1px solid var(--line-strong);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:4px}
.gp-tier.on{border-color:var(--gold,#e2b04a);box-shadow:0 0 0 1px var(--gold,#e2b04a) inset}
.gp-tier h4{margin:0;font-size:16px;color:var(--ink);font-family:var(--disp)}
.gp-tier .gp-price{margin:0;font-size:20px;font-weight:700}
.gp-tier ul{margin:4px 0;padding-left:18px;font-size:13px}
.gp-tier .btn{margin-top:auto;align-self:flex-start}
.game-card .gc-ribbon{position:absolute;top:10px;right:10px;display:inline-flex;align-items:center;gap:6px;background:#FF5FA2;color:#2b0418;font-weight:700;font-size:11px;letter-spacing:.1em;text-transform:uppercase;padding:5px 10px;border-radius:6px;box-shadow:0 3px 0 #9c2a5d}
.game-card .gc-ribbon i{width:7px;height:7px;border-radius:50%;background:#2b0418;display:inline-block;animation:gcPulse 1.4s ease-in-out infinite}
@keyframes gcPulse{50%{opacity:.25}}
@@ -1129,6 +1194,7 @@
<a href="/">Ad packages</a>
<a href="/ledger">Live ledger</a>
<a href="/contract">The contract</a>
<a href="#help">Support</a>
<a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>
</footer>
</div>
@@ -1153,10 +1219,13 @@
</div>
</div>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/wallet.js?v=20260911a"></script>
<script src="/assets/promo.js?v=20261015a"></script>
<script src="/assets/my.js?v=20261015a"></script>
<script src="/assets/chat.js?v=20260907l"></script>
<script src="/assets/promo.js?v=20261028td"></script>
<script src="/assets/support.js?v=20261016a"></script>
<script src="/assets/my.js?v=20261028td"></script>
<script src="/assets/fuel.js?v=20261025ff"></script>
<script src="/assets/engine-room.js?v=20261025ff"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+4 -2
View File
@@ -44,7 +44,7 @@
<p class="hello" id="pkHello"></p>
<div class="vid"><video id="pkVideo" controls playsinline preload="metadata" poster="/promo/partner-overview.jpg" src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/partner-overview.mp4"></video></div>
<div class="vid"><video id="pkVideo" controls playsinline preload="metadata" poster="/promo/partner-overview.jpg?v=20261016p" src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/partner-overview.mp4?v=20261016p"></video></div>
<p class="muted small">Watch first: the whole platform in about five minutes. Free and paid members, the seven ad formats, how people get paid, and the offer for your builder.</p>
<h2>Why I built it</h2>
@@ -74,10 +74,12 @@
<table>
<tr><th>Package</th><th>Price</th><th>Credits</th></tr>
<tr><td>Micro</td><td>$5</td><td>500</td></tr>
<tr><td>Starter</td><td>$10</td><td>1,000</td></tr>
<tr><td>Activation, the qualifying buy</td><td>$20</td><td>2,000</td></tr>
<tr><td>Builder</td><td>$50</td><td>5,500</td></tr>
<tr><td>Growth</td><td>$100</td><td>12,000</td></tr>
<tr><td>Leader</td><td>$250</td><td>32,500</td></tr>
<tr><td>Elite</td><td>$500</td><td>70,000</td></tr>
</table>
<h2>What your members get</h2>
@@ -128,7 +130,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/partners.js?v=20260914a"></script>
</body>
</html>
+1 -1
View File
@@ -193,7 +193,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/plays.js?v=20260910b"></script>
</body>
</html>
+11 -11
View File
@@ -8,12 +8,12 @@
<meta property="og:type" content="video.other"><meta property="og:site_name" content="InstantAdPay">
<meta property="og:title" content="Build wide. Get paid instantly. | InstantAdPay presentation">
<meta property="og:description" content="The whole plan in six minutes, narrated, with captions in six languages.">
<meta property="og:image" content="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.jpg?v=20261015a"><meta property="og:image:width" content="1280"><meta property="og:image:height" content="720">
<meta property="og:image" content="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.jpg?v=20261016p"><meta property="og:image:width" content="1280"><meta property="og:image:height" content="720">
<meta property="og:url" content="https://instantadpay.com/presentation">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Build wide. Get paid instantly.">
<meta name="twitter:description" content="The InstantAdPay presentation: narrated, with captions in six languages.">
<meta name="twitter:image" content="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.jpg?v=20261015a">
<meta name="twitter:image" content="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.jpg?v=20261016p">
<link rel="canonical" href="https://instantadpay.com/presentation">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
<link rel="icon" type="image/png" href="/logo-icon.png">
@@ -56,14 +56,14 @@
<div class="pr-player">
<video id="prVideo" controls playsinline preload="metadata"
poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.jpg?v=20261015a"
src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.mp4?v=20261015a">
<track kind="captions" srclang="en" label="English" src="/captions/iap-presentation.en.vtt?v=20261015a">
<track kind="captions" srclang="it" label="Italiano" src="/captions/iap-presentation.it.vtt?v=20261015a">
<track kind="captions" srclang="fr" label="Français" src="/captions/iap-presentation.fr.vtt?v=20261015a">
<track kind="captions" srclang="es" label="Español" src="/captions/iap-presentation.es.vtt?v=20261015a">
<track kind="captions" srclang="de" label="Deutsch" src="/captions/iap-presentation.de.vtt?v=20261015a">
<track kind="captions" srclang="pt" label="Português" src="/captions/iap-presentation.pt.vtt?v=20261015a">
poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.jpg?v=20261016p"
src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/iap-presentation.mp4?v=20261016p">
<track kind="captions" srclang="en" label="English" src="/captions/iap-presentation.en.vtt?v=20261016p">
<track kind="captions" srclang="it" label="Italiano" src="/captions/iap-presentation.it.vtt?v=20261016p">
<track kind="captions" srclang="fr" label="Français" src="/captions/iap-presentation.fr.vtt?v=20261016p">
<track kind="captions" srclang="es" label="Español" src="/captions/iap-presentation.es.vtt?v=20261016p">
<track kind="captions" srclang="de" label="Deutsch" src="/captions/iap-presentation.de.vtt?v=20261016p">
<track kind="captions" srclang="pt" label="Português" src="/captions/iap-presentation.pt.vtt?v=20261016p">
</video>
</div>
<div class="cap-bar" id="prCaps"></div>
@@ -86,6 +86,6 @@
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/presentation.js?v=20261015b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/presentation.js?v=20261015b"></script>
</body>
</html>
+5 -3
View File
@@ -10,7 +10,7 @@
<body>
<div id="nav"></div>
<section><div class="wrap" style="max-width:820px">
<div class="sectionhead" style="text-align:left"><h2>Privacy Policy</h2><p class="muted small">Last updated: September 2026</p></div>
<div class="sectionhead" style="text-align:left"><h2>Privacy Policy</h2><p class="muted small">Last updated: October 2026</p></div>
<div class="card">
<h3>What we collect</h3>
<p class="muted small">A minimal set: the email you sign up with, a username and any profile details you choose to add (avatar, bio, social links), and, only if you link one, your public wallet address. Campaign content you create and reports you submit are stored to run the service. We also read on-chain activity that is already public on the blockchain.</p>
@@ -21,15 +21,17 @@
<h3>Cookies</h3>
<p class="muted small">We use a session cookie to keep you signed in, a referral cookie to credit the sponsor whose link you arrived through, and a browser identifier cookie used only to enforce one account per person. No third-party ad-tracking cookies.</p>
<p class="muted small"><strong>Abuse prevention.</strong> When you create an account and when you sign in we record your IP address, browser type and the browser identifier. We use them to detect duplicate accounts and self-referral, which the Terms prohibit, and for nothing else. They are visible to the site administrator only and are not sold or shared.</p>
<h3>Conversion tracking on ad links</h3>
<p class="muted small">When you click an ad here, the link to the advertiser's site gets a random click id added to its address (it looks like <code>lsclk=i3f9a0c1b2d4e</code>). The id says nothing about you. We record which ad it belongs to, the time, your country, phone or computer, and the page the click came from, and pass that to LinkSpin, our sister site, which counts the advertiser's results. If the advertiser has added the LinkSpin landing tag to their own site, that tag keeps the click id on their site (in the browser's local storage and a first-party cookie of their site). If you later sign up or buy there, their goal pixel on the thank-you page tells LinkSpin that one goal happened for that click. Nothing personal is sent: no name, no email, no wallet. Your IP address is never stored; it is only used in hashed form, together with your browser type, for a match within 24 hours of the click when the click id is missing.</p>
<h3>Sharing</h3>
<p class="muted small">Your username, public profile, and public wall are visible to others by design, and on-chain transactions are public by nature. We share data with infrastructure providers (hosting, email delivery) only as needed to operate the service, and when required by law.</p>
<h3>Your choices</h3>
<p class="muted small">You can edit your profile, adjust notification and chat settings, and request account deletion by contacting us. Note that on-chain records cannot be deleted by anyone.</p>
<p class="muted small">You can edit your profile, adjust notification and chat settings, and request account deletion by contacting us through the <a href="/support">support page</a> or at <a href="mailto:support@instantadpay.com">support@instantadpay.com</a>. Note that on-chain records cannot be deleted by anyone.</p>
<h3>Security</h3>
<p class="muted small">We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.</p>
</div>
</div></section>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+265
View File
@@ -0,0 +1,265 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Fuel Your Offers: the Monthly Refuel guide | InstantAdPay</title>
<meta name="description" content="How the Monthly Refuel streak works on InstantAdPay and LinkSpin: refuel your ads every month with a $20+ package here or $25+ on LinkSpin, and your bonus ad credits climb from +10% to +40%. The flow, the numbers and the member steps.">
<meta name="theme-color" content="#043b2f">
<link rel="canonical" href="https://instantadpay.com/refuel">
<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay">
<meta property="og:title" content="Fuel Your Offers: refuel every month, watch your bonus climb">
<meta property="og:description" content="The Monthly Refuel streak on InstantAdPay and LinkSpin: bonus ad credits from +10% up to +40% when you refuel your ads every month. Here is how it works, step by step.">
<meta property="og:image" content="https://instantadpay.com/banners/fuel-your-offers-1200x675.jpg">
<meta property="og:image:width" content="1200"><meta property="og:image:height" content="675">
<meta property="og:url" content="https://instantadpay.com/refuel">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://instantadpay.com/banners/fuel-your-offers-1200x675.jpg">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
<link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="/assets/site.css?v=20260912b">
<style>
.rg{max-width:900px}
.rg .hero{padding:44px 0 10px}
.rg-banner{display:block;width:100%;height:auto;border-radius:16px;border:1px solid var(--line);margin:18px 0 14px}
.rg h2{font-size:26px;margin:38px 0 6px}
.rg h3{font-size:17px;margin:0 0 6px}
.rg-eye{font-family:var(--mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--amber);font-weight:700;margin:38px 0 0}
.rg-eye + h2{margin-top:6px}
.rg-gauge{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:8px 0 18px}
.rg-gauge div{border:1px solid var(--line);border-radius:12px;padding:12px;background:rgba(255,255,255,.02);min-width:0}
.rg-gauge b{display:block;font-family:var(--mono);font-size:22px;color:var(--amber);font-variant-numeric:tabular-nums}
.rg-gauge span{font-size:13px;color:var(--muted)}
.rg-gauge div:last-child{border-color:rgba(255,178,56,.55);background:rgba(255,178,56,.08)}
.rg-cta{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin:6px 0 10px}
.rg-cta .btn.big{font-size:17px;padding:14px 22px}
/* the flow: one spine down the page, decisions open into branch cards that stack on a phone */
.rg-flow{list-style:none;margin:14px 0 8px;padding:0;display:grid;gap:0}
.rg-flow > li{display:grid;gap:10px;position:relative;padding-bottom:30px}
.rg-flow > li:not(:last-child)::after{content:"";position:absolute;left:22px;bottom:4px;width:2px;height:22px;background:var(--line-strong)}
.rg-flow > li:not(:last-child)::before{content:"";position:absolute;left:17px;bottom:0;border:6px solid transparent;border-top-color:var(--line-strong);border-bottom:0}
.rg-n{border:1px solid var(--line-strong);border-radius:12px;padding:11px 14px;font-size:14.5px;line-height:1.45;background:rgba(255,255,255,.02);min-width:0}
.rg-n b{display:block;font-family:var(--disp);font-size:15px;color:var(--ink);margin-bottom:2px}
.rg-n .k{display:inline-grid;place-items:center;width:24px;height:24px;border-radius:50%;font-family:var(--mono);font-size:12px;font-weight:700;margin-right:6px;vertical-align:1px;background:var(--ink);color:#04120e}
.rg-n.start{border-color:var(--mint);background:var(--mint-soft)}
.rg-n.ask{border-style:dashed;border-color:rgba(238,247,243,.45)}
.rg-n.go{border-color:rgba(67,232,195,.6);background:rgba(67,232,195,.08)}
.rg-n.fuel{border-color:rgba(255,178,56,.7);background:rgba(255,178,56,.09)}
.rg-n.stop{border-color:rgba(139,166,156,.45);background:rgba(139,166,156,.07);color:var(--muted)}
.rg-n .to{display:block;margin-top:4px;font-family:var(--mono);font-size:12px;color:var(--muted)}
.rg-br{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,230px),1fr));gap:10px;padding-left:18px;border-left:2px solid var(--line-strong);margin-left:22px}
.rg-b{display:grid;gap:6px;align-content:start;min-width:0}
.rg-e{font-family:var(--mono);font-size:11.5px;letter-spacing:.04em;color:var(--mint);font-weight:700}
.rg-b .rg-br{margin-left:4px;padding-left:12px}
.rg-legend{display:flex;flex-wrap:wrap;gap:8px 18px;font-size:13px;color:var(--muted);margin:0 0 6px}
.rg-legend i{display:inline-block;width:12px;height:12px;border-radius:3px;margin-right:6px;vertical-align:-1px;border:1px solid}
/* the numbers */
.rg-tbl{border:1px solid var(--line);border-radius:14px;overflow:hidden;margin:10px 0 8px}
.rg-tbl table{width:100%;border-collapse:collapse;font-size:15px}
.rg-tbl th,.rg-tbl td{padding:10px 12px;text-align:left;border-bottom:1px solid var(--line)}
.rg-tbl th{font-family:var(--mono);font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);font-weight:600}
.rg-tbl td.n,.rg-tbl th.n{text-align:right;font-family:var(--mono);font-variant-numeric:tabular-nums}
.rg-tbl td.both{color:var(--amber);font-weight:700}
.rg-tbl tr:last-child td{border-bottom:0}
.rg-note{font-size:14.5px;color:var(--muted);margin:8px 0 0}
/* member route */
.rg-route{list-style:none;counter-reset:s;margin:12px 0 0;padding:0;display:grid;gap:14px}
.rg-route li{counter-increment:s;display:grid;grid-template-columns:42px minmax(0,1fr);gap:14px;align-items:start;border:1px solid var(--line);border-radius:14px;padding:14px 16px;background:rgba(255,255,255,.02)}
.rg-route li::before{content:counter(s);font-family:var(--disp);font-weight:800;font-size:20px;width:42px;height:42px;border-radius:50%;display:grid;place-items:center;background:var(--amber);color:#1b1203}
.rg-route p{margin:0 0 8px;font-size:14.5px;color:var(--muted)}
.rg-where{display:flex;flex-wrap:wrap;gap:6px}
.rg-chip{font-size:12.5px;font-weight:600;padding:3px 10px;border-radius:999px;background:var(--mint-soft);color:var(--mint);border:1px solid rgba(67,232,195,.35)}
.rg-chip.ls{background:rgba(84,204,255,.08);color:var(--cyan);border-color:rgba(84,204,255,.35)}
.rg-two{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:14px;margin:30px 0 0}
.rg-box{border:1px solid var(--line);border-radius:14px;padding:16px 18px;background:rgba(255,255,255,.02);min-width:0}
.rg-box p{margin:0;font-size:14.5px;color:var(--muted)}
.rg-coach{border-left:4px solid var(--amber);background:rgba(255,178,56,.07);padding:16px 18px;border-radius:0 14px 14px 0;margin:30px 0 0}
.rg-coach ul{margin:8px 0 0;padding-left:20px;display:grid;gap:6px;font-size:14.5px}
.rg-faq{display:grid;gap:14px;margin:12px 0 0}
.rg-faq dt{font-family:var(--disp);font-weight:700}
.rg-faq dd{margin:4px 0 0;color:var(--muted);font-size:14.5px}
.rg-rule{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:14px 18px;border-radius:0 12px 12px 0;margin:30px 0 22px;font-size:14.5px}
@media (max-width:640px){.rg-gauge{grid-template-columns:repeat(2,minmax(0,1fr))}.rg .hero h1{font-size:30px}.rg-br{margin-left:10px;padding-left:12px}}
</style>
</head>
<body>
<div class="wrap rg">
<section class="hero">
<p class="eyebrow">InstantAdPay + LinkSpin · live since October 24, 2026</p>
<h1>Fuel Your Offers: <em>refuel every month</em>, watch your bonus climb.</h1>
<p class="lead">Your ads run on fuel. Refuel them every month with a new package and the Monthly Refuel streak adds bonus ad credits that climb each month, a fresh Refuel Kit lands with your name on it, and the Engine Room tells you the next move. Either site keeps your streak going. Refuel both in the same cycle and the bonus is bigger on both.</p>
</section>
<video class="rg-banner" src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/refuel-iap.mp4?v=20261024" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/refuel-iap.jpg?v=20261024" controls playsinline preload="metadata" width="1200" height="675" style="background:#000" aria-label="Video: Marty walks through Fuel Your Offers on InstantAdPay, 3 minutes"></video>
<div class="rg-gauge" aria-label="Bonus when you refuel both sites, by streak month">
<div><b>+15%</b><span>Month 1, both engines</span></div>
<div><b>+20%</b><span>Month 2</span></div>
<div><b>+30%</b><span>Month 3</span></div>
<div><b>+40%</b><span>Month 4 and on, + 100 Featured credits</span></div>
</div>
<div class="rg-cta">
<a class="btn big" href="/join">Join free by email</a>
<a class="btn sec" href="/my#buy">Already a member? Buy a package</a>
</div>
<p class="rg-eye">Why it matters</p>
<h2>Why keep refueling</h2>
<p class="lead" style="margin:0 0 14px">Traffic is what makes an offer work, and traffic stops the day your credits run out. An ad that runs for a week and then goes dark gives people one look. Most people don't act on the first look. They act after they've seen your offer a few times, over days and weeks. Refueling every month keeps your offer in front of people the whole month, not just the week you bought.</p>
<div class="rg-two" style="margin-top:0">
<div class="rg-box"><h3 style="margin:0 0 6px">Steady beats bursts</h3><p>One big push, then nothing, means every new visitor sees you once. A monthly refuel keeps your ads running every day, so the people who saw you last week see you again this week. That repeat exposure is what turns a click into a sign-up.</p></div>
<div class="rg-box"><h3 style="margin:0 0 6px">Your numbers get useful</h3><p>With ads running all month you collect enough clicks and goals to see which ad actually works. The Engine Room and conversion tracking show you the winner, and next month's fuel goes behind it instead of guessing.</p></div>
<div class="rg-box"><h3 style="margin:0 0 6px">Fresh creative every month</h3><p>The Refuel Kit gives you new banners with your name and QR code each month, so the same audience sees something new instead of tuning out the ad they've already passed ten times.</p></div>
<div class="rg-box"><h3 style="margin:0 0 6px">Each month buys more</h3><p>The bonus climbs the longer you keep the streak, so the same package delivers more ads in month four than in month one. Refuel both sites and it climbs faster.</p></div>
</div>
<p style="margin:14px 0 30px;font-size:15px;color:var(--muted)">The bonus isn't the point. It just makes the habit cheaper. The point is that your offer never goes dark.</p>
<p class="rg-eye">The flow</p>
<h2>What happens when you buy a package</h2>
<div class="rg-legend">
<span><i style="background:rgba(67,232,195,.15);border-color:#43e8c3"></i>Streak moves forward</span>
<span><i style="background:rgba(255,178,56,.18);border-color:#ffb238"></i>Bonus boost</span>
<span><i style="background:rgba(139,166,156,.12);border-color:#8ba69c"></i>No refuel bonus</span>
<span><i style="border-style:dashed;border-color:#eef7f3"></i>A question</span>
</div>
<ol class="rg-flow" aria-label="Refuel flow, step by step">
<li><div class="rg-n start"><b><span class="k">1</span>You buy a new ad package on either site</b>InstantAdPay or LinkSpin, paid from your own wallet.</div></li>
<li>
<div class="rg-n ask"><b><span class="k">2</span>Does it meet that site's minimum?</b>InstantAdPay package: $20 or more. LinkSpin package: $25 or more. Bought by you or one of your own linked positions.</div>
<div class="rg-br">
<div class="rg-b"><span class="rg-e">No</span><div class="rg-n stop"><b>Normal purchase</b>No refuel bonus.</div></div>
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n go"><b>Keep going</b><span class="to">down to the next question</span></div></div>
</div>
</li>
<li>
<div class="rg-n ask"><b><span class="k">3</span>Are you already on a streak?</b></div>
<div class="rg-br">
<div class="rg-b"><span class="rg-e">No: your first refuel, or your streak ended</span><div class="rg-n go"><b>Streak starts at month 1</b>Today becomes your refuel day. Your very first one also earns the Engine Started badge.<span class="to">then step 5</span></div></div>
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n go"><b>Keep going</b><span class="to">down to the next question</span></div></div>
</div>
</li>
<li>
<div class="rg-n ask"><b><span class="k">4</span>When is it, against your refuel day?</b></div>
<div class="rg-br">
<div class="rg-b"><span class="rg-e">Inside the window: 5 days before to 5 days after</span><div class="rg-n go"><b>Counted refuel</b>Your streak moves up a month.<span class="to">then step 5</span></div></div>
<div class="rg-b"><span class="rg-e">After the 5-day grace</span>
<div class="rg-n ask"><b>Free miss left in the last 365 days?</b></div>
<div class="rg-br">
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n go"><b>Streak kept</b>This package counts as your next month.<span class="to">then step 5</span></div></div>
<div class="rg-b"><span class="rg-e">No</span><div class="rg-n go"><b>Streak starts over at month 1</b>Today becomes your new refuel day.<span class="to">then step 5</span></div></div>
</div>
</div>
<div class="rg-b"><span class="rg-e">More than 5 days before</span>
<div class="rg-n ask"><b>Already refueled on this site this cycle?</b></div>
<div class="rg-br">
<div class="rg-b"><span class="rg-e">No</span><div class="rg-n fuel"><b>Second engine</b>This is the other site's refuel for the same cycle: both-engines rate here, and the first site is topped up to match (step 6). Your refuel day stays put.</div></div>
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n fuel"><b>Pit Stop</b>Half your current rate, once per site per cycle. Not a refuel, so your refuel day stays put. A second top-up on the same site is a normal purchase.</div></div>
</div>
</div>
</div>
</li>
<li><div class="rg-n go"><b><span class="k">5</span>Bonus credits land at your month's rate</b>One engine: +10% in month 1, +15% in month 2, +20% in month 3, +25% from month 4. Added on the site where you bought.</div></li>
<li>
<div class="rg-n ask"><b><span class="k">6</span>Later this cycle: refuel the other site too, before your next window opens?</b></div>
<div class="rg-br">
<div class="rg-b"><span class="rg-e">Yes: both engines</span><div class="rg-n fuel"><b>Higher rate on both sites</b>+15%, +20%, +30%, then +40% from month 4. The first site is topped up to match. From month 4 you also get 100 Featured bonus credits on InstantAdPay.</div></div>
<div class="rg-b"><span class="rg-e">No: one engine</span><div class="rg-n go"><b>One-engine rate</b>Your streak still counts. Either site keeps it going.</div></div>
</div>
</li>
<li><div class="rg-n go"><b><span class="k">7</span>This month's Refuel Kit unlocks</b>Badges at 3, 6 and 12 months in a row.</div></li>
<li><div class="rg-n go"><b><span class="k">8</span>Next refuel day = 30 days after this one</b>Reminders 5 days before, on the day, and a last call at the end of your grace. Then it is back to step 1 next month.</div></li>
</ol>
<p class="rg-eye">The numbers</p>
<h2>The bonus climbs</h2>
<div class="rg-tbl"><table>
<thead><tr><th>Months in a row</th><th class="n">One engine</th><th class="n">Both engines</th></tr></thead>
<tbody>
<tr><td>Month 1</td><td class="n">+10%</td><td class="n both">+15%</td></tr>
<tr><td>Month 2</td><td class="n">+15%</td><td class="n both">+20%</td></tr>
<tr><td>Month 3</td><td class="n">+20%</td><td class="n both">+30%</td></tr>
<tr><td>Month 4 and on</td><td class="n">+25%</td><td class="n both">+40% each</td></tr>
</tbody>
</table></div>
<p class="rg-note">A percent of the package's credits, added as bonus ad credits on the site where you bought. One engine means you refueled one site this cycle; both engines means InstantAdPay and LinkSpin in the same cycle. From month 4 with both engines you also get 100 Featured bonus credits on InstantAdPay. A Pit Stop pays half your current rate. The refuel bonus is its own grant, so it stacks on Five Dollar Friday (+20% on $5+ packages) and Wired Wednesday (+25% on $20+ packages). Bonus credits buy ad delivery only. They are never cash.</p>
<p class="rg-eye">Member guide</p>
<h2>Your route, step by step</h2>
<ol class="rg-route">
<li><div>
<h3>Start your engine</h3>
<p>Buy a new package of $20 or more here, or $25 or more on LinkSpin. Today becomes your refuel day, your first bonus lands right away, and you earn the Engine Started badge. Buying from one of your linked positions counts too, and so do Game Pass packages of $20 or more.</p>
<div class="rg-where"><span class="rg-chip">InstantAdPay: Buy packages</span><span class="rg-chip ls">LinkSpin: Credits</span></div>
</div></li>
<li><div>
<h3>Find your Refuel card</h3>
<p>It shows your refuel day, your streak month, the bonus your next refuel earns, which sites you refueled this cycle, and whether your Pit Stop is still open.</p>
<div class="rg-where"><span class="rg-chip">InstantAdPay: Overview</span><span class="rg-chip ls">LinkSpin: Credits and Ads</span></div>
</div></li>
<li><div>
<h3>Put this month's Refuel Kit to work</h3>
<p>Your refuel unlocks the month's members-only banners in five sizes (728x90, 468x60, 300x250, 160x600 and 1200x630 for social posts) with your @name and a QR code to your own link. Tap Make mine, then send one straight into an InstantAdPay banner campaign, or load the set into your Banner Spin on LinkSpin. From a 3-month streak you also get an animated version. Kits you unlock stay yours after the month ends.</p>
<div class="rg-where"><span class="rg-chip">InstantAdPay: Promo tools</span><span class="rg-chip ls">LinkSpin: Ads</span></div>
</div></li>
<li><div>
<h3>Check the Engine Room</h3>
<p>Your first refuel opens it. Three dials: fuel left across both sites, clicks this week against last week, and goals this month against a goal you set. Warning lights flag ads running low or out, a refuel day coming, or a login slot opening. Then press the one next-move button.</p>
<div class="rg-where"><span class="rg-chip">InstantAdPay: Engine Room tab</span><span class="rg-chip ls">LinkSpin: top of Ads</span></div>
</div></li>
<li><div>
<h3>Refuel inside your window every month</h3>
<p>The window opens 5 days before your refuel day and stays open 5 days after it (Central time). You get an email and an on-site notice 5 days before, on the day, and a last call. Your next refuel day is 30 days after the day you actually refuel, so it moves with you.</p>
</div></li>
<li><div>
<h3>Light up the second engine</h3>
<p>Refuel on both sites in the same cycle and both get the higher rate. Buy on one site, then the other, in either order, before your next window opens. The first site is topped up automatically to match.</p>
<div class="rg-where"><span class="rg-chip">InstantAdPay $20+</span><span class="rg-chip ls">LinkSpin $25+</span></div>
</div></li>
<li><div>
<h3>Running low early? Take a Pit Stop</h3>
<p>Another package on a site you already refueled this cycle, bought before your window opens, is a Pit Stop: half your current rate, once per site per cycle. It keeps your ads running. Your monthly refuel is still due on your refuel day.</p>
</div></li>
</ol>
<div class="rg-two">
<div class="rg-box">
<h3>If you miss a month</h3>
<p>You get one free miss in any 365 days. Miss your window once and the streak holds: your next qualifying package counts as the next month. Miss again inside the year and the streak starts over at month 1, with a new refuel day.</p>
</div>
<div class="rg-box">
<h3>What counts and what doesn't</h3>
<p>Counts: a new package at or above the minimum, bought by you or one of your own linked positions, Game Pass packages included. Doesn't count: smaller packages, or credits you earned by viewing ads.</p>
</div>
</div>
<div class="rg-coach">
<h3>For leaders: how to coach it</h3>
<ul>
<li>When someone in your line buys their first package, help them pick a refuel day they can keep every month.</li>
<li>Show them the Refuel card and the Engine Room on day one, so they know where to look.</li>
<li>Teach both engines. One package on each site per cycle earns the higher rate on both.</li>
<li>Use your own Refuel Kit in a live campaign, so they see it working before they try it.</li>
<li>Repeat ad spend keeps every level of your line active, so this is the habit to build.</li>
</ul>
</div>
<p class="rg-eye">Quick answers</p>
<h2>Questions members ask</h2>
<dl class="rg-faq">
<div><dt>Do I have to use both sites?</dt><dd>No. Either site keeps your streak going at the one-engine rate. Refueling both in the same cycle earns the bigger bonus on both.</dd></div>
<div><dt>Is the bonus cash?</dt><dd>No. Bonus credits are purchased-grade ad credits that run on any format, login ads included. They show in your credit log by name.</dd></div>
<div><dt>Does the bonus stack with Friday and Wednesday?</dt><dd>Yes. They are separate grants, so a Friday refuel gets both.</dd></div>
<div><dt>I refueled early. Did I lose my place?</dt><dd>Inside the 5-day window it counts as your refuel and your next date moves to 30 days after it. Earlier than that it is a Pit Stop (or your second engine, if it is the other site's first package this cycle), and your refuel day stays put.</dd></div>
<div><dt>When does the Refuel Kit change?</dt><dd>Each month gets its own kit. A counted refuel unlocks that month's kit, and kits you unlocked stay yours.</dd></div>
<div><dt>Is anything billed automatically?</dt><dd>No. You choose every package. Nothing renews on its own.</dd></div>
</dl>
<div class="rg-rule"><b>What a credit is.</b> One credit is one cent of ad delivery across the network. Credits are not money and cannot be withdrawn. Fuel Your Offers runs on InstantAdPay and LinkSpin.</div>
<p class="muted small" style="margin-top:10px">No income is guaranteed. Any commissions depend on real purchases in your line and on your own effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.</p>
<footer>
<div>InstantAdPay · <a href="/">Home</a> · <a href="/friday">Five Dollar Friday</a> · <a href="/wednesday">Wired Wednesday</a> · <a href="/earning">How earning works</a> · <a href="https://linkspin.app/refuel">The LinkSpin side</a></div>
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261023ov"></script>
</body>
</html>
+1 -1
View File
@@ -37,6 +37,6 @@ a.rf-open{color:#8FF0FF;font-size:12px}
<button class="rf-btn" id="rfDone" type="button" disabled>Waiting…</button>
<button class="rf-btn ghost" id="rfBack" type="button" hidden>Back to the game</button>
</div>
<script src="/assets/refuel.js?v=20261004sw"></script>
<script src="/assets/refuel.js?v=20261028td"></script>
</body>
</html>
+27
View File
@@ -0,0 +1,27 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Support | InstantAdPay</title>
<meta name="description" content="Ask InstantAdPay for help: send a support ticket and get a reply by email. Members can also use Help in the dashboard.">
<meta name="theme-color" content="#043b2f">
<link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=20260910h">
</head>
<body>
<section><div class="wrap" style="max-width:720px">
<div class="sectionhead" style="text-align:left">
<p class="eyebrow">Support</p>
<h2>Ask for <em>help</em></h2>
<p class="muted small">Tell us what is going on and Marty will reply by email. Members can also open <a href="/my#help">Help in the dashboard</a>, and you can email <a href="mailto:support@instantadpay.com">support@instantadpay.com</a>. Quick answers to common questions are in the chat bubble and on the <a href="/facts">platform facts</a> page.</p>
</div>
<div id="supMain"><div class="card"><p class="muted small">Loading…</p></div></div>
<p class="small muted">We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.</p>
</div></section>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/legal.js?v=20260908a"></script>
<script src="/assets/support.js?v=20261016a"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+2 -2
View File
@@ -35,10 +35,10 @@
<p class="muted small">To the fullest extent permitted by law, InstantAdPay and its operators are not liable for indirect, incidental, or consequential damages, or for losses arising from crypto volatility, irreversible transactions, third-party sites, or your own decisions.</p>
<h3>10. Changes and termination</h3>
<p class="muted small">We may update these Terms and the Platform, and continued use means you accept the changes. We may discontinue features. The immutable contract's rules cannot be changed by anyone, including us.</p>
<p class="muted small" style="margin-top:18px">See also the <a href="/disclaimer">Disclaimer</a> and <a href="/privacy">Privacy Policy</a>.</p>
<p class="muted small" style="margin-top:18px">See also the <a href="/disclaimer">Disclaimer</a> and <a href="/privacy">Privacy Policy</a>. Questions: the <a href="/support">support page</a> or <a href="mailto:support@instantadpay.com">support@instantadpay.com</a>.</p>
</div>
</div></section>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+1 -1
View File
@@ -34,7 +34,7 @@
<p><a href="/ledger">← Back to the live ledger</a> · <a href="/contract">Read the contract review</a></p>
</div>
</section>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/tx.js?v=20260906m"></script>
</body>
</html>
+1 -1
View File
@@ -47,7 +47,7 @@
</div>
</div>
</section>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/wall.js?v=20260911v"></script>
</body>
</html>
+1 -1
View File
@@ -122,7 +122,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/wallets.js?v=20260911b"></script>
</body>
</html>
+1 -1
View File
@@ -64,6 +64,6 @@
</footer>
</div>
<script src="/assets/wednesday.js?v=20260929c"></script>
<script src="/assets/common.js?v=20261015a"></script>
<script src="/assets/common.js?v=20261023ov"></script>
</body>
</html>
+5 -2
View File
@@ -76,7 +76,8 @@ const WANT = {
PIF: /PIF is a gift/,
PRICE: /Five packages, priced/,
EARN: /Every package splits the same way/,
TANK: /The holding tank is where free members/
TANK: /The holding tank is where free members/,
GAMEPOL: /Game POL is paid to the wallet linked/
};
const ROUTES = [
['PIF', 'should I pif someone from the holding tank'], ['PIF', 'what is pif'],
@@ -89,7 +90,9 @@ const ROUTES = [
['PRICE', 'how much does it cost'],
['EARN', 'how much do I earn'], ['EARN', 'how much can i make'],
['EARN', 'what will i get paid'], ['EARN', 'what is the commission'],
['TANK', 'how does the holding tank work'], ['TANK', 'can I adopt someone from the tank']
['TANK', 'how does the holding tank work'], ['TANK', 'can I adopt someone from the tank'],
['GAMEPOL', 'my gem kingdom pol was never sent'], ['GAMEPOL', 'it says 1.50 POL is waiting for your wallet'],
['GAMEPOL', 'do I need to switch on payouts to get my game pol']
];
for (const [want, q] of ROUTES) {
const reply = await ask(q);
+11 -3
View File
@@ -1,6 +1,10 @@
// Chatbot knowledge guard (Marty, 2026-09-16: "ensure the chatbot is completely current, and keep it that way").
// Compares chatbot.js KNOWLEDGE_DATE with the newest public release note. If a note is newer, the
// chatbot was not brought up to date with that change: fix chatbot.js (canned + prompt), bump the date.
// Since the knowledge base (2026-10-20, kb.js) the assistant also answers from Admin > Knowledge base, so a
// KB change made after a release counts too: the guard takes the later of KNOWLEDGE_DATE and the site's
// newest KB edit by a person (/api/chat/kb-stamp, a Central-time day; seed refreshes from the code do not count). Either way a release must be followed by a
// knowledge update, in the code or in the admin pane.
// node qa/chatbot-sync.mjs (checks the live site's /api/releases)
// LOCAL=http://127.0.0.1:8796 node qa/chatbot-sync.mjs
import fs from 'node:fs';
@@ -8,14 +12,18 @@ const B = process.env.LOCAL || 'https://instantadpay.com';
const src = fs.readFileSync(new URL('../chatbot.js', import.meta.url), 'utf8');
const m = /KNOWLEDGE_DATE = '(\d{4}-\d{2}-\d{2})'/.exec(src);
if (!m) { console.log('[bug] chatbot.js has no KNOWLEDGE_DATE constant'); process.exit(1); }
const known = m[1];
let known = m[1], via = 'chatbot.js KNOWLEDGE_DATE';
try {
const st = await (await fetch(B + '/api/chat/kb-stamp')).json();
if (st && /^\d{4}-\d{2}-\d{2}$/.test(st.updated || '') && st.updated > known) { known = st.updated; via = 'knowledge base (' + st.count + ' entries)'; }
} catch (e) { console.log('[warn] no knowledge-base stamp from ' + B + ' (' + e.message + '), using KNOWLEDGE_DATE only'); }
let notes = [];
try { const r = await (await fetch(B + '/api/releases')).json(); notes = r.notes || []; } catch (e) { console.log('[warn] could not read ' + B + '/api/releases: ' + e.message); process.exit(0); }
const newer = notes.filter(n => (n.date || '') > known);
if (newer.length) {
console.log('[bug] chatbot knowledge date ' + known + ' is older than ' + newer.length + ' release note(s):');
for (const n of newer) console.log(' ' + n.date + ' ' + n.title);
console.log(' -> update chatbot.js (canned answers + systemPrompt) for each, then bump KNOWLEDGE_DATE.');
console.log(' -> update chatbot.js (canned answers + systemPrompt) or the entries in Admin > Knowledge base for each, then bump KNOWLEDGE_DATE.');
process.exit(1);
}
console.log('chatbot knowledge date ' + known + ' covers all ' + notes.length + ' release notes (newest ' + (notes[0] ? notes[0].date : 'none') + ')');
console.log('chatbot knowledge date ' + known + ' (' + via + ') covers all ' + notes.length + ' release notes (newest ' + (notes[0] ? notes[0].date : 'none') + ')');
+259
View File
@@ -0,0 +1,259 @@
// Conversion pixel, InstantAdPay half (2026-10-23), end to end against a LOCAL copy and a MOCK LinkSpin.
// node qa/convpixel.test.mjs (or: bash qa/run.sh convpixel)
// Boots server.js on its own port with a throwaway DATA_DIR seeded with two advertisers and a few campaigns (JSON store,
// DATABASE_URL blank, no mail key, devCode sign-in, a minimal environment so no live secret can leak in), LS_URL pointing at a
// mock LinkSpin on localhost that verifies the HMAC on every call, records the pushed clicks and answers op summary.
// Nothing touches production or a real member. Checks: lsclk on the 302 (existing params and #hash kept, a LinkSpin /r/ link
// gets it, an existing lsclk is never replaced, an unparsable target goes out unchanged), the click rows pushed with a valid
// signature and the contract fields, the owner's own click flagged self=1 and not counted, the proxies, the Campaigns pane
// showing goals and cost per goal (300 credits / 4 = 75), LinkSpin down: pane still loads, panel says so, rows kept and
// pushed once it is back. 2026-10-26: own soft keys pushed as owners and an own-browser click flagged self (billing
// unchanged), Send a test conversion loads the real pixel in test mode (routed in the browser, nothing leaves the machine)
// with the partner call as fallback, the own-click test count on the card, cost per goal (30 days) from the credit log.
// Exit code 1 on any failure.
import http from 'node:http';
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { pathToFileURL, fileURLToPath } from 'node:url';
const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const PORT = Number(process.env.CONV_PORT || 8831), MPORT = PORT + 1;
const B = 'http://127.0.0.1:' + PORT, MOCK = 'http://127.0.0.1:' + MPORT;
const SECRET = 'qa-convpixel-' + crypto.randomBytes(24).toString('hex'); // throwaway, 32+ chars
const ADMIN = 'localtest';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-conv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const OUT = path.join(SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (!cond && extra ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 15000)) { try { const v = await fn(); if (v) return v; } catch (e) {} await sleep(400); } return null; }
// ---- seed: two advertisers, campaigns with every target shape ----
const now = Date.now();
const acct = (email, username, code) => ({ email, pass: null, sponsorRef: '', code, username, address: null, created: now - 5 * 86400000, lastSeen: now - 3600000, memberId: 0 });
const A1 = 'qa-adv@example.com', A2 = 'qa-adv2@example.com';
{ const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} };
for (const a of [acct(A1, 'qaadv', 'cqaadv1'), acct(A2, 'qaadvtwo', 'cqaadv2')]) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; }
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(db)); }
const camp = (id, owner, name, targetUrl, spent) => ({ id, owner, memberId: 0, type: 'banner', name, targetUrl, imageUrl: 'https://example.com/b.png', title: null, body: null,
budget: 1000, spent, accrued: 0, imps: 50, clicks: 0, batchImps: 0, width: 468, height: 60, status: 'paused', created: now - 86400000 });
const T1 = 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world#top';
const CAMPS = [camp(1, A1, 'QA landing', T1, 300), camp(2, A1, 'QA spin link', 'https://linkspin.app/r/abc12', 120),
camp(3, A1, 'QA has lsclk', 'https://adv.example/p?lsclk=keepme', 0), camp(4, A1, 'QA odd target', 'adv.example/no-scheme', 0), camp(5, A2, 'QA other', 'https://other.example/', 50),
Object.assign(camp(6, A1, 'QA old no log', 'https://adv.example/old', 500), { created: now - 60 * 86400000 }), Object.assign(camp(7, A1, 'QA new no log', 'https://adv.example/new', 90), { created: now - 3 * 86400000 })];
// cost per goal (30 days): campaign 1 spent 150 today + 50 five days ago inside the window, 100 forty days ago outside it
const ctd = t => new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const cl = (t, delta, ref) => ({ email: A1, ts: t, day: ctd(t), delta, kind: 'delivery', note: 'Ad views: QA landing', ref: String(ref) });
fs.writeFileSync(path.join(DATA, 'credit-log.json'), JSON.stringify({ items: [cl(now - 40 * 86400000, -100, 1), cl(now - 5 * 86400000, -50, 1), cl(now - 60000, -150, 1), Object.assign(cl(now - 60000, -999, 1), { email: A2 })] }));
fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 6, campaigns: CAMPS, burnsPending: [] }));
// ---- mock LinkSpin ----
const PX1 = 'px0123456789', PX2 = 'pxabcdef0123';
const mock = { clicks: new Map(), owners: [], badSig: 0, calls: [], down: false, goals: { [A1]: [{ px: PX1, name: 'subscriber', value: null, created: now - 86400000, conv: 6, convDays: 30, lastAt: now - 3600000, lastTest: null }, { px: PX2, name: 'sale', value: 19.95, created: now - 86400000, conv: 1, convDays: 30, lastAt: now - 7200000, lastTest: null }] } };
const verify = (ts, sig, raw) => { if (!ts || !sig || Math.abs(Date.now() - Number(ts)) > 300000) return false; const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex'); return want.length === String(sig).length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(String(sig))); };
const send = (res, code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); };
function mockHandler(req, res) {
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
if (mock.down) { res.writeHead(503); return res.end('down'); }
if (req.method !== 'POST') return send(res, 404, { error: 'not found' });
if (!verify(req.headers['x-ls-ts'], req.headers['x-ls-sig'], raw)) { mock.badSig++; return send(res, 401, { error: 'bad signature' }); }
const b = JSON.parse(raw || '{}');
if (req.url === '/api/partner/clicks') { for (const c of b.clicks || []) mock.clicks.set(c.id, c); for (const o of b.owners || []) mock.owners.push(o); return send(res, 200, { ok: true, n: (b.clicks || []).length, owners: (b.owners || []).length }); }
if (req.url === '/api/partner/conv') {
mock.calls.push(b); const email = String(b.email || '');
const goals = mock.goals[email] || (mock.goals[email] = []);
if (b.op === 'summary') return send(res, 200, { ok: true, goals, byCampaign: email === A1 ? { 1: { clicks: 9, conv: { [PX1]: 4, [PX2]: 1 }, value: { [PX2]: 19.95 } }, 2: { clicks: 3, conv: {} }, 6: { clicks: 4, conv: { [PX1]: 2 } }, 7: { clicks: 5, conv: { [PX1]: 3 } } } : {}, methods: { url: 2, stored: 2, cookie: 1, soft: 1 }, selfTests: email === A1 ? 3 : 0, host: 'linkspin.app' });
if (b.op === 'create') { const g = { px: 'px' + crypto.randomBytes(5).toString('hex'), name: b.name, value: b.value == null ? null : b.value, created: Date.now(), conv: 0, convDays: 30, lastAt: null, lastTest: null }; goals.push(g); return send(res, 200, { ok: true, goal: g }); }
if (b.op === 'remove') { const i = goals.findIndex(g => g.px === b.px); if (i < 0) return send(res, 404, { error: 'No such goal.' }); goals.splice(i, 1); return send(res, 200, { ok: true }); }
if (b.op === 'test') { const g = goals.find(x => x.px === b.px); if (!g) return send(res, 404, { error: 'No such goal.' }); g.lastTest = Date.now(); return send(res, 200, { ok: true, at: g.lastTest }); }
return send(res, 400, { error: 'unknown op' });
}
return send(res, 404, { error: 'not found' }); // registry sync and anything else: ignored
});
}
let mockSrv = http.createServer(mockHandler); await new Promise(r => mockSrv.listen(MPORT, '127.0.0.1', r));
// ---- the local copy, minimal environment (no live secrets can ride along) ----
const ENV = {};
for (const k of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'windir']) if (process.env[k]) ENV[k] = process.env[k];
Object.assign(ENV, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, DATABASE_URL: '', LS_SYNC_SECRET: SECRET, LS_URL: MOCK });
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env: ENV, stdio: ['ignore', 'pipe', 'pipe'] });
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
let browser = null;
const cleanup = async () => { try { if (browser) await browser.close(); } catch (e) {} try { srv.kill(); } catch (e) {} try { mockSrv.close(); } catch (e) {} await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
try {
const up = await waitFor(async () => (await fetch(B + '/api/config')).ok, 30000);
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
const api = async (p, body, hdr) => { const r = await fetch(B + p, { method: body ? 'POST' : 'GET', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: body ? JSON.stringify(body) : undefined }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
const click = async (id, hdr) => { const r = await fetch(B + '/api/ads/click/' + id, { redirect: 'manual', headers: Object.assign({ 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148', Referer: 'https://instantadpay.com/ledger?secret=1' }, hdr || {}) }); return { status: r.status, loc: r.headers.get('location') }; };
async function signIn(email) {
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000, fage: 5000 });
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
return (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
}
const ID = /lsclk=(i[0-9a-f]{11})(?=$|[&#])/;
// 1. click ids on the redirect
const c1 = await click(1);
const id1 = (ID.exec(c1.loc || '') || [])[1];
ok(c1.status === 302 && !!id1, 'click -> 302 with lsclk=i+11 hex', c1.status + ' ' + c1.loc);
ok(c1.loc === 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world&lsclk=' + id1 + '#top', 'existing params kept byte for byte, lsclk before the #hash', c1.loc);
const c2 = await click(2); const id2 = (ID.exec(c2.loc || '') || [])[1];
ok(!!id2 && c2.loc === 'https://linkspin.app/r/abc12?lsclk=' + id2, 'a LinkSpin /r/ spin link gets lsclk', c2.loc);
const c3 = await click(3);
ok(c3.loc === 'https://adv.example/p?lsclk=keepme', 'an existing lsclk is never replaced', c3.loc);
const c4 = await click(4);
ok(c4.status === 302 && c4.loc === 'adv.example/no-scheme', 'an unparsable target redirects unchanged', c4.status + ' ' + c4.loc);
const c1b = await click(1); const id1b = (ID.exec(c1b.loc || '') || [])[1];
ok(id1b && id1b !== id1, 'every click gets its own id');
// 2. pushed to the mock, signed, with the contract fields
const got = await waitFor(() => mock.clicks.has(id1) && mock.clicks.has(id2) && mock.clicks.has(id1b), 15000);
ok(!!got, 'click rows pushed to LinkSpin /api/partner/clicks within ~3 s', [...mock.clicks.keys()].join(','));
ok(mock.badSig === 0, 'every push carried a valid HMAC signature', 'bad: ' + mock.badSig);
const r1 = mock.clicks.get(id1) || {};
ok(r1.camp === 1 && r1.cname === 'QA landing' && r1.type === 'banner' && r1.owner === A1, 'row: camp, cname, type, owner', JSON.stringify(r1));
ok(r1.spent === 300 && r1.self === 0 && r1.target === T1, 'row: spent 300, self 0, target', JSON.stringify(r1));
ok(/^s:[0-9a-f]{20}$/.test(r1.sk || '') && r1.dv === 'mobile' && r1.pl === 'instantadpay.com/ledger' && Math.abs(r1.ts - Date.now()) < 120000, 'row: soft key, device, placement (query dropped), ts', JSON.stringify(r1));
const ip = '127.0.0.1', ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148';
const sks = ['s:' + crypto.createHash('sha256').update(ip + '|' + ua).digest('hex').slice(0, 20), 's:' + crypto.createHash('sha256').update('::ffff:127.0.0.1|' + ua).digest('hex').slice(0, 20)];
ok(sks.includes(r1.sk), 'soft key = sha256(ip|ua) first 20 hex, no raw IP in the row', r1.sk);
ok(!JSON.stringify([...mock.clicks.values()]).includes('127.0.0.1'), 'no raw IP anywhere in the pushed rows');
ok(!mock.clicks.has('keepme') && [...mock.clicks.values()].filter(r => r.camp === 3).length === 1, 'the click on the lsclk target is still recorded (its own id), the URL untouched');
// 3. the owner's own click: still an id, flagged self, not counted as a click
const ck1 = await signIn(A1);
const before = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
const clicksBefore = ((before && before.campaigns) || []).find(c => c.id === 1);
const own = await click(1, { Cookie: ck1 }); const idOwn = (ID.exec(own.loc || '') || [])[1];
ok(!!idOwn, 'own click still gets a click id (so the owner can test)', own.loc);
ok(!!(await waitFor(() => mock.clicks.get(idOwn), 10000)) && mock.clicks.get(idOwn).self === 1, 'own click pushed with self=1', JSON.stringify(mock.clicks.get(idOwn)));
const after = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
const clicksAfter = ((after && after.campaigns) || []).find(c => c.id === 1);
ok(clicksBefore && clicksAfter && clicksAfter.clicks === clicksBefore.clicks && clicksBefore.clicks === 2, 'own click not counted (clicks stay 2)', JSON.stringify([clicksBefore && clicksBefore.clicks, clicksAfter && clicksAfter.clicks]));
// fix 1 (2026-10-26): the soft keys the owner signs in from go to LinkSpin as owners; a click from that browser while
// signed out is flagged self for conversions (billing unchanged: it is still a counted click)
const skNode = ['127.0.0.1', '::ffff:127.0.0.1'].map(x => 's:' + crypto.createHash('sha256').update(x + '|node').digest('hex').slice(0, 20));
ok(!!(await waitFor(() => mock.owners.some(o => o.owner === A1 && skNode.includes(o.sk)), 10000)), "owner's session soft key pushed to LinkSpin as owners (no raw IP)", JSON.stringify(mock.owners));
ok(!JSON.stringify(mock.owners).includes('127.0.0.1'), 'no raw IP in the owners rows');
const ownSk = await click(1, { 'User-Agent': 'node' }); const idOwnSk = (ID.exec(ownSk.loc || '') || [])[1];
ok(!!(await waitFor(() => mock.clicks.get(idOwnSk), 10000)) && mock.clicks.get(idOwnSk).self === 1, "a click from the owner's own browser, signed out, is pushed self=1", JSON.stringify(mock.clicks.get(idOwnSk)));
const strangerC = await click(1, { 'User-Agent': 'Mozilla/5.0 Stranger QA' }); const idStr = (ID.exec(strangerC.loc || '') || [])[1];
ok(!!(await waitFor(() => mock.clicks.get(idStr), 10000)) && mock.clicks.get(idStr).self === 0, "a stranger's click is still self=0");
const nOwners = mock.owners.length; await api('/api/my/campaigns', null, { Cookie: ck1 }); await sleep(3500);
ok(mock.owners.length === nOwners, 'the same session soft key is not pushed again within 6 h');
// 4. proxies
const sum = await api('/api/my/conversions', null, { Cookie: ck1 });
ok(sum.j && sum.j.ok === true && sum.j.goals.length === 2 && sum.j.byCampaign['1'].conv[PX1] === 4, 'GET /api/my/conversions relays the LinkSpin summary', JSON.stringify(sum.j).slice(0, 200));
ok(sum.j && sum.j.spend30 && sum.j.spend30['1'] === 200 && sum.j.spend30['6'] == null && sum.j.spend30['7'] == null && sum.j.spendSince > Date.now() - 31 * 86400000, 'spend30 from the credit log: campaign 1 = 150 + 50 inside the 30 days (the 100 from 40 days ago and another member\'s row left out)', JSON.stringify(sum.j && sum.j.spend30));
const lastSum = mock.calls.filter(c => c.op === 'summary').pop();
ok(lastSum && lastSum.email === A1 && lastSum.days === 30, 'summary asked for the signed-in email, 30 days', JSON.stringify(lastSum));
const nSum = mock.calls.filter(c => c.op === 'summary').length; await api('/api/my/conversions', null, { Cookie: ck1 });
ok(mock.calls.filter(c => c.op === 'summary').length === nSum, 'summary cached (second call within 60 s does not hit LinkSpin)');
ok((await api('/api/my/conversions')).status === 401, 'signed out: 401');
const bad = await api('/api/my/conversions/goal', { op: 'create', name: ' ' }, { Cookie: ck1 });
ok(bad.status === 400, 'create without a name refused locally');
const cr = await api('/api/my/conversions/goal', { op: 'create', name: 'Free Report', value: '7.5' }, { Cookie: ck1 });
ok(cr.j && cr.j.ok && cr.j.goal && /^px[0-9a-f]{10}$/.test(cr.j.goal.px) && cr.j.goal.name === 'free-report' && cr.j.goal.value === 7.5, 'create relays op create (name normalized, value number)', JSON.stringify(cr.j));
const ts = await api('/api/my/conversions/test', { px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
ok(ts.j && ts.j.ok && ts.j.at, 'test relays op test', JSON.stringify(ts.j));
const rm = await api('/api/my/conversions/goal', { op: 'remove', px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
ok(rm.j && rm.j.ok, 'remove relays op remove');
const rm2 = await api('/api/my/conversions/goal', { op: 'remove', px: 'px9999999999' }, { Cookie: ck1 });
ok(rm2.status === 400 && rm2.j && rm2.j.error === 'No such goal.', 'LinkSpin plain-words error passed through as 400', JSON.stringify(rm2));
ok(mock.calls.every(c => c.email === A1), 'every conv call carried only the signed-in email');
// 5. the Campaigns pane in a real browser
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
browser = await chromium.launch();
async function pane(cookie, shot) {
const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } });
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
const [k, v] = cookie.split(';')[0].split('='); await ctx.addCookies([{ name: k, value: v, url: B }]);
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
await page.goto(B + '/my', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); });
await page.click('.bo-menu [data-pane="campaigns"]'); await page.waitForTimeout(2500);
const st = await page.evaluate(() => ({
rows: document.querySelectorAll('#campList .camp-table tbody tr').length,
line1: (document.querySelector('[data-convcamp="1"]') || {}).textContent || '', line1Hidden: !!(document.querySelector('[data-convcamp="1"]') || {}).hidden,
line5Hidden: (document.querySelector('[data-convcamp="5"]') || { hidden: true }).hidden,
line6: (document.querySelector('[data-convcamp="6"]') || {}).textContent || '', line7: (document.querySelector('[data-convcamp="7"]') || {}).textContent || '', title1: (document.querySelector('[data-convcamp="1"]') || {}).title || '',
card: !document.getElementById('convCard').hidden, status: document.getElementById('convStatus').textContent,
goals: document.querySelectorAll('#convGoals tbody tr').length, convCells: [...document.querySelectorAll('#convGoals td[data-l="Conversions (30 days)"]')].map(td => (td.firstChild && td.firstChild.textContent || '').trim()), landing: (document.getElementById('convLanding') || {}).value || '', img: (document.getElementById('convImg') || {}).value || '',
js: (document.getElementById('convJs') || {}).value || '', tip: document.getElementById('convCard').textContent }));
await page.screenshot({ path: path.join(OUT, shot), fullPage: true }).catch(() => {});
await ctx.close(); return { st, errs };
}
const p1 = await pane(ck1, 'convpixel-pane.png');
ok(p1.st.rows >= 4 && p1.st.card, 'Campaigns pane loads with the Conversion tracking card', JSON.stringify(p1.st).slice(0, 200));
ok(!p1.st.line1Hidden && /cost per goal \(30 days\)/.test(p1.st.line1) && /subscriber 4 \(50 credits each\)/.test(p1.st.line1) && /sale 1 \(200 credits each\)/.test(p1.st.line1), 'campaign row: cost per goal (30 days) = 200 credits spent in the 30 days / 4 = 50 (not lifetime 300 / 4 = 75)', p1.st.line1);
ok(/same 30 days/.test(p1.st.title1), 'its tooltip says the spend is the same 30 days', p1.st.title1);
ok(/subscriber 2/.test(p1.st.line6) && !/credits each/.test(p1.st.line6) && /no spend on record/.test(p1.st.line6), 'an older campaign with no spend in the log shows no cost per goal rather than a lifetime figure', p1.st.line6);
ok(/subscriber 3 \(30 credits each\)/.test(p1.st.line7), 'a campaign started inside the window with no log rows uses its spend since start (90 / 3 = 30)', p1.st.line7);
ok(/3 from your own clicks, kept as tests/.test(p1.st.status), 'card shows the own-click test count (selfTests from LinkSpin)', p1.st.status);
ok(!/\$/.test(p1.st.line1), 'cost per goal is in credits, never dollars');
ok(JSON.stringify(p1.st.convCells) === '["6","1"]', 'goal rows show the conversion count, not the 30-day window (convDays is the window length)', JSON.stringify(p1.st.convCells));
ok(p1.st.goals === 2 && p1.st.landing === '<script async src="https://linkspin.app/t.js?px=' + PX1 + '"></script>', 'goal list + landing tag snippet', p1.st.landing);
ok(p1.st.img === '<img src="https://linkspin.app/cv.gif?px=' + PX1 + '&goal=subscriber" width="1" height="1" alt="" style="display:none">' && p1.st.js === '<script async src="https://linkspin.app/cv.js?px=' + PX1 + '&goal=subscriber"></script>', 'goal pixel image + JS snippets match the contract', p1.st.img + ' | ' + p1.st.js);
ok(/Thank You Page: custom page/.test(p1.st.tip) && /Thank-you page: custom URL/.test(p1.st.tip) && /24-hour match/.test(p1.st.tip), 'autoresponder advice + match legend present');
ok(/url 2, stored 2, cookie 1, soft 1/.test(p1.st.status), 'match methods line', p1.st.status);
ok(!p1.errs.length, 'no page errors', p1.errs.join(' | '));
// fix 2 (2026-10-26): Send a test conversion loads the REAL pixel in test mode. The browser's request to linkspin.app is
// routed here (nothing leaves the machine): PX1 answers X-LS-Result: test like LinkSpin; PX2 answers unknown, so the
// card falls back to the signed partner call (op test).
{
const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } });
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
const [k, v] = ck1.split(';')[0].split('='); await ctx.addCookies([{ name: k, value: v, url: B }]);
const pixelHits = [];
await ctx.route(/^https:\/\/linkspin\.app\/cv\.gif/, route => { const u = new URL(route.request().url()); pixelHits.push(u.search); const px = u.searchParams.get('px'); const g = (mock.goals[A1] || []).find(x => x.px === px);
const good = px === PX1 && u.searchParams.get('test') === '1' && g; if (good) g.lastTest = Date.now();
return route.fulfill({ status: 200, headers: { 'Content-Type': 'image/gif', 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-LS-Result': good ? 'test' : 'unknown' }, body: Buffer.from('R0lGODlhAQABAAAAACw=', 'base64') }); });
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
await page.goto(B + '/my', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); });
await page.click('.bo-menu [data-pane="campaigns"]'); await page.waitForTimeout(2500);
const testsBefore = mock.calls.filter(c => c.op === 'test').length;
await page.click('[data-convtest="' + PX1 + '"]'); await page.waitForTimeout(2000);
const msg1 = await page.evaluate(() => document.body.innerText);
const last1 = await page.evaluate(px => { const b = document.querySelector('[data-convtest="' + px + '"]'); const tr = b && b.closest('tr'); const td = tr && tr.querySelector('td[data-l="Last test"]'); return td ? td.textContent.trim() : ''; }, PX1);
ok(pixelHits.some(q => q.includes('px=' + PX1) && q.includes('test=1')), 'Send a test conversion loads the real pixel cv.gif?px=..&test=1 from the browser', JSON.stringify(pixelHits));
ok(/received by your real pixel/.test(msg1) && last1 && last1 !== 'never' && mock.calls.filter(c => c.op === 'test').length === testsBefore, 'pixel answered test: Last test updates, no partner fallback needed', last1);
await page.click('[data-convtest="' + PX2 + '"]'); await page.waitForTimeout(2000);
const msg2 = await page.evaluate(() => document.body.innerText);
const tcall = mock.calls.filter(c => c.op === 'test').pop();
ok(pixelHits.some(q => q.includes('px=' + PX2)) && tcall && tcall.px === PX2 && /recorded through InstantAdPay/.test(msg2), 'pixel did not confirm: falls back to the signed partner call (op test)', JSON.stringify(tcall));
ok(!errs.length, 'no page errors during the tests', errs.join(' | '));
await page.screenshot({ path: path.join(OUT, 'convpixel-test-button.png'), fullPage: true }).catch(() => {});
await ctx.close();
}
// 6. LinkSpin down: the pane still loads, the panel says so, campaign rows omit the goal line; clicks are kept and pushed later
mock.down = true;
const ck2 = await signIn(A2);
const down = await api('/api/my/conversions', null, { Cookie: ck2 });
ok(down.j && down.j.ok === false && down.j.reason === 'down' && /did not answer/.test(down.j.error), 'proxy says LinkSpin is down in plain words', JSON.stringify(down.j));
const p2 = await pane(ck2, 'convpixel-down.png');
ok(p2.st.rows >= 1 && p2.st.card && /did not answer/.test(p2.st.status) && p2.st.line5Hidden, 'LinkSpin down: Campaigns pane still loads, no goal line, panel explains', JSON.stringify(p2.st).slice(0, 220));
ok(!p2.errs.length, 'no page errors while LinkSpin is down', p2.errs.join(' | '));
const cd = await click(5); const idDown = (ID.exec(cd.loc || '') || [])[1];
ok(!!idDown, 'clicks still get ids while LinkSpin is down');
await sleep(4000);
ok(!mock.clicks.has(idDown), 'nothing marked pushed while LinkSpin refuses');
mock.down = false;
ok(!!(await waitFor(() => mock.clicks.has(idDown), 30000)), 'row kept and pushed once LinkSpin is back (retry with backoff)');
const adm = await api('/api/admin/lssync', null, { Authorization: 'Bearer ' + ADMIN });
ok(adm.j && adm.j.conv && adm.j.conv.on === true && adm.j.conv.pushed >= 5, 'admin lssync view carries conv push stats', JSON.stringify(adm.j && adm.j.conv));
} catch (e) { ok(false, 'run', e.stack); }
finally {
await cleanup();
fs.writeFileSync(path.join(OUT, 'convpixel-server.log'), srvLog);
console.log(fails ? fails + ' FAILED' : 'all passed');
process.exit(fails ? 1 : 0);
}
+1 -1
View File
@@ -151,7 +151,7 @@ try {
await sleep(2200);
const rch = (await api('/api/refuel/challenge?n=' + nr2)).j;
const rd = (await api('/api/refuel/done', { n: nr2, answer: rch.options.indexOf(CAP[rch.prompt]) })).j;
ok(rd && rd.ok && rd.posted === true && refuelCalls.length === 1 && JSON.parse(refuelCalls[0]).credits === 3, 'refuel completes with its own callback', JSON.stringify(rd && { ok: rd.ok, posted: rd.posted }));
ok(rd && rd.ok && rd.posted === true && refuelCalls.length === 1 && JSON.parse(refuelCalls[0]).credits === 3, 'refuel completes with its own callback', JSON.stringify(rd && { ok: rd.ok, posted: rd.posted, calls: refuelCalls }));
const nr3 = crypto.randomBytes(12).toString('hex');
const rcap = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ kind: 'refuel', memberId: 77, email: player, nonce: nr3, ret: SD + '/play?refuel=' + nr3 }, DRSECRET)))).j;
ok(rcap && rcap.none && rcap.why === 'cap', 'refuel cap (1) reached after one refuel, not before', JSON.stringify(rcap));
+188
View File
@@ -0,0 +1,188 @@
// Game Pass integration test (2026-10-16): the REAL games' shared client (spooky-doors/server/polgrant.js) and PolHunter's tournament
// payer (polhunter/lib/tournament.js) against a LOCAL copy of this server, booted the way qa/gamepass.mjs boots it (JSON store,
// throwaway DATA_DIR, devCode sign-in, throwaway game secrets). Nothing touches production.
// node qa/gamepass-games.cjs (or: bash qa/run.sh gamepass-games)
// Needs the sibling game repos (GAMES_ROOT, default ../.. = D:/Projects/HighRisk): spooky-doors/server/{polgrant,store}.js and
// polhunter/lib/{polgrant,store,tournament,faucet}.js. The games' client has no devDay field, so for the "next Central day" calls a
// fetch wrapper adds devDay to the already-built body and re-signs it with the same secret; every "today" call goes through untouched.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');
const SITE = path.resolve(__dirname, '..');
const GAMES = (process.env.GAMES_ROOT || path.resolve(SITE, '..', '..')).replace(/\\/g, '/');
const SD = GAMES + '/spooky-doors/server';
const PH = GAMES + '/polhunter/lib';
const PORT = Number(process.env.GP_PORT || 8798);
const B = 'http://127.0.0.1:' + PORT;
const SDS = crypto.randomBytes(24).toString('hex'), HUNT = crypto.randomBytes(24).toString('hex');
const ADMIN = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-gpint-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const SDDATA = fs.mkdtempSync(path.join(os.tmpdir(), 'sd-gpint-'));
const PHDATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ph-gpint-'));
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const near = (a, b, tol) => Math.abs(Number(a) - Number(b)) <= (tol || 1e-6);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const ctDay = t => new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL, ADMIN_PASSWORD: ADMIN, SD_SSO_SECRET: SDS, HUNT_SSO_SECRET: HUNT, DEV_POL_USD: '0.10' }) });
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
const cleanup = () => { try { srv.kill(); } catch (e) {} for (const d of [DATA, SDDATA, PHDATA]) { try { fs.rmSync(d, { recursive: true, force: true }); } catch (e) {} } };
async function api(p, o, headers) {
const opts = { method: (o && o.method) || (o && 'data' in o ? 'POST' : 'GET'), headers: Object.assign({ 'Content-Type': 'application/json' }, headers || {}) };
if (o && 'data' in o) opts.body = JSON.stringify(o.data);
const r = await fetch(B + p, opts); let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, j, headers: r.headers };
}
const adminH = { Authorization: 'Bearer ' + ADMIN };
// harness-side signed GET of the player card (to READ caps; the client's fetchPass caches 10 min and only returns the pass)
async function rawPlayer(secret, game, email, devDay) {
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret).update('player:' + email + ':' + ts).digest('hex');
const q = Object.assign({ game, m: 0, e: email, ts, sig }, devDay ? { devDay } : {});
const r = await fetch(B + '/api/partner/player?' + new URLSearchParams(q)); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
}
(async () => {
try {
for (let i = 0; i < 40; i++) { try { if ((await fetch(B + '/api/config')).ok) break; } catch (e) {} await sleep(500); }
async function signIn(email, username) {
const s = await api('/api/auth/email/start', { data: { email, fts: Date.now() - 5000 } });
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
if (username) await api('/api/my/profile', { data: { username } }, { Cookie: cookie });
return { Cookie: cookie };
}
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10, gamePassEnabled: '1', capsStartDate: '2026-01-01' } }, adminH);
const F = 'qa-int-free@example.com', P = 'qa-int-pass@example.com';
const hF = await signIn(F, 'qaintfree'), hP = await signIn(P, 'qaintpass');
// the pass holder: buy (charge stubbed, local only) -> active 7 days
let r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hP);
ok(r.status === 200 && r.j.ok && r.j.active === true, 'setup: P buys the pass (devPaid) -> active', new Date(r.j.until).toISOString());
const untilP = r.j.until;
// the pass holder links a wallet through the real challenge/verify flow (signed locally with ethers) so tournament.js has somewhere to pay
const { ethers } = require(SITE + '/node_modules/ethers');
const w = ethers.Wallet.createRandom();
const ch = await api('/api/auth/challenge', { data: { address: w.address } });
const sigm = await w.signMessage(ch.j.message);
const lv = await api('/api/auth/verify', { data: { address: w.address, signature: sigm } }, hP);
ok(lv.status === 200 && lv.j.linked === true && lv.j.address === w.address.toLowerCase(), 'setup: P links a wallet via /api/auth/challenge + /verify', JSON.stringify(lv.j));
const walletP = w.address.toLowerCase();
// ---- the REAL games' client, configured the way spooky-doors/server/server.js does (line 17-28) ----
process.env.GAMEPASS = 'on'; process.env.IAP_URL = B; process.env.SD_SSO_SECRET = SDS;
const sdStore = require(SD + '/store.js'); sdStore.init(SDDATA);
const gp = require(SD + '/polgrant.js');
const SECRET = String(process.env.SD_SSO_SECRET || '').trim(); const IAP = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
const notes = []; gp.use({ game: 'spookydoors', secret: SECRET, iap: IAP, store: sdStore, notify: (k, p) => notes.push([k, p]) });
ok(gp.on() && gp._cfg().iap === B && gp._cfg().game === 'spookydoors', 'client: GAMEPASS=on, IAP_URL honoured, slug spookydoors', gp._cfg().iap);
// next-Central-day plumbing: the client has no devDay field, so (only while fakeDay is set) the already-built POST body gets
// devDay added and is re-signed with the same secret; every "today" call goes through the client untouched
let fakeDay = null; const realFetch = globalThis.fetch;
gp.use({ fetch: (u, o) => { if (fakeDay && o && o.method === 'POST' && o.body) { const b = JSON.parse(o.body); b.devDay = fakeDay; const raw = JSON.stringify(b); const ts = o.headers['X-Game-Ts']; o = Object.assign({}, o, { body: raw, headers: Object.assign({}, o.headers, { 'X-Game-Sig': crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex') }) }); } return realFetch(u, o); } });
// 1. fetchPass: free member vs pass holder
let pf = await gp.fetchPass(0, F); ok(pf.active === false && pf.until === null, 'fetchPass(free) -> active false', JSON.stringify(pf));
let pp = await gp.fetchPass(0, P); ok(pp.active === true && pp.until === untilP, 'fetchPass(pass holder) -> active true, until = IAP until', JSON.stringify(pp));
let vw = gp.view(0, P); ok(vw.on === true && vw.active === true && vw.untilText && vw.url === 'https://instantadpay.com/my#games?pass=1', 'view(P) for the lobby', JSON.stringify(vw));
// 2. daily within / over the cap (free caps 0.30 / 2.0, enforced since capsStartDate 2026-01-01)
const today = ctDay(Date.now());
let g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d1' });
ok(g.retry === false && g.allowed === 0.2 && g.deferred === 0 && g.carried === 0 && g.pass === false && g.enforced === true && g.capHit === null && g.day === today, 'daily 0.2 within cap -> allowed 0.2, enforced, day = Central today', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d2' });
ok(g.retry === false && g.allowed === 0.1 && g.capHit === 'daily' && g.deferred === 0, 'daily 0.2 over cap -> allowed 0.1, capHit daily, nothing deferred', JSON.stringify(g));
ok(gp.note(g, 'daily', 0.2) === 'Daily cap reached for today. Get the Pass for a higher cap.', 'note() for the capped free daily', gp.note(g, 'daily', 0.2));
// 3. progress over the total cap -> deferred
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 5, ref: 'rung:7' });
ok(g.retry === false && g.allowed === 1.7 && g.deferred === 3.3 && g.capHit === 'total', 'progress 5 -> allowed 1.7 (2.0 total minus 0.3 daily), 3.3 deferred', JSON.stringify(g));
ok(gp.note(g, 'progress', 5) === '3.3 POL is yours; it pays out over the next days (daily cap).', 'note() for the deferred progress', gp.note(g, 'progress', 5));
let pl = await rawPlayer(SDS, 'spookydoors', F); ok(pl.j.caps.used.daily === 0.3 && pl.j.caps.used.total === 2 && pl.j.caps.pending === 3.3, 'IAP caps today: used 0.30 / 2.0, 3.3 pending for spookydoors', JSON.stringify(pl.j.caps));
// 4. the carrySweep-style zero-POL call on the NEXT Central day (pol.js carrySweep: kind progress, pol 0, ref carry:<day>)
const day2 = ctDay(Date.now() + 86400000), day3 = ctDay(Date.now() + 2 * 86400000);
fakeDay = day2;
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:' + day2 });
ok(g.retry === false && g.allowed === 2 && g.carried === 2 && g.deferred === 0 && g.day === day2, 'NEXT day carry (pol 0) -> accepted, allowed 2.0, carried 2.0 (not rejected)', JSON.stringify(g));
const g2 = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:' + day2 });
ok(g2.retry === false && g2.repeat === true && g2.allowed === 2 && g2.carried === 2, 'the same carry ref again -> repeat true, same answer (idempotent)', JSON.stringify(g2));
pl = await rawPlayer(SDS, 'spookydoors', F, day2); ok(pl.j.caps.used.total === 2 && pl.j.caps.pending === 1.3, 'IAP caps on day 2: total 2.0 used (all carried), 1.3 still pending', JSON.stringify(pl.j.caps));
fakeDay = day3;
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:' + day3 });
ok(g.retry === false && g.allowed === 1.3 && g.carried === 1.3 && g.day === day3, 'day 3 carry -> the last 1.3', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:x:' + day3 });
ok(g.retry === false && g.allowed === 0 && g.carried === 0 && g.deferred === 0, 'a carry call with nothing owed -> allowed 0, no error, not retry', JSON.stringify(g));
fakeDay = null;
// 5. void: the ref's own share comes back (today's daily 0.2), so a new daily grant fits again
let vd = await gp.voidGrant({ memberId: 0, email: F, ref: 'it:d1' }); ok(vd.ok === true, 'voidGrant(it:d1) -> ok', JSON.stringify(vd));
pl = await rawPlayer(SDS, 'spookydoors', F); ok(pl.j.caps.used.daily === 0.1 && pl.j.caps.used.total === 1.8, 'IAP caps today after the void: daily 0.1, total 1.8', JSON.stringify(pl.j.caps));
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d3' });
ok(g.allowed === 0.2 && g.capHit === null, 'daily 0.2 after the void -> allowed 0.2', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d1' });
ok(g.repeat === true && g.allowed === 0, 'replaying the voided ref -> repeat, allowed 0', JSON.stringify(g));
// pass holder: pass caps apply
g = await gp.grant({ memberId: 0, email: P, kind: 'daily', pol: 1.0, ref: 'p:d1' });
ok(g.allowed === 1 && g.pass === true && g.capHit === null, 'pass holder daily 1.0 -> allowed 1.0, pass true', JSON.stringify(g));
ok(gp.passOf(0, P).active === true, 'the grant answer refreshed the cached pass flag', JSON.stringify(gp.passOf(0, P)));
// 6. failure modes: bad secret / IAP down / unknown member -> the client answers { allowed: 0, retry: true }
gp.use({ secret: crypto.randomBytes(24).toString('hex') });
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.1, ref: 'bad:1' });
ok(g.allowed === 0 && g.retry === true && /401/.test(g.error), 'bad secret -> { allowed: 0, retry: true } (IAP 401)', JSON.stringify(g));
gp.use({ secret: SECRET, iap: 'http://127.0.0.1:1' });
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.1, ref: 'down:1' });
ok(g.allowed === 0 && g.retry === true, 'IAP down -> { allowed: 0, retry: true }', JSON.stringify(g));
// the retry queue pays once IAP is back
gp.enqueue({ memberId: 0, email: F, kind: 'daily', pol: 0.1, ref: 'down:1' });
ok(gp.queued(0, F, 'down:1') === true, 'enqueue -> queued() guards the ref', '');
let rt = await gp.retry(() => {}, Date.now() + gp.RETRY_MS + 1); ok(rt.tried === 1 && rt.paid === 0 && gp.queued(0, F, 'down:1'), 'retry while IAP is down -> still queued', JSON.stringify(rt));
gp.use({ iap: B });
let paidItems = []; rt = await gp.retry((item, resp) => paidItems.push([item.ref, resp.allowed, resp.capHit]), Date.now() + 2 * gp.RETRY_MS + 2);
ok(rt.tried === 1 && rt.paid === 1 && paidItems.length === 1 && paidItems[0][1] === 0 && paidItems[0][2] === 'daily' && !gp.queued(0, F, 'down:1'), 'retry once IAP is back -> settled (allowed 0: F already used today\'s 0.30 daily cap), dequeued', JSON.stringify(rt) + ' ' + JSON.stringify(paidItems));
g = await gp.grant({ memberId: 0, email: 'nobody-here@example.com', kind: 'daily', pol: 0.1, ref: 'nb:1' });
ok(g.allowed === 0 && g.retry === true && /404/.test(g.error), 'unknown member -> retry: true (IAP 404; the game would queue it 48 h) [observation]', JSON.stringify(g));
// 7. the tournament: P plays in the week of Oct 19 and buys again that week (a sale), then admin settles the week
fakeDay = '2026-10-20';
g = await gp.grant({ memberId: 0, email: P, kind: 'daily', pol: 0.1, ref: 'wk:1' }); ok(g.allowed === 0.1, 'P plays (Oct 20) #1', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: P, kind: 'progress', pol: 0.1, ref: 'wk:2' }); ok(g.allowed === 0.1, 'P plays (Oct 20) #2', JSON.stringify(g));
fakeDay = null;
r = await api('/api/my/gamepass/buy', { data: { devPaid: true, devDay: '2026-10-20' } }, hP); ok(r.j.ok, 'P buys again stamped Oct 20 (a sale in the week of Oct 19)', '');
let t = await api('/api/admin/gamepass/tournament/run', { data: { week: '2026-10-21' } }, adminH);
ok(t.status === 200 && t.j.week === '2026-10-19' && t.j.winners.length === 1 && t.j.winners[0].email === P && near(t.j.winners[0].pol, 1.25) && t.j.winners[0].wallet === walletP, 'tournament settled: P #1, 1.25 POL, wallet set', JSON.stringify(t.j.winners));
// ---- PolHunter's payer: lib/tournament.js with its own store + polgrant copy, configured like polhunter/server.js line 50-61 ----
process.env.HUNT_SSO_SECRET = HUNT;
const phStore = require(PH + '/store.js'); phStore.init(PHDATA);
const gph = require(PH + '/polgrant.js');
const phNotes = []; gph.use({ game: 'polhunter', secret: String(process.env.HUNT_SSO_SECRET || '').trim(), iap: String(process.env.IAP_URL || '').replace(/\/+$/, ''), store: phStore, notify: (k, p) => phNotes.push([k, p]) });
let dryFn; try { dryFn = require(PH + '/faucet.js').dry; } catch (e) { console.log(' (faucet.js not requirable here: ' + e.message.slice(0, 80) + '; using the same HUNT_DRY_RUN rule)'); dryFn = () => String(process.env.HUNT_DRY_RUN || 'off').trim().toLowerCase() !== 'off'; }
const tournament = require(PH + '/tournament.js');
const sends = []; const TX = '0x' + crypto.randomBytes(32).toString('hex');
const faucet = { address: () => '0x' + '1'.repeat(40), balance: async () => 50, send: async (to, pol, onHash) => { sends.push({ to, pol }); if (onHash) await onHash(TX); return { tx: TX, ok: true }; } };
tournament.init({ faucet, notify: (k, p) => phNotes.push([k, p]), dry: dryFn });
const tp = await gph.tournamentPending();
ok(tp.ok === true && tp.rows.length === 1 && tp.rows[0].email === P && tp.rows[0].week === '2026-10-19' && tp.rows[0].place === 1 && tp.rows[0].wallet === walletP && near(tp.rows[0].pol, 1.25), 'client tournamentPending() sees the 1 unpaid row', JSON.stringify(tp));
process.env.HUNT_DRY_RUN = 'on';
let st = await tournament.run();
ok(st.on === true && st.dry === true && st.pending === 1 && near(st.wouldPay, 1.25) && st.paid === 0 && sends.length === 0, 'HUNT_DRY_RUN=on: run() lists the row as wouldPay 1.25, sends nothing', JSON.stringify(st));
let cl = phStore.read('tourney-claims', {}); ok(cl['wk:2026-10-19:1'] && cl['wk:2026-10-19:1'].dry === true, 'dry claim recorded in tourney-claims', JSON.stringify(cl));
process.env.HUNT_DRY_RUN = 'off';
st = await tournament.run();
ok(st.dry === false && st.paid === 0 && st.skipped === 1 && sends.length === 0, 'dry OFF with the dry claim still there: the row is SKIPPED, never paid (games-side trap: a dry-run claim is permanent)', JSON.stringify(st));
phStore.write('tourney-claims', {}); // a fresh volume (what a real deploy without a dry run looks like)
st = await tournament.run();
ok(st.paid === 1 && st.acked === 1 && st.failures.length === 0 && sends.length === 1 && sends[0].to === walletP && near(sends[0].pol, 1.25), 'dry OFF, fresh claims: faucet.send(wallet, 1.25) + POST /paid acked', JSON.stringify(st) + ' ' + JSON.stringify(sends));
cl = phStore.read('tourney-claims', {}); ok(cl['wk:2026-10-19:1'] && cl['wk:2026-10-19:1'].tx === TX && cl['wk:2026-10-19:1'].acked, 'claim carries the tx + acked', JSON.stringify(cl['wk:2026-10-19:1']));
ok(phNotes.some(n => n[0] === 'tourneypaid'), 'notify(tourneypaid) fired', phNotes.map(n => n[0]).join(','));
let pend = await api('/api/partner/tournament/pending', null, adminH); ok(pend.j.pending.length === 0, 'IAP pending is empty after the payout', JSON.stringify(pend.j));
st = await tournament.run(); ok(st.pending === 0 && st.paid === 0 && sends.length === 1, 'next run: nothing pending, nothing re-sent', JSON.stringify(st));
const tstate = tournament.state(); ok(tstate.paidTotal === 1 && tstate.recent.length >= 3, 'tournament.state() for the admin: paidTotal 1', JSON.stringify({ paidTotal: tstate.paidTotal, runs: tstate.recent.length }));
ok(/gamepass prize paid 2026-10-19 #1 by polhunter/.test(srvLog), 'IAP logged the prize as paid by polhunter', '');
} catch (e) { console.error('FAIL harness error', e && e.stack || e); fails++; }
finally { cleanup(); }
if (fails) console.log('--- server log (gamepass lines) ---\n' + srvLog.split('\n').filter(l => /gamepass|Error|error/.test(l)).slice(-30).join('\n'));
console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS');
process.exit(fails ? 1 : 0);
})();
+230
View File
@@ -0,0 +1,230 @@
// Game Pass + account-wide POL caps, end to end against a LOCAL copy (2026-10-16, docs/GAME-PASS.md).
// node qa/gamepass.mjs (or: bash qa/run.sh gamepass)
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB, no mail key, devCode sign-in) and throwaway game
// secrets. Nothing touches production. Covers: settings on/off; buy without purchased credits -> waiting order -> a $5 package
// fulfils it; buy -> active, buy again -> extended (the charge is stubbed with devPaid, the real ads.gamePurchase(purchasedOnly)
// path needs a position with on-chain credits and is the live PolyWarriors mint path); partner auth (bad sig / stale / unknown game);
// /api/partner/player pass + caps; polgrant before capsStartDate (allowed, recorded); daily within/over the cap; progress deferral
// and carry-forward on the next day (the Central day is faked with devDay); caps account-wide across games; idempotent ref; void;
// pass expiry back to free caps; the tournament settle + pending + paid seam; admin stats. Exit code 1 on any failure.
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.GP_PORT || 8799);
const B = 'http://127.0.0.1:' + PORT;
const GK = crypto.randomBytes(24).toString('hex'), HUNT = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
const ADMIN = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-gamepass-')); fs.mkdirSync(path.join(DATA, 'uploads'));
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
const near = (a, b, tol) => Math.abs(Number(a) - Number(b)) <= (tol || 1e-6);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL, ADMIN_PASSWORD: ADMIN, GK_SSO_SECRET: GK, HUNT_SSO_SECRET: HUNT, DEV_POL_USD: '0.10' }) });
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
const cleanup = () => { try { srv.kill(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
async function api(p, o, headers) {
const opts = { method: (o && o.method) || (o && 'data' in o ? 'POST' : 'GET'), headers: Object.assign({ 'Content-Type': 'application/json' }, headers || {}) };
if (o && 'data' in o) opts.body = JSON.stringify(o.data);
const r = await fetch(B + p, opts); let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, j, headers: r.headers };
}
const adminH = { Authorization: 'Bearer ' + ADMIN };
// a game's signed POST (3a): X-Game-Ts + X-Game-Sig = HMAC(secret, ts + '\n' + rawBody)
async function gamePost(p, body, secret, tsOverride) {
const raw = JSON.stringify(body); const ts = tsOverride || String(Date.now());
const sig = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
const r = await fetch(B + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game-Ts': ts, 'X-Game-Sig': sig }, body: raw });
let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
}
// a game's signed GET (3a): sig = HMAC(secret, 'player:' + who + ':' + ts)
async function gameGet(p, q, who, secret) {
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret).update('player:' + who + ':' + ts).digest('hex');
const r = await fetch(B + p + '?' + new URLSearchParams(Object.assign({}, q, { ts, sig })).toString()); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
}
const grant = (o, secret, tsOverride) => gamePost('/api/partner/polgrant', o, secret || GK, tsOverride);
try {
for (let i = 0; i < 40; i++) { try { if ((await fetch(B + '/api/config')).ok) break; } catch (e) {} await sleep(500); }
async function signIn(email, username) {
const s = await api('/api/auth/email/start', { data: { email, fts: Date.now() - 5000 } });
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
if (username) await api('/api/my/profile', { data: { username } }, { Cookie: cookie });
return { Cookie: cookie };
}
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10 } }, adminH);
const A = 'qa-gp-a@example.com', Bm = 'qa-gp-b@example.com', C = 'qa-gp-c@example.com';
const hA = await signIn(A, 'qagpa'), hB = await signIn(Bm, 'qagpb'), hC = await signIn(C, 'qagpc');
// 1. settings: off by default, member GET says so, buy refused
let g = (await api('/api/my/gamepass', null, hA)).j;
ok(g && g.enabled === false && g.active === false && g.price === 500 && g.days === 7, 'GET /api/my/gamepass with the pass OFF: enabled false, price 500, days 7', JSON.stringify(g));
let r = await api('/api/my/gamepass/buy', { data: {} }, hA);
ok(r.status === 400 && /not open/.test(r.j && r.j.error || ''), 'buy refused while the pass is off', JSON.stringify(r.j));
await api('/api/admin/site', { method: 'PATCH', data: { gamePassEnabled: '1', capsStartDate: '' } }, adminH);
g = (await api('/api/my/gamepass', null, hA)).j;
ok(g && g.enabled === true && g.caps && g.caps.enforced === false && g.caps.daily === 0.3 && g.caps.total === 2, 'pass ON: GET shows free caps 0.30 / 2 and enforced false (no capsStartDate)', JSON.stringify(g.caps));
// 2. buy (2026-10-22: no pass is ever bought with credits) -> waiting order; only a FRESH package by the member's own position fulfils it.
// A's purchases are stamped Sun Oct 18 (week of Oct 12) and B's Tue Oct 20 (week of Oct 19), so the tournament below sees one sale.
const SUN = Date.parse('2026-10-18T17:00:00Z'), TUE = Date.parse('2026-10-20T17:00:00Z');
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
ok(r.status === 200 && r.j && r.j.needPay === true && r.j.payUrl === '/my?from=gamepass#buy' && r.j.order && r.j.package === 5 && /package/.test(r.j.message || ''), 'buy -> needPay + payUrl + waiting order (never a credit charge)', JSON.stringify(r.j && { needPay: r.j.needPay, payUrl: r.j.payUrl, pkg: r.j.package }));
const order1 = r.j && r.j.order, order1Ts = r.j && r.j.orderTs;
r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hA);
ok(r.j && r.j.order === order1 && r.j.needPay === true && !r.j.ok, 'a second buy (even with the retired devPaid flag) reuses the same waiting order, no pass', r.j && r.j.order);
g = (await api('/api/my/gamepass', null, hA)).j; ok(g.waiting === true && g.active === false, 'GET shows waiting: true', '');
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, minedAt: order1Ts - 10 * 60000 } });
ok(r.j && r.j.order === null, 'a package mined BEFORE the order was opened does not fulfil it', JSON.stringify(r.j));
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 200 } });
ok(r.j && r.j.order === null, 'a $2 package does not fulfil a $5 pass order', JSON.stringify(r.j));
r = await api('/api/dev/gamepass-purchase', { data: { email: Bm, cents: 500 } });
ok(r.j && r.j.order === null, 'another member’s package does not fulfil A’s order', JSON.stringify(r.j));
const tx1 = '0x' + crypto.randomBytes(32).toString('hex');
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, tx: tx1, now: SUN } });
ok(r.j && r.j.order && r.j.order.order === order1, 'a fresh $5 package by A fulfils the waiting order', JSON.stringify(r.j));
g = (await api('/api/my/gamepass', null, hA)).j; const until1 = g.until;
ok(g.active === true && g.waiting === false && g.until === SUN + 7 * 86400000 && g.bought === 1, 'pass active for 7 days from the purchase, waiting cleared', new Date(g.until).toISOString());
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500 } });
ok(r.j && r.j.order === null, 'another package with no waiting order does nothing', JSON.stringify(r.j));
// 3. buy while active -> a new order; the same tx again is refused, a new package extends from the current until
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
ok(r.j && r.j.needPay && r.j.order && r.j.order !== order1, 'buy while active opens a new waiting order', r.j && r.j.order);
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, tx: tx1, now: SUN } });
ok(r.j && r.j.order === null, 'replaying a purchase tx that already paid a pass does nothing (each tx once)', JSON.stringify(r.j));
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, now: SUN } });
ok(r.j && r.j.order && near(r.j.order.until, until1 + 7 * 86400000, 1000), 'a fresh package while active extends by 7 days from the current until', r.j && r.j.order && new Date(r.j.order.until).toISOString());
r = await api('/api/my/gamepass/buy', { data: {} }, hB);
r = await api('/api/dev/gamepass-purchase', { data: { email: Bm, cents: 1000, now: TUE } });
g = (await api('/api/my/gamepass', null, hB)).j;
ok(r.j && r.j.order && g.active === true, 'member B: order + a $10 package -> active (sale stamped in the week of Oct 19 for the tournament)', JSON.stringify(r.j));
// 4. partner auth + /api/partner/player
let pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: A }, A, GK);
ok(pl.status === 200 && pl.j.pass && pl.j.pass.active === true && pl.j.pass.until === until1 + 7 * 86400000 && pl.j.caps.daily === 1.5 && pl.j.caps.total === 5 && pl.j.caps.used.total === 0 && /^\d{4}-\d{2}-\d{2}$/.test(pl.j.caps.day), 'player (pass holder): pass.active, pass caps 1.50 / 5, used 0, Central day', JSON.stringify(pl.j.pass) + ' ' + JSON.stringify(pl.j.caps));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C }, C, GK);
ok(pl.status === 200 && pl.j.pass.active === false && pl.j.pass.until === null && pl.j.caps.daily === 0.3 && pl.j.caps.total === 2, 'player (free): pass false, free caps 0.30 / 2', JSON.stringify(pl.j.caps));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C }, C, HUNT);
ok(pl.status === 401, 'player signed with another game’s secret -> 401', String(pl.status));
pl = await gameGet('/api/partner/player', { game: 'nosuchgame', m: 0, e: C }, C, GK);
ok(pl.status === 400, 'unknown game -> 400', String(pl.status));
pl = await gameGet('/api/partner/player', { game: 'spellwheel', m: 0, e: C }, C, GK);
ok(pl.status === 503, 'a game with no secret configured -> 503', String(pl.status));
let gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'auth-stale' }, GK, String(Date.now() - 20 * 60000));
ok(gr.status === 401 && /stale/.test(gr.j.error), 'polgrant with a 20-minute-old timestamp -> 401 stale', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'auth-bad' }, HUNT);
ok(gr.status === 401, 'polgrant signed with the wrong secret -> 401', String(gr.status));
gr = await grant({ memberId: 0, email: 'nobody-here@example.com', game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'x' });
ok(gr.status === 404, 'polgrant for an unknown member -> 404', String(gr.status));
// 5. before capsStartDate: everything allowed, nothing deferred, usage recorded
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'pre:1', devDay: '2026-10-19' });
ok(gr.status === 200 && gr.j.allowed === 1 && gr.j.deferred === 0 && gr.j.pass === false && gr.j.enforced === false && gr.j.day === '2026-10-19', 'before capsStartDate: daily 1.0 -> allowed 1.0 (over the 0.30 free cap), enforced false', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 5, ref: 'pre:boss', devDay: '2026-10-19' });
ok(gr.j.allowed === 5 && gr.j.deferred === 0, 'before capsStartDate: progress 5 -> allowed 5, nothing deferred', JSON.stringify(gr.j));
let st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st && st.enabled === true && st.settings.enforced === false, 'admin stats: enabled, caps not enforced', JSON.stringify(st.settings));
// 6. enforced: daily within / over the cap, idempotent ref, progress deferral
await api('/api/admin/site', { method: 'PATCH', data: { capsStartDate: '2026-10-20' } }, adminH);
const D1 = '2026-10-20', D2 = '2026-10-21', D3 = '2026-10-22';
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f1', devDay: D1 });
ok(gr.j.allowed === 0.2 && gr.j.deferred === 0 && gr.j.enforced === true && gr.j.capHit === null, 'D1 daily 0.2 -> allowed 0.2', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f2', devDay: D1 });
ok(gr.j.allowed === 0.1 && gr.j.deferred === 0 && gr.j.capHit === 'daily', 'D1 daily 0.2 -> allowed 0.1 (daily cap 0.30), the rest dropped, capHit daily', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'f3', devDay: D1 });
ok(gr.j.allowed === 0 && gr.j.deferred === 0 && gr.j.capHit === 'daily', 'D1 daily 0.1 at the cap -> allowed 0, nothing deferred', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f2', devDay: D2 });
ok(gr.j.allowed === 0.1 && gr.j.repeat === true && gr.j.day === D1, 'same ref f2 again (even on another day) -> the same answer, nothing re-applied', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 5, ref: 'boss:1', devDay: D1 });
ok(gr.j.allowed === 1.7 && gr.j.deferred === 3.3 && gr.j.capHit === 'total', 'D1 progress 5 -> allowed 1.7 (total cap 2 minus 0.3 daily), 3.3 deferred', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.5, ref: 'stage:2', devDay: D1 });
ok(gr.j.allowed === 0 && gr.j.deferred === 0.5, 'D1 progress 0.5 with the total cap used -> all 0.5 deferred', JSON.stringify(gr.j));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D1 }, C, GK);
ok(pl.j.caps.used.daily === 0.3 && pl.j.caps.used.total === 2 && pl.j.caps.pending === 3.8 && pl.j.caps.enforced === true, 'player caps on D1: used 0.30 / 2.0, 3.8 POL pending for Gem Kingdom', JSON.stringify(pl.j.caps));
// 7. carry-forward on the next day, inside the total cap, before the new grant
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'f4', devDay: D2 });
ok(gr.j.allowed === 2 && gr.j.carried === 2 && gr.j.deferred === 0 && gr.j.capHit === 'total' && gr.j.day === D2, 'D2 daily 0.1 -> allowed 2.0 (2.0 carried from the boss fills the day), the 0.1 dropped', JSON.stringify(gr.j));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D2 }, C, GK);
ok(pl.j.caps.used.total === 2 && pl.j.caps.used.daily === 0 && pl.j.caps.pending === 1.8, 'D2 caps: total 2.0 used (all carried), 1.8 still pending', JSON.stringify(pl.j.caps));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.3, ref: 'stage:3', devDay: D3 });
ok(gr.j.allowed === 2 && gr.j.carried === 1.8 && gr.j.deferred === 0.1, 'D3 progress 0.3 -> 1.8 carried + 0.2 own = 2.0 allowed, 0.1 deferred', JSON.stringify(gr.j));
// account-wide: another game on the same day sees the cap used
gr = await grant({ memberId: 0, email: C, game: 'polhunter', kind: 'daily', pol: 0.3, ref: 'find:1', devDay: D3 }, HUNT);
ok(gr.j.allowed === 0 && gr.j.capHit === 'total', 'D3 PolHunter daily 0.3 -> allowed 0: the cap is account-wide across games', JSON.stringify(gr.j));
// 8. void: this ref's own share is reversed, the carry it triggered stays; a replay stays voided
let vd = await gamePost('/api/partner/polgrant/void', { memberId: 0, email: C, game: 'gemkingdom', ref: 'stage:3' }, GK);
ok(vd.status === 200 && vd.j.voided === true && vd.j.reversed.allowed === 0.2 && vd.j.reversed.deferred === 0.1, 'void stage:3 -> reversed 0.2 allowed + 0.1 deferred', JSON.stringify(vd.j));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D3 }, C, GK);
ok(pl.j.caps.used.total === 1.8 && pl.j.caps.pending === 0, 'D3 caps after the void: 1.8 used (the carry stays), nothing pending', JSON.stringify(pl.j.caps));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.3, ref: 'stage:3', devDay: D3 });
ok(gr.j.allowed === 0 && gr.j.repeat === true && gr.j.voided === true, 'replaying a voided ref -> allowed 0, voided', JSON.stringify(gr.j));
vd = await gamePost('/api/partner/polgrant/void', { memberId: 0, email: C, game: 'gemkingdom', ref: 'never-granted' }, GK);
ok(vd.j.ok === true && vd.j.unknown === true, 'voiding an unknown ref is harmless', JSON.stringify(vd.j));
// the Overview nudge source: the free player's last cap hit
g = (await api('/api/my/gamepass', null, hC)).j;
ok(g.lastCapHit && g.lastCapHit.game === 'polhunter' && g.lastCapHit.kind === 'total' && g.lastCapHit.pass === false, 'member GET carries lastCapHit for the Overview nudge', JSON.stringify(g.lastCapHit));
// 9. a pass holder gets the pass caps; after expiry the free caps are back
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:f1', devDay: D1 });
ok(gr.j.allowed === 1 && gr.j.pass === true && gr.j.capHit === null, 'pass holder: daily 1.0 -> allowed 1.0 (pass daily cap 1.50)', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:f2', devDay: D1 });
ok(gr.j.allowed === 0.5 && gr.j.capHit === 'daily', 'pass holder: second daily 1.0 -> allowed 0.5 (1.50 reached)', JSON.stringify(gr.j));
g = (await api('/api/my/gamepass?devDay=2026-12-01', null, hA)).j;
ok(g.active === false && g.caps.daily === 0.3, 'after expiry (faked Dec 1): active false, free caps', JSON.stringify(g.caps));
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:dec', devDay: '2026-12-01' });
ok(gr.j.allowed === 0.3 && gr.j.pass === false, 'after expiry: daily 1.0 -> allowed 0.30, pass false', JSON.stringify(gr.j));
// 10. tournament: the week of Oct 19 (A played, B bought); 5% of $5 = $0.25 at $0.10/POL = 2.5 POL pool, 50% to #1
let t = await api('/api/admin/gamepass/tournament/run', { data: { week: '2026-10-21' } }, adminH);
ok(t.status === 200 && t.j.week === '2026-10-19' && t.j.sales === 1 && near(t.j.poolPol, 2.5) && t.j.winners.length === 1 && t.j.winners[0].email === A && near(t.j.winners[0].pol, 1.25) && t.j.winners[0].score === 2, 'tournament week of Oct 19: 1 sale, pool 2.5 POL, A wins #1 with 2 plays -> 1.25 POL pending', JSON.stringify(t.j && { week: t.j.week, sales: t.j.sales, poolPol: t.j.poolPol, winners: t.j.winners.map(w => [w.email, w.score, w.pol, w.status]) }));
t = await api('/api/admin/gamepass/tournament/run', { data: { week: '2026-10-21' } }, adminH);
ok(t.j.winners && t.j.winners.length === 1 && t.j.ranAt, 'running the same week again returns the recorded row (no double prizes)', '');
let pend = await api('/api/partner/tournament/pending', null, adminH);
ok(pend.j.ok && pend.j.pending.length === 1 && pend.j.pending[0].place === 1 && near(pend.j.pending[0].pol, 1.25), 'GET /api/partner/tournament/pending (admin) lists the unpaid prize', JSON.stringify(pend.j.pending));
pend = await gameGet('/api/partner/tournament/pending', { game: 'gemkingdom' }, 'tournament', GK);
ok(pend.status === 200 && pend.j.pending.length === 1 && pend.j.pending[0].email === A && Array.isArray(pend.j.rows) && pend.j.rows.length === 1, 'a game can read the pending prizes with its signature (answer carries `rows`, the field the games\' polgrant.js reads)', '');
let paid = await gamePost('/api/partner/tournament/paid', { game: 'gemkingdom', week: '2026-10-19', place: 1, tx: '0xabc123' }, GK);
ok(paid.j.ok === true, 'a game marks the prize paid', JSON.stringify(paid.j));
pend = await api('/api/partner/tournament/pending', null, adminH);
ok(pend.j.pending.length === 0, 'pending is empty after the payout', '');
const inbox = (await api('/api/my/messages', null, hA)).j;
const stored = (() => { try { return JSON.parse(fs.readFileSync(path.join(DATA, 'sponsor-messages.json'), 'utf8')).items || []; } catch (e) { return []; } })().find(i => /Game Pass Tournament/.test(i.subject || ''));
ok(inbox && JSON.stringify(inbox).includes('Game Pass Tournament') && stored && stored.kind === 'notice', 'the winner got an inbox message of kind notice (never a broadcast pop-up)', stored ? 'kind=' + stored.kind : 'not stored');
// 11. admin stats + comp
st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st.passes.soldTotal === 3 && st.passes.active >= 2 && st.deferredQueue.entries === 0 && st.tournament.last && st.tournament.last.week === '2026-10-19' && typeof st.capHits.week.free.daily === 'number', 'admin stats: 3 passes sold, active >= 2, tournament recorded', JSON.stringify({ passes: st.passes, q: st.deferredQueue, hits: st.capHits.week }));
r = await api('/api/admin/gamepass/comp', { data: { email: C, why: 'qa' } }, adminH);
g = (await api('/api/my/gamepass', null, hC)).j;
ok(r.j.ok && g.active === true && g.caps.daily === 1.5, 'admin comp gives C a pass week: caps now 1.50 / 5', JSON.stringify(g.caps));
st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st.passes.soldTotal === 3 && st.passes.usdTotal === 15 && st.passes.comped === 1 && st.passes.active === 3, 'a comp is not a sale (soldTotal 3, $15, comped 1, active 3)', JSON.stringify(st.passes));
// 12. the hand-off token carries the flag
const gkO = { Origin: 'https://gemkingdom.app' }; // the game's own origin, as its sign-in page sends it
const hv = await api('/api/game/auth/start', { data: { email: A, game: 'gemkingdom', fts: Date.now() - 5000 } }, gkO);
const vv = await api('/api/game/auth/verify', { data: { email: A, game: 'gemkingdom', code: hv.j && hv.j.devCode } }, gkO);
if (!(vv.j && vv.j.token)) console.log(' game auth answer:', JSON.stringify(hv.j), JSON.stringify(vv.j));
const tokenClaims = vv.j && vv.j.token ? JSON.parse(Buffer.from(String(vv.j.token).split('.')[0].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')) : null;
ok(tokenClaims && tokenClaims.gamePass && tokenClaims.gamePass.active === true && tokenClaims.gamePass.until === until1 + 7 * 86400000, 'in-game sign-in token carries gamePass { active, until }', JSON.stringify(tokenClaims && tokenClaims.gamePass));
// the ledger file on the volume (saves are debounced 500 ms)
await sleep(1200);
ok(fs.existsSync(path.join(DATA, 'gamepass-ledger.json')), 'cap ledger persisted to DATA_DIR/gamepass-ledger.json', fs.readdirSync(DATA).join(','));
const ot = JSON.parse(fs.readFileSync(path.join(DATA, 'open-tokens.json'), 'utf8'));
ok(ot.gamepass && ot.gamepass[A] && ot.gporders && ot.gpprizes && ot.gpprizes['2026-10-19'], 'pass store, orders and prizes persisted in the durable open-tokens store', Object.keys(ot).join(','));
} catch (e) {
console.error('FAIL harness error', e && e.stack || e); fails++;
} finally {
cleanup();
}
if (fails && /gamepass/i.test(srvLog)) console.log('--- server log (gamepass lines) ---\n' + srvLog.split('\n').filter(l => /gamepass|Error|error/.test(l)).slice(-30).join('\n'));
console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS');
process.exit(fails ? 1 : 0);
+130
View File
@@ -0,0 +1,130 @@
// Knowledge-base chat, end to end against a LOCAL copy (2026-10-20).
// node qa/kb-chat.mjs (or: bash qa/run.sh kb)
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB) and a mock OpenRouter that
// records every request and answers from the "Knowledge base" block it was given. Nothing touches production:
// OPENROUTER_URL points at the mock and the key is a throwaway string.
// Covers: the Coinbase question answered from the KB through the AI path, the CANNED fast path served from the
// KB (no AI call), an off-topic question told to say "I'm not sure, ask support", admin create / edit / test /
// delete, an admin edit to a canned entry changing the instant answer, and /api/chat/kb-stamp. Exit 1 on failure.
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.KB_PORT || 8799), MOCK = PORT + 100;
const B = 'http://127.0.0.1:' + PORT;
const ADMIN = 'localtest';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-kb-')); fs.mkdirSync(path.join(DATA, 'uploads'));
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
// -- the mock OpenRouter: answers with the first KB answer it was handed, or the not-sure line
const calls = [];
const mock = http.createServer((req, res) => {
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
let body = {}; try { body = JSON.parse(raw); } catch (e) {}
calls.push({ url: req.url, auth: req.headers.authorization, body });
const sys = ((body.messages || [])[0] || {}).content || '';
const m = /\nAnswer: ([^\n]+)/.exec(sys.slice(sys.indexOf('KNOWLEDGE BASE')));
const content = m ? m[1] : "I'm not sure, ask support: open Help at https://instantadpay.com/my#help.";
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end('\n\n' + JSON.stringify({ choices: [{ message: { content } }] })); // keepalive padding first, like the real thing
});
});
await new Promise(r => mock.listen(MOCK, '127.0.0.1', r));
let srv = null, srvLog = '';
async function boot() {
srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN,
OPENROUTER_API_KEY: 'qa-throwaway', OPENROUTER_URL: 'http://127.0.0.1:' + MOCK + '/api/v1/chat/completions', DATABASE_URL: '' }) });
srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
}
async function halt() { if (!srv) return; const s = srv; srv = null; s.kill(); await new Promise(r => { s.once('exit', r); setTimeout(r, 3000); }); await sleep(300); }
const cleanup = async () => { try { await halt(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
try {
await boot();
const api = async (p, data, method, hdr) => { const r = await fetch(B + p, data !== undefined || method ? { method: method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: data === undefined ? undefined : JSON.stringify(data) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
const chat = message => api('/api/chat', { message }, 'POST'); // six questions in all, under the 10-a-minute chat limit
// 1. seeds landed in DATA_DIR/kb.json
await sleep(300);
const list0 = await api('/api/admin/kb', undefined, undefined, adminH);
const ids = (list0.j && list0.j.entries || []).map(e => e.id);
ok(ids.includes('f-coinbase') && ids.includes('c-withdraw') && ids.length >= 55, 'KB seeded from CANNED + FAQ + the Coinbase ticket', ids.length + ' entries');
ok(fs.existsSync(path.join(DATA, 'kb.json')), 'JSON store at DATA_DIR/kb.json');
// 2. the Coinbase question goes to the AI with the Coinbase entry in its knowledge base
let n = calls.length;
const cb = await chat('Can I use my regular Coinbase account?');
const sys = calls[n] && calls[n].body.messages[0].content || '';
ok(cb.status === 200 && calls.length === n + 1, 'Coinbase question goes to the AI path (one call)', 'status ' + cb.status);
ok(sys.includes('KNOWLEDGE BASE') && sys.includes('Coinbase is an exchange') && sys.indexOf('[1] Can I use my regular Coinbase account?') > 0, 'system prompt carries the Coinbase entry first');
ok(sys.includes('NEVER promise or estimate income') && sys.includes('No em dashes'), 'compliance rules still in the prompt');
ok(calls[n] && calls[n].body.reasoning && calls[n].body.reasoning.enabled === false, 'reasoning stays off');
ok(cb.j && /Coinbase is an exchange/.test(cb.j.reply) && (cb.j.kb || [])[0] === 'f-coinbase', 'reply drawn from the KB entry', JSON.stringify(cb.j).slice(0, 140));
// 3. the CANNED fast path, now served from the KB: no AI call
n = calls.length;
const wd = await chat('how do I withdraw my money');
ok(wd.j && wd.j.canned && wd.j.kb === 'c-withdraw' && /no withdrawals here/.test(wd.j.reply) && calls.length === n, 'canned answer served from the KB, no AI call', JSON.stringify(wd.j).slice(0, 100));
const sup = await chat('I want to talk to a real person');
ok(sup.j && sup.j.handoff && sup.j.kb === 'c-support', 'support hand-off flag kept on the instant answer');
// 4. nothing fits: the prompt says so and the reply hands off
n = calls.length;
const off = await chat('What is the capital of Mongolia?');
const sys2 = calls[n] && calls[n].body.messages[0].content || '';
ok(/no entry matches this question/.test(sys2) && /I'm not sure, ask support/.test(sys2), 'off-topic: prompt tells the AI to say it is not sure');
ok(off.j && off.j.handoff, 'off-topic reply offers "Send this to support"');
// 5. admin: create, find, test, edit, delete
const cr = await api('/api/admin/kb', { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?', 'Do you take PayPal'], answer: 'No. Packages are paid in POL on Polygon only — PayPal is not accepted.', tags: 'paypal, payment' }, 'POST', adminH);
ok(cr.j && cr.j.ok && cr.j.entry.answer.indexOf('—') < 0, 'admin creates an entry (em dash cleaned)', cr.j && cr.j.entry && cr.j.entry.answer);
const kid = cr.j && cr.j.entry && cr.j.entry.id;
const noAuth = await api('/api/admin/kb', { title: 'x', answer: 'y' }, 'POST');
ok(noAuth.status === 401, 'KB admin routes need the admin');
const t = await api('/api/admin/kb/test', { question: 'do you accept paypal' }, 'POST', adminH);
ok(t.j && t.j.ranked[0] && t.j.ranked[0].id === kid && t.j.ranked[0].used, 'Try a question ranks the new entry first');
n = calls.length;
await chat('can I pay using paypal?');
ok(calls[n] && calls[n].body.messages[0].content.includes('PayPal is not accepted'), 'new entry reaches the AI prompt right away');
const ed = await api('/api/admin/kb/' + kid, { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?'], answer: 'No, PayPal is not accepted. Packages are paid in POL on Polygon.', tags: ['paypal'] }, 'PUT', adminH);
ok(ed.j && ed.j.ok && ed.j.entry.answer.startsWith('No, PayPal'), 'admin edits the entry');
const srch = await api('/api/admin/kb?q=paypal', undefined, undefined, adminH);
ok(srch.j && srch.j.entries[0] && srch.j.entries[0].id === kid, 'admin search finds it');
const bad = await api('/api/admin/kb', { title: 'x', answer: 'y', pattern: '(' }, 'POST', adminH);
ok(bad.status === 400, 'a broken instant-answer pattern is refused');
const del = await api('/api/admin/kb/' + kid, undefined, 'DELETE', adminH);
const gone = await api('/api/admin/kb/' + kid, undefined, undefined, adminH);
ok(del.j && del.j.ok && gone.status === 404, 'admin deletes it');
// 6. editing a canned entry changes the instant answer (one source)
const cw = (await api('/api/admin/kb/c-withdraw', undefined, undefined, adminH)).j.entry;
await api('/api/admin/kb/c-withdraw', Object.assign({}, cw, { answer: cw.answer + ' (edited in QA)' }), 'PUT', adminH);
const wd2 = await chat('how do I withdraw');
ok(wd2.j && /\(edited in QA\)$/.test(wd2.j.reply), 'admin edit to a canned entry is what the fast path serves');
// 7. the sync guard's stamp: today (Central), because a person just edited entries
const st = await api('/api/chat/kb-stamp');
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
ok(st.j && st.j.updated === today && st.j.count >= 55, '/api/chat/kb-stamp reports the newest human edit', JSON.stringify(st.j));
// 8. a restart (the seed sync runs again) keeps admin work and does not bring a deleted seed back
await api('/api/admin/kb/f-refunds', undefined, 'DELETE', adminH);
await halt(); await boot();
const after = await api('/api/admin/kb', undefined, undefined, adminH);
const aIds = (after.j && after.j.entries || []).map(e => e.id);
const cw2 = (after.j && after.j.entries || []).find(e => e.id === 'c-withdraw');
ok(!aIds.includes('f-refunds') && aIds.includes('f-coinbase'), 'restart: a deleted seed stays deleted');
ok(cw2 && /\(edited in QA\)$/.test(cw2.answer) && cw2.edited, 'restart: an admin edit to a seed is not overwritten by the code');
} catch (e) { ok(false, 'run', e.message); }
await cleanup();
console.log(fails ? fails + ' failure(s)' : 'all KB chat checks passed');
process.exit(fails ? 1 : 0);
+49
View File
@@ -0,0 +1,49 @@
// Knowledge-base retrieval unit test (kb.js): the right entry must rank first for each sample question,
// scored over the real seeds (chatbot.js CANNED + kb-seed.js). No server, no network.
// node qa/kb-retrieval.cjs
const path = require('path');
const kb = require(path.join(__dirname, '..', 'kb.js'));
const chatbot = require(path.join(__dirname, '..', 'chatbot.js'));
const { buildIndex, rank, relevant, validate } = kb._pure;
const entries = chatbot.seeds();
const idx = buildIndex(entries);
const CASES = [
['Can I hook up my Coinbase account to pay for a package?', 'f-coinbase'],
['can i just use coinbase', 'f-coinbase'],
['Is my payment refundable if I change my mind?', 'f-refunds'],
['Can I give some of my credits to a friend?', 'f-credits-transfer'],
['Why does the amount of POL keep changing when I buy?', 'f-price-feed'],
['What is the smart contract address on polygonscan?', 'f-contract'],
['My video stopped playing when I switched tabs', 'f-active-viewing'],
['How many extra POL should I keep for gas fees?', 'f-how-much-pol'],
['My bank refused my card on MoonPay', 'f-moonpay-declined'],
['Trust wallet says this will drain my wallet', 'c-trust-drain'],
['How do I adopt somebody from the holding tank?', 'c-holding-tank'],
['I keep getting signed out every few hours', 'c-session-4h'],
['Where does the 20 percent platform share go?', 'f-platform-share']
];
let bad = 0;
for (const [q, want] of CASES) {
const hits = rank(idx, q, 5), top = hits[0];
const ok = top && top.entry.id === want && relevant(hits).length > 0;
if (!ok) bad++;
console.log((ok ? 'ok ' : 'FAIL ') + q + ' -> ' + hits.slice(0, 3).map(h => h.entry.id + ' ' + h.score).join(', ') + (ok ? '' : ' (wanted ' + want + ')'));
}
// off-topic questions should bring nothing back, so the prompt says "I'm not sure, ask support"
for (const q of ['What is the weather in Paris tomorrow?', 'Recommend a good pizza recipe']) {
const r = relevant(rank(idx, q, 5));
if (r.length) bad++;
console.log((r.length ? 'FAIL ' : 'ok ') + 'off-topic: ' + q + ' -> ' + (r.map(h => h.entry.id + ' ' + h.score).join(', ') || 'nothing'));
}
// admin input hygiene: em dashes are turned into commas, a bad pattern is refused
const v = validate({ title: 'T', answer: 'One — two', questions: 'a\nb', tags: 'X, y' });
if (v.answer !== 'One, two' || v.questions.length !== 2 || v.tags[0] !== 'x') { bad++; console.log('FAIL validate', v); } else console.log('ok validate cleans em dashes, splits questions and tags');
if (!validate({ title: 'T', answer: 'a', pattern: '(' }).error) { bad++; console.log('FAIL validate accepted a broken pattern'); } else console.log('ok validate refuses a broken pattern');
// every CANNED regex still answers through the KB fast path in the same order
const ordered = entries.filter(e => e.pattern).sort((a, b) => a.order - b.order);
const first = msg => ordered.find(e => new RegExp(e.pattern, 'i').test(msg));
const canned = chatbot.CANNED.find(c => c.re.test('how do I withdraw'));
if (!first('how do I withdraw') || first('how do I withdraw').answer !== canned.a) { bad++; console.log('FAIL fast-path order'); } else console.log('ok fast path keeps CANNED order');
console.log(bad ? bad + ' failure(s)' : 'all retrieval checks passed');
process.exit(bad ? 1 : 0);
+151
View File
@@ -0,0 +1,151 @@
// Prepaid login-ad line, MySQL code path (2026-10-23).
// node qa/login-queue-sql.cjs
// There is no MySQL on the test machine, so this swaps db.js for an in-memory fake that understands exactly the SQL the
// line uses and runs each statement atomically after a random 0-3 ms wait, so concurrent callers interleave BETWEEN
// statements the way two app copies do during a deploy overlap. That tests the guard logic of the SQL path (the
// app_locks lease and the conditional UPDATE ... WHERE status='queued'), not MySQL itself: real InnoDB locking, the
// schema migration and mysql2's affectedRows semantics are not exercised here. Unknown SQL throws, so a statement
// this fake does not model fails the test instead of passing silently. Exit 1 on failure.
'use strict';
const path = require('path');
const DAY = 86400000;
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
// ---- the fake ----
const T = { campaigns: [], locks: {}, earned: {}, log: [] }; let nextId = 1;
const wait = () => new Promise(r => setTimeout(r, Math.floor(Math.random() * 4)));
const norm = s => String(s).replace(/\s+/g, ' ').trim();
const liveRows = now => T.campaigns.filter(c => c.type === 'login' && c.status === 'active' && c.house === 0 && (c.expires == null || c.expires > now));
async function q(sql, p) {
await wait();
const s = norm(sql); p = p || [];
let m;
if (s.startsWith('INSERT IGNORE INTO app_locks')) { if (!T.locks[p[0]]) T.locks[p[0]] = { holder: null, until: 0 }; return { affectedRows: 1 }; }
if (s === 'UPDATE app_locks SET holder=?, lease_until=? WHERE name=? AND (holder IS NULL OR lease_until<?)') {
const L = T.locks[p[2]]; if (L && (L.holder === null || L.until < p[3])) { L.holder = p[0]; L.until = p[1]; return { affectedRows: 1 }; } return { affectedRows: 0 };
}
if (s === 'UPDATE app_locks SET holder=NULL, lease_until=0 WHERE name=? AND holder=?') {
const L = T.locks[p[0]]; if (L && L.holder === p[1]) { L.holder = null; L.until = 0; return { affectedRows: 1 }; } return { affectedRows: 0 };
}
if (s === "SELECT COUNT(*) n FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return [{ n: liveRows(p[0]).length }];
if (s === "SELECT expires FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return liveRows(p[0]).map(c => ({ expires: c.expires }));
if ((m = /^SELECT \* FROM campaigns WHERE type='login' AND status='queued' AND house=0 ORDER BY queued_at ASC, id ASC( LIMIT (\d+))?$/.exec(s))) {
const rows = T.campaigns.filter(c => c.type === 'login' && c.status === 'queued' && c.house === 0).sort((a, b) => (a.queued_at - b.queued_at) || (a.id - b.id));
return (m[2] ? rows.slice(0, Number(m[2])) : rows).map(c => Object.assign({}, c));
}
if (s === "UPDATE campaigns SET status='active', starts=?, expires=?, body=? WHERE id=? AND type='login' AND status='queued'") {
const c = T.campaigns.find(x => x.id === p[3] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
c.status = 'active'; c.starts = p[0]; c.expires = p[1]; c.body = p[2]; return { affectedRows: 1 };
}
if (s === "UPDATE campaigns SET status='cancelled' WHERE id=? AND type='login' AND status='queued'") {
const c = T.campaigns.find(x => x.id === p[0] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
c.status = 'cancelled'; return { affectedRows: 1 };
}
if (s === 'SELECT * FROM campaigns WHERE id=?') return T.campaigns.filter(c => c.id === p[0]).map(c => Object.assign({}, c));
if (s === 'SELECT * FROM campaigns WHERE owner_email=? ORDER BY id DESC') return T.campaigns.filter(c => c.owner_email === p[0]).sort((a, b) => b.id - a.id).map(c => Object.assign({}, c));
if (s === 'UPDATE campaigns SET status=? WHERE id=? AND owner_email=?') { const c = T.campaigns.find(x => x.id === p[1] && x.owner_email === p[2]); if (!c) return { affectedRows: 0 }; c.status = p[0]; return { affectedRows: 1 }; }
if (s.startsWith('INSERT INTO earned_credits (email,balance,purchase_grade,granted_welcome,updated)')) {
const e = T.earned[p[0]] = T.earned[p[0]] || { balance: 0, grade: 0 }; e.balance += p[1]; e.grade += p[2]; return { affectedRows: 1 };
}
if (s.startsWith('INSERT INTO credit_log')) { T.log.push({ email: p[0], delta: p[3], kind: p[4], note: p[5], ref: p[6] }); return { affectedRows: 1 }; }
throw new Error('fake db: unmodelled SQL: ' + s);
}
const fake = { enabled: () => true, q, init: async () => true };
const dbPath = require.resolve(path.join(__dirname, '..', 'db.js'));
require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: fake };
const fs = require('fs'); const os = require('os');
const ads = require('../ads');
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-loginq-sql-'));
ads.init({ dataDir, chain: { creditBalance: async () => 0 } });
ads.setRates({ loginSlotsMax: 6, loginSlotCredits: 1000, loginSlotDays: 30 });
const notified = []; ads.onLoginPromoted(async c => { notified.push(c.id); });
const row = (o) => { const c = Object.assign({ id: nextId++, owner_email: 'x@qa.test', member_id: 1, house: 0, type: 'login', name: 'QA', target_url: 'https://example.com', image_url: null, title: null, body: '30', budget: 1000, spent: 1000, accrued: 0, imps: 0, clicks: 0, batch_imps: 0, status: 'active', created: Date.now(), expires: Date.now() + 10 * DAY, starts: Date.now(), queued_at: null }, o); T.campaigns.push(c); return c; };
const reset = () => { T.campaigns = []; T.locks = {}; T.earned = {}; T.log = []; notified.length = 0; };
const live = () => liveRows(Date.now()).length;
const tick = () => new Promise(r => setTimeout(r, 30));
(async () => {
// 1. one slot frees, two queued, five promoters at once: exactly one start, the oldest
for (let round = 0; round < 25; round++) {
reset();
const slots = []; for (let i = 0; i < 6; i++) slots.push(row({ owner_email: 's' + i + '@qa.test', expires: Date.now() + (i + 1) * DAY }));
const a = row({ owner_email: 'a@qa.test', status: 'queued', queued_at: 1000, expires: null, starts: null });
const b = row({ owner_email: 'b@qa.test', status: 'queued', queued_at: 2000, expires: null, starts: null });
slots[0].expires = Date.now() - 1000;
const res = await Promise.all([1, 2, 3, 4, 5].map(() => ads.promoteLoginQueue()));
await tick();
const started = res.flatMap(r => r.promoted.map(c => c.id));
const good = started.length === 1 && started[0] === a.id && a.status === 'active' && b.status === 'queued' && live() === 6 && notified.length === 1 && T.locks.login_queue.holder === null;
if (!good || round === 24) ok(good, 'round ' + (round + 1) + '/25: five concurrent promoters, one free slot -> exactly one start (the oldest), 6 live, one notice, lock released', JSON.stringify({ started, a: a.status, b: b.status, live: live(), notified, lock: T.locks.login_queue }));
if (!good) break;
}
// 2. two free slots, three queued, concurrent promoters: exactly two start, the two oldest, never over the cap
{
reset();
for (let i = 0; i < 4; i++) row({});
const q = [3000, 1000, 2000].map(t => row({ status: 'queued', queued_at: t, expires: null, starts: null }));
const res = await Promise.all([1, 2, 3].map(() => ads.promoteLoginQueue()));
const started = res.flatMap(r => r.promoted.map(c => c.id)).sort();
ok(started.length === 2 && started.join() === [q[1].id, q[2].id].sort().join() && q[0].status === 'queued' && live() === 6, 'two slots free: the two oldest start, the third waits, cap 6', JSON.stringify({ started, live: live() }));
}
// 3. a cancel racing a start: exactly one wins, the refund is paid only if the cancel won
{
let bad = 0;
for (let round = 0; round < 40; round++) {
reset();
for (let i = 0; i < 5; i++) row({});
const a = row({ owner_email: 'race@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null });
const [cn, pr] = await Promise.all([ads.cancelLoginReservation('race@qa.test', a.id), ads.promoteLoginQueue()]);
const refunded = (T.earned['race@qa.test'] || { balance: 0 }).balance;
const cancelWon = !!cn.ok, startWon = pr.promoted.length === 1;
if (cancelWon === startWon || (cancelWon && (a.status !== 'cancelled' || refunded !== 1000)) || (startWon && (a.status !== 'active' || refunded !== 0))) bad++;
}
ok(bad === 0, '40 rounds of cancel vs start on the same reservation: always exactly one winner, refund only when the cancel won', bad + ' bad rounds');
}
// 4. a lease held by the other app copy: the tick backs off; an expired lease is taken over
{
reset();
for (let i = 0; i < 5; i++) row({});
const a = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 10000 };
let r = await ads.promoteLoginQueue();
ok(r.busy === true && !r.promoted.length && a.status === 'queued' && T.locks.login_queue.holder === 'other-copy', 'lease held by the other copy: no start, the tick backs off, the lease is untouched', JSON.stringify(r));
T.locks.login_queue.until = Date.now() - 1; // that copy died holding it
r = await ads.promoteLoginQueue();
ok(r.promoted.length === 1 && a.status === 'active' && T.locks.login_queue.holder === null, 'an expired lease is taken over, the reservation starts, the lease is released', JSON.stringify({ n: r.promoted.length, lock: T.locks.login_queue }));
}
// 5. resume rule in SQL mode: a paused slot stays paused while the line is non-empty, even with a slot free
{
reset();
for (let i = 0; i < 4; i++) row({});
const p = row({ owner_email: 'pz@qa.test', status: 'paused' });
const w = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 60000 }; // keep the line from starting w during the check
const t0 = Date.now(); let r = await ads.setStatus('pz@qa.test', p.id, 'active');
ok(r.error && /busy/.test(r.error) && p.status === 'paused' && Date.now() - t0 >= 3000, 'resume waits for the lease and gives up cleanly while another copy holds it', JSON.stringify(r));
T.locks.login_queue = { holder: null, until: 0 };
// 4 live + 1 waiting = 5 of 6: one place is open, so the paused slot may resume
r = await ads.setStatus('pz@qa.test', p.id, 'active');
ok(r.ok && p.status === 'active', '4 live + 1 waiting of 6: a place is open, the paused slot resumes', JSON.stringify(r).slice(0, 100));
p.status = 'paused'; row({}); // now 5 live + 1 waiting = 6
r = await ads.setStatus('pz@qa.test', p.id, 'active');
ok(r.error && /line goes first/.test(r.error) && p.status === 'paused', '5 live + 1 waiting of 6: resume refused, the line goes first', JSON.stringify(r));
r = await ads.setStatus(w.owner_email, w.id, 'active');
ok(r.error && /already in line/.test(r.error), 'a reservation cannot be "resumed" past the line', JSON.stringify(r));
}
// 6. cancel refunds once, at purchase grade, with the ledger line
{
reset();
const a = row({ owner_email: 'c@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null, spent: 600, accrued: 400 });
const r1 = await ads.cancelLoginReservation('c@qa.test', a.id), r2 = await ads.cancelLoginReservation('c@qa.test', a.id);
const e = T.earned['c@qa.test'];
ok(r1.ok && r1.refunded === 1000 && r2.error && e.balance === 1000 && e.grade === 1000, 'cancel: 1,000 back once (spent + accrued), purchased grade; the second cancel pays nothing', JSON.stringify({ r1, r2, e }));
ok(T.log.some(l => l.delta === 1000 && /^Login slot reservation cancelled: refund/.test(l.note) && l.kind === 'refund'), 'credit_log row "Login slot reservation cancelled: refund"', JSON.stringify(T.log));
const r3 = await ads.cancelLoginReservation('someone@else.test', a.id);
ok(r3.error === 'No such reservation.', 'another member cannot cancel it or learn its state', JSON.stringify(r3));
}
fs.rmSync(dataDir, { recursive: true, force: true });
console.log(fails ? fails + ' FAILED' : 'ALL PASS');
process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });
+131
View File
@@ -0,0 +1,131 @@
// Prepaid login-ad line (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line").
// node qa/login-queue.cjs
// Store-level test of ads.js in JSON mode on a throwaway data dir (no server, no DB, no chain: a fake chain returns
// made-up on-chain balances for made-up members). Nothing here can reach production or a real member.
// Covers: fill 6 slots, a 7th buy is refused with the reserve offer, reserve 2 (balances drop at once, credit log lines),
// places + estimated starts, one slot expires -> two concurrent promoters start the first reservation exactly once
// (owner notified once, cap never exceeded), cancel the second -> full refund once, edit before start is free,
// a freed slot goes to the line before a paused slot, paused-resume blocked while the line is non-empty, earned credits
// never pay. Exit 1 on any failure.
'use strict';
delete process.env.DATABASE_URL; // JSON store, always
const fs = require('fs'); const os = require('os'); const path = require('path');
const ads = require('../ads');
const DAY = 86400000;
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-loginq-'));
const onchain = {}; // memberId -> on-chain credits (fake)
ads.init({ dataDir, chain: { creditBalance: async id => onchain[id] || 0 } });
ads.setRates({ loginSlotsMax: 6, loginSlotCredits: 1000, loginSlotDays: 30 });
const notified = []; ads.onLoginPromoted(async c => { notified.push(c.id); });
const tick = () => new Promise(r => setTimeout(r, 30));
const M = n => ({ email: 'lq' + n + '@qa.test', id: 500 + n });
const avail = async n => (await ads.balances([M(n).id], M(n).email)).available;
const buy = (n, extra) => ads.createCampaign(M(n).email, M(n).id, Object.assign({ type: 'login', name: 'QA login ' + n, targetUrl: 'https://example.com/' + n, budget: 1000 }, extra || {}), [M(n).id]);
const row = async id => ads.campaignById(id); // JSON mode: the live row
const live = async () => (await ads.adminLoginQueue()).used;
(async () => {
for (let n = 1; n <= 14; n++) onchain[M(n).id] = 5000;
// 1. six slots fill and go live, each paid up front
const slot = {};
for (let n = 1; n <= 6; n++) { const r = await buy(n); slot[n] = r.campaign && r.campaign.id; ok(r.ok && r.campaign.status === 'active', 'slot ' + n + ' of 6 goes live', JSON.stringify(r).slice(0, 160)); }
ok(await avail(1) === 4000, 'a live slot drops the balance by 1,000', String(await avail(1)));
// give the six slots distinct end dates: slot n ends in n days
for (let n = 1; n <= 6; n++) (await row(slot[n])).expires = Date.now() + n * DAY;
// 2. the seventh buy is refused with the reserve offer, nothing charged
let r = await buy(7);
ok(r.error && r.full === true && r.place === 1 && /reserve the next slot/i.test(r.error), 'all 6 taken: plain buy refused with a reserve offer (place #1)', JSON.stringify(r).slice(0, 220));
ok(await avail(7) === 5000, 'the refused buy charged nothing', String(await avail(7)));
// 3. reserve two: paid now, status queued, no clock, credit log line
const q7 = await buy(7, { reserve: true }), q8 = await buy(8, { reserve: true });
ok(q7.ok && q7.queued && q7.place === 1 && q7.campaign.status === 'queued', 'member 7 reserves: queued, place #1', JSON.stringify(q7).slice(0, 200));
ok(q8.ok && q8.queued && q8.place === 2, 'member 8 reserves: place #2', JSON.stringify(q8).slice(0, 120));
ok(await avail(7) === 4000 && await avail(8) === 4000, 'both balances dropped by 1,000 at reserve time', (await avail(7)) + ' / ' + (await avail(8)));
const c7 = await row(q7.campaign.id);
ok(c7.status === 'queued' && !c7.expires && !c7.starts && c7.queuedAt > 0 && (c7.spent + (c7.accrued || 0)) === 1000, 'a reservation has no start/end yet, a queuedAt stamp, and is fully charged', JSON.stringify({ s: c7.status, e: c7.expires, st: c7.starts, q: c7.queuedAt, spent: c7.spent, acc: c7.accrued }));
const log7 = await ads.creditActivity(M(7).email);
ok(log7.some(i => /^Login slot reserved \(queue #1\)/.test(i.note) && i.delta === -1000), 'credit log: "Login slot reserved (queue #1)" -1000', JSON.stringify(log7.map(i => i.note + ' ' + i.delta)));
ok(await live() === 6, 'reservations do not count as live slots', String(await live()));
ok(!(await ads.serve('login', {})) || ![q7.campaign.id, q8.campaign.id].includes((await ads.serve('login', {})).id), 'a reservation never serves');
{ let served = new Set(); for (let i = 0; i < 60; i++) { const s = await ads.serve('login', {}); if (s) served.add(s.id); } ok(!served.has(q7.campaign.id) && !served.has(q8.campaign.id), 'sixty serves: never a queued ad', [...served].join(',')); }
// 4. places and estimated starts: #1 when slot 1 ends (1 day), #2 when slot 2 ends (2 days), a new one at slot 3 (3 days)
let A = await ads.adminLoginQueue();
const near = (a, b) => a && Math.abs(a - b) < 5000;
ok(A.queue.length === 2 && A.queue[0].id === q7.campaign.id && A.queue[0].place === 1 && A.queue[1].place === 2, 'admin view: the line in paid order', JSON.stringify(A.queue.map(x => [x.id, x.place])));
ok(near(A.queue[0].estStart, (await row(slot[1])).expires) && near(A.queue[1].estStart, (await row(slot[2])).expires), 'estimated starts follow the live slots\' end dates', JSON.stringify(A.queue.map(x => x.estStart)));
const V = await ads.loginQueueView(M(8).email);
ok(V.free === 0 && V.nextPlace === 3 && near(V.nextEstStart, (await row(slot[3])).expires) && V.mine.length === 1 && V.mine[0].place === 2 && !JSON.stringify(V).includes(M(7).email), 'member view: own place #2, next place #3 at slot 3\'s end, nobody else\'s email', JSON.stringify(V).slice(0, 260));
// estimator alone: 6 slots ending day 1..6, 8 waiting -> the 7th starts when the first reservation's 30 days end
{ const now = 1e12; const e = ads.estimateStarts(6, [1, 2, 3, 4, 5, 6].map(d => now + d * DAY), 8, now, 30 * DAY);
ok(e[0] === now + DAY && e[5] === now + 6 * DAY && e[6] === now + 31 * DAY && e[7] === now + 32 * DAY, 'estimator: a full round, then reservations wait on reservations', JSON.stringify(e.map(x => (x - now) / DAY))); }
// 5. edit before the start: free, place unchanged
const before = await avail(8);
r = await ads.editLoginReservation(M(8).email, q8.campaign.id, { targetUrl: 'https://example.org/new', title: 'New headline' });
ok(r.ok && (await row(q8.campaign.id)).targetUrl === 'https://example.org/new' && await avail(8) === before, 'edit a reservation: saved, nothing charged', JSON.stringify(r).slice(0, 120));
r = await ads.editLoginReservation(M(7).email, q8.campaign.id, { targetUrl: 'https://evil.example' });
ok(r.error, 'another member cannot edit it', JSON.stringify(r));
r = await ads.setStatus(M(7).email, q7.campaign.id, 'paused');
ok(r.error && /waiting in line/.test(r.error), 'a reservation cannot be paused', JSON.stringify(r));
// 6. slot 1 expires -> two promoters at once: the first reservation starts exactly once
(await row(slot[1])).expires = Date.now() - 1000;
const [p1, p2] = await Promise.all([ads.promoteLoginQueue(), ads.promoteLoginQueue()]);
await tick();
const started = [...p1.promoted, ...p2.promoted];
ok(started.length === 1 && started[0].id === q7.campaign.id, 'two concurrent promoters: exactly one start, the oldest paid', JSON.stringify([p1, p2]).slice(0, 200));
const s7 = await row(q7.campaign.id);
ok(s7.status === 'active' && Math.abs(s7.starts - Date.now()) < 5000 && Math.abs(s7.expires - (s7.starts + 30 * DAY)) < 5 && s7.body === '30', 'the started ad: active, starts now, ends in 30 days', JSON.stringify({ st: s7.status, starts: s7.starts, expires: s7.expires }));
ok(notified.length === 1 && notified[0] === q7.campaign.id, 'its owner is notified once', JSON.stringify(notified));
ok(await live() === 6, 'the cap holds: 6 live', String(await live()));
r = await ads.promoteLoginQueue(); ok(!r.promoted.length, 'a third promoter finds nothing to do (slots full)');
ok(await avail(7) === 4000, 'starting charged nothing more', String(await avail(7)));
// 7. cancel the second reservation: full refund, exactly once
r = await ads.cancelLoginReservation(M(8).email, q8.campaign.id);
ok(r.ok && r.refunded === 1000, 'cancel before the start refunds the full 1,000', JSON.stringify(r));
ok(await avail(8) === 5000, 'member 8 balance back to 5,000', String(await avail(8)));
const sp8 = await ads.earnedSplit(M(8).email);
ok(sp8.grade === 1000, 'the refund is purchased-grade (same kind as paid)', JSON.stringify(sp8));
const log8 = await ads.creditActivity(M(8).email);
ok(log8.some(i => /^Login slot reservation cancelled: refund/.test(i.note) && i.delta === 1000), 'credit log: "Login slot reservation cancelled: refund" +1000', JSON.stringify(log8.map(i => i.note + ' ' + i.delta)));
r = await ads.cancelLoginReservation(M(8).email, q8.campaign.id);
ok(r.error && await avail(8) === 5000, 'a second cancel refunds nothing', JSON.stringify(r));
r = await ads.cancelLoginReservation(M(7).email, q7.campaign.id);
ok(r.error && /already started/.test(r.error) && await avail(7) === 4000, 'a started ad cannot be cancelled for a refund', JSON.stringify(r));
ok((await row(q8.campaign.id)).status === 'cancelled', 'cancelled stays cancelled');
r = await ads.archive(M(8).email, q8.campaign.id); ok(r.ok && r.freed === 0, 'a cancelled reservation can be archived, freeing 0', JSON.stringify(r));
// 8. a freed slot goes to the line before a paused slot
const q9 = await buy(9, { reserve: true });
ok(q9.queued && q9.place === 1, 'member 9 reserves: place #1');
r = await ads.setStatus(M(2).email, slot[2], 'paused'); await tick();
ok(r.ok && (await row(q9.campaign.id)).status === 'active', 'pausing slot 2 hands its place to the line at once', (await row(q9.campaign.id)).status);
ok(notified.includes(q9.campaign.id), 'member 9 notified');
r = await ads.setStatus(M(2).email, slot[2], 'active');
ok(r.error && /taken/.test(r.error), 'slot 2 cannot resume while all 6 are live', JSON.stringify(r));
// 9. paused-resume blocked while the line is non-empty, even with a slot free
const q10 = await buy(10, { reserve: true });
(await row(slot[3])).expires = Date.now() - 1000; // slot 3 ends; no tick yet: 5 live, 1 waiting
ok(await live() === 5, 'slot 3 ended: 5 live, 1 waiting', String(await live()));
r = await ads.setStatus(M(2).email, slot[2], 'active');
ok(r.error && /line goes first/.test(r.error) && (await row(slot[2])).status === 'paused', 'resume refused while the line is non-empty (the line goes first)', JSON.stringify(r));
r = await buy(11);
// a new plain buy also respects the line: the freed slot went to member 10, member 11 is offered a reservation
ok((await row(q10.campaign.id)).status === 'active', 'a new buy first starts the waiting reservation (member 10 live)', (await row(q10.campaign.id)).status);
ok(r.error && r.full === true, 'and member 11 is offered the line, not the slot', JSON.stringify(r).slice(0, 160));
ok(await live() === 6, 'still 6 live', String(await live()));
// 10. with nobody waiting and a slot open, the paused slot resumes
(await row(slot[4])).expires = Date.now() - 1000;
r = await ads.setStatus(M(2).email, slot[2], 'active');
ok(r.ok && (await row(slot[2])).status === 'active' && await live() === 6, 'slot open and nobody waiting: the paused slot resumes', JSON.stringify(r).slice(0, 120));
// 11. earned (viewing) credits never pay for a reservation
await ads.addEarned(M(12).email, 5000); onchain[M(12).id] = 0;
r = await buy(12, { reserve: true });
ok(r.error && /purchased credits only/.test(r.error), 'earned credits cannot buy a reservation', JSON.stringify(r).slice(0, 160));
ok((await ads.adminLoginQueue()).queue.length === 0, 'nothing was queued for it');
// 12. admin cancel refunds the owner in full
const q13 = await buy(13, { reserve: true });
r = await ads.cancelLoginReservation(null, q13.campaign.id, { admin: true });
ok(r.ok && r.refunded === 1000 && await avail(13) === 5000, 'admin cancel: full refund to the owner', JSON.stringify(r));
fs.rmSync(dataDir, { recursive: true, force: true });
console.log(fails ? fails + ' FAILED' : 'ALL PASS');
process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });
+1 -1
View File
@@ -27,7 +27,7 @@ t('same total as 30 days at the old daily rate',
const src = require('fs').readFileSync(new URL('../ads.js', import.meta.url), 'utf8');
t('buying a slot charges the whole price up front',
/Login-ad slot \(/.test(src) && /chargeCredits\(campaign\.id, v\.c\.budget, 'Login-ad slot/.test(src));
/Login-ad slot \(/.test(src) && /chargeCredits\(campaign\.id, (v\.)?c\.budget, 'Login-ad slot/.test(src));
t('a slot gets an end date at purchase',
/out\.expires = Date\.now\(\) \+ days \* 86400000/.test(src));
t('the MySQL daily meter skips slot campaigns',
+81
View File
@@ -0,0 +1,81 @@
// Syndicated rate (Marty, 2026-10-27, approved 4:1): delivery off instantadpay.com costs 1/synRateDivisor of the on-site rate.
// JSON store, NAS layer stubbed, throwaway data dir: no server, DB, chain, NAS or PassiveDrip. node qa/nas-ratio.mjs
// Covers: N=4 NAS views charge 1 credit per 20 banner views, fractions carried exactly, own credit-log line, budget is the
// limit (exhaustion stops the NAS ad with the true count), a lowered rate tops NAS up to what the budget now buys, N=1 is the
// old rule, on-site batches unchanged, PassiveDrip: 4 partner visits use 1 pack visit, all counted in synImps, PD offered x4.
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const require = createRequire(import.meta.url);
delete process.env.DATABASE_URL;
const ok = [], bad = [];
const t = (n, c, extra) => { (c ? ok : bad).push(n + (c || extra === undefined ? '' : ' -> ' + extra)); };
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-nas-ratio-'));
const nas = require('../nas.js');
const rows = {}; const calls = { topUp: [], deactivate: 0 };
nas.enabled = () => true;
nas.impressionsPerCredit = type => type === 'banner' ? 5 : 10;
nas.readServed = async id => { const r = rows[id]; return r ? { assigned: r.assigned, remaining: r.remaining, served: Math.max(0, Math.min(r.assigned, r.assigned - r.remaining)), clicks: 0 } : null; };
nas.deactivate = async id => { const r = rows[id]; const served = Math.max(0, r.assigned - r.remaining); r.remaining = 0; calls.deactivate++; return { ok: true, served }; };
nas.topUp = async (id, add) => { rows[id].assigned += add; rows[id].remaining += add; calls.topUp.push([id, add]); return { ok: true }; };
nas.restart = async (id, base, add) => { rows[id].assigned = base + add; rows[id].remaining = add; return { ok: true }; };
const ads = require('../ads.js');
const OWNER = 'ratio@qa.test', FILE = path.join(DATA, 'campaigns.json');
const banner = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'banner', name: 'QA ' + id, targetUrl: 'https://example.com/', imageUrl: 'https://example.com/b.png', width: 728, height: 90,
budget: 1000, spent: 0, accrued: 0, imps: 0, batchImps: 0, clicks: 0, status: 'active', nasAdId: id, nasServed: 0, created: Date.now() }, x || {});
const visits = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'visits', name: 'QA visits ' + id, targetUrl: 'https://example.com/v', body: '100', budget: 300, spent: 300, accrued: 0, imps: 10, clicks: 0, status: 'active', created: Date.now() }, x || {});
const seed = camps => { fs.writeFileSync(FILE, JSON.stringify({ v: 1, nextId: 9100, campaigns: camps, burnsPending: [] })); ads.init({ dataDir: DATA, chain: { creditBalance: async () => 0 } }); };
const C = id => JSON.parse(fs.readFileSync(FILE, 'utf8')).campaigns.find(c => c.id === id);
const used = c => (c.spent || 0) + (c.accrued || 0);
const deliver = (id, n) => { rows[id].remaining -= n; };
seed([banner(9001), visits(9101)]);
await ads.addEarned(OWNER, 100000);
t('default divisor is 4', ads.synRateDivisor() === 4, String(ads.synRateDivisor()));
rows[9001] = { assigned: 20000, remaining: 20000 }; rows[9002] = { assigned: 200, remaining: 200 };
deliver(9001, 1000); await ads.reconcileNas();
t('N=4: 1,000 network banner views charge 50 credits (1 per 20)', used(C(9001)) === 50, String(used(C(9001))));
deliver(9001, 10); await ads.reconcileNas();
t('10 more views: no whole credit yet', used(C(9001)) === 50, String(used(C(9001))));
deliver(9001, 10); await ads.reconcileNas();
t('10 more: the fraction completes one credit (exact)', used(C(9001)) === 51, String(used(C(9001))));
const log = (await ads.creditActivity(OWNER, 50)).filter(i => i.delta < 0);
t('credit log line names the network rate', log.some(i => /^Network views \(1\/4 rate\): /.test(i.note) && i.delta === -51), JSON.stringify(log.map(i => i.note + ' ' + i.delta)));
// on-site batches unchanged
for (let i = 0; i < 10; i++) await ads.serve('banner', { width: 728, height: 90 });
t('on-site: 10 views still charge 2 credits', used(C(9001)) === 53, String(used(C(9001))));
// budget is the limit
seed([C(9001), C(9101), banner(9002, { budget: 10 })]);
const onsite2 = used(C(9002));
deliver(9002, 200); await ads.reconcileNas();
const x = C(9002);
t('budget is the limit: the network charge stops at the budget', used(x) === 10 && x.status === 'out', JSON.stringify({ used: used(x), onsite2, st: x.status }));
t('exhaustion stops the NAS ad', calls.deactivate >= 1 && rows[9002].remaining === 0);
// rate lowered: NAS gets topped up to what the budget now buys
ads.setRates({ synRateDivisor: 1 });
rows[9003] = { assigned: 1000, remaining: 1000 };
seed([C(9001), C(9002), C(9101), banner(9003)]);
deliver(9003, 500); await ads.reconcileNas();
t('N=1 (old rule): 500 network views charge 100 credits', used(C(9003)) === 100, String(used(C(9003))));
ads.setRates({ synRateDivisor: 4 });
const before = calls.topUp.length; await ads.reconcileNas();
const tu = calls.topUp.slice(before).find(x => x[0] === 9003);
t('rate lowered to 1/4: NAS is topped up to what the 900 credits left now buy (18,000 views)', tu && rows[9003].remaining === 18000, JSON.stringify({ tu, row: rows[9003] }));
await ads.reconcileNas();
t('and not topped up again on the next pass', calls.topUp.slice(before).filter(x => x[0] === 9003).length === 1);
// PassiveDrip
let a = await ads.applyExternalVisits(9101, Math.floor(7 / 4) - Math.floor(0 / 4), 'PassiveDrip', 7);
let v = C(9101);
t('PD: 7 partner visits use up 1 pack visit', a.applied === 1 && v.imps === 11, JSON.stringify(a) + ' imps ' + v.imps);
t('PD: all 7 counted as partner visits', v.synImps === 7, String(v.synImps));
a = await ads.applyExternalVisits(9101, Math.floor(8 / 4) - Math.floor(7 / 4), 'PassiveDrip', 1);
v = C(9101);
t('PD: the 8th completes the second pack visit (fraction carried)', v.imps === 12 && v.synImps === 8, JSON.stringify({ imps: v.imps, syn: v.synImps }));
const pd = require('../pdsync.js'); pd.init({ dataDir: DATA, ads });
const L = (await pd.listing()).find(c => c.id === 9101);
t('pdsync offers PD the visits left x 4 (88 x 4 = 352)', L && L.visitsLeft === 352, JSON.stringify(L));
console.log('PASS ' + ok.length);
for (const b of bad) console.log('FAIL ' + b);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
process.exit(bad.length ? 1 : 0);
+55
View File
@@ -0,0 +1,55 @@
// NAS phantom delivery on resume / top-up (found 2026-10-27). stopNas zeroes `remaining` after recording the true served
// count. Resuming (or topping up) used a plain topUp, so assigned - remaining then read the zeroed remainder as served
// and the next reconcileNas CHARGED it. Fix: a stopped ad restarts from the true count (nas.restart).
// JSON store, NAS layer stubbed, throwaway data dir. node qa/nas-restart.mjs
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const require = createRequire(import.meta.url);
delete process.env.DATABASE_URL;
const ok = [], bad = [];
const t = (n, c, extra) => { (c ? ok : bad).push(n + (c || extra === undefined ? '' : ' -> ' + extra)); };
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-nas-restart-'));
const nas = require('../nas.js');
const rows = {}; const calls = { restart: 0, topUp: 0 };
nas.enabled = () => true;
nas.impressionsPerCredit = type => type === 'banner' ? 5 : 10;
nas.readServed = async id => { const r = rows[id]; return r ? { assigned: r.assigned, remaining: r.remaining, served: Math.max(0, Math.min(r.assigned, r.assigned - r.remaining)), clicks: 0 } : null; };
nas.deactivate = async id => { const r = rows[id]; const served = Math.max(0, r.assigned - r.remaining); r.remaining = 0; return { ok: true, served }; };
nas.topUp = async (id, add) => { rows[id].assigned += add; rows[id].remaining += add; calls.topUp++; return { ok: true }; };
nas.restart = async (id, base, add) => { rows[id].assigned = base + add; rows[id].remaining = add; calls.restart++; return { ok: true }; };
const ads = require('../ads.js');
const OWNER = 'restart@qa.test', FILE = path.join(DATA, 'campaigns.json');
const banner = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'banner', name: 'QA ' + id, targetUrl: 'https://example.com/', imageUrl: 'https://example.com/b.png', width: 728, height: 90,
budget: 1000, spent: 0, accrued: 0, imps: 0, batchImps: 0, clicks: 0, status: 'active', nasAdId: id, nasServed: 0, created: Date.now() }, x || {});
fs.writeFileSync(FILE, JSON.stringify({ v: 1, nextId: 9100, campaigns: [banner(9001)], burnsPending: [] }));
ads.init({ dataDir: DATA, chain: { creditBalance: async () => 0 } });
ads.setRates({ synRateDivisor: 1 }); // the restart logic at the on-site rate (qa/nas-ratio.mjs covers the network rate)
const C = id => JSON.parse(fs.readFileSync(FILE, 'utf8')).campaigns.find(c => c.id === id);
const used = c => (c.spent || 0) + (c.accrued || 0);
await ads.addEarned(OWNER, 10000);
rows[9001] = { assigned: 5000, remaining: 5000 };
rows[9001].remaining -= 1000; await ads.reconcileNas();
t('1,000 real NAS views charge 200 credits', used(C(9001)) === 200, String(used(C(9001))));
await ads.setStatus(OWNER, 9001, 'paused');
t('pause records the true 1,000 served', C(9001).nasServed === 1000, String(C(9001).nasServed));
const r0 = calls.restart; await ads.setStatus(OWNER, 9001, 'active');
t('resume restarts the stopped ad (not a plain top-up)', calls.restart === r0 + 1, String(calls.restart - r0));
t('resume books the budget left (800 credits x 5 = 4,000)', rows[9001].remaining === 4000 && rows[9001].assigned === 5000, JSON.stringify(rows[9001]));
await ads.reconcileNas();
t('no phantom charge after the resume', used(C(9001)) === 200, String(used(C(9001))));
rows[9001].remaining -= 500; await ads.reconcileNas();
t('real views after the resume still charge (500 views = 100)', used(C(9001)) === 300, String(used(C(9001))));
// a running ad that is topped up keeps a plain top-up
const tu = calls.topUp; await ads.topUpCampaign(OWNER, 0, 9001, 100);
t('top-up of a running ad is a plain top-up (+500)', calls.topUp === tu + 1 && rows[9001].remaining === 4000, JSON.stringify(rows[9001]));
// a stopped ad that is topped up restarts from the true count
await ads.setStatus(OWNER, 9001, 'paused'); const before = used(C(9001));
const r1 = calls.restart; await ads.topUpCampaign(OWNER, 0, 9001, 100); await ads.reconcileNas();
t('top-up of a stopped ad restarts it', calls.restart === r1 + 1, String(calls.restart - r1));
t('and charges nothing that was not served', used(C(9001)) === before, used(C(9001)) + ' vs ' + before);
console.log('PASS ' + ok.length);
for (const b of bad) console.log('FAIL ' + b);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
process.exit(bad.length ? 1 : 0);
+236
View File
@@ -0,0 +1,236 @@
// Level-4 override payer tests (2026-10-23). Throwaway DATA_DIR in the OS temp folder, a FAKE chain, a FAKE signer and a
// FAKE database: nothing here touches Polygon, the production volume or a real member. Run: node qa/override.test.cjs
'use strict';
const fs = require('fs'), os = require('os'), path = require('path'), assert = require('assert');
const OV = require(path.join(__dirname, '..', 'override.js'));
const { create, weekOf, weekBounds, payableAt, polStr, toWei } = OV;
const E = 10n ** 18n;
let pass = 0, fail = 0;
async function test(name, fn) { try { await fn(); pass++; console.log(' ok ' + name); } catch (e) { fail++; console.log(' FAIL ' + name + '\n ' + (e && e.stack || e).toString().split('\n').slice(0, 3).join('\n ')); } }
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ovtest-'));
const tickAsync = () => new Promise(r => setImmediate(r));
// ---- fakes ----
// tree: spec { id: [sponsorId, buyerCount] }
function fakeChain(tree, purchases, extraEvents) {
const events = purchases.map((p, i) => Object.assign({ type: 'Purchase', tx: '0xbuy' + i, li: 0, block: 1000 + i }, p)).concat(extraEvents || []);
return {
events,
member: async id => { await tickAsync(); const t = tree[id]; if (!t) return { sponsorId: 0, buyerCount: 0 }; return { sponsorId: t[0], buyerCount: t[1] }; },
recentEvents: () => events,
getConfig: () => ({ explorer: 'https://polygonscan.example', contract: '0xcontract', chainId: 137 }),
suggestedFees: async () => ({ maxPriorityFeePerGas: '0x' + (30n * 10n ** 9n).toString(16), maxFeePerGas: '0x' + (100n * 10n ** 9n).toString(16) })
};
}
function fakePayer(balanceWei, opts) {
const o = opts || {}; let n = 0;
const p = { address: '0x00000000000000000000000000000000000000aa', bal: BigInt(balanceWei), sends: [], opts: o,
balance: async () => { await tickAsync(); return p.bal; },
fees: async () => ({ maxFeePerGas: 100n * 10n ** 9n, maxPriorityFeePerGas: 30n * 10n ** 9n }),
preflight: async id => { await tickAsync(); if ((o.reject || []).includes(id)) throw Object.assign(new Error('execution reverted'), { reason: 'Send failed' }); },
send: async (id, wei) => {
await tickAsync(); await tickAsync();
if ((o.throwOn || []).includes(id)) throw new Error('server response 502');
p.sends.push({ id, wei: BigInt(wei) }); p.bal -= BigInt(wei); const hash = '0x' + (++n).toString(16).padStart(64, '0');
return { hash, wait: async () => { await tickAsync(); return { status: 1 }; } };
} };
return p;
}
function fakeDb(opts) {
const set = new Set(); const o = opts || {};
return { set, enabled: () => true, q: async (sql, params) => {
await tickAsync();
if (o.broken) throw new Error('connection lost');
if (/^INSERT IGNORE INTO event_marks/.test(sql)) { if (set.has(params[0])) return { affectedRows: 0 }; set.add(params[0]); return { affectedRows: 1 }; }
throw new Error('unexpected sql ' + sql);
} };
}
function instance(o) {
const ov = create(); const sent = [];
ov.init({ dataDir: o.dir, chain: o.chain, db: o.db || null, payer: o.payer, now: () => o.clock.t, siteConfig: () => o.site, notify: async t => { (o.tg || sent).push(t); return true; } });
return ov;
}
// a world: buyers under a qualified #10 (6 buyers) four levels up; #20 unqualified (2 buyers) is skipped once
const WK1 = '2026-10-26', WK2 = '2026-11-02';
const goLive = weekBounds(WK1).from;
const TREE = { 1: [0, 99], 10: [1, 6], 20: [10, 2], 30: [20, 0], 40: [30, 0], 50: [40, 0], 60: [50, 0],
// a short line under the company: 70 -> 71 -> 1
71: [1, 1], 70: [71, 0],
// #11 (qualified, 5 buyers) is the 4th upline of #81
11: [1, 5], 12: [11, 0], 13: [12, 0], 14: [13, 0], 81: [14, 0] };
const at = (wk, h) => weekBounds(wk).from + h * 3600000;
const buy = (buyerId, cents, pol, ts) => ({ buyerId, priceCents: cents, paidWei: (toWei(String(pol))).toString(), ts });
(async () => {
console.log('override.test: week math');
await test('weekOf: Sunday 11:30 PM CT belongs to the week before, Monday 12:30 AM CT to the new week', () => {
assert.strictEqual(weekOf(Date.parse('2026-10-26T04:30:00Z')), '2026-10-19'); // Sun 23:30 CDT
assert.strictEqual(weekOf(Date.parse('2026-10-26T05:30:00Z')), '2026-10-26'); // Mon 00:30 CDT
});
await test('week across the November DST change: Mon 00:00 CDT to Mon 00:00 CST (169 hours)', () => {
const b = weekBounds('2026-10-26');
assert.strictEqual(new Date(b.from).toISOString(), '2026-10-26T05:00:00.000Z');
assert.strictEqual(new Date(b.to).toISOString(), '2026-11-02T06:00:00.000Z');
assert.strictEqual((b.to - b.from) / 3600000, 169);
assert.strictEqual(weekOf(Date.parse('2026-11-02T05:30:00Z')), '2026-10-26'); // Sun 23:30 CST
});
await test('week across the March DST change: 167 hours', () => { const b = weekBounds('2027-03-08'); assert.strictEqual((b.to - b.from) / 3600000, 167); });
await test('payable from 9 AM Central the Monday after', () => { assert.strictEqual(new Date(payableAt('2026-10-19')).toISOString(), '2026-10-26T14:00:00.000Z'); assert.strictEqual(new Date(payableAt('2026-10-26')).toISOString(), '2026-11-02T15:00:00.000Z'); });
await test('polStr / toWei round trip', () => { assert.strictEqual(polStr(toWei('12.3456')), '12.3456'); assert.strictEqual(toWei('0.01'), 10n ** 16n); });
console.log('override.test: who gets it');
const clock = { t: payableAt(WK1) + 3600000 };
await test('hunt: 4th upline #20 (2 buyers) is skipped, #10 (6 buyers) gets it with 1 hop', async () => {
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) });
const r = await ov.recipientFor(60); // 60 -> 50, 40, 30, [20 skipped], 10
assert.strictEqual(r.recipientId, 10); assert.strictEqual(r.hops, 1); assert.deepStrictEqual(r.skipped, [{ id: 20, buyers: 2 }]);
});
await test('exactly 5 buyers qualifies (#11 for #81)', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) }); assert.strictEqual((await ov.recipientFor(81)).recipientId, 11); });
await test('house: a hunt that reaches #1 leaves it with the company', async () => {
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) });
const r = await ov.recipientFor(40); // 40 -> 30, 20, 10, 1 : 4th up is #1
assert.strictEqual(r.recipientId, 0); assert.match(r.reason, /company account #1/);
});
await test('overrideHouseIds can add company positions (#10 as house)', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: { overrideHouseIds: '1,10' }, payer: fakePayer(0) }); assert.strictEqual((await ov.recipientFor(60)).recipientId, 0); });
await test('short line: company keeps it', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) }); assert.match((await ov.recipientFor(70)).reason, /shorter than 4/); });
await test('hunt cap: 30 unqualified uplines above the 4th, nobody within 25 hops', async () => {
const t = { 1: [0, 99] }; for (let i = 200; i < 240; i++) t[i] = [i + 1, 0]; t[240] = [1, 0]; t[199] = [200, 0];
const ov = instance({ dir: tmp(), chain: fakeChain(t, []), clock, site: {}, payer: fakePayer(0) });
const r = await ov.recipientFor(199); assert.strictEqual(r.recipientId, 0); assert.match(r.reason, /within 25 hops/); assert.strictEqual(r.skipped.length, 25);
});
console.log('override.test: the payer');
const PUR = [buy(60, 2000, 200, at(WK1, 30)), buy(60, 5000, 500, at(WK1, 50)), buy(81, 2000, 200, at(WK1, 60)), buy(40, 2000, 200, at(WK1, 70)),
buy(60, 2000, 200, goLive - 3600000) /* before go-live: never paid */, buy(81, 500, 0.2, at(WK2, 10)) /* next week */];
const LIVE = { overrideMode: 'live', overrideGoLive: goLive };
await test('default mode is dry run: nothing planned, nothing sent', async () => {
const dir = tmp(), payer = fakePayer(1000n * E); const ov = instance({ dir, chain: fakeChain(TREE, PUR), clock, site: { overrideGoLive: goLive }, payer });
const r = await ov.payDue(); assert.strictEqual(r.ready, false); assert.match(r.why.join(), /dryrun/); assert.strictEqual(payer.sends.length, 0);
assert.ok(!fs.existsSync(path.join(dir, 'override', 'weeks')));
});
await test('live without overrideGoLive is not ready', async () => { const payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), clock, site: { overrideMode: 'live' }, payer }); assert.strictEqual(ov.liveState().ready, false); await ov.payDue(); assert.strictEqual(payer.sends.length, 0); });
await test('live without a payer key is not ready (real key path)', async () => { delete process.env.OVERRIDE_PAYER_KEY; const ov = create(); ov.init({ dataDir: tmp(), chain: fakeChain(TREE, PUR), siteConfig: () => LIVE }); assert.match(ov.liveState().why.join(), /no payer key/); });
await test('a week is not planned before it closes, nor paid before Monday 9 AM CT', async () => {
const c2 = { t: weekBounds(WK1).to + 3600000 }; const payer = fakePayer(1000n * E); // Monday 1 AM
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), clock: c2, site: LIVE, payer });
assert.deepStrictEqual(ov.dueWeeks(), []); await ov.payDue(); assert.strictEqual(payer.sends.length, 0);
assert.deepStrictEqual(ov.dueWeeks(true), [WK1]); // the admin's "pay this week now" may settle a closed week early
});
await test('two payers at once (deploy overlap, shared DB + volume): each recipient paid exactly once', async () => {
const dir = tmp(), db = fakeDb(), payer = fakePayer(1000n * E), tg = [], chain = fakeChain(TREE, PUR);
const A = instance({ dir, chain, db, payer, clock, site: LIVE, tg }), B = instance({ dir, chain, db, payer, clock, site: LIVE, tg });
await Promise.all([A.payDue(), B.payDue(), A.payDue(), B.payDue()]);
const by = {}; for (const s of payer.sends) by[s.id] = (by[s.id] || 0n) + s.wei;
assert.strictEqual(payer.sends.length, 2, 'two recipients, two sends: ' + JSON.stringify(payer.sends.map(s => s.id)));
assert.strictEqual(by[10], toWei('21')); // 3% of 200 + 500 POL (two buys by #60)
assert.strictEqual(by[11], toWei('6')); // 3% of 200 POL
const st = A.weekStatus(WK1); assert.strictEqual(st.state, 'paid'); assert.ok(st.rows.every(r => r.state === 'paid' && r.txHash));
assert.strictEqual(tg.filter(t => /PAID/.test(t)).length, 1, 'one paid summary'); assert.match(tg.find(t => /PAID/.test(t)), /polygonscan\.example\/tx\//);
await Promise.all([A.payDue(), B.payDue()]); assert.strictEqual(payer.sends.length, 2, 'a second pass sends nothing');
});
await test('two payers at once with NO database (LinkSpin JSON mode): file claims alone hold', async () => {
const dir = tmp(), payer = fakePayer(1000n * E), chain = fakeChain(TREE, PUR);
const A = instance({ dir, chain, payer, clock, site: LIVE }), B = instance({ dir, chain, payer, clock, site: LIVE });
await Promise.all([A.payDue(), B.payDue(), A.payDue(), B.payDue()]);
assert.strictEqual(payer.sends.length, 2);
});
await test('a database that errors fails closed: nothing is planned or sent', async () => {
const payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), db: fakeDb({ broken: true }), payer, clock, site: LIVE });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK1).state, 'not planned');
});
await test('purchases before overrideGoLive are never paid (no back-pay)', async () => {
const payer = fakePayer(1000n * E); const late = { overrideMode: 'live', overrideGoLive: at(WK1, 55) }; // after #60's buys, before #81's
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: late });
await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id), [11]);
});
await test('dust: under 0.01 POL is carried, then rolled into the next week and paid', async () => {
const dir = tmp(), payer = fakePayer(1000n * E);
const P = [buy(81, 500, 0.2, at(WK1, 30)), buy(81, 2000, 200, at(WK2, 30))]; // week 1: 3% of 0.2 = 0.006 POL
const ck = { t: clock.t }; const ov = instance({ dir, chain: fakeChain(TREE, P), payer, clock: ck, site: LIVE });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0);
const s1 = ov.weekStatus(WK1); assert.strictEqual(s1.state, 'paid'); assert.strictEqual(s1.rows[0].state, 'carried');
ck.t = payableAt(WK2) + 60000; await ov.payDue();
assert.strictEqual(payer.sends.length, 1); assert.strictEqual(payer.sends[0].wei, toWei('6.006'));
assert.strictEqual(ov.weekStatus(WK1).rows[0].state, 'rolled'); assert.deepStrictEqual(ov.weekStatus(WK2).rows[0].carriedFrom, [WK1]);
});
await test('a dust amount that stays under the minimum keeps carrying', async () => {
const payer = fakePayer(1000n * E), P = [buy(81, 500, 0.1, at(WK1, 30)), buy(81, 500, 0.1, at(WK2, 30))];
const ck = { t: payableAt(WK2) + 60000 }; const ov = instance({ dir: tmp(), chain: fakeChain(TREE, P), payer, clock: ck, site: LIVE });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK2).rows[0].state, 'carried'); assert.strictEqual(ov.weekStatus(WK2).rows[0].amountWei, toWei('0.006').toString());
});
await test('cap: a week over overridePayCapPol is held whole, nothing sent, one alert', async () => {
const tg = [], payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: Object.assign({ overridePayCapPol: 20 }, LIVE), tg });
await ov.payDue(); await ov.payDue();
assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK1).state, 'held'); assert.match(ov.weekStatus(WK1).heldWhy, /cap/);
assert.strictEqual(tg.filter(t => /HELD/.test(t)).length, 1);
});
await test('a held week stops the weeks after it', async () => {
const payer = fakePayer(1000n * E), ck = { t: payableAt(WK2) + 60000 };
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock: ck, site: Object.assign({ overridePayCapPol: 20 }, LIVE) });
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK2).state, 'not planned'); assert.strictEqual(payer.sends.length, 0);
});
await test('insufficient balance: held with a clear message, then pays once funded', async () => {
const tg = [], payer = fakePayer(26n * E); // needs 27 POL + gas
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: LIVE, tg });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.match(ov.weekStatus(WK1).heldWhy, /holds 26\.0000 POL, needs 27\.0300/);
assert.match(tg.join(), /Fund it/);
payer.bal = 27n * E; await ov.payDue(); assert.strictEqual(payer.sends.length, 0, 'still short of the gas reserve');
payer.bal = 28n * E; await ov.payDue(); assert.strictEqual(payer.sends.length, 2); assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
});
await test('a wallet that would refuse POL: pre-flight catches it, nothing sent, carried', async () => {
const payer = fakePayer(1000n * E, { reject: [11] }); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: LIVE });
await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id), [10]);
const r11 = ov.weekStatus(WK1).rows.find(r => r.memberId === 11); assert.strictEqual(r11.state, 'carried'); assert.match(r11.note, /Send failed/);
assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
});
await test('a send whose answer is lost becomes review, is never re-sent, and blocks later weeks until resolved', async () => {
const tg = [], payer = fakePayer(1000n * E, { throwOn: [11] }), ck = { t: payableAt(WK2) + 60000 };
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock: ck, site: LIVE, tg });
await ov.payDue(); await ov.payDue(); await ov.payDue();
assert.deepStrictEqual(payer.sends.map(s => s.id), [10], 'only #10 went out, #11 never retried');
assert.strictEqual(ov.weekStatus(WK1).rows.find(r => r.memberId === 11).state, 'review');
assert.strictEqual(ov.weekStatus(WK2).state, 'not planned');
assert.strictEqual(tg.filter(t => /needs review/.test(t)).length, 1);
const bad = await ov.resolve(WK1, 11, 'paid', '0xnot-a-real-tx'); assert.ok(bad.error, 'an unverifiable tx is refused');
payer.opts.throwOn = []; // the node is healthy again
await ov.resolve(WK1, 11, 'carry'); assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
await ov.payDue(); assert.strictEqual(payer.sends.length, 2); assert.strictEqual(payer.sends[1].id, 11); // week 2 pays #11: carried 6 + 0.006
assert.strictEqual(payer.sends[1].wei, toWei('6.006'));
});
await test('a review row is settled from the chain index when the AwardPaid shows up', async () => {
const payer = fakePayer(1000n * E, { throwOn: [11] }), chain = fakeChain(TREE, PUR);
const ov = instance({ dir: tmp(), chain, payer, clock, site: LIVE });
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK1).rows.find(r => r.memberId === 11).state, 'review');
chain.events.push({ type: 'AwardPaid', tx: '0xlanded', from: payer.address, toId: 11, amountWei: toWei('6').toString(), ts: clock.t });
await ov.payDue(); const r = ov.weekStatus(WK1).rows.find(x => x.memberId === 11); assert.strictEqual(r.state, 'paid'); assert.strictEqual(r.txHash, '0xlanded');
assert.strictEqual(payer.sends.length, 1); assert.ok(ov.txInfo('0xLANDED'));
});
await test('a plan is frozen: a buyer count that changes after planning does not change the amounts', async () => {
const tree = JSON.parse(JSON.stringify(TREE)); const payer = fakePayer(26n * E), chain = fakeChain(tree, PUR);
const ov = instance({ dir: tmp(), chain, payer, clock, site: LIVE });
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK1).state, 'held'); // planned, short of funds
tree[20][1] = 9; // #20 qualifies later
payer.bal = 100n * E; await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id).sort(), [10, 11]);
});
await test('dry run Monday report: once per week across two copies, says no money moved', async () => {
const dir = tmp(), tg = [], chain = fakeChain(TREE, PUR), mon = { t: payableAt(WK1) + 600000 };
const A = instance({ dir, chain, clock: mon, site: {}, tg, payer: fakePayer(0) }), B = instance({ dir, chain, clock: mon, site: {}, tg, payer: fakePayer(0) });
await Promise.all([A.tick(), B.tick(), A.tick()]);
assert.strictEqual(tg.length, 1); assert.match(tg[0], /DRY RUN/); assert.match(tg[0], /No money moved/); assert.match(tg[0], /\$0\.21|\$2\.10/);
});
await test('payer status never exposes a key', async () => {
process.env.OVERRIDE_PAYER_KEY = '0x' + '11'.repeat(32);
const ov = create(); ov.init({ dataDir: tmp(), chain: fakeChain(TREE, PUR), siteConfig: () => ({}) });
const s = JSON.stringify(ov.liveState()) + JSON.stringify(Object.assign({}, await ov.payerStatus().catch(e => ({ e: e.message }))));
assert.ok(!s.includes('1111111111'), 'no key material'); delete process.env.OVERRIDE_PAYER_KEY;
});
console.log('override.test: ' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
})();
+75
View File
@@ -0,0 +1,75 @@
// Refill notice copy + deploy-overlap claim (refill.js) on throwaway data. Run: node qa/refill.test.cjs
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const assert = require('assert');
const ROOT = path.join(__dirname, '..');
let fails = 0, n = 0;
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.message); } }
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
const now = Date.now();
function world(dir, cfg) {
const W = { inbox: [], mail: [], cfg: cfg || {} };
W.campaigns = [
{ id: 1, owner: 'a@x.test', type: 'banner', name: 'Alpha', budget: 1000, spent: 1000, accrued: 0, imps: 5000, clicks: 40, status: 'out', created: now - 30 * 864e5 },
{ id: 2, owner: 'b@x.test', type: 'text', name: 'Bravo', budget: 1000, spent: 850, accrued: 0, imps: 8500, clicks: 9, status: 'active', created: now - 30 * 864e5 },
];
W.deps = {
dataDir: dir, siteConfig: () => W.cfg,
ads: { adminList: async () => W.campaigns.map(c => Object.assign({}, c)), rates: () => ({ videoTiers: [] }) },
accounts: { byEmail: async e => ({ email: e, memberId: 5 }), positions: async () => [] },
chain: { recentEvents: () => [] },
mailer: { hasKey: () => true, send: async (to, subject, text) => { W.mail.push({ to, subject, text }); } },
drip: { isUnsubscribed: async () => false },
creditsFor: async () => 300,
message: async (to, subject, html) => { W.inbox.push({ to, subject, html }); },
};
return W;
}
(async () => {
await t('bonus block names Five Dollar Friday AND Wired Wednesday ($20 floor, +25%)', async () => {
const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')));
const r = fresh('refill.js'); r.init(W.deps);
const m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
assert.ok(/Five Dollar Friday: any package from \$5 up/.test(m.text), 'friday text');
assert.ok(/Wired Wednesday: any package from \$20 up, bought on a Wednesday \(Central time\), earns an extra 25%/.test(m.text), 'wednesday text');
assert.ok(/<b>Wired Wednesday:<\/b>/.test(m.html), 'wednesday html');
assert.ok(!/—/.test(m.text + m.html), 'no em dash');
});
await t('Wednesday follows its settings (off, other floor and pct)', async () => {
const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')), { wednesdayPromo: '0' });
const r = fresh('refill.js'); r.init(W.deps);
let m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
assert.ok(!/Wired Wednesday/.test(m.text));
W.cfg = { wednesdayBonusPct: '30', wednesdayMinCents: '5000', fridayPromo: '0' };
m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
assert.ok(/from \$50 up.*extra 30%/.test(m.text) && !/Five Dollar Friday/.test(m.text));
});
await t('streak hook line (stage 2) lands in text and html; absent hook changes nothing', async () => {
const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')));
const r = fresh('refill.js'); r.init(Object.assign({}, W.deps, { streakLine: async e => e === 'a@x.test' ? { text: 'Refuel streak: 2 months.', html: '<b>Refuel streak:</b> 2 months.' } : null }));
const m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
assert.ok(/Refuel streak: 2 months\./.test(m.text) && /<b>Refuel streak:<\/b>/.test(m.html));
const m2 = await r.compose('b@x.test', [W.campaigns[1]], 'low', 300);
assert.ok(!/Refuel streak/.test(m2.text));
});
await t('two app copies (shared claims): each owner gets one message', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-'));
const W = world(dir);
const marks = fresh('marks.js'); marks.init({}); // no DB: one process-wide set stands in for event_marks
const A = fresh('refill.js'); A.init(Object.assign({}, W.deps, { marks }));
const B = fresh('refill.js'); B.init(Object.assign({}, W.deps, { marks }));
await Promise.all([A.tick(), B.tick()]);
const per = {}; for (const x of W.inbox) per[x.to] = (per[x.to] || 0) + 1;
assert.deepStrictEqual(per, { 'a@x.test': 1, 'b@x.test': 1 }, JSON.stringify(per));
assert.strictEqual(W.mail.length, 2);
await Promise.all([A.tick(), B.tick()]);
assert.strictEqual(W.inbox.length, 2, 'nothing repeats on later passes');
});
console.log('\n' + (n - fails) + '/' + n + ' passed');
process.exit(fails ? 1 : 0);
})();

Some files were not shown because too many files have changed in this diff Show More