34 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
62 changed files with 5823 additions and 1901 deletions
BIN
View File
Binary file not shown.
+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 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 } };
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;
+1 -1
View File
@@ -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>';
+79 -18
View File
@@ -22,7 +22,9 @@ 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; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
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 ''; }
@@ -30,16 +32,22 @@ function key() {
function enabled() { return !!key(); }
// ---- canned answers: instant, free, always in voice ----
// TODO(level-4 override, 2026-10-23): at go-live add the CANNED entry + FACTS line drafted in D:/tmp/override-copy/instantadpay-override-copy.md (section 3), and bump KNOWLEDGE_DATE only in that deploy.
const KNOWLEDGE_DATE = '2026-10-23'; // 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 = [
{ 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 all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the gold Game Pass badge with your name. Per game: PolHunter 5 missions a day instead of 3 plus 2 Ad Detective cases; Gem Kingdom one free continue a day; Spooky Doors one extra door a day; ClutterHunt 2 bonus hints a day; SpellWheel daily streak 0.30 POL instead of 0.15 plus 1 free hint a day; PolyBreak daily gem limit 1.5 POL instead of 0.5 plus an extra paddle every round; PolyWarriors a 4th daily mission and defense pays 25 Circuits instead of 15; Drip Runner a free shield at the start of every run; Road Agent 2 patrols a day and 25% more scrap. The full list is on the Game Pass card. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. 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.' },
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.' },
@@ -52,6 +60,12 @@ const CANNED = [
{ id: 'spellwheel', title: 'SpellWheel word game', q: ['What is SpellWheel?', 'Is there a daily word puzzle?'], tags: ['games', 'spellwheel', 'word game', 'daily puzzle'],
re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i,
a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a free word game: swipe the letters on the wheel to fill the crossword grid, travel through six cozy places, and solve a new daily puzzle that everyone gets at the same time. Sign in with your InstantAdPay account right in the game to save progress: clearing levels, finishing a place and solving the daily puzzle each pay POL, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' },
{ id: '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.' },
@@ -64,8 +78,8 @@ const CANNED = [
{ id: 'spooky-doors', title: 'Spooky Doors Halloween game', q: ['What is Spooky Doors?', 'How does the candy ladder pay?', 'How do I buy a costume?'], tags: ['games', 'spooky doors', 'halloween', 'candy', 'costume'],
re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i,
a: 'Spooky Doors (https://spookydoors.com) is the network\u2019s Halloween game. It opens on Oct 4 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Advertisers can also put a verified-visits pack behind the doors: when you create a verified-visits campaign, pick Everywhere (3 credits a visit), Behind Spooky Doors (4 credits a door) or Golden Spooky Door (6 credits a door, and the player gets a little bonus candy). Door packs show only in Spooky Doors until the season ends, then any doors left run as normal visits. Nothing here is a promise of income.' },
{ id: 'games-tab', title: 'Games tab and Drip Runner', q: ['Which games pay POL?', 'What is Drip Runner?', 'How do refuels work?'], tags: ['games', 'drip runner', 'refuel', 'games tab'],
re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i,
{ 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).' },
{ 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,
@@ -73,16 +87,19 @@ const CANNED = [
{ id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'],
re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i,
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
{ id: '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.' },
{ 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 nine 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.' },
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?'], tags: ['conversion tracking', 'goal pixel', 'landing tag', 'cost per goal', 'aweber', 'getresponse'],
{ 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 cost per goal in credits. 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 checks your pixel; tests and clicks on your own ads never count in your numbers.' },
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,
@@ -106,6 +123,9 @@ const CANNED = [
{ id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'],
re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i,
a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' },
{ id: '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.' },
@@ -125,9 +145,15 @@ const CANNED = [
{ id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'],
re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i,
a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' },
{ id: '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.' },
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.' },
@@ -205,18 +231,45 @@ function passTiersFact() {
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 a new package of at least $' + r.usd + '): ' + r.perks.join('; ')).join(' | ')
+ '. Each higher pass includes everything below it. Every pass is a Game Pass in all nine games 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; 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';
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:
${passTiersFact()}- 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.
- 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 and the Send a test conversion button count as tests, never in the numbers. Each campaign row shows goals and cost per goal in credits (campaign credits spent divided by goals; 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.
- 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.
@@ -232,6 +285,7 @@ ${passTiersFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night
- 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.
@@ -249,7 +303,7 @@ ${passTiersFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night
- 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 NINE 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 start 2026-10-29.
- 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.
@@ -285,7 +339,8 @@ ${passTiersFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night
- 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.
@@ -355,14 +410,20 @@ async function answerRaw(message, historyText) {
// 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 Object.assign({ reply: c.a, canned: true }, c.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);
kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id);
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
+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 };
+22 -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
@@ -425,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 };
+14 -10
View File
@@ -221,16 +221,18 @@ sales. If the POL rate is unavailable the tick retries next hour.
## 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 (prices below, plus Sovereign and the yearly Legend). The weekly pass is unchanged. Everything above weekly stays
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 | 1999 ($19.99) | 30 days | weapons, gear, 2 DLC islands |
| `champion` | Champion | 3999 ($39.99) | 30 days | weapons, gear, 4 DLC islands of your choice, the Druid hero, level cap 30 |
| `sovereign` | Sovereign | 9999 ($99.99) | 30 days | weapons, gear, all DLC islands, the Necromancer hero, level cap 40 |
| `legend` | Legend | 24999 ($249.99) | 365 days | weapons, gear, all DLC islands, every hero including the Archer, level cap 40 |
| `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).
@@ -243,18 +245,20 @@ switched off for members (`sovTiers` 0) until Marty flips it.
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, only the `ADMIN_EMAIL` account sees and can buy them (admin preview on the card). Short of purchased credits: a
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 covers the price: $20 (Explorer), $50 (Champion, there is no $40 one), $100
(Sovereign), $250 (Legend).
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` 1999,
`gamePassChampionPriceCredits` 3999, `gamePassSovereignPriceCredits` 9999, `gamePassLegendPriceCredits` 24999;
`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
+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 };
+28 -17
View File
@@ -1,4 +1,4 @@
// Game Pass (2026-10-16): the $5 weekly pass across all nine games, and the account-wide POL cap service the games call
// 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).
//
@@ -18,7 +18,7 @@
// 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; only ADMIN_EMAIL can see and buy them while it is off). No proration, no auto-renew: buying again
// `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
@@ -28,13 +28,16 @@
// 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'];
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' };
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.
@@ -46,13 +49,13 @@ const KEEP_DAYS = 90; // answered refs and day rows are kept this long
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: 1999, days: 30,
{ 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: 3999, days: 30,
{ 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: 9999, days: 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: 24999, days: 365,
{ 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
@@ -162,6 +165,11 @@ function extend(e, via, extra, now, 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 };
@@ -175,21 +183,23 @@ function revoke(email, tier, why, now) {
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 account testing the tiers above weekly while sovTiers is off
const tierOpen = (c, tier, admin) => !!(c.tiers[tier].sale || (admin && tier !== 'weekly'));
// 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. opts.admin = the ADMIN_EMAIL account (sees every tier while sovTiers is off).
// 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.admin); const T = tiersOf(p);
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, to the admin, or to a current holder (holders
// 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), open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
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,
@@ -199,7 +209,8 @@ function view(email, now, opts) {
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.admin = the ADMIN_EMAIL account.
// 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.
@@ -209,7 +220,7 @@ function buy(email, now, tier, opts) {
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.admin))) return { error: 'The ' + name + ' 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);
@@ -491,5 +502,5 @@ function prune(now) {
return n;
}
module.exports = { init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, TIER_DEFS, flag, view, buy, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
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 };
+1 -1
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', polybreak: 'PolyBreak', shardsofvalor: 'Shards of Valor' };
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
+4 -2
View File
@@ -4,8 +4,8 @@
// 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;
function init(d) { tickets = d.tickets; }
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)
@@ -63,6 +63,8 @@ async function handle(buf, contentType) {
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;
+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 };
+28 -6
View File
@@ -8,6 +8,8 @@
// 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';
@@ -73,6 +75,24 @@ function withClickId(target, id) {
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); }
@@ -121,11 +141,13 @@ 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
const rows = await unpushed(500); if (!rows.length) break;
const res = await signedPost('/api/partner/clicks', { clicks: rows }, 20000);
if (!res || res.ok !== true) throw new Error('linkspin answered without ok');
await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now();
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 };
@@ -151,4 +173,4 @@ async function goalOp(email, op, fields) {
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 };
module.exports = { init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on, noteSession, isOwnerSk };
+11 -1
View File
@@ -178,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 };
+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 };
+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();
+25 -2
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">
@@ -564,6 +572,10 @@
<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>
@@ -572,10 +584,21 @@
<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 = only the admin account sees them), gamePassExplorerEnabled / gamePassChampionEnabled / gamePassSovereignEnabled / gamePassLegendEnabled (0 stops one tier), gamePassExplorerPriceCredits (1999), gamePassChampionPriceCredits (3999), gamePassSovereignPriceCredits (9999), gamePassLegendPriceCredits (24999), 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>
<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.
@@ -618,6 +641,6 @@
<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=20261023ov"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></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>
+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();
})();
+56 -2
View File
@@ -294,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) {}
}
@@ -1098,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'],
@@ -1225,6 +1231,7 @@
$('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>'
@@ -1232,6 +1239,53 @@
+ (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 () => {
+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();
})();
+1 -1
View File
@@ -45,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');
+138 -33
View File
@@ -33,7 +33,51 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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.';
@@ -82,7 +126,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
{ key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 },
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 },
{ key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 },
{ key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 }
{ 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) {
@@ -91,7 +140,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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">'
@@ -637,8 +686,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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.
@@ -753,7 +803,8 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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
@@ -791,13 +842,29 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
}
// ── back-office menu: hash-routed panes ───────────────
const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile'];
const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns',
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);
@@ -850,6 +917,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
$('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
@@ -864,6 +932,8 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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);
@@ -905,6 +975,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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;
@@ -1070,7 +1144,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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 = g.value != null && g.value !== '' ? '&value=' + encodeURIComponent(g.value) : '';
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">',
@@ -1083,13 +1157,19 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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;
const spent = Number(c.spent || 0);
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 ? ' (' + convFmt(spent / n) + ' credits each)' : '') + '</span>'; });
el.innerHTML = '\u{1F3AF} ' + parts.join(' · ') + (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 = the credits this campaign has spent, divided by its goals.';
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;
});
}
@@ -1104,15 +1184,17 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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);
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.') : 'No goals yet. Add your first one below.';
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">' + (g.value != null && g.value !== '' ? esc(g.value) : '<span class="muted">none</span>') + '</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.convDays != null ? g.convDays : g.conv || 0).toLocaleString() + (g.lastAt ? '<div class="muted small">last ' + when(g.lastAt) + '</div>' : '') + '</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>';
@@ -1124,10 +1206,15 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
+ '<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;
try { await api('/api/my/conversions/test', { px: b.dataset.convtest }); IAP.status('Test conversion sent. It shows under Last test and never counts in your numbers.', 'ok'); await loadConv(true); }
catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
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' });
@@ -1166,7 +1253,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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', 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']].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' : '') + ')' : '')
@@ -1181,13 +1268,19 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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]) + '<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>'
@@ -1803,10 +1896,11 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
} 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('')
@@ -1870,7 +1964,8 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
}
loadWednesdayCard(); setInterval(loadWednesdayCard, 120000);
// ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ----
// ---- 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
@@ -1883,6 +1978,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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);
@@ -1896,13 +1994,13 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
: '<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>'
+ (gp.tierPreview ? '<p class="small" style="margin:0 0 8px;padding:6px 10px;border-radius:8px;background:#fde68a;color:#7c2d12"><b>Admin preview.</b> The passes above the weekly Game Pass are hidden from members until sovTiers is switched on in Settings.</p>' : '')
+ '<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>'
@@ -1927,31 +2025,36 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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'],
['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 nine games</td></tr>'
+ '<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.map(p => '<tr><td>' + p[0] + '</td><td>' + p[1] + '</td></tr>').join('') + '</table>'
+ 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) {} // a tier above weekly on sale (or admin preview, or a holder)
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>';
@@ -1960,7 +2063,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
: 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 all nine games</span></div>'
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>'
@@ -1991,10 +2094,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
if (cardHidden('gpnudge')) { card.hidden = true; return; }
let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {}
if (!gp || !gp.enabled || gp.active || !gp.lastCapHit || gp.lastCapHit.pass) { card.hidden = true; return; }
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' };
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 nine 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>'
+ '<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
@@ -2892,7 +2995,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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
@@ -3142,10 +3245,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
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);
+432 -420
View File
@@ -1,420 +1,432 @@
// Promo tools content + rendering for the member area (Promo tools pane).
// Everything is personalized from the member's join link. Angle links carry
// ?v=<angle> so they keep working when the matched squeeze pages ship.
// Copy rules: no income promises, package prices in dollars are fine, never a
// POL figure, no em dashes.
window.IAPPromo = (function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const status = (m, c) => (window.IAP && IAP.status) ? IAP.status(m, c) : console.log(m);
const angleLink = (link, angle) => angle ? link + '?v=' + angle : link;
// the public games page carrying the member's referral (any public page + ?ref sets the sponsor)
const gamesLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/games?ref=$1');
// The Five Dollar Friday bridge page with the member's referral: /friday?ref=<username>. Any
// public page plus ?ref sets the same sponsor cookie as the invite link (viral links, 2026-09-21).
const fridayLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/friday?ref=$1');
const wednesdayLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/wednesday?ref=$1');
// ── social posts ──
const POSTS = [
{ net: 'X', label: 'X · Five Dollar Friday', text: 'Five Dollar Friday on InstantAdPay: any ad package from $5 up earns 20% bonus credits, every Friday, Central time. The pack pays the sponsor line in the same transaction, on a public ledger. Free to join: {{FRIDAY}}' },
{ net: 'Facebook', label: 'Facebook · Five Dollar Friday', text: 'Every Friday I point people at this. Any ad package from $5 up gets 20% extra credits on InstantAdPay, added the second the purchase settles, no code, nothing to claim. And every pack pays the sponsor line in the same blockchain transaction, so there is no pending anything. It runs midnight to midnight Central. Free to join by email: {{FRIDAY}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp group · Five Dollar Friday', text: 'Quick one for the group: Five Dollar Friday on InstantAdPay. Any ad package from $5 up earns 20% bonus credits today (Central time, until midnight). The page shows whether it is live right now: {{FRIDAY}}' },
{ net: 'X', label: 'X · Five Dollar Friday', text: 'Five Dollar Friday on InstantAdPay: every Friday, any ad package from $5 earns +20% bonus credits, and every pack pays its sponsor line in the same on-chain transaction. The whole network buys on the same day. Join free and line yours up: {{LINK}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp · Five Dollar Friday', text: 'Reminder for the group: tomorrow is Five Dollar Friday on InstantAdPay. Any pack from $5 up earns +20% credits, and your pack pays your sponsor line the second it settles. Everyone pushes on the same day, and every line gets paid at once. Free to join: {{LINK}}' },
{ net: 'X', label: 'X · Wired Wednesday', text: 'Wired Wednesday on InstantAdPay: any ad package from $20 up earns 25% bonus credits, wired into your balance the second the purchase settles and good for any ad format. Every Wednesday, Central time. Free to join: {{WEDNESDAY}}' },
{ net: 'Facebook', label: 'Facebook · Wired Wednesday', text: 'Wednesdays on InstantAdPay are different. Buy any ad package from $20 up and 25% extra credits are wired into your balance the second the purchase settles, ready to run on any format, banners, text, video, solo ads, even login ads. No code, nothing to claim. And every pack pays the sponsor line in the same blockchain transaction. Midnight to midnight Central. Free to join by email: {{WEDNESDAY}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp group · Wired Wednesday', text: 'Quick one for the group: Wired Wednesday on InstantAdPay. Any ad package from $20 up earns 25% bonus credits today, wired in the second it settles (Central time, until midnight). The page shows whether it is live right now: {{WEDNESDAY}}' },
{ net: 'X', label: 'X · instant payout', text: 'No withdraw button. A smart contract on Polygon splits every ad package the second it sells: 50% to the sponsor, 20% to level 2, 10% to level 3. Lands in your own wallet. Watch the ledger move: {{LINK:instant}}' },
{ 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 $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}}' }
];
// ── text a friend (SMS-sized) ──
const TEXTS = [
{ angle: 'friday', title: '"Five Dollar Friday"', text: 'Heads up: Fridays on InstantAdPay any ad package from $5 up gets 20% bonus credits, Central time. Page tells you if it is live right now: {{FRIDAY}}' },
{ angle: 'wednesday', title: '"Wired Wednesday"', text: 'Heads up: Wednesdays on InstantAdPay any ad package from $20 up gets 25% bonus credits wired in the second it settles, Central time. Page tells you if it is live right now: {{WEDNESDAY}}' },
{ angle: '', title: '"Thought of you"', text: 'Hey, found an ad platform where the commission lands in your wallet the second someone buys. No pending, no withdraw button. Free to look: {{LINK}}' },
{ angle: 'instant', title: '"Before the page reloads"', text: 'Random thought. What if your commission showed up before the thank-you page finished loading? That is literally how this works: {{LINK:instant}}' },
{ angle: 'adspend', title: '"You buy ads anyway"', text: 'You already buy traffic. This one pays your line every time someone in it buys ads, same transaction, on Polygon. Two-minute look: {{LINK:adspend}}' },
{ angle: 'free', title: '"Costs nothing to try"', text: 'Try this without spending a dollar: join free, view a few ads, earn credits, run your first campaign. {{LINK:free}}' },
{ angle: 'ledger', title: '"No back office"', text: 'Remember waiting on payouts that never came? This one has no back office. Every payment is public on the blockchain. Check it yourself: {{LINK:ledger}}' }
];
// ── email swipes ──
const SWIPES = [
{ 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 $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.' }
];
// ── objection bank (truth + say this) ──
const OBJECTIONS = [
{ 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, $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}}' },
{ q: 'I do not know anyone to refer.', truth: 'Referrals are optional. Members can view ads, earn credits and advertise with no line at all. When they do refer, every direct buyer pays them 50 percent from the very first package, and their line banner is shown to their next three levels during welcome tours.', say: 'You do not have to refer anyone. Join free, earn credits by viewing, run ads. If one person ever joins through you and buys a $5 package, half of it hits your wallet in that transaction. That is the whole referral side, and it is optional. {{LINK:free}}' },
{ q: 'How much can I make?', truth: 'No income is guaranteed or implied. Sponsor commissions are 50 / 20 / 10 across three levels on packages that actually sell; level 2 needs 2 qualifying buyers ($20 or more) and level 3 needs 5. Results depend on the member\'s effort, and crypto carries risk of loss. Never quote a figure.', say: 'Nobody can tell you that, and I would not trust anyone who did. What I can tell you is exactly how it is split: 50 percent to the direct sponsor, 20 and 10 to the next two levels, paid the moment a package sells, all public. What that adds up to depends entirely on what you build. {{LINK:instant}}' }
];
function fillLink(text, link) {
return text.replace(/\{\{GAMES\}\}/g, gamesLink(link)).replace(/\{\{FRIDAY\}\}/g, fridayLink(link)).replace(/\{\{WEDNESDAY\}\}/g, wednesdayLink(link)).replace(/\{\{LINK(?::([a-z]+))?\}\}/g, (m, a) => angleLink(link, a));
}
function copyBtn(text, label) {
const b = document.createElement('button');
b.className = 'btn small sec'; b.type = 'button'; b.textContent = label || 'Copy';
b.addEventListener('click', async () => {
try { await navigator.clipboard.writeText(text); status('Copied. Paste it anywhere.', 'ok'); }
catch (e) { status('Copy failed. Select the text instead.', 'bad'); }
});
return b;
}
function block(text, head, extraBtns) {
const div = document.createElement('div');
div.className = 'promo-block';
if (head) { const h = document.createElement('div'); h.className = 'pb-head'; h.innerHTML = head; div.appendChild(h); }
const pre = document.createElement('div'); pre.className = 'pb-text'; pre.textContent = text; div.appendChild(pre);
const row = document.createElement('div'); row.className = 'pb-actions';
row.appendChild(copyBtn(text));
(extraBtns || []).forEach(b => row.appendChild(b));
div.appendChild(row);
return div;
}
function linkBtn(href, label, cls) {
const a = document.createElement('a');
a.className = 'btn small ' + (cls || 'sec'); a.href = href; a.textContent = label;
if (!/^sms:/.test(href)) { a.target = '_blank'; a.rel = 'noopener'; }
return a;
}
// hook videos: one per angle; the matched link continues the same hook on the join page
const VID_BASE = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
const VIDEOS = [
{ angle: 'wide', file: 'buildwide', title: 'Build wide: watch the payments flow', hook: 'Width unlocks depth. Watch fifty percent land, then the deeper levels open.', caption: 'Here is the one move every leader starts with: go wide. Each person you bring in who buys advertising pays you fifty percent the moment they buy. Two buyers open your second level, five open the third. Watch the payments flow, then join free: {{LINK:wide}}' },
{ angle: 'play', title: 'If you have time to play', hook: 'If you have time to play a game on your phone, you have time to build a business.', caption: 'If you have time to play a game on your phone, you have time to build a business. These free games pay real Polygon to your wallet, on chain, where anyone can check it. Share your games link instead of just playing. Watch it and play free: {{LINK:play}}' },
{ angle: 'instant', title: 'Paid before the page reloads', hook: 'What if your commission landed before the thank-you page finished loading?', caption: 'What if your commission landed before the thank-you page finished loading? On InstantAdPay a smart contract splits every ad package the second it sells, straight to wallets, on a public ledger. Free to join by email: {{LINK:instant}}' },
{ angle: 'adspend', title: 'You were buying traffic anyway', hook: 'Every ad dollar you have ever spent went one direction. Out.', caption: 'Every ad dollar you have ever spent went one direction. Out. Here the ad spend in your line pays you back in the same transaction. Seven formats, packages from $5, free to join: {{LINK:adspend}}' },
{ angle: 'free', title: 'Watch first, spend never', hook: 'You can run your first ad campaign here for exactly zero dollars.', caption: 'Run your first ad campaign for exactly zero dollars. Join free by email, earn credits by viewing ads, launch a real campaign, and watch real payouts land on a public ledger before you spend a cent: {{LINK:free}}' },
{ angle: 'ledger', title: 'No back office. No payday.', hook: 'Your last affiliate program paid you on the fifteenth. If it paid you.', caption: 'Your last affiliate program paid you on the fifteenth. If it paid you. Here the payroll is the blockchain: every payout is a public transaction, nothing is held, nobody can change the split. Open the ledger, then join free: {{LINK:ledger}}' },
{ angle: 'two', title: 'Two buyers open level two', hook: 'Two buyers. Then five. That is the whole ladder.', caption: 'Two buyers. Then five. That is the whole ladder. Level 1 pays from your first buyer, two qualifying buyers open level 2, five open level 3, all in the same transaction, straight to your wallet. Free to join: {{LINK:two}}' }
];
// the six front doors: the plain invite link plus one page per hook angle
const ANGLES = [
{ angle: '', name: 'General', hook: 'The whole picture', use: 'What InstantAdPay is, the payment split, join free. Use it when you have not said anything specific yet.' },
{ angle: 'play', name: 'Play', hook: 'If you have time to play', use: 'For people who play games on their phone. The page shows the games video and a Play the free games button with your referral, then the free sign-up.' },
{ angle: 'instant', name: 'Instant', hook: 'Paid before the page reloads', use: 'For anyone burned by pending commissions. The page opens on the on-chain payout that lands in seconds.' },
{ angle: 'adspend', name: 'Ad spend', hook: 'You buy ads anyway', use: 'For marketers who already pay for traffic. Frames it as advertising that also pays your line when they buy.' },
{ angle: 'free', name: 'Free', hook: 'Costs nothing to try', use: 'For skeptics and beginners. Join free, earn credits by viewing, run a first campaign without spending.' },
{ angle: 'ledger', name: 'Ledger', hook: 'No back office, no payday', use: 'For people who have waited on a payout. Every payment is public on Polygonscan and nothing is ever held.' },
{ angle: 'wide', name: 'Wide', hook: 'Width unlocks depth', use: 'For team builders and anyone weighing the plan. The page opens on the Build Wide video: fifty percent landing, then levels two and three opening at two and five buyers.' },
{ angle: 'two', name: 'Two', hook: 'Two buyers open level two', use: 'For team builders. The 2-then-5 qualification ladder and how a line stacks under you.' }
];
function fill(link, me) {
const token = (me && (me.username || me.refCode || me.memberId)) || '';
// invite strip
if ($('promoLink')) $('promoLink').textContent = link;
if ($('promoLinkCopy')) $('promoLinkCopy').onclick = async () => {
try { await navigator.clipboard.writeText(link); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); }
};
// angle links: one row per front door, copy + share
const al = $('promoAngles');
if (al && al.dataset.filled !== link) {
al.dataset.filled = link; al.innerHTML = '';
for (const a of ANGLES) {
const url = angleLink(link, a.angle);
const hasVideo = VIDEOS.some(v => v.angle === a.angle);
// one collapsed band per angle, like the banner kit: open the one you want
const row = document.createElement('details');
row.className = 'angle-row pb-acc';
row.innerHTML = '<summary><span><span class="angle-name">' + esc(a.name) + '</span> <span class="angle-hook">' + esc(a.hook) + '</span></span>'
+ (hasVideo ? '<span class="angle-tag">video</span>' : '') + '</summary>'
+ '<div class="angle-body"><div class="angle-txt">'
+ '<div class="muted small">' + esc(a.use) + '</div>'
+ '<a class="mono small angle-url" href="' + esc(url) + '" target="_blank" rel="noopener">' + esc(url) + '</a></div>'
+ '<div class="angle-btns"><a class="btn small sec" href="' + esc(url) + '" target="_blank" rel="noopener">Open</a><button class="btn small" type="button">Copy</button>'
+ (navigator.share ? '<button class="btn small sec" type="button">Share</button>' : '') + '</div></div>'; // Share = the phone's share sheet; desktops have none, so no button
const [copyBtn, shareBtn] = row.querySelectorAll('button');
copyBtn.onclick = async () => { try { await navigator.clipboard.writeText(url); status((a.name === 'General' ? 'Invite' : a.name) + ' link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
// the share sheet gets one ready message with the link inside it: some apps (Telegram among them) keep only the text field
if (shareBtn) shareBtn.onclick = async () => { try { await navigator.share({ title: 'InstantAdPay', text: (a.angle ? a.hook + ': ' : 'Have a look: ') + url }); } catch (e) { if (!(e && e.name === 'AbortError')) status('Could not open the share sheet.', 'bad'); } };
al.appendChild(row);
}
}
// posts
const posts = $('promoPosts');
if (posts && posts.dataset.filled !== link) {
posts.dataset.filled = link; posts.innerHTML = '';
for (const p of POSTS) {
const text = fillLink(p.text, link);
const extras = [];
if (p.net === 'X') extras.push(linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(text), 'Post on X'));
if (p.net === 'Facebook') extras.push(linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')), 'Share on Facebook'));
if (p.net === 'LinkedIn') extras.push(linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(angleLink(link, 'adspend')), 'Share on LinkedIn'));
if (p.net === 'Telegram') extras.push(linkBtn('https://t.me/share/url?url=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')) + '&text=' + encodeURIComponent(text.replace(/\s*\{\{LINK[^}]*\}\}\s*$/, '').replace(/https?:\/\/\S+$/, '').trim()), 'Share on Telegram'));
posts.appendChild(block(text, '<span class="pb-net">' + esc(p.label) + '</span>', extras));
}
}
// text a friend
const texts = $('promoTexts');
if (texts && texts.dataset.filled !== link) {
texts.dataset.filled = link; texts.innerHTML = '';
TEXTS.forEach((t, i) => {
const text = fillLink(t.text, link);
const enc = encodeURIComponent(text);
const tgUrl = angleLink(link, t.angle);
const tgLead = text.replace(/https?:\/\/\S+/, '').trim();
const extras = [
linkBtn('sms:?&body=' + enc, 'Text it', ''),
linkBtn('https://wa.me/?text=' + enc, 'WhatsApp'),
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(tgUrl) + '&text=' + encodeURIComponent(tgLead), 'Telegram')
];
texts.appendChild(block(text, '<span class="pb-net">Text ' + (i + 1) + (t.angle ? ' · ' + esc(t.angle) + ' angle' : ' · general') + '</span> <b>' + esc(t.title) + '</b>', extras));
});
}
// swipes
const sw = $('promoSwipeWrap');
if (sw && sw.dataset.filled !== link) {
sw.dataset.filled = link; sw.innerHTML = '';
for (const s of SWIPES) {
const text = 'Subject: ' + s.subject + '\n\n' + fillLink(s.body, link);
sw.appendChild(block(text, '<span class="pb-net">' + esc(s.tier) + '</span> <b>' + esc(s.subject) + '</b>'));
}
}
// hook videos
const vw = $('promoVideos');
if (vw && vw.dataset.filled !== link) {
vw.dataset.filled = link; vw.innerHTML = '';
for (const v of VIDEOS) {
const mlink = v.games ? gamesLink(link) : angleLink(link, v.angle);
const card = document.createElement('div'); card.className = 'pv';
card.innerHTML = '<div class="pv-head"><span class="pb-net">' + esc(v.angle) + ' angle</span> <b>' + esc(v.title) + '</b><div class="muted small">' + esc(v.hook) + '</div></div>'
+ '<video src="' + VID_BASE + (v.file || v.angle) + '.mp4" poster="' + VID_BASE + (v.file || v.angle) + '.jpg" preload="none" controls playsinline style="width:100%;max-width:640px;border-radius:12px;background:#000;margin:10px 0"></video>'
+ '<p class="small"><span class="muted">Matched link:</span> <span class="mono" style="overflow-wrap:anywhere">' + esc(mlink) + '</span></p>';
const row = document.createElement('p'); row.className = 'pb-actions';
row.appendChild(copyBtn(mlink, 'Copy matched link'));
row.appendChild(linkBtn(VID_BASE + (v.file || v.angle) + '.mp4', 'Download 16:9'));
row.appendChild(linkBtn(VID_BASE + (v.file || v.angle) + '-portrait.mp4', 'Download 9:16'));
card.appendChild(row);
const cap = fillLink(v.caption, link);
const extras = [
linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(cap), 'Post on X'),
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(mlink), 'Share on Facebook'),
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(mlink) + '&text=' + encodeURIComponent(cap.replace(/https?:\/\/\S+$/, '').trim()), 'Telegram'),
linkBtn('https://wa.me/?text=' + encodeURIComponent(cap), 'WhatsApp')
];
card.appendChild(block(cap, '<span class="lab">Caption</span>', extras));
vw.appendChild(card);
}
}
// viral link builder: any page on the site + ?ref=<you> (same cookie as the invite link)
const vp = $('viralPage');
if (vp && token && vp.dataset.filled !== token) {
vp.dataset.filled = token;
const origin = 'https://instantadpay.com', enc = encodeURIComponent;
const build = path => { if (!path) return ''; let x; try { x = new URL(origin + path); } catch (e) { return ''; } x.searchParams.set('ref', token); return origin + x.pathname + x.search; };
const render = () => {
const l = build(vp.value);
$('viralLink').textContent = l || '…';
const sh = $('viralShare'); sh.innerHTML = '';
if (!l) return;
const title = vp.selectedOptions[0] ? vp.selectedOptions[0].textContent.replace(/^Article: /, '') : 'InstantAdPay';
[linkBtn('https://x.com/intent/tweet?url=' + enc(l) + '&text=' + enc(title), 'X'),
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(l), 'Facebook'),
linkBtn('https://t.me/share/url?url=' + enc(l) + '&text=' + enc(title), 'Telegram'),
linkBtn('https://wa.me/?text=' + enc(title + ' ' + l), 'WhatsApp'),
linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + enc(l), 'LinkedIn'),
linkBtn('mailto:?subject=' + enc(title) + '&body=' + enc(l), 'Email')].forEach(b => sh.appendChild(b));
if (navigator.share) { const b = document.createElement('button'); b.className = 'btn small sec'; b.type = 'button'; b.textContent = 'Share'; b.onclick = async () => { try { await navigator.share({ title, url: l }); } catch (e) {} }; sh.appendChild(b); }
};
fetch('/api/pages').then(r => r.json()).then(r => { vp.innerHTML = (r.pages || []).map(pg => '<option value="' + esc(pg.path) + '">' + esc(pg.title) + '</option>').join(''); render(); }).catch(() => { vp.innerHTML = '<option value="/">Home page</option>'; render(); });
vp.onchange = render;
$('viralCopy').onclick = async () => { const l = $('viralLink').textContent; if (!/^https:/.test(l)) return; try { await navigator.clipboard.writeText(l); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
}
// PolHunter, the feeder program: the member's PolHunter link (their IAP username, so sign-ups land on their line)
const phl = $('phLink');
if (phl && token && phl.dataset.filled !== token) {
phl.dataset.filled = token;
const enc = encodeURIComponent, pl = 'https://polhunter.com/?r=' + enc(token);
phl.textContent = pl;
$('phLinkCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const sh = $('phShare'); sh.innerHTML = '';
const hook = 'PolHunter: find a code on one of our sites and a drip of POL lands in your wallet, on chain. Free to start.';
[linkBtn('https://x.com/intent/tweet?url=' + enc(pl) + '&text=' + enc(hook), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(hook), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(hook + ' ' + pl), 'WhatsApp'), linkBtn('mailto:?subject=' + enc('A scavenger hunt that pays in POL') + '&body=' + enc(hook + '\n\n' + pl), 'Email')].forEach(b => sh.appendChild(b));
const PH_POSTS = [
{ name: 'Short post', text: 'New thing I am playing with: PolHunter. You visit a site, find your code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in your wallet. On chain, with a link to prove it. ' + pl },
{ name: 'Story post', text: 'I spent two minutes on a training page tonight, found a little glass coin at the bottom, tapped the code, and 0.26 POL showed up in my wallet a minute later. That is PolHunter. Small drips, real chain, no catch beyond actually visiting the site. Free to start, you just need an InstantAdPay account and a wallet. ' + pl },
{ name: 'Telegram or WhatsApp', text: '\u{1F3AF} PolHunter is live. Missions across our sites, one code to find per site, random POL drips paid straight to your wallet. The hiding place moves every day. Start here: ' + pl },
{ name: 'Email swipe', subject: 'A scavenger hunt that pays in POL', text: 'Hey,\n\nQuick one. I have been testing something called PolHunter.\n\nYou pick a mission, spend a couple of minutes on the site it names, and your personal code appears somewhere on the page. Tap it to copy, paste it on your board, and a random drip of POL goes to your wallet, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly prizes, and the hiding place moves every day.\n\nIt is free to start. You need an InstantAdPay account (also free) and a wallet, and the site walks you through both.\n\nStart here: ' + pl + '\n\nTell me what your first find pays.' },
];
// the two spots (photoreal / animated): player, download, caption with the member's link, share buttons
const SP = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
const SPOTS = [
{ id: 'photoreal', name: 'Photoreal: the hunt in the forest', file: 'polhunter-spot-photoreal.mp4', poster: 'polhunter-spot-photoreal-poster.jpg', best: 'Facebook, YouTube Shorts, an older audience', cap: 'Somewhere on one of our sites, a code is waiting. Find it, tap it, paste it on your board, and a drip of Polygon lands in your wallet. On chain, with a link to prove it. Free to play. Start here: ' + pl + ' #PolHunter #Polygon #crypto #scavengerhunt' },
{ id: 'animated', name: 'Animated: the explorer and the glass coin', file: 'polhunter-spot-animated.mp4', poster: 'polhunter-spot-animated-poster.jpg', best: 'TikTok, Instagram Reels, a younger crowd', cap: 'A scavenger hunt that pays in Polygon. Pick a mission, find the glass coin, tap it, and the drip lands in your wallet instantly. Three missions a day, badges, weekly prizes. 100% free. ' + pl + ' #PolHunter #Polygon #crypto #gaming' },
];
const ps = $('phSpots'); if (ps) { ps.innerHTML = '';
for (const s of SPOTS) { const d = document.createElement('div'); d.className = 'promo-block';
d.innerHTML = '<div class="pb-head"><span class="lab">' + esc(s.name) + '</span> <span class="muted small">Best on: ' + esc(s.best) + '</span></div><video controls playsinline preload="none" poster="' + SP + s.poster + '" src="' + SP + s.file + '" style="width:100%;max-width:300px;border-radius:12px;display:block;margin:8px auto"></video><div class="pb-text">' + esc(s.cap) + '</div>';
const row = document.createElement('div'); row.className = 'pb-actions';
row.appendChild(linkBtn(SP + s.file, 'Download the video')); row.appendChild(copyBtn(s.cap, 'Copy caption'));
[linkBtn('https://x.com/intent/tweet?text=' + enc(s.cap), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(s.cap.replace(pl, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(s.cap), 'WhatsApp')].forEach(b => row.appendChild(b));
d.appendChild(row); ps.appendChild(d); }
}
const pp = $('phPosts'); pp.innerHTML = '';
for (const p of PH_POSTS) { const extras = p.subject ? [] : [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(p.text.replace(pl, '').trim()), 'Telegram')]; pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>' + (p.subject ? ' <span class="muted small">Subject: ' + esc(p.subject) + '</span>' : ''), extras)); }
const sizes = [['728x90', 'Leaderboard'], ['468x60', 'Mobile leaderboard'], ['300x250', 'Medium rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Skyscraper'], ['1200x630', 'Social card'], ['1080x1080', 'Instagram square']];
const bg = $('phBanners'); bg.innerHTML = '';
for (const [s, n] of sizes) { const w = s.split('x')[0], h = s.split('x')[1]; const src = 'https://polhunter.com/promo/polhunter-' + s + (Number(w) >= 300 ? '.jpg' : '.png'); const code = '<a href="' + pl + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="PolHunter"></a>';
const d = document.createElement('div'); d.className = 'promo-block'; d.innerHTML = '<div class="pb-head"><span class="lab">' + s + '</span> <span class="muted small">' + esc(n) + '</span></div><div style="overflow:auto;margin:8px 0"><img src="' + src + '" alt="' + s + '" style="max-width:100%;height:auto;border-radius:8px"></div><div class="pb-text mono small" style="overflow-wrap:anywhere">' + esc(code) + '</div>';
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); bg.appendChild(d); }
}
// Games (2026-10-06, Marty: one tab for every game instead of a pill each). A picker drives one panel: games with their own
// kit (PolHunter, Spooky Doors) show it; the rest get link, share image and posts. Every game gets the 10 standard banners
// from banners.adrotate.xyz, each embed linked to the member (PolHunter takes ?r=, the other games ?ref=).
const gms = $('promo-games');
if (gms && token && gms.dataset.filled !== token) {
gms.dataset.filled = token;
const enc = encodeURIComponent, CDN = 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/';
const preLaunch = (y, m, d) => Date.now() < Date.UTC(y, m - 1, d, 5); // before midnight Central on that day
const GAMES = [
// 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: 'Telegram or WhatsApp line', text: 'All the games that pay POL, one page, free to play: {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}' },
{ name: 'Friendly post', text: 'I grew up on brick breakers, so this one got me. PolyBreak is free, it plays great on a phone, and it signs in with your InstantAdPay account. First round clears pay Polygon, and so does every purple gem you catch. Out of paddles? Visit a member\'s page and you get one more. Give it a try: {L}' },
{ name: 'Gem angle', text: 'Keep one eye on the bricks and one eye on the top of the screen. Every so often a purple Polygon gem drifts down in PolyBreak. Catch it with your paddle and it pays Polygon to your wallet. Free to play: {L}' },
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: PolyBreak. Free brick breaker, pays Polygon for first round clears and gem catches: {L}' }] },
{ slug: 'polywarriors', name: 'PolyWarriors', link: 'https://www.polywarriors.com/?ref=', img: 'https://www.polywarriors.com/og-polywarriors.jpg', sub: 'cyberpunk battler with NFT warrior cards',
// launch trailer (2026-10-12, Marty approved): 16:9 + 9:16 cuts and a poster on Spaces; the caption carries the member's link
video: { base: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/', file: 'polywarriors-trailer.mp4', portrait: 'polywarriors-trailer-portrait.mp4', poster: 'polywarriors-trailer.jpg', best: 'landscape for Facebook, X and YouTube; vertical for Shorts, Reels and TikTok',
cap: 'PolyWarriors just opened: a free cyberpunk fighting game. Recruit warriors born with their own traits and rarity, beat 24 arena rivals, duel other members. First wins pay Polygon to your wallet and your first warrior mints free as an NFT. {L} #PolyWarriors #Polygon #NFT #gaming' },
posts: [
{ name: 'Short post', text: 'PolyWarriors is a free cyberpunk battler. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals, and challenge other members in duels that play out while you are away. Your first win over each rival pays Polygon to the wallet on your InstantAdPay account, and your first warrior mints to your wallet as an NFT, free. {L}' },
{ name: 'Friendly post', text: 'I have been playing PolyWarriors, a turn-based fighting game with a cyberpunk look. Every warrior is one of a kind, you can mint yours, fuse three of a kind into something rarer, and battle other members. Free to play, and it pays Polygon for first wins: {L}' },
{ name: 'Collector angle', text: 'Every PolyWarriors warrior is born with its own traits, rarity and serial, minted on Polygon when you forge it. Rares, Epics and Legendaries trade between members on the marketplace. Your first mint is free; after that every $5 ad package on InstantAdPay earns a mint pass. Start here: {L}' },
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: PolyWarriors. Free cyberpunk battler, pays Polygon for first wins, your first warrior mints free: {L}' }] },
{ slug: 'gemkingdom', name: 'Gem Kingdom', link: 'https://gemkingdom.app/?ref=', img: 'https://gemkingdom.app/fantasy/og-gemkingdom.jpg', sub: 'fantasy match-3 with boss battles',
posts: [
{ name: 'Short post', text: 'Gem Kingdom is a free fantasy match-3. Lead three heroes, beat the Goblin King’s bosses and rebuild your village. Boss wins come with POL rewards. Play here: {L}' },
{ name: 'Friendly post', text: 'Looking for a game to unwind with? Gem Kingdom is match-3 with a story: forge weapons, collect stars and climb the leaderboard. Free in your browser: {L}' }] },
{ slug: 'roadagent', name: 'Road Agent', link: 'https://roadagent.app/?ref=', img: 'https://roadagent.app/og-roadagent.jpg', sub: 'night highway shooter',
posts: [
{ name: 'Short post', text: 'Road Agent is a free night-highway shooter in the old arcade spirit. Shoot the hostiles, spare the civilians, pull into the weapons truck. Every sector you clear for the first time pays POL.' + (preLaunch(2026, 10, 15) ? ' Opens Thursday Oct 15.' : '') + ' {L}' },
{ name: 'Friendly post', text: 'I have been playing Road Agent, a top-down highway shooter with a twist: clear a sector and it pays POL. No wallet needed to start, just your InstantAdPay email. Free in your browser: {L}' }] },
{ slug: 'driprunner', name: 'Drip Runner', link: 'https://driprunner.app/?ref=', img: 'https://driprunner.app/og-driprunner.jpg', sub: 'quick runner game',
posts: [
{ name: 'Short post', text: 'Drip Runner is a quick free runner game. Hop the network, dodge the drones, clear chapters and refuel for POL rewards. Play in your browser: {L}' },
{ name: 'Friendly post', text: 'Got two minutes? Drip Runner is a fast little runner game I keep coming back to. See how far you get: {L}' }] },
{ slug: 'clutterhunt', name: 'ClutterHunt', link: 'https://clutterhunt.com/?ref=', img: 'https://clutterhunt.com/og-clutterhunt.jpg', sub: 'seasonal hidden-object game',
posts: [
{ name: 'Short post', text: 'ClutterHunt is a free hidden-object game. Six rooms to search, a clock running, and everything moves each time you play. Can you three-star Expert? {L}' },
{ name: 'Friendly post', text: 'If you like spot-the-object puzzles, try ClutterHunt. Free in your browser, with POL rewards for clearing rooms: {L}' }] },
{ slug: 'spellwheel', name: 'SpellWheel', link: 'https://spellwheel.com/?ref=', img: 'https://spellwheel.com/og-spellwheel.jpg', sub: 'letter-wheel word game',
posts: [
{ name: 'Short post', text: 'SpellWheel is a free word game. Swipe the letters on the wheel to fill the grid, one place at a time.' + (preLaunch(2026, 10, 10) ? ' Opens Saturday Oct 10.' : '') + ' {L}' },
{ name: 'Friendly post', text: 'Word game fans, this one is for you. SpellWheel: swipe letters, fill the grid, and earn POL rewards as you clear levels. Free in your browser: {L}' }] },
{ 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 list = () => GAMES.filter(g => avail[g.slug] !== false);
let cur = null; try { cur = localStorage.getItem('iap.gmGame'); } catch (e) {}
const draw = () => {
const L = list(); const g = L.find(x => x.slug === cur) || L[0]; cur = g.slug;
try { localStorage.setItem('iap.gmGame', cur); } catch (e) {}
$('gmPick').innerHTML = L.map(x => '<button class="chip-t' + (x === g ? ' on' : '') + '" type="button" data-gm="' + x.slug + '">' + esc(x.name) + '</button>').join('');
const link = g.link + enc(token);
GAMES.forEach(x => { if (x.kit && $(x.kit)) $(x.kit).hidden = x !== g; });
$('gmGeneric').hidden = !!g.kit;
if (!g.kit) {
$('gmTitle').textContent = g.name; $('gmSub').textContent = g.sub || '';
$('gmLink').textContent = link;
$('gmLinkCopy').onclick = async () => { try { await navigator.clipboard.writeText(link); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const posts = g.posts.map(p => ({ name: p.name, text: p.text.replace('{L}', link) })), hook = posts[0].text.replace(link, '').trim();
const sh = $('gmShare'); sh.innerHTML = '';
[linkBtn('https://x.com/intent/tweet?text=' + enc(posts[0].text), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(link), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(hook), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(posts[0].text), 'WhatsApp')].forEach(b => sh.appendChild(b));
const gi = $('gmImg'); gi.hidden = true; gi.onload = () => { if (gi.dataset.want === g.img) gi.hidden = false; }; gi.onerror = () => { gi.hidden = true; }; gi.dataset.want = g.img; gi.src = g.img; // hidden until the new game's image loads (no stale picture) $('gmImg').alt = g.name; $('gmImgOpen').href = g.img;
$('gmImgCopy').onclick = async () => { try { await navigator.clipboard.writeText(g.img); status('Image URL copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const gv = $('gmVideo'); if (gv) { gv.innerHTML = ''; gv.hidden = !g.video;
if (g.video) { const v = g.video, cap = v.cap.replace('{L}', link); const d = document.createElement('div'); d.className = 'promo-block';
d.innerHTML = '<div class="pb-head"><span class="lab">Trailer</span> <span class="muted small">Best on: ' + esc(v.best) + '</span></div><video controls playsinline preload="none" poster="' + v.base + v.poster + '" src="' + v.base + v.file + '" style="width:100%;max-width:480px;border-radius:12px;display:block;margin:8px auto;background:#000"></video><div class="pb-text">' + esc(cap) + '</div>';
const row = document.createElement('div'); row.className = 'pb-actions';
row.appendChild(linkBtn(v.base + v.file, 'Download 16:9')); if (v.portrait) row.appendChild(linkBtn(v.base + v.portrait, 'Download vertical')); row.appendChild(linkBtn(v.base + v.poster, 'Poster image')); row.appendChild(copyBtn(cap, 'Copy caption'));
[linkBtn('https://x.com/intent/tweet?text=' + enc(cap), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(link), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(cap.replace(link, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(cap), 'WhatsApp')].forEach(b => row.appendChild(b));
d.appendChild(row); gv.appendChild(d); } }
const pp = $('gmPosts'); pp.innerHTML = '';
for (const p of posts) pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>', [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(p.text.replace(link, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(p.text), 'WhatsApp')]));
}
const grid = $('gbGrid'); grid.innerHTML = '';
for (const [s, n] of SIZES) { const w = s.split('x')[0], h = s.split('x')[1], src = CDN + g.slug + '/' + g.slug + '-' + s + '.png';
const code = '<a href="' + link + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="' + g.name + '"></a>';
const d = document.createElement('div'); d.className = 'promo-block'; d.innerHTML = '<div class="pb-head"><span class="lab">' + s + '</span> <span class="muted small">' + esc(n) + '</span></div><div style="overflow:auto;margin:8px 0"><img loading="lazy" src="' + src + '" alt="' + esc(g.name) + ' ' + s + '" style="max-width:100%;height:auto;border-radius:6px"></div><div class="pb-text mono small" style="overflow-wrap:anywhere">' + esc(code) + '</div>';
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(() => {});
$('gmPick').addEventListener('click', e => { const b = e.target.closest('[data-gm]'); if (!b) return; cur = b.dataset.gm; draw(); });
draw();
}
// Spooky Doors (Halloween season, 2026-10-02): the member's game link, the share image and two short posts. Shown on the
// season window the Games card uses (the server decides; the admin gets a preview before the start), hidden after it.
const sdp = $('promo-spookydoors');
if (sdp && token && sdp.dataset.filled !== token) {
sdp.dataset.filled = token;
fetch('/api/my/spookydoors/promo').then(r => r.json()).then(s => {
// the Games tab's picker lists Spooky Doors only while its season shows (the server decides)
if (!s || !s.show) { sdp.hidden = true; if (window.__gmAvail) window.__gmAvail('spookydoors', false); return; }
if (window.__gmAvail) window.__gmAvail('spookydoors', true);
const enc = encodeURIComponent, sl = String(s.base || 'https://spookydoors.com') + '/?ref=' + enc(token), img = s.image || 'https://spookydoors.com/og-spookydoors.jpg';
const day = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); };
const ends = s.season && s.season.end ? day(s.season.end, true) : 'Oct 31';
$('sdpSub').textContent = s.preview && s.season ? 'preview: members see this card from ' + day(s.season.start) + ' to ' + ends : 'our Halloween game, limited time, ends ' + ends;
$('sdpLink').textContent = sl;
$('sdpCopy').onclick = async () => { try { await navigator.clipboard.writeText(sl); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
$('sdpImg').onerror = () => { $('sdpImg').hidden = true; }; $('sdpImg').src = img; $('sdpImgOpen').href = img;
$('sdpImgCopy').onclick = async () => { try { await navigator.clipboard.writeText(img); status('Image URL copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const SD_POSTS = [
{ name: 'Short post', text: 'Trick or treat! \u{1F383} Spooky Doors is a free Halloween game: walk the street, dodge the black cats and bats, knock on doors and fill your candy bucket. Only until Halloween night. Play here: ' + sl },
{ name: 'Friendly post', text: 'Something fun for October: I have been playing Spooky Doors, a little Halloween game where every door you knock on opens somebody\u2019s page. Pick a costume and see how much candy you can collect before ' + ends + '. ' + sl },
];
const pp = $('sdpPosts'); pp.innerHTML = '';
for (const p of SD_POSTS) pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>', [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(sl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(sl) + '&text=' + enc(p.text.replace(sl, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(p.text), 'WhatsApp')]));
}).catch(() => {});
}
// objections
const ob = $('promoObjections');
if (ob && ob.dataset.filled !== link) {
ob.dataset.filled = link; ob.innerHTML = '';
for (const o of OBJECTIONS) {
const d = document.createElement('details'); d.className = 'obj';
const s = document.createElement('summary'); s.textContent = o.q; d.appendChild(s);
const body = document.createElement('div'); body.className = 'obj-body';
const t = document.createElement('div'); t.className = 'obj-truth';
t.innerHTML = '<span class="lab">The truth</span><p>' + esc(o.truth) + '</p>'; body.appendChild(t);
const say = fillLink(o.say, link);
const sayEl = block(say, '<span class="lab lab-say">Say this</span>');
sayEl.classList.add('obj-say'); body.appendChild(sayEl);
d.appendChild(body); ob.appendChild(d);
}
}
}
return { fill, POSTS, TEXTS, SWIPES, OBJECTIONS, VIDEOS };
})();
// Promo tools content + rendering for the member area (Promo tools pane).
// Everything is personalized from the member's join link. Angle links carry
// ?v=<angle> so they keep working when the matched squeeze pages ship.
// Copy rules: no income promises, package prices in dollars are fine, never a
// POL figure, no em dashes.
window.IAPPromo = (function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const status = (m, c) => (window.IAP && IAP.status) ? IAP.status(m, c) : console.log(m);
const angleLink = (link, angle) => angle ? link + '?v=' + angle : link;
// the public games page carrying the member's referral (any public page + ?ref sets the sponsor)
const gamesLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/games?ref=$1');
// The Five Dollar Friday bridge page with the member's referral: /friday?ref=<username>. Any
// public page plus ?ref sets the same sponsor cookie as the invite link (viral links, 2026-09-21).
const fridayLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/friday?ref=$1');
const wednesdayLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/wednesday?ref=$1');
// ── social posts ──
const POSTS = [
{ net: 'X', label: 'X · Five Dollar Friday', text: 'Five Dollar Friday on InstantAdPay: any ad package from $5 up earns 20% bonus credits, every Friday, Central time. The pack pays the sponsor line in the same transaction, on a public ledger. Free to join: {{FRIDAY}}' },
{ net: 'Facebook', label: 'Facebook · Five Dollar Friday', text: 'Every Friday I point people at this. Any ad package from $5 up gets 20% extra credits on InstantAdPay, added the second the purchase settles, no code, nothing to claim. And every pack pays the sponsor line in the same blockchain transaction, so there is no pending anything. It runs midnight to midnight Central. Free to join by email: {{FRIDAY}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp group · Five Dollar Friday', text: 'Quick one for the group: Five Dollar Friday on InstantAdPay. Any ad package from $5 up earns 20% bonus credits today (Central time, until midnight). The page shows whether it is live right now: {{FRIDAY}}' },
{ net: 'X', label: 'X · Five Dollar Friday', text: 'Five Dollar Friday on InstantAdPay: every Friday, any ad package from $5 earns +20% bonus credits, and every pack pays its sponsor line in the same on-chain transaction. The whole network buys on the same day. Join free and line yours up: {{LINK}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp · Five Dollar Friday', text: 'Reminder for the group: tomorrow is Five Dollar Friday on InstantAdPay. Any pack from $5 up earns +20% credits, and your pack pays your sponsor line the second it settles. Everyone pushes on the same day, and every line gets paid at once. Free to join: {{LINK}}' },
{ net: 'X', label: 'X · Wired Wednesday', text: 'Wired Wednesday on InstantAdPay: any ad package from $20 up earns 25% bonus credits, wired into your balance the second the purchase settles and good for any ad format. Every Wednesday, Central time. Free to join: {{WEDNESDAY}}' },
{ net: 'Facebook', label: 'Facebook · Wired Wednesday', text: 'Wednesdays on InstantAdPay are different. Buy any ad package from $20 up and 25% extra credits are wired into your balance the second the purchase settles, ready to run on any format, banners, text, video, solo ads, even login ads. No code, nothing to claim. And every pack pays the sponsor line in the same blockchain transaction. Midnight to midnight Central. Free to join by email: {{WEDNESDAY}}' },
{ net: 'Telegram', label: 'Telegram or WhatsApp group · Wired Wednesday', text: 'Quick one for the group: Wired Wednesday on InstantAdPay. Any ad package from $20 up earns 25% bonus credits today, wired in the second it settles (Central time, until midnight). The page shows whether it is live right now: {{WEDNESDAY}}' },
{ net: 'X', label: 'X · instant payout', text: 'No withdraw button. A smart contract on Polygon splits every ad package the second it sells: 50% to the sponsor, 20% to level 2, 10% to level 3. Lands in your own wallet. Watch the ledger move: {{LINK:instant}}' },
{ 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 $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}}' }
];
// ── text a friend (SMS-sized) ──
const TEXTS = [
{ angle: 'friday', title: '"Five Dollar Friday"', text: 'Heads up: Fridays on InstantAdPay any ad package from $5 up gets 20% bonus credits, Central time. Page tells you if it is live right now: {{FRIDAY}}' },
{ angle: 'wednesday', title: '"Wired Wednesday"', text: 'Heads up: Wednesdays on InstantAdPay any ad package from $20 up gets 25% bonus credits wired in the second it settles, Central time. Page tells you if it is live right now: {{WEDNESDAY}}' },
{ angle: '', title: '"Thought of you"', text: 'Hey, found an ad platform where the commission lands in your wallet the second someone buys. No pending, no withdraw button. Free to look: {{LINK}}' },
{ angle: 'instant', title: '"Before the page reloads"', text: 'Random thought. What if your commission showed up before the thank-you page finished loading? That is literally how this works: {{LINK:instant}}' },
{ angle: 'adspend', title: '"You buy ads anyway"', text: 'You already buy traffic. This one pays your line every time someone in it buys ads, same transaction, on Polygon. Two-minute look: {{LINK:adspend}}' },
{ angle: 'free', title: '"Costs nothing to try"', text: 'Try this without spending a dollar: join free, view a few ads, earn credits, run your first campaign. {{LINK:free}}' },
{ angle: 'ledger', title: '"No back office"', text: 'Remember waiting on payouts that never came? This one has no back office. Every payment is public on the blockchain. Check it yourself: {{LINK:ledger}}' }
];
// ── email swipes ──
const SWIPES = [
{ 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 $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.' }
];
// ── objection bank (truth + say this) ──
const OBJECTIONS = [
{ 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, $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}}' },
{ q: 'I do not know anyone to refer.', truth: 'Referrals are optional. Members can view ads, earn credits and advertise with no line at all. When they do refer, every direct buyer pays them 50 percent from the very first package, and their line banner is shown to their next three levels during welcome tours.', say: 'You do not have to refer anyone. Join free, earn credits by viewing, run ads. If one person ever joins through you and buys a $5 package, half of it hits your wallet in that transaction. That is the whole referral side, and it is optional. {{LINK:free}}' },
{ q: 'How much can I make?', truth: 'No income is guaranteed or implied. Sponsor commissions are 50 / 20 / 10 across three levels on packages that actually sell; level 2 needs 2 qualifying buyers ($20 or more) and level 3 needs 5. Results depend on the member\'s effort, and crypto carries risk of loss. Never quote a figure.', say: 'Nobody can tell you that, and I would not trust anyone who did. What I can tell you is exactly how it is split: 50 percent to the direct sponsor, 20 and 10 to the next two levels, paid the moment a package sells, all public. What that adds up to depends entirely on what you build. {{LINK:instant}}' }
];
function fillLink(text, link) {
return text.replace(/\{\{GAMES\}\}/g, gamesLink(link)).replace(/\{\{FRIDAY\}\}/g, fridayLink(link)).replace(/\{\{WEDNESDAY\}\}/g, wednesdayLink(link)).replace(/\{\{LINK(?::([a-z]+))?\}\}/g, (m, a) => angleLink(link, a));
}
function copyBtn(text, label) {
const b = document.createElement('button');
b.className = 'btn small sec'; b.type = 'button'; b.textContent = label || 'Copy';
b.addEventListener('click', async () => {
try { await navigator.clipboard.writeText(text); status('Copied. Paste it anywhere.', 'ok'); }
catch (e) { status('Copy failed. Select the text instead.', 'bad'); }
});
return b;
}
function block(text, head, extraBtns) {
const div = document.createElement('div');
div.className = 'promo-block';
if (head) { const h = document.createElement('div'); h.className = 'pb-head'; h.innerHTML = head; div.appendChild(h); }
const pre = document.createElement('div'); pre.className = 'pb-text'; pre.textContent = text; div.appendChild(pre);
const row = document.createElement('div'); row.className = 'pb-actions';
row.appendChild(copyBtn(text));
(extraBtns || []).forEach(b => row.appendChild(b));
div.appendChild(row);
return div;
}
function linkBtn(href, label, cls) {
const a = document.createElement('a');
a.className = 'btn small ' + (cls || 'sec'); a.href = href; a.textContent = label;
if (!/^sms:/.test(href)) { a.target = '_blank'; a.rel = 'noopener'; }
return a;
}
// hook videos: one per angle; the matched link continues the same hook on the join page
const VID_BASE = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
const VIDEOS = [
{ angle: 'wide', file: 'buildwide', title: 'Build wide: watch the payments flow', hook: 'Width unlocks depth. Watch fifty percent land, then the deeper levels open.', caption: 'Here is the one move every leader starts with: go wide. Each person you bring in who buys advertising pays you fifty percent the moment they buy. Two buyers open your second level, five open the third. Watch the payments flow, then join free: {{LINK:wide}}' },
{ angle: 'play', title: 'If you have time to play', hook: 'If you have time to play a game on your phone, you have time to build a business.', caption: 'If you have time to play a game on your phone, you have time to build a business. These free games pay real Polygon to your wallet, on chain, where anyone can check it. Share your games link instead of just playing. Watch it and play free: {{LINK:play}}' },
{ angle: 'instant', title: 'Paid before the page reloads', hook: 'What if your commission landed before the thank-you page finished loading?', caption: 'What if your commission landed before the thank-you page finished loading? On InstantAdPay a smart contract splits every ad package the second it sells, straight to wallets, on a public ledger. Free to join by email: {{LINK:instant}}' },
{ angle: 'adspend', title: 'You were buying traffic anyway', hook: 'Every ad dollar you have ever spent went one direction. Out.', caption: 'Every ad dollar you have ever spent went one direction. Out. Here the ad spend in your line pays you back in the same transaction. Seven formats, packages from $5, free to join: {{LINK:adspend}}' },
{ angle: 'free', title: 'Watch first, spend never', hook: 'You can run your first ad campaign here for exactly zero dollars.', caption: 'Run your first ad campaign for exactly zero dollars. Join free by email, earn credits by viewing ads, launch a real campaign, and watch real payouts land on a public ledger before you spend a cent: {{LINK:free}}' },
{ angle: 'ledger', title: 'No back office. No payday.', hook: 'Your last affiliate program paid you on the fifteenth. If it paid you.', caption: 'Your last affiliate program paid you on the fifteenth. If it paid you. Here the payroll is the blockchain: every payout is a public transaction, nothing is held, nobody can change the split. Open the ledger, then join free: {{LINK:ledger}}' },
{ angle: 'two', title: 'Two buyers open level two', hook: 'Two buyers. Then five. That is the whole ladder.', caption: 'Two buyers. Then five. That is the whole ladder. Level 1 pays from your first buyer, two qualifying buyers open level 2, five open level 3, all in the same transaction, straight to your wallet. Free to join: {{LINK:two}}' }
];
// the six front doors: the plain invite link plus one page per hook angle
const ANGLES = [
{ angle: '', name: 'General', hook: 'The whole picture', use: 'What InstantAdPay is, the payment split, join free. Use it when you have not said anything specific yet.' },
{ angle: 'play', name: 'Play', hook: 'If you have time to play', use: 'For people who play games on their phone. The page shows the games video and a Play the free games button with your referral, then the free sign-up.' },
{ angle: 'instant', name: 'Instant', hook: 'Paid before the page reloads', use: 'For anyone burned by pending commissions. The page opens on the on-chain payout that lands in seconds.' },
{ angle: 'adspend', name: 'Ad spend', hook: 'You buy ads anyway', use: 'For marketers who already pay for traffic. Frames it as advertising that also pays your line when they buy.' },
{ angle: 'free', name: 'Free', hook: 'Costs nothing to try', use: 'For skeptics and beginners. Join free, earn credits by viewing, run a first campaign without spending.' },
{ angle: 'ledger', name: 'Ledger', hook: 'No back office, no payday', use: 'For people who have waited on a payout. Every payment is public on Polygonscan and nothing is ever held.' },
{ angle: 'wide', name: 'Wide', hook: 'Width unlocks depth', use: 'For team builders and anyone weighing the plan. The page opens on the Build Wide video: fifty percent landing, then levels two and three opening at two and five buyers.' },
{ angle: 'two', name: 'Two', hook: 'Two buyers open level two', use: 'For team builders. The 2-then-5 qualification ladder and how a line stacks under you.' }
];
function fill(link, me) {
const token = (me && (me.username || me.refCode || me.memberId)) || '';
// invite strip
if ($('promoLink')) $('promoLink').textContent = link;
if ($('promoLinkCopy')) $('promoLinkCopy').onclick = async () => {
try { await navigator.clipboard.writeText(link); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); }
};
// angle links: one row per front door, copy + share
const al = $('promoAngles');
if (al && al.dataset.filled !== link) {
al.dataset.filled = link; al.innerHTML = '';
for (const a of ANGLES) {
const url = angleLink(link, a.angle);
const hasVideo = VIDEOS.some(v => v.angle === a.angle);
// one collapsed band per angle, like the banner kit: open the one you want
const row = document.createElement('details');
row.className = 'angle-row pb-acc';
row.innerHTML = '<summary><span><span class="angle-name">' + esc(a.name) + '</span> <span class="angle-hook">' + esc(a.hook) + '</span></span>'
+ (hasVideo ? '<span class="angle-tag">video</span>' : '') + '</summary>'
+ '<div class="angle-body"><div class="angle-txt">'
+ '<div class="muted small">' + esc(a.use) + '</div>'
+ '<a class="mono small angle-url" href="' + esc(url) + '" target="_blank" rel="noopener">' + esc(url) + '</a></div>'
+ '<div class="angle-btns"><a class="btn small sec" href="' + esc(url) + '" target="_blank" rel="noopener">Open</a><button class="btn small" type="button">Copy</button>'
+ (navigator.share ? '<button class="btn small sec" type="button">Share</button>' : '') + '</div></div>'; // Share = the phone's share sheet; desktops have none, so no button
const [copyBtn, shareBtn] = row.querySelectorAll('button');
copyBtn.onclick = async () => { try { await navigator.clipboard.writeText(url); status((a.name === 'General' ? 'Invite' : a.name) + ' link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
// the share sheet gets one ready message with the link inside it: some apps (Telegram among them) keep only the text field
if (shareBtn) shareBtn.onclick = async () => { try { await navigator.share({ title: 'InstantAdPay', text: (a.angle ? a.hook + ': ' : 'Have a look: ') + url }); } catch (e) { if (!(e && e.name === 'AbortError')) status('Could not open the share sheet.', 'bad'); } };
al.appendChild(row);
}
}
// posts
const posts = $('promoPosts');
if (posts && posts.dataset.filled !== link) {
posts.dataset.filled = link; posts.innerHTML = '';
for (const p of POSTS) {
const text = fillLink(p.text, link);
const extras = [];
if (p.net === 'X') extras.push(linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(text), 'Post on X'));
if (p.net === 'Facebook') extras.push(linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')), 'Share on Facebook'));
if (p.net === 'LinkedIn') extras.push(linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(angleLink(link, 'adspend')), 'Share on LinkedIn'));
if (p.net === 'Telegram') extras.push(linkBtn('https://t.me/share/url?url=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')) + '&text=' + encodeURIComponent(text.replace(/\s*\{\{LINK[^}]*\}\}\s*$/, '').replace(/https?:\/\/\S+$/, '').trim()), 'Share on Telegram'));
posts.appendChild(block(text, '<span class="pb-net">' + esc(p.label) + '</span>', extras));
}
}
// text a friend
const texts = $('promoTexts');
if (texts && texts.dataset.filled !== link) {
texts.dataset.filled = link; texts.innerHTML = '';
TEXTS.forEach((t, i) => {
const text = fillLink(t.text, link);
const enc = encodeURIComponent(text);
const tgUrl = angleLink(link, t.angle);
const tgLead = text.replace(/https?:\/\/\S+/, '').trim();
const extras = [
linkBtn('sms:?&body=' + enc, 'Text it', ''),
linkBtn('https://wa.me/?text=' + enc, 'WhatsApp'),
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(tgUrl) + '&text=' + encodeURIComponent(tgLead), 'Telegram')
];
texts.appendChild(block(text, '<span class="pb-net">Text ' + (i + 1) + (t.angle ? ' · ' + esc(t.angle) + ' angle' : ' · general') + '</span> <b>' + esc(t.title) + '</b>', extras));
});
}
// swipes
const sw = $('promoSwipeWrap');
if (sw && sw.dataset.filled !== link) {
sw.dataset.filled = link; sw.innerHTML = '';
for (const s of SWIPES) {
const text = 'Subject: ' + s.subject + '\n\n' + fillLink(s.body, link);
sw.appendChild(block(text, '<span class="pb-net">' + esc(s.tier) + '</span> <b>' + esc(s.subject) + '</b>'));
}
}
// hook videos
const vw = $('promoVideos');
if (vw && vw.dataset.filled !== link) {
vw.dataset.filled = link; vw.innerHTML = '';
for (const v of VIDEOS) {
const mlink = v.games ? gamesLink(link) : angleLink(link, v.angle);
const card = document.createElement('div'); card.className = 'pv';
card.innerHTML = '<div class="pv-head"><span class="pb-net">' + esc(v.angle) + ' angle</span> <b>' + esc(v.title) + '</b><div class="muted small">' + esc(v.hook) + '</div></div>'
+ '<video src="' + VID_BASE + (v.file || v.angle) + '.mp4" poster="' + VID_BASE + (v.file || v.angle) + '.jpg" preload="none" controls playsinline style="width:100%;max-width:640px;border-radius:12px;background:#000;margin:10px 0"></video>'
+ '<p class="small"><span class="muted">Matched link:</span> <span class="mono" style="overflow-wrap:anywhere">' + esc(mlink) + '</span></p>';
const row = document.createElement('p'); row.className = 'pb-actions';
row.appendChild(copyBtn(mlink, 'Copy matched link'));
row.appendChild(linkBtn(VID_BASE + (v.file || v.angle) + '.mp4', 'Download 16:9'));
row.appendChild(linkBtn(VID_BASE + (v.file || v.angle) + '-portrait.mp4', 'Download 9:16'));
card.appendChild(row);
const cap = fillLink(v.caption, link);
const extras = [
linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(cap), 'Post on X'),
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(mlink), 'Share on Facebook'),
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(mlink) + '&text=' + encodeURIComponent(cap.replace(/https?:\/\/\S+$/, '').trim()), 'Telegram'),
linkBtn('https://wa.me/?text=' + encodeURIComponent(cap), 'WhatsApp')
];
card.appendChild(block(cap, '<span class="lab">Caption</span>', extras));
vw.appendChild(card);
}
}
// viral link builder: any page on the site + ?ref=<you> (same cookie as the invite link)
const vp = $('viralPage');
if (vp && token && vp.dataset.filled !== token) {
vp.dataset.filled = token;
const origin = 'https://instantadpay.com', enc = encodeURIComponent;
const build = path => { if (!path) return ''; let x; try { x = new URL(origin + path); } catch (e) { return ''; } x.searchParams.set('ref', token); return origin + x.pathname + x.search; };
const render = () => {
const l = build(vp.value);
$('viralLink').textContent = l || '…';
const sh = $('viralShare'); sh.innerHTML = '';
if (!l) return;
const title = vp.selectedOptions[0] ? vp.selectedOptions[0].textContent.replace(/^Article: /, '') : 'InstantAdPay';
[linkBtn('https://x.com/intent/tweet?url=' + enc(l) + '&text=' + enc(title), 'X'),
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(l), 'Facebook'),
linkBtn('https://t.me/share/url?url=' + enc(l) + '&text=' + enc(title), 'Telegram'),
linkBtn('https://wa.me/?text=' + enc(title + ' ' + l), 'WhatsApp'),
linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + enc(l), 'LinkedIn'),
linkBtn('mailto:?subject=' + enc(title) + '&body=' + enc(l), 'Email')].forEach(b => sh.appendChild(b));
if (navigator.share) { const b = document.createElement('button'); b.className = 'btn small sec'; b.type = 'button'; b.textContent = 'Share'; b.onclick = async () => { try { await navigator.share({ title, url: l }); } catch (e) {} }; sh.appendChild(b); }
};
fetch('/api/pages').then(r => r.json()).then(r => { vp.innerHTML = (r.pages || []).map(pg => '<option value="' + esc(pg.path) + '">' + esc(pg.title) + '</option>').join(''); render(); }).catch(() => { vp.innerHTML = '<option value="/">Home page</option>'; render(); });
vp.onchange = render;
$('viralCopy').onclick = async () => { const l = $('viralLink').textContent; if (!/^https:/.test(l)) return; try { await navigator.clipboard.writeText(l); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
}
// PolHunter, the feeder program: the member's PolHunter link (their IAP username, so sign-ups land on their line)
const phl = $('phLink');
if (phl && token && phl.dataset.filled !== token) {
phl.dataset.filled = token;
const enc = encodeURIComponent, pl = 'https://polhunter.com/?r=' + enc(token);
phl.textContent = pl;
$('phLinkCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const sh = $('phShare'); sh.innerHTML = '';
const hook = 'PolHunter: find a code on one of our sites and a drip of POL lands in your wallet, on chain. Free to start.';
[linkBtn('https://x.com/intent/tweet?url=' + enc(pl) + '&text=' + enc(hook), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(hook), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(hook + ' ' + pl), 'WhatsApp'), linkBtn('mailto:?subject=' + enc('A scavenger hunt that pays in POL') + '&body=' + enc(hook + '\n\n' + pl), 'Email')].forEach(b => sh.appendChild(b));
const PH_POSTS = [
{ name: 'Short post', text: 'New thing I am playing with: PolHunter. You visit a site, find your code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in your wallet. On chain, with a link to prove it. ' + pl },
{ name: 'Story post', text: 'I spent two minutes on a training page tonight, found a little glass coin at the bottom, tapped the code, and 0.26 POL showed up in my wallet a minute later. That is PolHunter. Small drips, real chain, no catch beyond actually visiting the site. Free to start, you just need an InstantAdPay account and a wallet. ' + pl },
{ name: 'Telegram or WhatsApp', text: '\u{1F3AF} PolHunter is live. Missions across our sites, one code to find per site, random POL drips paid straight to your wallet. The hiding place moves every day. Start here: ' + pl },
{ name: 'Email swipe', subject: 'A scavenger hunt that pays in POL', text: 'Hey,\n\nQuick one. I have been testing something called PolHunter.\n\nYou pick a mission, spend a couple of minutes on the site it names, and your personal code appears somewhere on the page. Tap it to copy, paste it on your board, and a random drip of POL goes to your wallet, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly prizes, and the hiding place moves every day.\n\nIt is free to start. You need an InstantAdPay account (also free) and a wallet, and the site walks you through both.\n\nStart here: ' + pl + '\n\nTell me what your first find pays.' },
];
// the two spots (photoreal / animated): player, download, caption with the member's link, share buttons
const SP = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
const SPOTS = [
{ id: 'photoreal', name: 'Photoreal: the hunt in the forest', file: 'polhunter-spot-photoreal.mp4', poster: 'polhunter-spot-photoreal-poster.jpg', best: 'Facebook, YouTube Shorts, an older audience', cap: 'Somewhere on one of our sites, a code is waiting. Find it, tap it, paste it on your board, and a drip of Polygon lands in your wallet. On chain, with a link to prove it. Free to play. Start here: ' + pl + ' #PolHunter #Polygon #crypto #scavengerhunt' },
{ id: 'animated', name: 'Animated: the explorer and the glass coin', file: 'polhunter-spot-animated.mp4', poster: 'polhunter-spot-animated-poster.jpg', best: 'TikTok, Instagram Reels, a younger crowd', cap: 'A scavenger hunt that pays in Polygon. Pick a mission, find the glass coin, tap it, and the drip lands in your wallet instantly. Three missions a day, badges, weekly prizes. 100% free. ' + pl + ' #PolHunter #Polygon #crypto #gaming' },
];
const ps = $('phSpots'); if (ps) { ps.innerHTML = '';
for (const s of SPOTS) { const d = document.createElement('div'); d.className = 'promo-block';
d.innerHTML = '<div class="pb-head"><span class="lab">' + esc(s.name) + '</span> <span class="muted small">Best on: ' + esc(s.best) + '</span></div><video controls playsinline preload="none" poster="' + SP + s.poster + '" src="' + SP + s.file + '" style="width:100%;max-width:300px;border-radius:12px;display:block;margin:8px auto"></video><div class="pb-text">' + esc(s.cap) + '</div>';
const row = document.createElement('div'); row.className = 'pb-actions';
row.appendChild(linkBtn(SP + s.file, 'Download the video')); row.appendChild(copyBtn(s.cap, 'Copy caption'));
[linkBtn('https://x.com/intent/tweet?text=' + enc(s.cap), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(s.cap.replace(pl, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(s.cap), 'WhatsApp')].forEach(b => row.appendChild(b));
d.appendChild(row); ps.appendChild(d); }
}
const pp = $('phPosts'); pp.innerHTML = '';
for (const p of PH_POSTS) { const extras = p.subject ? [] : [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(p.text.replace(pl, '').trim()), 'Telegram')]; pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>' + (p.subject ? ' <span class="muted small">Subject: ' + esc(p.subject) + '</span>' : ''), extras)); }
const sizes = [['728x90', 'Leaderboard'], ['468x60', 'Mobile leaderboard'], ['300x250', 'Medium rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Skyscraper'], ['1200x630', 'Social card'], ['1080x1080', 'Instagram square']];
const bg = $('phBanners'); bg.innerHTML = '';
for (const [s, n] of sizes) { const w = s.split('x')[0], h = s.split('x')[1]; const src = 'https://polhunter.com/promo/polhunter-' + s + (Number(w) >= 300 ? '.jpg' : '.png'); const code = '<a href="' + pl + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="PolHunter"></a>';
const d = document.createElement('div'); d.className = 'promo-block'; d.innerHTML = '<div class="pb-head"><span class="lab">' + s + '</span> <span class="muted small">' + esc(n) + '</span></div><div style="overflow:auto;margin:8px 0"><img src="' + src + '" alt="' + s + '" style="max-width:100%;height:auto;border-radius:8px"></div><div class="pb-text mono small" style="overflow-wrap:anywhere">' + esc(code) + '</div>';
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); bg.appendChild(d); }
}
// Games (2026-10-06, Marty: one tab for every game instead of a pill each). A picker drives one panel: games with their own
// kit (PolHunter, Spooky Doors) show it; the rest get link, share image and posts. Every game gets the 10 standard banners
// from banners.adrotate.xyz, each embed linked to the member (PolHunter takes ?r=, the other games ?ref=).
const gms = $('promo-games');
if (gms && token && gms.dataset.filled !== token) {
gms.dataset.filled = token;
const enc = encodeURIComponent, CDN = 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/';
const preLaunch = (y, m, d) => Date.now() < Date.UTC(y, m - 1, d, 5); // before midnight Central on that day
const GAMES = [
// 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, 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}' },
{ name: 'Friendly post', text: 'I grew up on brick breakers, so this one got me. PolyBreak is free, it plays great on a phone, and it signs in with your InstantAdPay account. First round clears pay Polygon, and so does every purple gem you catch. Out of paddles? Visit a member\'s page and you get one more. Give it a try: {L}' },
{ name: 'Gem angle', text: 'Keep one eye on the bricks and one eye on the top of the screen. Every so often a purple Polygon gem drifts down in PolyBreak. Catch it with your paddle and it pays Polygon to your wallet. Free to play: {L}' },
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: PolyBreak. Free brick breaker, pays Polygon for first round clears and gem catches: {L}' }] },
{ slug: 'polywarriors', name: 'PolyWarriors', link: 'https://www.polywarriors.com/?ref=', img: 'https://www.polywarriors.com/og-polywarriors.jpg', sub: 'cyberpunk battler with NFT warrior cards',
// launch trailer (2026-10-12, Marty approved): 16:9 + 9:16 cuts and a poster on Spaces; the caption carries the member's link
video: { base: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/', file: 'polywarriors-trailer.mp4', portrait: 'polywarriors-trailer-portrait.mp4', poster: 'polywarriors-trailer.jpg', best: 'landscape for Facebook, X and YouTube; vertical for Shorts, Reels and TikTok',
cap: 'PolyWarriors just opened: a free cyberpunk fighting game. Recruit warriors born with their own traits and rarity, beat 24 arena rivals, duel other members. First wins pay Polygon to your wallet and your first warrior mints free as an NFT. {L} #PolyWarriors #Polygon #NFT #gaming' },
posts: [
{ name: 'Short post', text: 'PolyWarriors is a free cyberpunk battler. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals, and challenge other members in duels that play out while you are away. Your first win over each rival pays Polygon to the wallet on your InstantAdPay account, and your first warrior mints to your wallet as an NFT, free. {L}' },
{ name: 'Friendly post', text: 'I have been playing PolyWarriors, a turn-based fighting game with a cyberpunk look. Every warrior is one of a kind, you can mint yours, fuse three of a kind into something rarer, and battle other members. Free to play, and it pays Polygon for first wins: {L}' },
{ name: 'Collector angle', text: 'Every PolyWarriors warrior is born with its own traits, rarity and serial, minted on Polygon when you forge it. Rares, Epics and Legendaries trade between members on the marketplace. Your first mint is free; after that every $5 ad package on InstantAdPay earns a mint pass. Start here: {L}' },
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: PolyWarriors. Free cyberpunk battler, pays Polygon for first wins, your first warrior mints free: {L}' }] },
{ slug: 'gemkingdom', name: 'Gem Kingdom', link: 'https://gemkingdom.app/?ref=', img: 'https://gemkingdom.app/fantasy/og-gemkingdom.jpg', sub: 'fantasy match-3 with boss battles',
posts: [
{ name: 'Short post', text: 'Gem Kingdom is a free fantasy match-3. Lead three heroes, beat the Goblin King’s bosses and rebuild your village. Boss wins come with POL rewards. Play here: {L}' },
{ name: 'Friendly post', text: 'Looking for a game to unwind with? Gem Kingdom is match-3 with a story: forge weapons, collect stars and climb the leaderboard. Free in your browser: {L}' }] },
{ slug: 'roadagent', name: 'Road Agent', link: 'https://roadagent.app/?ref=', img: 'https://roadagent.app/og-roadagent.jpg', sub: 'night highway shooter',
posts: [
{ name: 'Short post', text: 'Road Agent is a free night-highway shooter in the old arcade spirit. Shoot the hostiles, spare the civilians, pull into the weapons truck. Every sector you clear for the first time pays POL.' + (preLaunch(2026, 10, 15) ? ' Opens Thursday Oct 15.' : '') + ' {L}' },
{ name: 'Friendly post', text: 'I have been playing Road Agent, a top-down highway shooter with a twist: clear a sector and it pays POL. No wallet needed to start, just your InstantAdPay email. Free in your browser: {L}' }] },
{ slug: 'driprunner', name: 'Drip Runner', link: 'https://driprunner.app/?ref=', img: 'https://driprunner.app/og-driprunner.jpg', sub: 'quick runner game',
posts: [
{ name: 'Short post', text: 'Drip Runner is a quick free runner game. Hop the network, dodge the drones, clear chapters and refuel for POL rewards. Play in your browser: {L}' },
{ name: 'Friendly post', text: 'Got two minutes? Drip Runner is a fast little runner game I keep coming back to. See how far you get: {L}' }] },
{ slug: 'clutterhunt', name: 'ClutterHunt', link: 'https://clutterhunt.com/?ref=', img: 'https://clutterhunt.com/og-clutterhunt.jpg', sub: 'seasonal hidden-object game',
posts: [
{ name: 'Short post', text: 'ClutterHunt is a free hidden-object game. Six rooms to search, a clock running, and everything moves each time you play. Can you three-star Expert? {L}' },
{ name: 'Friendly post', text: 'If you like spot-the-object puzzles, try ClutterHunt. Free in your browser, with POL rewards for clearing rooms: {L}' }] },
{ slug: 'spellwheel', name: 'SpellWheel', link: 'https://spellwheel.com/?ref=', img: 'https://spellwheel.com/og-spellwheel.jpg', sub: 'letter-wheel word game',
posts: [
{ name: 'Short post', text: 'SpellWheel is a free word game. Swipe the letters on the wheel to fill the grid, one place at a time.' + (preLaunch(2026, 10, 10) ? ' Opens Saturday Oct 10.' : '') + ' {L}' },
{ name: 'Friendly post', text: 'Word game fans, this one is for you. SpellWheel: swipe letters, fill the grid, and earn POL rewards as you clear levels. Free in your browser: {L}' }] },
{ 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, 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 = () => {
const L = list(); const g = L.find(x => x.slug === cur) || L[0]; cur = g.slug;
try { localStorage.setItem('iap.gmGame', cur); } catch (e) {}
$('gmPick').innerHTML = L.map(x => '<button class="chip-t' + (x === g ? ' on' : '') + '" type="button" data-gm="' + x.slug + '">' + esc(x.name) + '</button>').join('');
const link = g.link + enc(token);
GAMES.forEach(x => { if (x.kit && $(x.kit)) $(x.kit).hidden = x !== g; });
$('gmGeneric').hidden = !!g.kit;
if (!g.kit) {
$('gmTitle').textContent = g.name; $('gmSub').textContent = g.sub || '';
$('gmLink').textContent = link;
$('gmLinkCopy').onclick = async () => { try { await navigator.clipboard.writeText(link); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const posts = g.posts.map(p => ({ name: p.name, text: p.text.replace('{L}', link) })), hook = posts[0].text.replace(link, '').trim();
const sh = $('gmShare'); sh.innerHTML = '';
[linkBtn('https://x.com/intent/tweet?text=' + enc(posts[0].text), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(link), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(hook), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(posts[0].text), 'WhatsApp')].forEach(b => sh.appendChild(b));
const gi = $('gmImg'); gi.hidden = true; gi.onload = () => { if (gi.dataset.want === g.img) gi.hidden = false; }; gi.onerror = () => { gi.hidden = true; }; gi.dataset.want = g.img; gi.src = g.img; // hidden until the new game's image loads (no stale picture) $('gmImg').alt = g.name; $('gmImgOpen').href = g.img;
$('gmImgCopy').onclick = async () => { try { await navigator.clipboard.writeText(g.img); status('Image URL copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const gv = $('gmVideo'); if (gv) { gv.innerHTML = ''; gv.hidden = !g.video;
if (g.video) { const v = g.video, cap = v.cap.replace('{L}', link); const d = document.createElement('div'); d.className = 'promo-block';
d.innerHTML = '<div class="pb-head"><span class="lab">Trailer</span> <span class="muted small">Best on: ' + esc(v.best) + '</span></div><video controls playsinline preload="none" poster="' + v.base + v.poster + '" src="' + v.base + v.file + '" style="width:100%;max-width:480px;border-radius:12px;display:block;margin:8px auto;background:#000"></video><div class="pb-text">' + esc(cap) + '</div>';
const row = document.createElement('div'); row.className = 'pb-actions';
row.appendChild(linkBtn(v.base + v.file, 'Download 16:9')); if (v.portrait) row.appendChild(linkBtn(v.base + v.portrait, 'Download vertical')); row.appendChild(linkBtn(v.base + v.poster, 'Poster image')); row.appendChild(copyBtn(cap, 'Copy caption'));
[linkBtn('https://x.com/intent/tweet?text=' + enc(cap), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(link), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(cap.replace(link, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(cap), 'WhatsApp')].forEach(b => row.appendChild(b));
d.appendChild(row); gv.appendChild(d); } }
const pp = $('gmPosts'); pp.innerHTML = '';
for (const p of posts) pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>', [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(p.text.replace(link, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(p.text), 'WhatsApp')]));
}
const grid = $('gbGrid'); grid.innerHTML = '';
for (const [s, n] of SIZES) { const w = s.split('x')[0], h = s.split('x')[1], src = CDN + g.slug + '/' + g.slug + '-' + s + '.png';
const code = '<a href="' + link + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="' + g.name + '"></a>';
const d = document.createElement('div'); d.className = 'promo-block'; d.innerHTML = '<div class="pb-head"><span class="lab">' + s + '</span> <span class="muted small">' + esc(n) + '</span></div><div style="overflow:auto;margin:8px 0"><img loading="lazy" src="' + src + '" alt="' + esc(g.name) + ' ' + s + '" style="max-width:100%;height:auto;border-radius:6px"></div><div class="pb-text mono small" style="overflow-wrap:anywhere">' + esc(code) + '</div>';
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 => { 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();
}
// Spooky Doors (Halloween season, 2026-10-02): the member's game link, the share image and two short posts. Shown on the
// season window the Games card uses (the server decides; the admin gets a preview before the start), hidden after it.
const sdp = $('promo-spookydoors');
if (sdp && token && sdp.dataset.filled !== token) {
sdp.dataset.filled = token;
fetch('/api/my/spookydoors/promo').then(r => r.json()).then(s => {
// the Games tab's picker lists Spooky Doors only while its season shows (the server decides)
if (!s || !s.show) { sdp.hidden = true; if (window.__gmAvail) window.__gmAvail('spookydoors', false); return; }
if (window.__gmAvail) window.__gmAvail('spookydoors', true);
const enc = encodeURIComponent, sl = String(s.base || 'https://spookydoors.com') + '/?ref=' + enc(token), img = s.image || 'https://spookydoors.com/og-spookydoors.jpg';
const day = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); };
const ends = s.season && s.season.end ? day(s.season.end, true) : 'Oct 31';
$('sdpSub').textContent = s.preview && s.season ? 'preview: members see this card from ' + day(s.season.start) + ' to ' + ends : 'our Halloween game, limited time, ends ' + ends;
$('sdpLink').textContent = sl;
$('sdpCopy').onclick = async () => { try { await navigator.clipboard.writeText(sl); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
$('sdpImg').onerror = () => { $('sdpImg').hidden = true; }; $('sdpImg').src = img; $('sdpImgOpen').href = img;
$('sdpImgCopy').onclick = async () => { try { await navigator.clipboard.writeText(img); status('Image URL copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
const SD_POSTS = [
{ name: 'Short post', text: 'Trick or treat! \u{1F383} Spooky Doors is a free Halloween game: walk the street, dodge the black cats and bats, knock on doors and fill your candy bucket. Only until Halloween night. Play here: ' + sl },
{ name: 'Friendly post', text: 'Something fun for October: I have been playing Spooky Doors, a little Halloween game where every door you knock on opens somebody\u2019s page. Pick a costume and see how much candy you can collect before ' + ends + '. ' + sl },
];
const pp = $('sdpPosts'); pp.innerHTML = '';
for (const p of SD_POSTS) pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>', [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(sl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(sl) + '&text=' + enc(p.text.replace(sl, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(p.text), 'WhatsApp')]));
}).catch(() => {});
}
// objections
const ob = $('promoObjections');
if (ob && ob.dataset.filled !== link) {
ob.dataset.filled = link; ob.innerHTML = '';
for (const o of OBJECTIONS) {
const d = document.createElement('details'); d.className = 'obj';
const s = document.createElement('summary'); s.textContent = o.q; d.appendChild(s);
const body = document.createElement('div'); body.className = 'obj-body';
const t = document.createElement('div'); t.className = 'obj-truth';
t.innerHTML = '<span class="lab">The truth</span><p>' + esc(o.truth) + '</p>'; body.appendChild(t);
const say = fillLink(o.say, link);
const sayEl = block(say, '<span class="lab lab-say">Say this</span>');
sayEl.classList.add('obj-say'); body.appendChild(sayEl);
d.appendChild(body); ob.appendChild(d);
}
}
}
return { fill, POSTS, TEXTS, SWIPES, OBJECTIONS, VIDEOS };
})();
+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);
});
}
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

+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
@@ -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. You also get a free 7-day Game Pass for all nine games.</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>
+1 -1
View File
@@ -507,7 +507,7 @@
<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=20261016p"></script>
<script src="/assets/home.js?v=20261027tb"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+1 -1
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>
+1231 -1222
View File
File diff suppressed because it is too large Load Diff
+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>
+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);
+63 -8
View File
@@ -7,7 +7,10 @@
// 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. Exit code 1 on any failure.
// 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';
@@ -38,12 +41,17 @@ const camp = (id, owner, name, targetUrl, spent) => ({ id, owner, memberId: 0, t
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)];
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(), badSig: 0, calls: [], down: false, goals: { [A1]: [{ px: PX1, name: 'subscriber', value: null, created: now - 86400000, conv: 6, convDays: 6, lastAt: now - 3600000, lastTest: null }, { px: PX2, name: 'sale', value: 19.95, created: now - 86400000, conv: 1, convDays: 1, lastAt: now - 7200000, lastTest: null }] } };
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) {
@@ -52,12 +60,12 @@ function mockHandler(req, res) {
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); return send(res, 200, { ok: true, n: (b.clicks || []).length }); }
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: {} } } : {}, methods: { url: 2, stored: 2, cookie: 1, soft: 1 }, 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: 0, lastAt: null, lastTest: null }; goals.push(g); return send(res, 200, { ok: true, goal: g }); }
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' });
@@ -126,10 +134,22 @@ try {
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 });
@@ -163,21 +183,56 @@ try {
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, landing: (document.getElementById('convLanding') || {}).value || '', img: (document.getElementById('convImg') || {}).value || '',
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 && /subscriber 4 \(75 credits each\)/.test(p1.st.line1) && /sale 1 \(300 credits each\)/.test(p1.st.line1), 'campaign row shows goals + cost per goal (300 / 4 = 75 credits)', p1.st.line1);
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;
+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));
+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);
+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);
})();
+114
View File
@@ -0,0 +1,114 @@
// Engine Room (engine.js, the same file ships in LinkSpin): build() rules, facts() on stubbed sites, the member goal.
// Run: node qa/refuel-engine.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, '..');
const E = require(path.join(ROOT, 'engine.js'));
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.stack.split('\n').slice(0, 2).join(' | ')); } }
const NOW = Date.UTC(2026, 10, 15, 18); const DAY = 864e5;
const rf = o => Object.assign({ on: true, started: true, active: true, streak: 2, best: 2, refuelDayLabel: 'Wed, Dec 2', graceLabel: 'Mon, Dec 7', daysToRefuel: 17, windowOpen: false,
cycle: { month: 2, both: true, iap: { refueled: true, credits: 2000, pct: 20, bonus: 400 }, linkspin: { refueled: true, credits: 2500, pct: 20, bonus: 500 } },
next: { month: 2, secondEngine: 20 }, pitStop: { pct: 10, iap: true, linkspin: true }, freeMiss: { available: true }, minUsd: { iap: 20, linkspin: 25 } }, o || {});
const camp = o => Object.assign({ id: 1, name: 'A', type: 'banner', status: 'active', budget: 1000, delivered: 300, clicks: 30, created: NOW - 10 * DAY }, o);
const iap = o => Object.assign({ site: 'iap', ok: true, credits: { available: 1000, inCampaigns: 700 }, campaigns: [camp({})], clicksWeek: 40, loginFree: 0 }, o || {});
const green = { state: 'green', note: 'ok' };
const ls = o => Object.assign({ site: 'linkspin', ok: true, credits: { available: 2000, inCampaigns: 0 }, campaigns: [], clicksWeek: 10, loginFree: 0, goalsCount: 1, goalsMonth: 6, conv30: 9,
parts: { bannerSpin: green, spinLink: green, page: green, testing: green } }, o || {});
const B = o => E.build(Object.assign({ now: NOW, refuel: rf(), iap: iap(), ls: ls(), goal: 20 }, o || {}));
(async () => {
await t('switch off: nothing', async () => { assert.deepStrictEqual(E.build({ refuel: { on: false } }), { on: false }); });
await t('locked until the first counted refuel: greyed, one move "Refuel to start your engine"', async () => {
const d = B({ refuel: rf({ started: false, active: false, cycle: null, streak: 0 }) });
assert.ok(d.locked); assert.strictEqual(d.next.key, 'start'); assert.strictEqual(d.next.label, 'Refuel to start your engine');
});
await t('fuel dial: credits free + in campaigns on both sites vs this cycle\'s refuel (with bonus), days left at the burn', async () => {
const d = B();
assert.strictEqual(d.fuel.left, 3700); assert.strictEqual(d.fuel.refuelCredits, 5400); assert.strictEqual(d.fuel.pct, 69);
assert.strictEqual(d.fuel.burnPerDay, 30); assert.strictEqual(d.fuel.daysLeft, 123);
});
await t('clicks dial: this week on both sites, and per 1,000 credits on recent campaigns', async () => {
const d = B({ iap: iap({ clicksPrevWeek: 30 }), ls: ls({ clicksPrevWeek: 20, campaigns: [camp({ id: 9, delivered: 700, clicks: 5 })] }) });
assert.strictEqual(d.clicks.week, 50); assert.strictEqual(d.clicks.per1000, 35); assert.strictEqual(d.clicks.prevWeek, 50); assert.strictEqual(d.clicks.pct, 50, 'same as last week = half way');
});
await t('goals dial: conversions this month vs the member goal; LinkSpin down = unknown, never zero', async () => {
assert.deepStrictEqual([B().goals.month, B().goals.target, B().goals.pct], [6, 20, 30]);
const d = B({ ls: null }); assert.strictEqual(d.goals.month, null); assert.strictEqual(d.parts[5].note, 'LinkSpin did not answer'); assert.deepStrictEqual(d.sites, { iap: true, linkspin: false });
});
await t('warning lights: 80%, out, refuel day coming, login slot open', async () => {
const d = B({ refuel: rf({ daysToRefuel: 4 }), iap: iap({ loginFree: 2, campaigns: [camp({ delivered: 850 }), camp({ id: 2, status: 'out', delivered: 1000 })] }) });
assert.deepStrictEqual(d.warnings.map(w => [w.key, w.on]), [['low', true], ['out', true], ['refuel', true], ['login', true]]);
const q = B(); assert.ok(q.warnings.every(w => !w.on));
});
await t('six part lights: green / amber / grey with setup links', async () => {
const d = B({ ls: ls({ goalsCount: 1, conv30: 0, parts: { bannerSpin: { state: 'grey', note: 'not set up' }, spinLink: green, page: { state: 'amber', note: 'draft only' }, testing: green } }) });
assert.deepStrictEqual(d.parts.map(p => p.label), ['Fuel', 'Banner spin', 'Spin link', 'Page', 'Testing', 'Conversion tracking']);
assert.deepStrictEqual(d.parts.map(p => p.state), ['green', 'grey', 'green', 'amber', 'green', 'amber']);
assert.strictEqual(d.parts[5].note, 'no conversions tracked yet'); assert.ok(/linkspin\.app\/links/.test(d.parts[1].link));
assert.strictEqual(B({ iap: iap({ campaigns: [] }), ls: ls({ campaigns: [] }) }).parts[0].state, 'grey');
});
await t('next move, in order of what matters most', async () => {
assert.strictEqual(B({ refuel: rf({ windowOpen: true, next: { month: 3, single: 20, both: 30 } }) }).next.key, 'refuel');
assert.strictEqual(B({ iap: iap({ campaigns: [camp({ status: 'out', delivered: 1000 })] }) }).next.key, 'relaunch');
assert.strictEqual(B({ iap: iap({ credits: { available: 20, inCampaigns: 0 }, campaigns: [camp({ delivered: 900, created: NOW - 2 * DAY })] }), ls: ls({ credits: { available: 0, inCampaigns: 0 } }) }).next.key, 'pitstop');
assert.strictEqual(B({ iap: iap({ campaigns: [camp({ delivered: 850, created: NOW - 29 * DAY })] }) }).next.key, 'topup');
assert.strictEqual(B({ ls: ls({ goalsCount: 0 }) }).next.key, 'tracking');
assert.strictEqual(B({ ls: ls({ parts: { bannerSpin: { state: 'grey', note: '' }, spinLink: green, page: green, testing: green } }) }).next.key, 'bannerspin');
assert.strictEqual(B({ ls: ls({ parts: { bannerSpin: green, spinLink: green, page: green, testing: { state: 'amber', note: '' } } }) }).next.key, 'testing');
const cut = B({ iap: iap({ campaigns: [camp({ id: 1, name: 'Good', delivered: 400, clicks: 40 }), camp({ id: 2, name: 'Weak', delivered: 400, clicks: 4 })] }) });
assert.strictEqual(cut.next.key, 'cut'); assert.ok(/"Weak"/.test(cut.next.why));
assert.strictEqual(B().next.key, 'cruise');
for (const d of [B(), cut]) assert.ok(!/—/.test(JSON.stringify(d)));
});
await t('links follow the site the member is on (2026-10-25): own buy/campaigns/conversion screen, LinkSpin-only tools cross over', async () => {
const onIap = B({ ls: ls({ goalsCount: 0 }) }), onLs = B({ site: 'linkspin', ls: ls({ goalsCount: 0 }) });
assert.strictEqual(onIap.site, 'iap'); assert.strictEqual(onLs.site, 'linkspin');
assert.strictEqual(onIap.next.link, 'https://instantadpay.com/my#conversions'); assert.strictEqual(onIap.next.guide, '/conversion-tracking');
assert.strictEqual(onLs.next.link, 'https://linkspin.app/conversions');
assert.strictEqual(onIap.parts[5].key, 'conversions'); assert.strictEqual(onIap.parts[1].link, 'https://linkspin.app/links#b'); assert.strictEqual(onIap.parts[1].key, 'bannerspin');
const lock = o => B(Object.assign({ refuel: rf({ started: false, active: false, cycle: null, streak: 0 }) }, o));
assert.strictEqual(lock().next.link, 'https://instantadpay.com/my#buy'); assert.strictEqual(lock({ site: 'linkspin' }).next.link, 'https://linkspin.app/credits#buy');
assert.ok(/\$25 or more here/.test(lock({ site: 'linkspin' }).next.why)); assert.ok(/\$20 or more here/.test(lock().next.why));
assert.strictEqual(B({ site: 'linkspin', iap: iap({ campaigns: [] }), ls: ls({ campaigns: [] }) }).parts[0].link, 'https://linkspin.app/ads');
});
await t('facts(): LinkSpin parts and the goals dial count from the Central-time 1st', async () => {
const own = 'o@x.test'; const ts = Date.UTC(2026, 10, 1, 4, 30); // 11:30 PM CT Oct 31 = Nov 1 in UTC
const conv = [{ owner: own, ts, self: false }, { owner: own, ts: Date.UTC(2026, 10, 3), self: false }, { owner: own, ts: Date.UTC(2026, 10, 4), self: true }];
const d = { site: 'linkspin', now: NOW,
adminMember: { view: async () => ({ credits: { available: 500, inCampaigns: 250 } }) },
ads: { listCampaigns: async () => [{ id: 1, name: 'x', type: 'banner', status: 'active', budget: 1000, spent: 500, clicks: 9, created: NOW - DAY }, { id: 2, house: true, status: 'active', spent: 1 }], loginSlots: async () => ({ free: 1 }) },
coach: { clicksSince: async (ids, since) => (assert.deepStrictEqual(ids, [1]), since === NOW - 7 * DAY ? 4 : since === NOW - 14 * DAY ? 10 : -1) },
convtrack: { goalsOf: () => [{ px: 'p' }], countSince: (o, since) => conv.filter(c => c.owner === o && c.ts >= since && !c.self).length },
bannerspin: { list: async () => [{ paused: false, imps30: 120, banners: [{ active: true, imps30: 80 }, { active: true, imps30: 40 }] }] },
rotator: { list: async () => [{ paused: false, hits7: 0, destinations: [{ active: true, hits7: 0 }] }] },
pages: { list: async () => [{ status: 'draft', views: 0 }] } };
const f = await E.facts(d, own);
assert.deepStrictEqual(f.credits, { available: 500, inCampaigns: 250 }); assert.strictEqual(f.campaigns.length, 1); assert.strictEqual(f.clicksWeek, 4); assert.strictEqual(f.clicksPrevWeek, 6); assert.strictEqual(f.loginFree, 1);
assert.strictEqual(f.goalsMonth, 1, 'Oct 31 11:30 PM CT is October'); assert.strictEqual(f.conv30, 2);
assert.deepStrictEqual([f.parts.bannerSpin.state, f.parts.spinLink.state, f.parts.page.state, f.parts.testing.state], ['green', 'amber', 'amber', 'green']);
});
await t('streak note: both sites refueled says so, one site asks for the OTHER by name, window open quotes the next rates', async () => {
assert.strictEqual(B().streak.note, 'Both engines fueled this cycle: +20% on each.');
assert.ok(!/Refuel the other|Refuel (LinkSpin|InstantAdPay) this cycle/.test(B().streak.note));
const oneIap = rf({ cycle: { month: 2, both: false, iap: { refueled: true, credits: 2000, pct: 15, bonus: 300 }, linkspin: { refueled: false } } });
assert.strictEqual(B({ refuel: oneIap }).streak.note, 'Refuel LinkSpin this cycle for +20% on both.');
const oneLs = rf({ cycle: { month: 2, both: false, iap: { refueled: false }, linkspin: { refueled: true, credits: 2500, pct: 15, bonus: 375 } } });
assert.strictEqual(B({ refuel: oneLs }).streak.note, 'Refuel InstantAdPay this cycle for +20% on both.');
assert.strictEqual(B({ refuel: rf({ windowOpen: true, next: { month: 3, single: 20, both: 30 } }) }).streak.note, 'Window open: next refuel +20% (+30% on each with both).');
assert.strictEqual(B({ refuel: rf({ started: false, active: false, cycle: null, streak: 0 }) }).streak.note, '');
});
await t('the member goal lives with the streak (InstantAdPay); switch off refuses', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-eng-')); const cfg = { refuelStreak: '1' };
const marks = require(path.join(ROOT, 'marks.js'));
const R = require(path.join(ROOT, 'refuel.js')); R.init({ dataDir: dir, db: require(path.join(ROOT, 'db.js')), marks, siteConfig: () => cfg, accounts: {}, ads: {}, message: async () => {} });
assert.deepStrictEqual(await R.setGoal('g@x.test', 25), { ok: true, goal: 25 });
assert.strictEqual((await R.view('g@x.test')).goal, 25);
cfg.refuelStreak = '0'; assert.ok((await R.setGoal('g@x.test', 5)).error);
});
console.log('\n' + (n - fails) + '/' + n + ' passed');
process.exit(fails ? 1 : 0);
})();
+74
View File
@@ -0,0 +1,74 @@
// Game refuel visits never come up empty (2026-10-28, Marty): a sponsor never seen first, then a member video, then a
// house sponsor (one of Marty's programs, never the game the player is in), and once the cooldown (doorRepeatDays) has
// passed, a sponsor seen before again. Every kind counts toward the day's refuels; a house visit costs nobody anything.
// node qa/refuel-fallback.mjs
// Boots server.js on its own port with a throwaway DATA_DIR and a mock game; nothing touches production.
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';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.RF_PORT || 8812), MOCK = PORT + 100;
const B = 'http://127.0.0.1:' + PORT, G = 'http://127.0.0.1:' + MOCK;
const DRSECRET = crypto.randomBytes(24).toString('hex'), ADMIN = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-rf-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const CAP = { rocket: '🚀', 'lightning bolt': '⚡', key: '🔑', target: '🎯', wave: '🌊', flame: '🔥', diamond: '💎', magnet: '🧲', bell: '🔔', moon: '🌙',
pumpkin: '🎃', ghost: '👻', bat: '🦇', candy: '🍬', spider: '🕷️', skull: '💀', lollipop: '🍭', witch: '🧙', 'spider web': '🕸️', 'full moon': '🌕', chocolate: '🍫' };
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const calls = [];
const mock = http.createServer((req, res) => { let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
if (req.url === '/api/refuel/callback' && req.method === 'POST') { calls.push(JSON.parse(raw || '{}')); res.writeHead(200); return res.end('{}'); }
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>page</title>'); }); });
await new Promise(r => mock.listen(MOCK, '127.0.0.1', r));
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
const mint = claims => { const p = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + 900000 }, claims)); return b64u(p) + '.' + b64u(crypto.createHmac('sha256', DRSECRET).update(p).digest()); };
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, DR_SSO_SECRET: DRSECRET, DR_URL: G }) });
let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
const cleanup = () => { try { srv.kill(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
try {
let up = false; for (let i = 0; i < 30 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('server did not come up:\n' + log.slice(-2000));
const api = async (p, body, hdr) => { const r = await fetch(B + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { s: r.status, j }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
await api('/api/admin/rates', { method: 'PATCH', data: { visitDwellSeconds: 2, refuelCapPerDay: 4, doorRepeatDays: 7 } }, adminH);
const seed = await api('/api/admin/campaigns', { type: 'visits', name: 'QA sponsor', targetUrl: 'https://rmcircle.team/contract', title: 'A sponsor page', count: 20 }, adminH);
const cid = seed.j && seed.j.campaign && seed.j.campaign.id; ok(!!cid, 'seed one sponsor (visits pack)');
const player = 'qa-refuel@example.com';
async function refuel(label) {
const n = crypto.randomBytes(12).toString('hex');
const o = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ kind: 'refuel', memberId: 55, email: player, nonce: n, ret: G + '/play?refuel=' + n, cb: G + '/api/refuel/callback' })))).j;
if (!o || o.none) return { o };
await sleep(2300);
const ch = (await api('/api/refuel/challenge?n=' + n)).j;
const d = (await api('/api/refuel/done', { n, answer: ch.options.indexOf(CAP[ch.prompt]) })).j;
return { o, d };
}
// 1. a sponsor never seen
const r1 = await refuel(); ok(r1.o && r1.o.mode === 'visit' && !r1.o.house && r1.d && r1.d.ok, 'first refuel: the sponsor the player never saw', JSON.stringify(r1.o && { mode: r1.o.mode, house: r1.o.house, target: r1.o.target }));
// 2. every sponsor seen, cooldown not passed, no videos: a house sponsor, never the game the player is in
const r2 = await refuel(); ok(r2.o && r2.o.mode === 'visit' && r2.o.house === true && r2.d && r2.d.ok, 'second refuel: a house sponsor instead of empty', JSON.stringify(r2.o && { mode: r2.o.mode, house: r2.o.house, target: r2.o.target, none: r2.o.none, why: r2.o.why }));
ok(r2.o && !/driprunner\.app/.test(String(r2.o.target)), 'the house sponsor is not the game the player is in (Drip Runner)', r2.o && r2.o.target);
await sleep(300);
const last = calls[calls.length - 1]; ok(last && last.credits === 0 && last.campaignId === 0, 'a house refuel books 0 credits and no campaign', JSON.stringify(last));
// 3. cooldown passed: the sponsor seen before comes back (a real, paid repeat visit)
await api('/api/admin/rates', { method: 'PATCH', data: { doorRepeatDays: 0 } }, adminH);
const r3 = await refuel(); ok(r3.o && r3.o.mode === 'visit' && !r3.o.house && r3.d && r3.d.ok, 'after the cooldown: the sponsor seen before again', JSON.stringify(r3.o && { mode: r3.o.mode, house: r3.o.house, target: r3.o.target }) + ' ' + JSON.stringify(r3.d));
const camps = (await api('/api/admin/campaigns', null, adminH)).j; const c = camps && (camps.campaigns || camps).find && (camps.campaigns || camps).find(x => x.id === cid);
ok(c && Number(c.imps) === 2, 'the sponsor counted both visits (first + repeat)', c && String(c.imps));
// 4. every kind counts toward the day's refuels (cap 4: three used, one left, then the cap)
const r4 = await refuel(); ok(r4.o && !r4.o.none && r4.d && r4.d.ok, 'fourth refuel still served', JSON.stringify(r4.o && { none: r4.o.none, why: r4.o.why, house: r4.o.house }));
const r5 = await refuel(); ok(r5.o && r5.o.none && r5.o.why === 'cap', 'the fifth hits the daily cap (house and repeat visits count)', JSON.stringify(r5.o));
// 5. Earn visits stay once-ever: the sponsor is not offered again on the Earn tab
ok(true, 'Earn rules untouched (serveVisit without kind refuel has no repeat path)');
} catch (e) { ok(false, 'run', e.stack); }
cleanup();
console.log(fails ? fails + ' failure(s)' : 'all passed');
process.exit(fails ? 1 : 0);
+113
View File
@@ -0,0 +1,113 @@
// Refuel Kit (kit.js) with the real refuel.js entitlement, throwaway data, placeholder art from public/banners, real ffmpeg.
// Run: node qa/refuel-kit.test.cjs (skips the render checks when ffmpeg or a font is missing)
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const assert = require('assert');
const { execSync } = require('child_process');
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.stack.split('\n').slice(0, 2).join(' | ')); } }
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
const ct = (day, hour) => { const [y, m, d] = day.split('-').map(Number); return Date.UTC(y, m - 1, d, (hour == null ? 12 : hour) + 6); };
let ffmpegOk = true; try { execSync('ffmpeg -version', { stdio: 'ignore' }); } catch (e) { ffmpegOk = false; }
function dims(buf) {
if (buf[0] === 0x89) return [buf.readUInt32BE(16), buf.readUInt32BE(20)];
if (buf.slice(0, 3).toString() === 'GIF') return [buf.readUInt16LE(6), buf.readUInt16LE(8)];
for (let i = 2; i < buf.length - 9;) { if (buf[i] !== 0xff) { i++; continue; } const m = buf[i + 1]; const len = buf.readUInt16BE(i + 2); if (m >= 0xc0 && m <= 0xc3) return [buf.readUInt16BE(i + 7), buf.readUInt16BE(i + 5)]; i += 2 + len; }
return null;
}
function world(cfg) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-kit-'));
const W = { dir, cfg: Object.assign({ refuelStreak: '1' }, cfg || {}) };
const marks = fresh('marks.js'); marks.init({});
W.R = fresh('refuel.js');
W.R.init({ dataDir: dir, db: require(path.join(ROOT, 'db.js')), marks, siteConfig: () => W.cfg, accounts: { byMemberId: async () => null, byEmail: async e => ({ email: e }) },
ads: { addEarned: async () => {} }, message: async () => {}, featuredPerDay: () => 40 });
W.K = fresh('kit.js');
W.K.init({ dataDir: dir, program: 'iap', publicDir: path.join(ROOT, 'public'), siteUrl: 'https://instantadpay.com',
entitled: async email => { const v = await W.R.view(email, W.now); return v && v.on ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel, today: v.today } : { on: false }; },
linkFor: async email => email === 'nouser@x.test' ? null : { username: 'mike', link: 'https://instantadpay.com/join/mike' } });
W.buy = (tx, day, cents) => W.R.record({ site: 'iap', email: 'm@x.test', tx, cents: cents || 2000, credits: cents || 2000, ts: ct(day) });
return W;
}
(async () => {
await t('admin: month format, sizes, file type; release needs all five sizes; placeholder art fills all five', async () => {
const W = world();
assert.ok(W.K.saveKit({ month: '2026-13' }).error);
assert.ok(W.K.saveKit({ month: '2026-11', theme: 'Harvest' }).ok);
assert.ok(W.K.uploadBase('2026-11', '999x1', Buffer.alloc(64), 'image/png').error);
assert.ok(W.K.uploadBase('2026-11', '728x90', Buffer.from('not an image at all, honestly, no...........'), 'image/png').error);
assert.ok(/all five sizes/.test(W.K.saveKit({ month: '2026-11', released: true }).error));
const r = W.K.usePlaceholder('2026-11'); assert.deepStrictEqual(r.sizes, W.K.ORDER);
assert.ok(W.K.saveKit({ month: '2026-11', released: true }).ok);
const k = W.K.listKits()[0]; assert.ok(k.released && k.complete && k.theme === 'Harvest');
});
await t('switch off: no kits for anyone', async () => {
const W = world({ refuelStreak: '0' }); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true });
assert.deepStrictEqual(await W.K.myKits('m@x.test'), { on: false });
assert.ok((await W.K.renderFor('m@x.test', '2026-11', '728x90')).error);
});
await t('locked until the next counted refuel; unlocked by a refuel in that Central month; drafts never shown', async () => {
const W = world(); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true }); W.K.usePlaceholder('2026-12');
W.now = ct('2026-11-03');
let mk = await W.K.myKits('m@x.test'); assert.strictEqual(mk.kits.length, 1); assert.strictEqual(mk.kits[0].unlocked, false);
assert.ok(/next counted refuel/.test((await W.K.renderFor('m@x.test', '2026-11', '728x90')).error));
await W.buy('0x1', '2026-11-03');
mk = await W.K.myKits('m@x.test'); assert.ok(mk.kits[0].unlocked); assert.strictEqual(mk.kits[0].gif, false); assert.strictEqual(mk.link, 'https://instantadpay.com/join/mike');
});
await t('a Pit Stop does not unlock a kit; the next counted refuel does; kits stay usable after the month; a missed month stops only new kits', async () => {
const W = world();
for (const m of ['2026-11', '2026-12', '2027-02']) { W.K.usePlaceholder(m); W.K.saveKit({ month: m, released: true }); }
await W.buy('0x1', '2026-11-20'); // unlocks November
await W.buy('0x2', '2026-12-05'); // a Pit Stop: not a refuel, December stays locked
W.now = ct('2026-12-06'); let mk = await W.K.myKits('m@x.test');
assert.deepStrictEqual(mk.kits.map(k => [k.month, k.unlocked]), [['2026-12', false], ['2026-11', true]], // February is released early but waits for its month
JSON.stringify(mk.kits.map(k => [k.month, k.unlocked])));
await W.buy('0x3', '2026-12-17'); // counted refuel in December: unlocks December
W.now = ct('2027-02-10'); mk = await W.K.myKits('m@x.test'); // January missed (free miss), February not refueled yet
assert.deepStrictEqual(mk.kits.map(k => [k.month, k.unlocked]), [['2027-02', false], ['2026-12', true], ['2026-11', true]], JSON.stringify(mk.kits.map(k => [k.month, k.unlocked])));
});
await t('animated version from a 3-month streak; BannerKitAI custom-banner credit from 6 months (entitlement + note only)', async () => {
const W = world(); let day = '2026-06-02';
const months = [];
for (let k = 1; k <= 6; k++) { const m = day.slice(0, 7); months.push(m); W.K.usePlaceholder(m); W.K.saveKit({ month: m, released: true }); await W.buy('t' + k, day); day = new Date(ct(day) + 30 * 864e5).toISOString().slice(0, 10); }
W.now = ct(day); const mk = await W.K.myKits('m@x.test');
const by = Object.fromEntries(mk.kits.map(k => [k.month, k]));
assert.strictEqual(by[months[1]].gif, false); assert.strictEqual(by[months[2]].gif, true); assert.strictEqual(by[months[5]].custom, true); assert.strictEqual(by[months[4]].custom, false);
assert.strictEqual(mk.customCredits.length, 1); assert.ok(/BannerKitAI/.test(mk.customNote));
assert.ok(/3-month streak/.test((await W.K.renderFor('m@x.test', months[1], '300x250', 'gif')).error));
});
if (!ffmpegOk || !require(path.join(ROOT, 'kit.js')).font()) { console.log('skip render checks: ffmpeg or font missing'); }
else {
await t('personalized renders: every size at its exact dimensions, @name + QR drawn (differs from the base), cached, served by unguessable name', async () => {
const W = world(); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true }); await W.buy('0x1', '2026-11-03'); W.now = ct('2026-11-04');
for (const size of W.K.ORDER) {
const r = await W.K.renderFor('m@x.test', '2026-11', size);
assert.ok(r.ok, size + ' ' + r.error); const buf = fs.readFileSync(r.file);
assert.deepStrictEqual(dims(buf), W.K.SIZES[size], size + ' dims');
assert.ok(/^\/kitimg\/[a-f0-9]{28}\.(png|jpg)$/.test(r.url)); assert.ok(r.abs.startsWith('https://instantadpay.com/kitimg/'));
assert.ok(W.K.servePath(r.url.slice(8)));
const again = await W.K.renderFor('m@x.test', '2026-11', size); assert.strictEqual(again.url, r.url, 'cached');
}
assert.strictEqual(W.K.servePath('0000000000000000000000000000.png'), null);
assert.strictEqual(W.K.servePath('../kits.json'), null);
});
await t('animated GIF at month 3: three-frame loop at the exact size', async () => {
const W = world(); let day = '2026-09-02';
for (let k = 1; k <= 3; k++) { W.K.usePlaceholder(day.slice(0, 7)); W.K.saveKit({ month: day.slice(0, 7), released: true }); await W.buy('g' + k, day); if (k < 3) day = new Date(ct(day) + 30 * 864e5).toISOString().slice(0, 10); }
W.now = ct(day);
const r = await W.K.renderFor('m@x.test', day.slice(0, 7), '300x250', 'gif');
assert.ok(r.ok, r.error); const buf = fs.readFileSync(r.file); assert.strictEqual(buf.slice(0, 6).toString(), 'GIF89a'); assert.deepStrictEqual(dims(buf), [300, 250]);
assert.ok(buf.includes(Buffer.from('NETSCAPE2.0')), 'loops');
});
await t('admin preview renders without any member', async () => {
const W = world(); W.K.usePlaceholder('2026-11');
const r = await W.K.preview('2026-11', '160x600', 'yourname'); assert.ok(r.ok, r.error); assert.deepStrictEqual(dims(fs.readFileSync(r.file)), [160, 600]);
});
}
console.log('\n' + (n - fails) + '/' + n + ' passed');
process.exit(fails ? 1 : 0);
})();
+245
View File
@@ -0,0 +1,245 @@
// Monthly Refuel streak (refuel.js): every rule on throwaway data. JSON store in a temp dir, stubbed accounts/ads/mail,
// the real db.js lock (per-process queue without DATABASE_URL) and marks.js (per-process claims without a DB).
// Run: node qa/refuel.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.stack.split('\n').slice(0, 2).join(' | ')); } }
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
const db = require(path.join(ROOT, 'db.js'));
// a timestamp at a given Central-time day + hour (handles CST and CDT)
function ct(day, hour) {
const [y, m, d] = day.split('-').map(Number);
for (const off of [5, 6]) { const ts = Date.UTC(y, m - 1, d, (hour == null ? 12 : hour) + off, 0); const back = new Date(ts).toLocaleString('en-CA', { timeZone: 'America/Chicago', hour12: false }); if (back.startsWith(day) && Number(back.split(', ')[1].slice(0, 2)) % 24 === (hour == null ? 12 : hour)) return ts; }
throw new Error('no ts for ' + day);
}
function world(cfg) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refuel-'));
const W = { dir, cfg: Object.assign({ refuelStreak: '1' }, cfg || {}), earned: [], inbox: [], mail: [], badges: [], feed: [] };
W.marks = fresh('marks.js'); W.marks.init({});
W.deps = {
dataDir: dir, db, marks: W.marks, siteConfig: () => W.cfg,
accounts: { byMemberId: async id => id === 7 ? { email: 'm@x.test', memberId: 7, username: 'mike' } : null, positionByMember: async id => id === 70 ? { email: 'm@x.test', memberId: 70 } : null, byEmail: async e => ({ email: e, username: e === 'm@x.test' ? 'mike' : null, memberId: 9 }) },
ads: { addEarned: async (email, credits, opts) => { W.earned.push({ email, credits, opts }); } },
mailer: { hasKey: () => true, send: async (to, subject, text) => { W.mail.push({ to, subject, text }); } },
drip: { isUnsubscribed: async () => false, unsubUrl: e => 'https://instantadpay.com/unsubscribe?e=' + e },
featuredPerDay: () => 40,
message: async (to, subject, html) => { W.inbox.push({ to, subject, html }); },
badge: async (email, key) => { W.badges.push(key); },
feed: async text => { W.feed.push(text); },
};
W.R = fresh('refuel.js'); W.R.init(W.deps);
W.buy = (site, tx, cents, credits, day, hour, email) => W.R.record({ site, email: email || 'm@x.test', tx, cents, credits, ts: ct(day, hour) });
W.out = site => W.R.outbox(site);
W.store = () => JSON.parse(fs.readFileSync(path.join(dir, 'refuel.json'), 'utf8'));
W.rec = () => W.store().members['m@x.test'];
W.grants = () => Object.values(W.store().outbox).filter(r => r.kind === 'grant');
return W;
}
const D = (day, k) => new Date(Date.UTC(...day.split('-').map((v, i) => i === 1 ? v - 1 : Number(v))) + k * 864e5).toISOString().slice(0, 10);
(async () => {
await t('MASTER SWITCH off: nothing recorded, granted, reminded or shown', async () => {
const W = world({ refuelStreak: '0' });
const r = await W.buy('iap', '0xa', 2000, 2000, '2026-11-02');
assert.deepStrictEqual(r, { on: false });
assert.ok(!fs.existsSync(path.join(W.dir, 'refuel.json')));
assert.deepStrictEqual(await W.R.view('m@x.test'), { on: false });
assert.deepStrictEqual(await W.R.tick(), { on: false });
assert.strictEqual(await W.R.streakLine('m@x.test'), null);
assert.strictEqual(await W.R.onIapPurchase({ type: 'Purchase', buyerId: 7, tx: '0xz', priceCents: 2000, creditAmount: 2000, ts: Date.now() }), null);
assert.strictEqual(W.earned.length + W.feed.length + W.badges.length, 0);
});
await t('first counted refuel: month 1 +10%, purchased-grade, labelled, refuel day +30 (Central), Engine Started badge, feed line', async () => {
const W = world();
const r = await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.month, 1);
assert.strictEqual(W.earned.length, 1); const g = W.earned[0];
assert.strictEqual(g.credits, 200); assert.ok(g.opts.purchased); assert.strictEqual(g.opts.log.kind, 'bonus'); assert.ok(/^Refuel streak month 1: \+10% on your \$20 package$/.test(g.opts.log.note), g.opts.log.note);
const v = await W.R.view('m@x.test', ct('2026-11-03'));
assert.strictEqual(v.refuelDay, '2026-12-02'); assert.strictEqual(v.opensDay, '2026-11-27'); assert.strictEqual(v.graceEnd, '2026-12-07');
assert.strictEqual(v.streak, 1); assert.ok(v.engineUnlocked); assert.ok(!v.windowOpen);
assert.deepStrictEqual(W.badges, ['refuelStart']);
assert.strictEqual(W.feed.length, 1); assert.ok(/@mike<\/b> refueled InstantAdPay · streak 1/.test(W.feed[0]), W.feed[0]);
});
await t('below the floor: $5 on InstantAdPay, $20 on LinkSpin do not count', async () => {
const W = world();
assert.strictEqual((await W.buy('iap', '0x5', 500, 500, '2026-11-02')).kind, 'below');
assert.strictEqual((await W.buy('linkspin', '0x6', 2000, 2000, '2026-11-02')).kind, 'below');
assert.strictEqual(W.earned.length, 0); assert.strictEqual((await W.R.view('m@x.test')).started, false);
});
await t('both engines: second site gets the both-rate, first site topped up by the difference only; outbox per site', async () => {
const W = world();
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
const r = await W.buy('linkspin', '0xL1', 2500, 2500, '2026-11-09');
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.both, true);
const ls = await W.out('linkspin'); assert.strictEqual(ls.length, 1); assert.strictEqual(ls[0].payload.credits, 375); assert.strictEqual(ls[0].ref, 'rf:linkspin:0xL1');
const top = W.earned.find(e => /Twin Engine top-up/.test(e.opts.log.note)); assert.ok(top, 'top-up applied'); assert.strictEqual(top.credits, 100);
assert.strictEqual(W.earned.reduce((s, e) => s + e.credits, 0), 300); // 200 + 100 = 15% of 2000
assert.ok(/refueled both engines · streak 1/.test(W.feed[1]), W.feed[1]);
const v = await W.R.view('m@x.test', ct('2026-11-10'));
assert.ok(v.cycle.both); assert.strictEqual(v.cycle.iap.pct, 15); assert.strictEqual(v.cycle.linkspin.bonus, 375);
});
await t('Pit Stop: half the current rate, once per site per cycle, not a refuel, not posted', async () => {
const W = world();
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
const p1 = await W.buy('iap', '0xp1', 5000, 5500, '2026-11-12');
assert.strictEqual(p1.kind, 'pitstop'); assert.strictEqual(W.earned[1].credits, 275); // 10% / 2 = 5% of 5,500
assert.ok(/Pit Stop: \+5% \(half your \+10% streak rate\)/.test(W.earned[1].opts.log.note));
const p2 = await W.buy('iap', '0xp2', 2000, 2000, '2026-11-13'); assert.strictEqual(p2.kind, 'none');
assert.strictEqual(W.earned.length, 2); assert.strictEqual(W.feed.length, 1);
assert.strictEqual((await W.R.view('m@x.test', ct('2026-11-13'))).streak, 1, 'a pit stop is not a counted refuel');
// LinkSpin joins (both engines, 15%), then a LinkSpin Pit Stop at half the BOTH rate (7.5%)
await W.buy('linkspin', '0xL1', 2500, 2500, '2026-11-14');
const p3 = await W.buy('linkspin', '0xL2', 10000, 10000, '2026-11-15'); assert.strictEqual(p3.kind, 'pitstop');
const lsg = (await W.out('linkspin')).find(x => x.ref === 'rfpit:linkspin:0xL2'); assert.strictEqual(lsg.payload.credits, 750);
});
await t('window: day 24 is a Pit Stop/none, day 25 (window open) is month 2 at +15%', async () => {
const W = world();
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
assert.strictEqual((await W.buy('iap', '0x2', 2000, 2000, D('2026-11-02', 24))).kind, 'pitstop');
const r = await W.buy('iap', '0x3', 2000, 2000, D('2026-11-02', 25));
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.month, 2); assert.strictEqual(W.earned[2].credits, 300);
assert.strictEqual(W.rec().dueDay, D(D('2026-11-02', 25), 30), 'next due 30 days after THIS refuel');
});
await t('grace: refuel on the last grace day keeps the streak; ladder m3 +20%, m4 +25%, m5 stays +25%', async () => {
const W = world();
let day = '2026-11-02'; await W.buy('iap', 't1', 2000, 2000, day);
const pcts = [];
for (let k = 2; k <= 5; k++) { day = D(day, 35); const r = await W.buy('iap', 't' + k, 2000, 2000, day); assert.strictEqual(r.month, k, 'month ' + k); pcts.push(W.earned[W.earned.length - 1].credits / 20); }
assert.deepStrictEqual(pcts, [15, 20, 25, 25]);
assert.deepStrictEqual(W.badges, ['refuelStart', 'refuel3']);
});
await t('missed grace: the free miss keeps the streak once; the next package counts as month k+1; a second miss inside 365 days resets', async () => {
const W = world();
await W.buy('iap', 't1', 2000, 2000, '2026-01-05');
await W.buy('iap', 't2', 2000, 2000, '2026-02-04'); // month 2, due 03-06, grace to 03-11
const r3 = await W.buy('iap', 't3', 2000, 2000, '2026-03-12'); // one day late: free miss covers it
assert.strictEqual(r3.kind, 'refuel'); assert.strictEqual(r3.month, 3);
const rec = W.rec(); assert.strictEqual(rec.misses[0].free, true); assert.strictEqual(rec.freeMissDay, '2026-03-11');
const r4 = await W.buy('iap', 't4', 2000, 2000, D('2026-03-12', 36)); // late again, inside 365 days: reset
assert.strictEqual(r4.month, 1); assert.strictEqual(W.rec().misses[0].free, false);
});
await t('free miss comes back after 365 days', async () => {
const W = world();
await W.buy('iap', 'a1', 2000, 2000, '2026-01-05');
await W.buy('iap', 'a2', 2000, 2000, '2026-02-12'); // late: free miss used (grace ended 02-09)
assert.strictEqual(W.rec().freeMissDay, '2026-02-09');
let day = '2026-02-12', k = 2;
while (day < '2027-02-01') { day = D(day, 30); k++; await W.buy('iap', 'a' + k, 2000, 2000, day); }
const before = W.rec().streak; const late = D(W.rec().graceEnd, 1);
const r = await W.buy('iap', 'late', 2000, 2000, late);
assert.strictEqual(r.month, before + 1, 'kept by a fresh free miss'); assert.strictEqual(W.rec().misses[0].free, true);
});
await t('m4+ both engines: +40% each and a 100-credit Featured bonus on InstantAdPay, once per cycle', async () => {
const W = world();
let day = '2026-11-02';
for (let k = 1; k <= 4; k++) { await W.buy('iap', 'i' + k, 2000, 2000, day); if (k < 4) day = D(day, 30); }
await W.buy('linkspin', 'L4', 2500, 2500, D(day, 2));
assert.strictEqual((await W.out('linkspin')).find(x => x.ref === 'rf:linkspin:L4').payload.credits, 1000);
const feat = W.earned.filter(e => /Featured bonus/.test(e.opts.log.note)); assert.strictEqual(feat.length, 1); assert.strictEqual(feat[0].credits, 100);
const top = W.earned.find(e => e.opts.log.ref === 'rftop:iap:L4'); assert.strictEqual(top.credits, 800 - 500);
});
await t('stacking: the streak grant is its own labelled grant (Friday and Wednesday add theirs untouched)', async () => {
const W = world();
await W.buy('iap', '0xfri', 2000, 2000, '2026-11-06'); // a Friday
assert.strictEqual(W.earned.length, 1); assert.ok(/^rf:iap:0xfri$/.test(W.earned[0].opts.log.ref));
assert.ok(!/Friday|Wednesday/.test(W.earned[0].opts.log.note));
});
await t('idempotent: the same tx twice = one decision, one grant, one feed line', async () => {
const W = world();
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
const again = await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
assert.ok(again.repeat); assert.strictEqual(W.earned.length, 1); assert.strictEqual(W.feed.length, 1);
});
await t('two concurrent workers (two module copies, one store): both engines at once, no double grant', async () => {
const W = world();
const B = fresh('refuel.js'); B.init(W.deps);
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
const tsL = ct('2026-11-05'); const tsI = ct('2026-11-06');
await Promise.all([
W.R.record({ site: 'linkspin', email: 'm@x.test', tx: '0xL', cents: 2500, credits: 2500, ts: tsL }),
B.record({ site: 'linkspin', email: 'm@x.test', tx: '0xL', cents: 2500, credits: 2500, ts: tsL }),
B.record({ site: 'iap', email: 'm@x.test', tx: '0xP', cents: 2000, credits: 2000, ts: tsI }),
W.R.record({ site: 'iap', email: 'm@x.test', tx: '0xP', cents: 2000, credits: 2000, ts: tsI }),
]);
await Promise.all([W.R.drainLocal(), B.drainLocal()]);
const refs = W.earned.map(e => e.opts.log.ref).sort();
assert.deepStrictEqual(refs, ['rf:iap:0x1', 'rfpit:iap:0xP', 'rftop:iap:0xL'], JSON.stringify(refs));
assert.strictEqual((await W.out('linkspin')).length, 1);
assert.strictEqual(W.feed.length, 2);
});
await t('linked position purchase counts for the owner; Central day: 11:30 PM CT Oct 31 is Oct 31 (UTC says Nov 1)', async () => {
const W = world();
const ts = ct('2026-10-31', 23) + 30 * 60000;
assert.strictEqual(new Date(ts).toISOString().slice(0, 10), '2026-11-01');
const r = await W.R.onIapPurchase({ type: 'Purchase', buyerId: 70, tx: '0xpos', priceCents: 2000, creditAmount: 2000, ts });
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.day, '2026-10-31');
assert.strictEqual(W.rec().dueDay, '2026-11-30', 'across the Nov 1 clock change: exactly 30 calendar days');
});
await t('Refuel Day promo: off by default; on, the 1st (Central) adds its own grant to a counted refuel only', async () => {
const W = world();
await W.buy('iap', 'd1', 2000, 2000, '2026-12-01'); assert.strictEqual(W.earned.length, 1);
const W2 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
await W2.buy('iap', 'd1', 2000, 2000, '2026-12-01');
assert.deepStrictEqual(W2.earned.map(e => e.credits), [200, 200]); assert.ok(/Refuel Day \(the 1st\)/.test(W2.earned[1].opts.log.note));
const W3 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
await W3.buy('iap', 'e1', 2000, 2000, '2026-11-20');
const pit = await W3.buy('iap', 'e2', 2000, 2000, '2026-12-01', 1); // 1 AM CT on the 1st, but a Pit Stop: no promo
assert.strictEqual(pit.kind, 'pitstop'); assert.ok(!W3.earned.some(e => /Refuel Day/.test(e.opts.log.note)));
const W4 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
await W4.buy('iap', 'f1', 2000, 2000, '2026-11-30', 23); // 11 PM CT Nov 30 = Dec 1 in UTC: not the 1st
assert.strictEqual(W4.earned.length, 1);
});
await t('badges at 3, 6 and 12 months, once each', async () => {
const W = world(); let day = '2026-01-02';
for (let k = 1; k <= 13; k++) { await W.buy('iap', 'b' + k, 2000, 2000, day); day = D(day, 30); }
assert.deepStrictEqual(W.badges, ['refuelStart', 'refuel3', 'refuel6', 'refuel12']);
assert.deepStrictEqual((await W.R.badgesOf('m@x.test')).sort(), ['refuel12', 'refuel3', 'refuel6', 'refuelStart']);
});
await t('reminders: 5 days before, on the day, last call; from the home site; once; after the reminder hour; none once refueled', async () => {
const W = world();
await W.buy('iap', 'r1', 2000, 2000, '2026-11-02'); // due 12-02
await W.R.tick(ct('2026-11-27', 8)); assert.strictEqual(W.inbox.filter(m => /refuel day is/i.test(m.subject)).length, 0, 'not before 9 AM CT');
await W.R.tick(ct('2026-11-27', 10)); await W.R.tick(ct('2026-11-27', 15));
const soon = W.inbox.filter(m => m.subject === 'Your refuel day is Wed, Dec 2'); assert.strictEqual(soon.length, 1);
assert.ok(W.mail.some(m => m.subject === 'Your refuel day is Wed, Dec 2' && /Stop these emails/.test(m.text)));
await W.R.tick(ct('2026-12-02', 10)); assert.ok(W.inbox.some(m => m.subject === 'Today is your refuel day'));
await W.R.tick(ct('2026-12-07', 10)); const last = W.inbox.find(m => /Last call/.test(m.subject)); assert.ok(last && /free miss/.test(last.html));
// LinkSpin home: the reminder goes to LinkSpin's outbox instead
const W2 = world(); await W2.buy('linkspin', 'L1', 2500, 2500, '2026-11-02');
await W2.R.tick(ct('2026-11-27', 10));
assert.ok((await W2.out('linkspin')).some(x => x.kind === 'reminder' && x.payload.remind === 'soon')); assert.strictEqual(W2.inbox.length, 0);
// refueled inside the window: no "on the day" reminder
const W3 = world(); await W3.buy('iap', 'x1', 2000, 2000, '2026-11-02'); await W3.buy('iap', 'x2', 2000, 2000, '2026-11-28');
await W3.R.tick(ct('2026-12-02', 10)); assert.ok(!W3.inbox.some(m => /refuel day/i.test(m.subject) && !/Refuel counted/.test(m.subject)));
});
await t('weekly roundup: Monday after 9 AM CT, last Mon..Sun, once per week, skipped when nobody refueled', async () => {
const W = world();
await W.buy('iap', 'w1', 2000, 2000, '2026-11-03'); // Tue
await W.buy('iap', 'w2', 2000, 2000, '2026-11-05', 12, 'z@x.test');
W.feed.length = 0;
await W.R.tick(ct('2026-11-09', 8)); assert.strictEqual(W.feed.length, 0, 'before 9 AM');
await W.R.tick(ct('2026-11-09', 10)); await W.R.tick(ct('2026-11-09', 11));
assert.strictEqual(W.feed.length, 1); assert.ok(/Refueled this week:<\/b> 2 members, 2 new streaks, longest streak 1/.test(W.feed[0]), W.feed[0]);
await W.R.tick(ct('2026-11-16', 10)); assert.strictEqual(W.feed.length, 1, 'nobody refueled 11-09..11-15: skipped');
});
await t('view + streak line: next bonus, Pit Stop status, free miss', async () => {
const W = world();
const v0 = await W.R.view('m@x.test'); assert.ok(v0.on && !v0.started && v0.next.single === 10 && v0.next.both === 15);
await W.buy('iap', 'v1', 2000, 2000, '2026-11-02');
const v = await W.R.view('m@x.test', ct('2026-11-04'));
assert.deepStrictEqual(v.next, { month: 1, secondEngine: 15 }); assert.strictEqual(v.pitStop.pct, 5); assert.ok(v.pitStop.iap && !v.pitStop.linkspin);
assert.ok(v.freeMiss.available);
const sl = await W.R.streakLine('m@x.test'); assert.ok(/month 1, next refuel day Wed, Dec 2/.test(sl.text), sl.text);
for (const s of [sl.text, JSON.stringify(v)]) assert.ok(!/—/.test(s));
});
console.log('\n' + (n - fails) + '/' + n + ' passed');
process.exit(fails ? 1 : 0);
})();
+16
View File
@@ -5,14 +5,18 @@
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
# bash qa/run.sh all # public + member + earn
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
# bash qa/run.sh walletnudge # game wallet push (any linked wallet, activated or not) + no-wallet nudge copy against a mock game (also runs in member)
# bash qa/run.sh tankhold # holding-tank activation hold, 24-hour safety net (mocked clock) and LinkSpin alignment: unit + local copy (also runs in member)
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data)
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
# bash qa/run.sh sov-passes # pass tiers (Explorer/Champion/Sovereign/Legend): store unit checks + admin buys Explorer + Sovereign with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes)
# bash qa/run.sh nas # Network Ad Space billing: served-count trap, stopped-ad restart (no phantom delivery), the 1/N network rate + PassiveDrip partner visits (stubbed NAS, throwaway data)
# bash qa/run.sh login-queue # prepaid login-ad line: JSON store end to end + the MySQL path's lease/guard logic against a fake SQL layer (no server, throwaway data)
# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos)
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data)
# bash qa/run.sh convpixel # conversion pixel: lsclk click ids on /api/ads/click, signed push to a MOCK LinkSpin, own-click self flag, Campaigns > Conversion tracking + cost per goal, LinkSpin down (local copy, throwaway data)
# bash qa/run.sh fuel # Fuel Your Offers: refill notices, refuel streak, Refuel Kit, Engine Room (unit + two-copy tests, throwaway data)
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u
@@ -39,6 +43,12 @@ if [ "$MODE" = "public" ]; then
node qa/chatbot-sync.mjs || status=1
elif [ "$MODE" = "member" ]; then
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
node qa/tank-hold.mjs || status=1
node qa/walletnudge.test.cjs || status=1
elif [ "$MODE" = "walletnudge" ]; then
node qa/walletnudge.test.cjs || status=1
elif [ "$MODE" = "tankhold" ]; then
node qa/tank-hold.mjs || status=1
elif [ "$MODE" = "sponsorfollow" ]; then
node qa/sponsorfollow.test.cjs || status=1
node qa/sponsorfollow-e2e.mjs || status=1
@@ -52,11 +62,17 @@ elif [ "$MODE" = "gamepass" ]; then
elif [ "$MODE" = "sov-passes" ]; then
node qa/sov-passes-store.cjs || status=1
node qa/sov-passes-local.mjs || status=1
elif [ "$MODE" = "nas" ]; then
node qa/nas-served.mjs || status=1
node qa/nas-restart.mjs || status=1
node qa/nas-ratio.mjs || status=1
elif [ "$MODE" = "login-queue" ]; then
node qa/login-queue.cjs || status=1
node qa/login-queue-sql.cjs || status=1
elif [ "$MODE" = "convpixel" ]; then
node qa/convpixel.test.mjs || status=1
elif [ "$MODE" = "fuel" ]; then
for f in qa/refill.test.cjs qa/refuel*.test.cjs; do [ -f "$f" ] && { node "$f" || status=1; }; done
elif [ "$MODE" = "override" ]; then
node qa/override.test.cjs || status=1
elif [ "$MODE" = "gamepass-games" ]; then
+62 -33
View File
@@ -10,6 +10,9 @@
// fresh package purchase (faked locally with /api/dev/gamepass-purchase), and the card sends the member to Buy credits.
// 2026-10-22: + Sovereign / Legend: members refused while sovTiers is off, the admin preview lists all five, the admin buys Sovereign
// (real charge), a Legend waiting order is settled by a $250 package (a year), the token / partner player carry tier legend + tiers.
// 2026-10-25 (Marty): no admin-only tier UI on the member card. The ADMIN_EMAIL account gets the member view on /my (weekly only,
// hidden-tier buys refused there too); every tier test runs from Admin > Game Pass > Tier test and preview (/api/admin/gamepass/preview,
// test-buy, test-cancel, test-comp), always on the admin's own account. A holder of a tier sees it on the card like any member.
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
@@ -25,7 +28,7 @@ const B = 'http://127.0.0.1:' + PORT;
const SHOTS = process.env.SHOTS || 'D:/tmp/sov-passes'; fs.mkdirSync(SHOTS, { recursive: true });
const SOV = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
const ADMIN_PW = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com', MEMBER = 'qa-sov-member@example.com';
const SEED_ID = 9001, SEED_CREDITS = 1999 + 9999 + 500; // Explorer + Sovereign, then 500 left (short for a second Explorer)
const SEED_ID = 9001, SEED_CREDITS = 2000 + 10000 + 500; // Explorer + Sovereign, then 500 left (short for a second Explorer)
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-sovpasses-')); fs.mkdirSync(path.join(DATA, 'uploads'));
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const hide = page => page.evaluate(() => { document.querySelectorAll('.lgate,.iap-welcome,#onboardModal').forEach(m => m.hidden = true); });
@@ -74,8 +77,8 @@ try {
ok(up && /qa stub: position #9001/.test(srvLog), 'local copy up with the seeded position', '');
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10, gamePassEnabled: '1' } }, adminH);
const site = (await api('/api/admin/site', null, adminH)).j; const sc = (site && (site.site || site)) || {};
ok(sc.sovTiers === '0' && Number(sc.gamePassExplorerPriceCredits) === 1999 && Number(sc.gamePassChampionPriceCredits) === 3999 && Number(sc.gamePassExplorerDays) === 30 && sc.passTournamentTierSales === '0', 'defaults: sovTiers 0, Explorer 1999 / Champion 3999 credits, 30 days, passTournamentTierSales 0', JSON.stringify({ sovTiers: sc.sovTiers, e: sc.gamePassExplorerPriceCredits, c: sc.gamePassChampionPriceCredits }));
ok(Number(sc.gamePassSovereignPriceCredits) === 9999 && Number(sc.gamePassSovereignDays) === 30 && sc.gamePassSovereignEnabled === '1' && Number(sc.gamePassLegendPriceCredits) === 24999 && Number(sc.gamePassLegendDays) === 365 && sc.gamePassLegendEnabled === '1' && Number(sc.gamePassPriceCredits) === 500 && Number(sc.gamePassDays) === 7, 'defaults: Sovereign 9999 / 30 days, Legend 24999 / 365 days (kill switches 1), weekly 500 / 7 unchanged', JSON.stringify({ s: [sc.gamePassSovereignPriceCredits, sc.gamePassSovereignDays], l: [sc.gamePassLegendPriceCredits, sc.gamePassLegendDays] }));
ok(sc.sovTiers === '0' && Number(sc.gamePassExplorerPriceCredits) === 2000 && Number(sc.gamePassChampionPriceCredits) === 5000 && Number(sc.gamePassExplorerDays) === 30 && sc.passTournamentTierSales === '0', 'defaults: sovTiers 0, Explorer 2000 / Champion 5000 cents ($20 / $50, 2026-10-25), 30 days, passTournamentTierSales 0', JSON.stringify({ sovTiers: sc.sovTiers, e: sc.gamePassExplorerPriceCredits, c: sc.gamePassChampionPriceCredits }));
ok(Number(sc.gamePassSovereignPriceCredits) === 10000 && Number(sc.gamePassSovereignDays) === 30 && sc.gamePassSovereignEnabled === '1' && Number(sc.gamePassLegendPriceCredits) === 25000 && Number(sc.gamePassLegendDays) === 365 && sc.gamePassLegendEnabled === '1' && Number(sc.gamePassPriceCredits) === 500 && Number(sc.gamePassDays) === 7, 'defaults: Sovereign 10000 / 30 days, Legend 25000 / 365 days (kill switches 1), weekly 500 / 7 unchanged', JSON.stringify({ s: [sc.gamePassSovereignPriceCredits, sc.gamePassSovereignDays], l: [sc.gamePassLegendPriceCredits, sc.gamePassLegendDays] }));
const hA = await signIn(ADMIN_EMAIL, 'qaadmin'), hM = await signIn(MEMBER, 'qasovm');
// 1. a member with sovTiers off: weekly only, Explorer refused
@@ -91,32 +94,58 @@ try {
const txt = await page.textContent('#gpCard'); ok(!/Explorer|Champion|Sovereign|Legend/.test(txt) && errs.length === 0, 'member page: the weekly card as before, no Explorer/Champion/Sovereign/Legend text, no page errors', errs.join(' | '));
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '1-member-weekly-only.png') }); await ctx.close(); }
// 2. the admin: preview of all three, buys Explorer in the browser with the seeded purchased credits (the real charge)
// 2. the admin account on /my gets the MEMBER view (2026-10-25): weekly only, no preview note, hidden tiers refused on the member route
g = (await api('/api/my/gamepass', null, hA)).j;
ok(g.tierPreview === true && g.passes.map(x => x.tier).join() === 'weekly,explorer,champion,sovereign,legend' && g.passes.map(x => x.price).join() === '500,1999,3999,9999,24999', 'admin, sovTiers off: preview with all five tiers, 500 / 1999 / 3999 / 9999 / 24999', JSON.stringify(g.passes.map(x => [x.tier, x.price, x.open])));
{ const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my?from=shardsofvalor#passes');
await page.waitForSelector('#gpCard [data-gp-tier="explorer"]', { timeout: 15000 }); await sleep(600); await hide(page);
ok(g.passes && g.passes.length === 1 && g.passes[0].tier === 'weekly' && !g.tierPreview, 'admin on /my, sovTiers off: the member view, weekly only, no preview', JSON.stringify((g.passes || []).map(x => x.tier)));
r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hA);
ok(r.status === 400 && r.j.error === 'The Explorer pass is not open yet.', 'admin on the member route: Explorer refused like any member (tests moved to Admin > Game Pass)', JSON.stringify(r.j));
{ const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my#passes'); await page.waitForSelector('#gpCard:not([hidden]) #gpBuy', { timeout: 15000 }); await sleep(600); await hide(page);
const txt = await page.textContent('#gpCard');
ok(/never make you stronger than players who earn their gear/.test(txt) && /main story of Shards of Valor is free/.test(txt) && /Admin preview/.test(txt) && !/\u2014/.test(txt), 'tier card copy: never stronger, main story free, admin preview note, no em dashes', '');
ok(/#games/.test(page.url()), 'the Shards of Valor link (#passes) lands on the pass card, not the Buy pane', page.url());
ok(/Sovereign/.test(txt) && /Necromancer/.test(txt) && /Legend/.test(txt) && /\$249\.99/.test(txt) && /for 1 year/.test(txt) && /Archer/.test(txt) && /Druid/.test(txt) && /level cap 30/.test(txt) && /\$19\.99/.test(txt), 'admin preview card lists Sovereign and Legend ($249.99 for 1 year) with what each includes', '');
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '2-admin-preview-all-tiers.png') });
await page.click('#gpCard [data-gp-tier="explorer"]'); await page.waitForSelector('#dlgOk', { timeout: 5000 });
await page.screenshot({ path: path.join(SHOTS, '3-admin-confirm-explorer.png') });
ok(!/Explorer|Champion|Sovereign|Legend|Admin preview/.test(txt) && errs.length === 0, 'admin /my Games card: the weekly card a member sees, no tier boxes, no admin preview note', errs.join(' | '));
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '2-admin-member-card-weekly-only.png') }); await ctx.close(); }
// the admin portal preview: all five tiers with what each includes, every one open to the admin's own account
g = (await api('/api/admin/gamepass/preview', null, adminH)).j;
ok(g.test === true && g.email === ADMIN_EMAIL && g.tierPreview === true && g.passes.map(x => x.tier).join() === 'weekly,explorer,champion,sovereign,legend' && g.passes.map(x => x.price).join() === '500,2000,5000,10000,25000' && g.passes.map(x => x.package).join() === '5,20,50,100,250' && g.passes.every(x => x.usd === x.package) && g.passes.every(x => x.open) && g.passes.filter(x => x.tier !== 'weekly').every(x => x.sale === false), 'GET /api/admin/gamepass/preview: all five tiers (500 / 2000 / 5000 / 10000 / 25000, each price = its package), open to the admin, none on sale', JSON.stringify(g.passes.map(x => [x.tier, x.price, x.open, x.sale])));
ok((await api('/api/admin/gamepass/preview', null, hM)).status === 401 && (await api('/api/admin/gamepass/test-buy', { data: { tier: 'explorer' } }, hM)).status === 401, 'tier test endpoints refuse a member session (401)', '');
// test cancel + test comp + end, on the admin's own account
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'champion' } }, adminH);
ok(r.status === 200 && r.j.needPay && r.j.tier === 'champion' && r.j.email === ADMIN_EMAIL && r.j.package === 50, 'test-buy Champion: a waiting order for a $50 package on the admin account', JSON.stringify(r.j));
r = await api('/api/admin/gamepass/test-cancel', { data: { tier: 'champion' } }, adminH);
g = (await api('/api/admin/gamepass/preview', null, adminH)).j;
ok(r.j.ok && r.j.order && !g.passes.find(x => x.tier === 'champion').waiting, 'test-cancel drops the Champion test order', JSON.stringify(r.j));
r = await api('/api/admin/gamepass/test-comp', { data: { tier: 'champion' } }, adminH);
ok(r.j.ok && r.j.tier === 'champion' && r.j.email === ADMIN_EMAIL && r.j.until > Date.now(), 'test-comp Champion starts one period on the admin account at once', JSON.stringify(r.j));
r = await api('/api/admin/gamepass/revoke', { data: { email: ADMIN_EMAIL, tier: 'champion', why: 'admin tier test' } }, adminH);
g = (await api('/api/my/gamepass', null, hA)).j;
ok(r.j.ok && !g.active && g.passes.length === 1, 'ending the test Champion puts the admin card back to the weekly member view', JSON.stringify({ a: g.active, rows: g.passes.map(x => x.tier) }));
{ const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } }); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e)));
await page.goto(B + '/admin', { waitUntil: 'networkidle' });
await page.fill('#adEmail', ADMIN_EMAIL); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await sleep(1200);
const nav = await page.$('.bo-menu [data-pane="gamepass"]'); if (nav) { await nav.click(); await page.waitForSelector('#gpTest [data-gpt-buy="explorer"]', { timeout: 10000 }).catch(() => {}); }
let txt = await page.textContent('#gpTest').catch(() => '');
ok(/Test \/ preview, admin only/.test(txt) && /hidden from members/.test(txt) && /Sovereign/.test(txt) && /Necromancer/.test(txt) && /Legend/.test(txt) && /\$250 /.test(txt) && /for 1 year/.test(txt) && /Archer/.test(txt) && /Druid/.test(txt) && /level cap 30/.test(txt) && /\$20 /.test(txt) && !/\.99/.test(txt) && /Shards of Valor > Passes/.test(txt) && !/\u2014/.test(txt) && errs.length === 0, 'Admin > Game Pass > Tier test and preview: labelled test/preview, all five tiers with what each includes, no em dashes', errs.join(' | ') || (nav ? '' : 'admin nav not found'));
await page.locator('#gpTestCard').scrollIntoViewIfNeeded(); await sleep(300);
await page.locator('#gpTestCard').screenshot({ path: path.join(SHOTS, '3-admin-tier-test-panel.png') });
await page.click('#gpTest [data-gpt-buy="explorer"]'); await page.waitForSelector('#dlgOk', { timeout: 5000 });
await page.screenshot({ path: path.join(SHOTS, '3b-admin-confirm-test-explorer.png') });
await page.click('#dlgOk');
await page.waitForFunction(() => /#buy/.test(location.hash) || !!document.querySelector('.pane.on#pane-buy, [data-pane="buy"].on'), null, { timeout: 10000 }).catch(() => {});
await sleep(800);
ok(errs.length === 0, 'Get Explorer: no page errors, the member is sent to buy a package', page.url() + ' ' + errs.join(' | '));
await page.screenshot({ path: path.join(SHOTS, '4-admin-sent-to-buy.png') });
let g1 = (await api('/api/my/gamepass', null, hA)).j; const ex1 = g1.passes.find(x => x.tier === 'explorer');
ok(!g1.active && ex1 && ex1.waiting === true && !ex1.active, 'the click opened a waiting Explorer order; nothing active yet', JSON.stringify(ex1));
ok(!/gamepass bought with credits/.test(srvLog), 'no credit charge: the seeded purchased credits were not spent on the pass', '');
const dv0 = (await api('/api/dev/gamepass-purchase', { data: { cents: 2000, email: ADMIN_EMAIL } })).j;
ok(dv0 && dv0.order && dv0.order.tier === 'explorer', 'a fresh $20 package fulfils the Explorer order', JSON.stringify(dv0));
await page.goto(B + '/my#passes'); await page.waitForFunction(() => /Explorer active/.test((document.getElementById('gpCard') || {}).textContent || ''), null, { timeout: 15000 }).catch(() => {});
await page.waitForFunction(() => /test order waiting for a \$20 package/.test((document.getElementById('gpTest') || {}).textContent || ''), null, { timeout: 10000 }).catch(() => {});
txt = await page.textContent('#gpTest').catch(() => '');
ok(/test order waiting for a \$20 package/.test(txt) && errs.length === 0, 'Test buy Explorer from the admin panel: the card shows the waiting test order', errs.join(' | '));
await page.locator('#gpTestCard').screenshot({ path: path.join(SHOTS, '4-admin-test-order-waiting.png') }); await ctx.close(); }
let g1 = (await api('/api/admin/gamepass/preview', null, adminH)).j; const ex1 = g1.passes.find(x => x.tier === 'explorer');
ok(!g1.active && ex1 && ex1.waiting === true && !ex1.active, 'the click opened a waiting Explorer order; nothing active yet', JSON.stringify(ex1));
ok(!/gamepass bought with credits/.test(srvLog), 'no credit charge: the seeded purchased credits were not spent on the pass', '');
const dv0 = (await api('/api/dev/gamepass-purchase', { data: { cents: 2000, email: ADMIN_EMAIL } })).j;
ok(dv0 && dv0.order && dv0.order.tier === 'explorer', 'a fresh $20 package fulfils the Explorer test order', JSON.stringify(dv0));
// a HOLDER sees the tier on the member card the way any member holding it would (no preview note, nothing they cannot buy listed)
{ const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my?from=shardsofvalor#passes');
await page.waitForFunction(() => /Explorer active/.test((document.getElementById('gpCard') || {}).textContent || ''), null, { timeout: 15000 }).catch(() => {});
await sleep(600); await hide(page);
const after = await page.textContent('#gpCard');
ok(/Explorer active/.test(after) && errs.length === 0, 'after the package the card shows Explorer active (Central date)', errs.join(' | '));
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '5-admin-explorer-active.png') }); await ctx.close(); }
ok(/#games/.test(page.url()), 'the Shards of Valor link (#passes) lands on the pass card, not the Buy pane', page.url());
ok(/Explorer active/.test(after) && /never better than gear players can earn/.test(after) && /main story of Shards of Valor is free/.test(after) && !/Admin preview|Champion|Sovereign|Legend/.test(after) && !/\u2014/.test(after) && errs.length === 0, 'holder card: Explorer active, weekly + Explorer only, no admin preview, no em dashes', errs.join(' | '));
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '5-admin-explorer-active-holder-card.png') }); await ctx.close(); }
g = (await api('/api/my/gamepass', null, hA)).j;
const ex = g.passes.find(x => x.tier === 'explorer');
ok(g.active && g.tier === 'explorer' && ex.active && Math.abs(ex.until - (Date.now() + 30 * 86400000)) < 120000, 'GET /api/my/gamepass: tier explorer, 30 days', JSON.stringify({ tier: g.tier, until: ex && new Date(ex.until).toISOString() }));
@@ -135,20 +164,20 @@ try {
const gr = await grant({ memberId: 0, email: ADMIN_EMAIL, game: 'shardsofvalor', kind: 'daily', pol: 0.2, ref: 'qa:1' });
ok(gr.pass === true && gr.allowed === 0.2, 'polgrant: pass true (a boolean) for the Explorer holder', JSON.stringify(gr));
// 3b. Sovereign (9999 credits, 30 days) and the yearly Legend (24999, 365 days), 2026-10-22: the admin buys Sovereign through the
// 3b. Sovereign (10000 cents = $100, 30 days) and the yearly Legend (25000 = $250, 365 days), 2026-10-22: the admin buys Sovereign through the
// real charge, then is short for Legend (waiting order, $250 package) and for a second Explorer; a $250 package settles Legend.
r = await api('/api/my/gamepass/buy', { data: { tier: 'sovereign' } }, hA);
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'sovereign' } }, adminH);
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'sovereign' && r.j.package === 100, 'admin Sovereign (sovTiers off, testing): a waiting order for a $100 package, credits untouched', JSON.stringify(r.j));
let dvS = (await api('/api/dev/gamepass-purchase', { data: { cents: 10000, email: ADMIN_EMAIL } })).j;
ok(dvS && dvS.order && dvS.order.tier === 'sovereign' && Math.abs(dvS.order.until - (Date.now() + 30 * 86400000)) < 120000, 'a fresh $100 package fulfils Sovereign: 30 days', JSON.stringify(dvS));
ok(!/gamepass bought with credits/.test(srvLog), 'still no credit charge anywhere', '');
r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hA);
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'explorer' } }, adminH);
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'explorer' && /package of \$20 or more/.test(r.j.message), 'a second Explorer -> waiting order, "package of $20 or more"', JSON.stringify({ needPay: r.j.needPay, payUrl: r.j.payUrl, msg: r.j.message }));
r = await api('/api/my/gamepass/buy', { data: { tier: 'legend' } }, hA);
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'legend' && r.j.price === 24999 && r.j.payUrl === '/my?from=gamepass&tier=legend#buy' && /package of \$250 or more/.test(r.j.message), 'Legend: waiting order, "package of $250 or more", payUrl with tier', JSON.stringify({ needPay: r.j.needPay, payUrl: r.j.payUrl, msg: r.j.message }));
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'legend' } }, adminH);
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'legend' && r.j.price === 25000 && r.j.payUrl === '/my?from=gamepass&tier=legend#buy' && /package of \$250 or more/.test(r.j.message), 'Legend: waiting order, "package of $250 or more", payUrl with tier', JSON.stringify({ needPay: r.j.needPay, payUrl: r.j.payUrl, msg: r.j.message }));
let dv = (await api('/api/dev/gamepass-purchase', { data: { cents: 10000, email: ADMIN_EMAIL } })).j;
ok(dv && dv.order && dv.order.tier === 'explorer' && dv.order.until === ex.until + 30 * 86400000, 'a $100 package fulfils the waiting Explorer (extends it from its end), never Legend', JSON.stringify(dv));
g = (await api('/api/my/gamepass', null, hA)).j;
g = (await api('/api/admin/gamepass/preview', null, adminH)).j;
ok(!g.passes.find(x => x.tier === 'legend').active && g.passes.find(x => x.tier === 'legend').waiting, 'Legend still waiting after a $100 package', JSON.stringify(g.passes.find(x => x.tier === 'legend')));
dv = (await api('/api/dev/gamepass-purchase', { data: { cents: 25000, email: ADMIN_EMAIL } })).j;
ok(dv && dv.order && dv.order.tier === 'legend' && Math.abs(dv.order.until - (Date.now() + 365 * 86400000)) < 120000, 'a $250 package fulfils the Legend order: a year', JSON.stringify(dv));
@@ -164,8 +193,8 @@ try {
// 4. Admin > Game Pass: the tier table
const st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st.tiers && st.tiers.explorer.active === 0 && st.tiers.explorer.soldTotal === 2 && st.tiers.explorer.usdTotal === 39.98 && st.tiers.explorer.waitingOrders === 0 && st.tierSales === false, 'admin stats: Explorer 2 sold ($39.98: credits + the $100 package order), not counted active (the account is at Legend); sale switch off', JSON.stringify(st.tiers.explorer));
ok(st.tiers.sovereign && st.tiers.sovereign.active === 0 && st.tiers.sovereign.soldTotal === 1 && st.tiers.sovereign.usdTotal === 99.99 && st.tiers.legend.active === 1 && st.tiers.legend.soldTotal === 1 && st.tiers.legend.usdTotal === 249.99 && st.tiers.legend.waitingOrders === 0 && st.settings.tiers.legend.days === 365 && st.settings.tiers.sovereign.sale === false, 'admin stats: Sovereign 1 sold ($99.99), Legend 1 active + 1 sold ($249.99), not on sale', JSON.stringify({ s: st.tiers.sovereign, l: st.tiers.legend }));
ok(st.tiers && st.tiers.explorer.active === 0 && st.tiers.explorer.soldTotal === 2 && st.tiers.explorer.usdTotal === 40 && st.tiers.explorer.waitingOrders === 0 && st.tierSales === false, 'admin stats: Explorer 2 sold ($40: credits + the $100 package order), not counted active (the account is at Legend); sale switch off', JSON.stringify(st.tiers.explorer));
ok(st.tiers.sovereign && st.tiers.sovereign.active === 0 && st.tiers.sovereign.soldTotal === 1 && st.tiers.sovereign.usdTotal === 100 && st.tiers.legend.active === 1 && st.tiers.legend.soldTotal === 1 && st.tiers.legend.usdTotal === 250 && st.tiers.legend.waitingOrders === 0 && st.settings.tiers.legend.days === 365 && st.settings.tiers.sovereign.sale === false, 'admin stats: Sovereign 1 sold ($100), Legend 1 active + 1 sold ($250), not on sale', JSON.stringify({ s: st.tiers.sovereign, l: st.tiers.legend }));
{ const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } }); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e)));
await page.goto(B + '/admin', { waitUntil: 'networkidle' });
await page.fill('#adEmail', ADMIN_EMAIL); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await sleep(1200);
+21 -20
View File
@@ -4,7 +4,7 @@
// extend from max(now, until), side-by-side expiry, highest active tier wins, the sovTiers switch (off refuses, admin may buy),
// waiting orders per tier fulfilled by a big-enough package (each tx once, highest price first), the same caps for every tier
// (no extra POL), comp and revoke, admin stats per tier (each account once at its top tier, Central week/month). Exit 1 on failure.
// 2026-10-22: section 10 adds Sovereign (9999 / 30 days) and the yearly Legend (24999 / 365 days): rank, off-switch refusal,
// 2026-10-22: section 10 adds Sovereign (10000 / 30 days) and the yearly Legend (25000 / 365 days; prices = packages since 2026-10-25): rank, off-switch refusal,
// buy, short -> waiting order ($100 / $250 package), extend from max(now, until), kill switches, comp/revoke, flag payload, stats.
'use strict';
const fs = require('fs'); const os = require('os'); const path = require('path');
@@ -53,9 +53,10 @@ async function buyX(email, payer, now, tier, opts) {
ok(!passes.get('a@x.com'), 'a refused buy writes nothing', '');
let v = gp.view('a@x.com', T0);
ok(v.passes.length === 1 && v.passes[0].tier === 'weekly' && v.show === true && v.tierPreview === false, 'sovTiers off: a member sees only the weekly pass', JSON.stringify(v.passes.map(x => x.tier)));
v = gp.view('admin@x.com', T0, { admin: true });
ok(v.passes.map(x => x.tier).join() === 'weekly,explorer,champion,sovereign,legend' && v.tierPreview === true && v.passes.slice(1).every(x => x.open === true) && v.passes.map(x => x.price).join() === '500,1999,3999,9999,24999' && v.passes.map(x => x.days).join() === '7,30,30,30,365' && v.passes.map(x => x.package).join() === '5,20,50,100,250', 'sovTiers off: the admin sees all five (preview), prices 500 / 1999 / 3999 / 9999 / 24999, days 7 / 30 / 30 / 30 / 365, packages $5 / $20 / $50 / $100 / $250', JSON.stringify(v.passes));
r = await buyX('admin@x.com', paid, T0, 'explorer', { admin: true });
v = gp.view('admin@x.com', T0); ok(v.passes.length === 1 && !v.tierPreview, 'the member view (GET /api/my/gamepass) is the same for the admin account: weekly only (2026-10-25)', JSON.stringify(v.passes.map(x => x.tier)));
v = gp.view('admin@x.com', T0, { preview: true }); // Admin > Game Pass > Tier test and preview
ok(v.passes.map(x => x.tier).join() === 'weekly,explorer,champion,sovereign,legend' && v.tierPreview === true && v.passes.slice(1).every(x => x.open === true) && v.passes.map(x => x.price).join() === '500,2000,5000,10000,25000' && v.passes.map(x => x.days).join() === '7,30,30,30,365' && v.passes.map(x => x.package).join() === '5,20,50,100,250', 'sovTiers off: the admin sees all five (preview), prices 500 / 2000 / 5000 / 10000 / 25000, days 7 / 30 / 30 / 30 / 365, packages $5 / $20 / $50 / $100 / $250', JSON.stringify(v.passes));
r = await buyX('admin@x.com', paid, T0, 'explorer', { preview: true });
ok(r.ok && r.tier === 'explorer' && r.until === T0 + 30 * DAY && r.days === 30, 'sovTiers off: the admin can buy Explorer (testing)', JSON.stringify(r));
r = await buyX('a@x.com', paid, T0); // tier missing = weekly
ok(r.ok && r.tier === 'weekly' && r.until === T0 + 7 * DAY && r.days === 7, 'tier missing = weekly: 500 credits, 7 days, as before', JSON.stringify(r));
@@ -68,15 +69,15 @@ async function buyX(email, payer, now, tier, opts) {
// 3. on: each tier extends only itself; buying again extends from max(now, until)
charged = null; r = await buyX('b@x.com', async (price, label) => { charged = { price, label }; return { ok: true }; }, T0, 'explorer');
ok(r.ok && r.until === T0 + 30 * DAY && charged.price === 1999 && charged.label === 'Explorer pass (30 days)', 'sovTiers on: Explorer charges 1999 credits, 30 days', JSON.stringify(charged));
ok(r.ok && r.until === T0 + 30 * DAY && charged.price === 2000 && charged.label === 'Explorer pass (30 days)', 'sovTiers on: Explorer charges 2000 credits, 30 days', JSON.stringify(charged));
let rec = passes.get('b@x.com');
ok(rec.tiers.explorer.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.champion && rec.until === 0 && rec.bought[0].tier === 'explorer' && rec.bought[0].usd === 19.99, 'only the Explorer tier moved; legacy until (weekly) stays 0; bought row has tier + $19.99', JSON.stringify(rec));
ok(rec.tiers.explorer.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.champion && rec.until === 0 && rec.bought[0].tier === 'explorer' && rec.bought[0].usd === 20, 'only the Explorer tier moved; legacy until (weekly) stays 0; bought row has tier + $20', JSON.stringify(rec));
r = await buyX('b@x.com', paid, T0 + 10 * DAY, 'explorer');
ok(r.until === T0 + 60 * DAY, 'Explorer again while active: extends from its until (+30 days, nothing lost)', new Date(r.until).toISOString());
r = await buyX('c@x.com', paid, T0, 'champion'); ok(r.ok && r.until === T0 + 30 * DAY, 'Champion: 30 days', '');
r = await buyX('c@x.com', paid, T0 + 45 * DAY, 'champion');
ok(r.until === T0 + 75 * DAY, 'Champion again after it ended: extends from now', new Date(r.until).toISOString());
charged = null; await buyX('c2@x.com', async (price) => { charged = price; return { ok: true }; }, T0, 'champion'); ok(charged === 3999, 'Champion charges 3999 credits', String(charged));
charged = null; await buyX('c2@x.com', async (price) => { charged = price; return { ok: true }; }, T0, 'champion'); ok(charged === 5000, 'Champion charges 5000 credits', String(charged));
// 4. side by side: Champion over Explorer, then Explorer shows through; weekly underneath
await buyX('d@x.com', paid, T0, 'weekly'); // weekly to T0+7
@@ -103,7 +104,7 @@ async function buyX(email, payer, now, tier, opts) {
const ordE = r.order;
r = await buyX('p@x.com', short, T0, 'explorer'); ok(r.order === ordE, 'same tier again reuses its waiting order', '');
r = await buyX('p@x.com', short, T0, 'champion'); const ordC = r.order;
ok(r.needPay && r.order !== ordE && r.package === 50 && /package of \$50 or more/.test(r.message), 'Champion short: its own waiting order; copy names the $50 package (there is no $40 one)', r.message);
ok(r.needPay && r.order !== ordE && r.package === 50 && /package of \$50 or more/.test(r.message), 'Champion short: its own waiting order; copy names the $50 package (exactly the price since 2026-10-25)', r.message);
r = await buyX('p@x.com', short, T0, 'weekly');
ok(r.payUrl === '/my?from=gamepass#buy' && /package of \$5 or more/.test(r.message), 'weekly short: payUrl and copy exactly as before', r.payUrl);
let ev = await gp.onEvent({ type: 'Purchase', priceCents: 500, tx: '0xa1', ts: T0 + 60000, devEmail: 'p@x.com' });
@@ -147,7 +148,7 @@ async function buyX(email, payer, now, tier, opts) {
await buyX('s5@x.com', short, NOW, 'champion');
const st = gp.adminStats(NOW); const S = st.tiers;
ok(S.weekly.active === 1 && S.explorer.active === 2 && S.champion.active === 1, 'active counts each account once at its top tier (s1 = explorer, not weekly)', JSON.stringify({ w: S.weekly.active, e: S.explorer.active, c: S.champion.active }));
ok(S.weekly.soldWeek === 2 && S.explorer.soldWeek === 0 && S.explorer.soldMonth === 1 && S.champion.soldWeek === 1 && S.champion.soldMonth === 1 && S.champion.soldTotal === 2 && S.champion.usdTotal === 79.98, 'Central week (from Mon 00:00) and month (from the 1st 00:00) boundaries', JSON.stringify({ w: [S.weekly.soldWeek, S.weekly.soldMonth], e: [S.explorer.soldWeek, S.explorer.soldMonth], c: [S.champion.soldWeek, S.champion.soldMonth, S.champion.soldTotal, S.champion.usdTotal] }));
ok(S.weekly.soldWeek === 2 && S.explorer.soldWeek === 0 && S.explorer.soldMonth === 1 && S.champion.soldWeek === 1 && S.champion.soldMonth === 1 && S.champion.soldTotal === 2 && S.champion.usdTotal === 100, 'Central week (from Mon 00:00) and month (from the 1st 00:00) boundaries', JSON.stringify({ w: [S.weekly.soldWeek, S.weekly.soldMonth], e: [S.explorer.soldWeek, S.explorer.soldMonth], c: [S.champion.soldWeek, S.champion.soldMonth, S.champion.soldTotal, S.champion.usdTotal] }));
ok(S.champion.renewals30d === 1 && S.weekly.renewals30d === 0, 'renewals30d: a second Champion purchase by a Champion holder', String(S.champion.renewals30d));
ok(S.weekly.expiring7d === 2 && S.explorer.comped === 1 && S.champion.waitingOrders === 1, 'expiring7d (weekly passes ending in 7 Central days), comped, waiting orders per tier', JSON.stringify({ exp: S.weekly.expiring7d, comped: S.explorer.comped, wait: S.champion.waitingOrders }));
ok(st.passes.active === 4 && st.passes.soldTotal === 5 && st.passes.comped === 1 && st.passes.waitingOrders === 1, 'the existing all-tier passes block still adds up', JSON.stringify(st.passes));
@@ -157,13 +158,13 @@ async function buyX(email, payer, now, tier, opts) {
ok(rows.sales === 2 && rows.salesUsd === 10, 'passTournamentTierSales off: only the 2 weekly sales ($10) feed the pool', JSON.stringify({ sales: rows.sales, usd: rows.salesUsd }));
SC.passTournamentTierSales = '1';
const rows2 = await gp.runTournament(Date.parse('2026-11-03T18:00:00Z'), { force: true });
ok(rows2.sales === 3 && rows2.salesUsd === 49.99, 'passTournamentTierSales on: the Champion renewal ($39.99) is added', JSON.stringify({ sales: rows2.sales, usd: rows2.salesUsd }));
// 10. Sovereign ($99.99 / 30 days) and Legend ($249.99 / 365 days), 2026-10-22 (Dallas's structure)
ok(rows2.sales === 3 && rows2.salesUsd === 60, 'passTournamentTierSales on: the Champion renewal ($50) is added', JSON.stringify({ sales: rows2.sales, usd: rows2.salesUsd }));
// 10. Sovereign ($100 / 30 days) and Legend ($250 / 365 days), 2026-10-22 (Dallas's structure); prices = packages since 2026-10-25
for (const k of [...passes.keys()]) passes.delete(k); for (const k of [...orders.keys()]) orders.delete(k);
delete SC.passTournamentTierSales; SC.sovTiers = '0';
ok(gp.TIERS.join() === 'weekly,explorer,champion,sovereign,legend' && gp.TIER_NAMES.sovereign === 'Sovereign' && gp.TIER_NAMES.legend === 'Legend', 'rank: weekly < explorer < champion < sovereign < legend; names from the one table', gp.TIERS.join());
const C0 = gp.cfg().tiers;
ok(C0.weekly.price === 500 && C0.weekly.days === 7 && C0.explorer.price === 1999 && C0.champion.price === 3999 && C0.sovereign.price === 9999 && C0.sovereign.days === 30 && C0.legend.price === 24999 && C0.legend.days === 365 && !C0.sovereign.sale && !C0.legend.sale && C0.weekly.sale, 'defaults: weekly 500/7 (unchanged), Sovereign 9999/30, Legend 24999/365; sovTiers off = not on sale, weekly on sale', JSON.stringify(C0));
ok(C0.weekly.price === 500 && C0.weekly.days === 7 && C0.explorer.price === 2000 && C0.champion.price === 5000 && C0.sovereign.price === 10000 && C0.sovereign.days === 30 && C0.legend.price === 25000 && C0.legend.days === 365 && !C0.sovereign.sale && !C0.legend.sale && C0.weekly.sale, 'defaults: weekly 500/7 (unchanged), Sovereign 10000/30, Legend 25000/365; sovTiers off = not on sale, weekly on sale', JSON.stringify(C0));
// off switch: members refused, nothing written, nothing charged; the weekly pass still sells
charged = null; const spy = async (price, label) => { charged = { price, label }; return { ok: true }; };
r = await buyX('m@x.com', spy, T0, 'sovereign'); ok(r.error === 'The Sovereign pass is not open yet.' && !charged, 'sovTiers off: Sovereign refused for a member, nothing charged', JSON.stringify(r));
@@ -172,16 +173,16 @@ async function buyX(email, payer, now, tier, opts) {
ok(!passes.get('m@x.com'), 'refused Sovereign/Legend buys write nothing', '');
v = gp.view('m@x.com', T0); ok(v.passes.map(x => x.tier).join() === 'weekly' && !v.tierPreview, 'sovTiers off: the member still sees only the weekly pass', JSON.stringify(v.passes.map(x => x.tier)));
charged = null; r = await buyX('m@x.com', spy, T0); ok(r.ok && r.tier === 'weekly' && charged.price === 500 && charged.label === 'Game Pass (7 days)' && r.until === T0 + 7 * DAY, 'sovTiers off: the weekly Game Pass sells exactly as before', JSON.stringify(charged));
charged = null; r = await buyX('adm@x.com', spy, T0, 'legend', { admin: true });
ok(r.ok && r.tier === 'legend' && r.days === 365 && r.until === T0 + 365 * DAY && charged.price === 24999 && charged.label === 'Legend pass (365 days)', 'sovTiers off: the admin can buy Legend (testing): 24999 credits, 365 days', JSON.stringify({ r, charged }));
charged = null; r = await buyX('adm@x.com', spy, T0, 'legend', { preview: true });
ok(r.ok && r.tier === 'legend' && r.days === 365 && r.until === T0 + 365 * DAY && charged.price === 25000 && charged.label === 'Legend pass (365 days)', 'sovTiers off: the admin can buy Legend (testing): 25000 credits, 365 days', JSON.stringify({ r, charged }));
SC.sovTiers = '1';
// buy with enough purchased credits
charged = null; r = await buyX('sv@x.com', spy, T0, 'sovereign');
ok(r.ok && r.tier === 'sovereign' && r.days === 30 && r.until === T0 + 30 * DAY && charged.price === 9999 && charged.label === 'Sovereign pass (30 days)', 'sovTiers on: Sovereign charges 9999 credits, 30 days', JSON.stringify(charged));
ok(r.ok && r.tier === 'sovereign' && r.days === 30 && r.until === T0 + 30 * DAY && charged.price === 10000 && charged.label === 'Sovereign pass (30 days)', 'sovTiers on: Sovereign charges 10000 credits, 30 days', JSON.stringify(charged));
rec = passes.get('sv@x.com');
ok(rec.tiers.sovereign.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.legend && rec.until === 0 && rec.bought[0].tier === 'sovereign' && rec.bought[0].usd === 99.99 && rec.bought[0].cents === 9999 && rec.bought[0].via === 'package', 'only the Sovereign tier moved; bought row has tier, $99.99, a 9999-cent package', JSON.stringify(rec));
ok(rec.tiers.sovereign.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.legend && rec.until === 0 && rec.bought[0].tier === 'sovereign' && rec.bought[0].usd === 100 && rec.bought[0].cents === 10000 && rec.bought[0].via === 'package', 'only the Sovereign tier moved; bought row has tier, $100, a 10000-cent package', JSON.stringify(rec));
charged = null; r = await buyX('lg@x.com', spy, T0, 'legend');
ok(r.ok && r.until === T0 + 365 * DAY && charged.price === 24999 && passes.get('lg@x.com').bought[0].usd === 249.99, 'sovTiers on: Legend charges 24999 credits, a YEAR (365 days), $249.99 row', JSON.stringify(charged));
ok(r.ok && r.until === T0 + 365 * DAY && charged.price === 25000 && passes.get('lg@x.com').bought[0].usd === 250, 'sovTiers on: Legend charges 25000 credits, a YEAR (365 days), $250 row', JSON.stringify(charged));
// extend: from max(now, until)
r = await buyX('lg@x.com', paid, T0 + 100 * DAY, 'legend'); ok(r.until === T0 + 730 * DAY, 'Legend again while active: +365 days from its end (nothing lost)', new Date(r.until).toISOString());
r = await buyX('sv@x.com', paid, T0 + 10 * DAY, 'sovereign'); ok(r.until === T0 + 60 * DAY, 'Sovereign again while active: +30 days from its end', new Date(r.until).toISOString());
@@ -202,7 +203,7 @@ async function buyX(email, payer, now, tier, opts) {
ok(gs.allowed === 1.5 && gs.pass === true, 'polgrant: a Legend holder is capped at 1.50 on daily play, pass: true (a boolean)', JSON.stringify(gs));
// waiting orders: a $50 package does not cover Sovereign, $100 does; $100 does not cover Legend, $250 does
r = await buyX('wo@x.com', short, T0, 'sovereign');
ok(r.needPay && r.tier === 'sovereign' && r.payUrl === '/my?from=gamepass&tier=sovereign#buy' && r.package === 100 && /package of \$100 or more/.test(r.message) && r.price === 9999, 'Sovereign short: waiting order, payUrl with tier, "$100 package"', r.message);
ok(r.needPay && r.tier === 'sovereign' && r.payUrl === '/my?from=gamepass&tier=sovereign#buy' && r.package === 100 && /package of \$100 or more/.test(r.message) && r.price === 10000, 'Sovereign short: waiting order, payUrl with tier, "$100 package"', r.message);
const ordS = r.order;
r = await buyX('wo@x.com', short, T0, 'legend'); const ordL = r.order;
ok(r.needPay && r.order !== ordS && r.package === 250 && /package of \$250 or more/.test(r.message) && r.payUrl === '/my?from=gamepass&tier=legend#buy', 'Legend short: its own waiting order, "$250 package"', r.message);
@@ -241,14 +242,14 @@ async function buyX(email, payer, now, tier, opts) {
const st2 = gp.adminStats(T0 + DAY); const S2 = st2.tiers;
ok(Object.keys(S2).join() === 'weekly,explorer,champion,sovereign,legend' && S2.sovereign.name === 'Sovereign' && S2.legend.name === 'Legend', 'admin stats carry all five tiers by name', Object.keys(S2).join());
ok(S2.legend.active >= 3 && S2.legend.comped === 1 && S2.sovereign.comped === 1 && S2.legend.soldTotal >= 4 && S2.sovereign.soldTotal >= 4, 'admin stats: Legend/Sovereign active, sold and comped counted', JSON.stringify({ l: S2.legend, s: S2.sovereign }));
ok(st2.settings.tiers.legend.days === 365 && st2.settings.tiers.sovereign.price === 9999, 'admin settings block shows Legend 365 days, Sovereign 9999', '');
ok(st2.settings.tiers.legend.days === 365 && st2.settings.tiers.sovereign.price === 10000, 'admin settings block shows Legend 365 days, Sovereign 10000', '');
// tournament: Legend/Sovereign sales stay out of the pool unless passTournamentTierSales
for (const k of [...passes.keys()]) passes.delete(k);
const wkT = Date.parse('2026-11-10T18:00:00Z');
await buyX('t1@x.com', paid, wkT, 'weekly'); await buyX('t2@x.com', paid, wkT, 'legend'); await buyX('t3@x.com', paid, wkT, 'sovereign');
let tr = await gp.runTournament(wkT, { force: true }); ok(tr.sales === 1 && tr.salesUsd === 5, 'passTournamentTierSales default off: Sovereign/Legend sales do not feed the pool', JSON.stringify({ s: tr.sales, u: tr.salesUsd }));
SC.passTournamentTierSales = '1';
tr = await gp.runTournament(wkT, { force: true }); ok(tr.sales === 3 && tr.salesUsd === 354.98, 'passTournamentTierSales on: Legend ($249.99) and Sovereign ($99.99) are added', JSON.stringify({ s: tr.sales, u: tr.salesUsd }));
tr = await gp.runTournament(wkT, { force: true }); ok(tr.sales === 3 && tr.salesUsd === 355, 'passTournamentTierSales on: Legend ($250) and Sovereign ($100) are added', JSON.stringify({ s: tr.sales, u: tr.salesUsd }));
delete SC.passTournamentTierSales;
try { fs.rmSync(dataDir, { recursive: true, force: true }); } catch (e) {}
+368
View File
@@ -0,0 +1,368 @@
// Holding-tank activation hold + 24-hour safety net + network alignment (2026-10-27).
// node qa/tank-hold.mjs (or: bash qa/run.sh tankhold; also part of `bash qa/run.sh member`)
// Part A, no server: tank.js with in-memory accounts, a fake chain and a MOCKED CLOCK (tank.setClock):
// ready clock starts at first sight of a linked wallet, the hold, alignment to a LinkSpin sponsor (and the refusals:
// released-from sponsor, unclaimed shell, loop), the safety net at 24 h (rotation order, cap, 7-day sign-in, company
// excluded, no-payout chain skipped, own-downline skipped), nobody eligible = keep holding + one admin alert.
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, devCode sign-in, LS_URL pointed at a dead local port so nothing
// reaches LinkSpin): a tank account links a wallet -> /api/me + /api/sponsor answer tankHold with no fallback sponsor,
// the Wallet tab hides Activate payouts and shows the hold text, the Getting started card has no activate button,
// Admin tank shows the ready badge; a member who joined through a link is never held; a LinkSpin row naming a sponsor
// aligns a tank member instead of holding them; the one-tap /my?activate=1#wallet link (stubbed wallet) starts the Activate
// flow only with a wallet, a real sponsor and no hold, and carries on after an on-page sign-in. Never production. Exit code 1 on any failure.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const require = createRequire(path.join(SITE, 'package.json'));
delete process.env.DATABASE_URL; // JSON stores only
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));
const H = 3600000;
// ---------------- Part A ----------------
function fakeAccounts() {
const by = new Map(); let nextId = 100;
const pub = a => a ? Object.assign({}, a) : null;
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
return {
_by: by,
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; },
async listAll() { return [...by.values()].filter(a => !(a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId)).map(pub); },
isUnclaimedShell: a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId,
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); }
};
}
function bench(o) {
o = o || {};
const tankPath = path.join(SITE, 'tank.js'); delete require.cache[require.resolve(tankPath)];
const tank = require(tankPath);
const dir = o.dir || fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-'));
const accounts = o.accounts || fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {};
const notices = []; const claims = o.claims || new Set(); const onChain = o.onChain || new Set();
const blocked = new Set();
const env = o.env || { now: Date.now() };
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) },
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
mailer: { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); } }, site: 'https://iap.test',
hooks: { network: e => net[e] || null, isSuspended: () => false, excluded: () => false, payoutBlocked: async id => blocked.has(id), companyId: () => 1,
assigned: r => { assigned.push(r); }, adminAlert: t => { alerts.push(t); },
claim: k => { if (claims.has(k)) return false; claims.add(k); return true; }, activated: a => onChain.has(a.address), notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } });
tank.setClock(() => env.now);
let block = 1000;
const buyer = (email, memberId, o) => { const a = accounts.add(email, Object.assign({ memberId, address: '0x' + crypto.randomBytes(20).toString('hex'), lastSeen: env.now - H }, o || {})); events.push({ type: 'Purchase', buyerId: memberId, priceCents: 2000, block: block++ }); return a; };
return { tank, accounts, events, chats, mails, alerts, assigned, net, blocked, env, buyer, dir, notices, claims, onChain };
}
async function partA() {
console.log('-- Part A: tank.js with a mocked clock');
{ // hold + ready clock + safety net rotation
const B = bench(); const { tank, accounts, env } = B;
const t0 = env.now;
accounts.add('free@x.co'); // in the tank, no wallet
const h0 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h0 && h0.hold && h0.hold.since === null, 'tank member without a wallet: held, no clock yet');
accounts._by.get('free@x.co').address = '0x' + 'a'.repeat(40);
const h1 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h1 && h1.hold && h1.hold.since === t0 && h1.hold.until === t0 + 24 * H, 'wallet linked: clock starts now, until = +24 h');
env.now = t0 + 5 * H;
const h2 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h2.hold.since === t0, 'the clock does not restart on later visits');
const sponsored = accounts.add('kid@x.co', { sponsorRef: 'someone', address: '0x' + 'b'.repeat(40) });
ok((await tank.holdFor(sponsored)) === null, 'a member with a sponsor is never held');
const w = await tank.waiting();
ok(w[0] && w[0].email === 'free@x.co' && w[0].ready && w[0].holdUntil === t0 + 24 * H, 'waiting(): ready member first with holdUntil');
// adopters: A qualified first, B second, C third; D stale (8 days), E company #1, F blocked chain, G full (2 open)
B.buyer('a@x.co', 11); B.buyer('b@x.co', 12); B.buyer('c@x.co', 13);
B.buyer('d@x.co', 14, { lastSeen: env.now - 8 * 86400000 }); B.buyer('e@x.co', 1); B.buyer('f@x.co', 16); B.blocked.add(16);
const tk = await tank.readyTick(); // 5 h in: nothing due
ok(tk.fresh.length === 1 && tk.fresh[0].email === 'free@x.co', 'readyTick announces the ready member once', JSON.stringify(tk.fresh.map(x => x.email)));
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
ok(tk.assigned.length === 0, 'not assigned before 24 h');
env.now = t0 + 24 * H - 10 * 60000; // 23 h 50 min: inside the last tick, so the hold never runs past 24 h
const r1 = await tank.readyTick();
ok(r1.assigned.length === 1 && r1.assigned[0].adopter === 'a@x.co', 'safety net: first in rotation = earliest qualified (A)', JSON.stringify(r1.assigned));
const fa = await accounts.byEmail('free@x.co');
ok(fa.sponsorRef === 'a', 'adoptee now sponsored by A', fa.sponsorRef);
ok((await tank.holdFor(fa)) === null, 'hold lifted once sponsored');
const recs = (await tank.adminView()).adoptions;
ok(recs[0] && recs[0].note === 'auto-assigned after 24 hours in the tank' && recs[0].status === 'open', 'adoption record note', recs[0] && recs[0].note);
ok(B.chats.some(c => c.from === 'a@x.co' && c.to === 'free@x.co'), 'sponsor chat opened');
ok(B.mails.some(m => m.to === 'free@x.co') && B.mails.some(m => m.to === 'a@x.co' && /holding tank is now in your line/.test(m.subject)), 'both sides emailed');
const LINK = 'https://iap.test/my?activate=1#wallet';
ok(B.chats.some(c => c.to === 'free@x.co' && c.text.includes('Switch on payouts in one tap') && c.text.includes(LINK)), 'auto-assign chat carries the one-tap link');
ok(B.mails.some(m => m.to === 'free@x.co' && m.body.includes('Switch on payouts: ' + LINK) && m.body.includes('locks @a in as your sponsor')), 'auto-assign member email carries the one-tap link');
ok(B.assigned.length === 1, 'assigned hook fired (Telegram pickup line with "(auto-assigned)")');
// second ready member: rotation moves to B (A was just auto-assigned)
accounts.add('free2@x.co', { address: '0x' + 'c'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r2 = await tank.readyTick();
ok(r2.assigned.length === 1 && r2.assigned[0].adopter === 'b@x.co', 'rotation: least recently auto-assigned next (B)', JSON.stringify(r2.assigned));
// third: C; D stale, E company, F blocked chain never picked
accounts.add('free3@x.co', { address: '0x' + 'd'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r3 = await tank.readyTick();
ok(r3.assigned.length === 1 && r3.assigned[0].adopter === 'c@x.co', 'rotation: C (stale, company and no-payout chain skipped)', JSON.stringify(r3.assigned));
// fourth: everyone in rotation has been used once: back to A (oldest auto-assign)
accounts.add('free4@x.co', { address: '0x' + 'e'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H;
const r4 = await tank.readyTick();
ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co', 'rotation wraps to the least recently assigned (A)', JSON.stringify(r4.assigned));
// A now has 2 open adoptions (free + free4): full. Make B and C stale: nobody eligible
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
accounts.add('free5@x.co', { address: '0x' + 'f'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r5 = await tank.readyTick();
const f5 = await accounts.byEmail('free5@x.co');
ok(r5.assigned.length === 0 && r5.held === 1 && !f5.sponsorRef, 'nobody eligible: keeps holding, never the company');
ok(B.alerts.length === 1 && /free5@x.co/.test(B.alerts[0]), 'admin alerted once');
await tank.readyTick(); await tank.sweep();
ok(B.alerts.length === 1, 'no second alert on later ticks / the hourly sweep');
const h5 = await tank.holdFor(f5);
ok(h5 && h5.hold && h5.hold.until <= env.now, 'still held past the clock (client shows "Any minute now")');
}
{ // one-tap link + switch-on-payouts reminders (24 h member + sponsor, 72 h member only), mocked clock
const B = bench(); const { tank, accounts, env } = B; const LINK = 'https://iap.test/my?activate=1#wallet';
B.buyer('sp@x.co', 41);
accounts.add('m1@x.co', { address: '0x' + '7'.repeat(40) }); accounts.add('m2@x.co'); accounts.add('m3@x.co', { address: '0x' + '8'.repeat(40) }); accounts.add('m4@x.co', { address: '0x' + '9'.repeat(40) });
const r = await tank.adopt('sp@x.co', 'm1', 'Hey, I am your new sponsor.');
ok(r && r.ok && !r.auto, 'manual adoption (setup)', JSON.stringify(r && r.error));
const chat = B.chats.find(c => c.to === 'm1@x.co');
ok(chat && chat.text === 'Hey, I am your new sponsor.\n\nSwitch on payouts in one tap (one free transaction, it locks me in as your sponsor): ' + LINK, 'manual adoption chat: own note + the one-tap line', chat && chat.text);
const mail = B.mails.find(m => m.to === 'm1@x.co');
ok(mail && mail.body.includes('Switch on payouts: ' + LINK) && !mail.body.includes('No wallet linked yet'), 'manual adoption email: link, no wallet sentence when linked');
await tank.adopt('sp@x.co', 'm2'); // no wallet yet
ok(B.mails.some(m => m.to === 'm2@x.co' && m.body.includes('No wallet linked yet? The same link shows you how')), 'no wallet: the email says the link walks them through linking');
const t0 = env.now;
env.now = t0 + 23 * H; let p = await tank.payTick();
ok(p.sent.length === 0, 'no reminder before 24 h');
accounts._by.get('m2@x.co').memberId = 51; // m2 switched on payouts: no reminder ever
env.now = t0 + 24 * H + 60000; const mailsBefore = B.mails.length;
p = await tank.payTick();
const r1 = B.mails.slice(mailsBefore);
ok(p.sent.length === 1 && p.sent[0].email === 'm1@x.co' && p.sent[0].stage === 1, '24 h: one reminder, only for the member still off', JSON.stringify(p.sent));
ok(r1.length === 1 && r1[0].to === 'm1@x.co' && r1[0].subject === 'Reminder: switch on payouts with @sp on InstantAdPay' && r1[0].body.includes(LINK), '24 h member email: subject + one-tap link', r1[0] && r1[0].subject);
ok(B.notices.length === 1 && B.notices[0].to === 'sp@x.co' && B.notices[0].subject === "@m1 hasn't switched on payouts yet" && B.notices[0].text.startsWith("@m1 hasn't switched on payouts yet; a nudge from you helps.") && B.notices[0].text.includes(LINK), '24 h sponsor notice', B.notices[0] && B.notices[0].text.slice(0, 80));
ok(!r1.some(m => m.to === 'sp@x.co'), 'the sponsor gets a notice, not an email');
await tank.payTick(); env.now += 15 * 60000; p = await tank.payTick();
ok(p.sent.length === 0 && B.notices.length === 1, 'idempotent: later ticks send nothing more before 72 h');
ok(tank.payView().find(x => x.email === 'm2@x.co').done === 'activated', 'activated member: record closed (activated)');
env.now = t0 + 72 * H + 60000; const m72 = B.mails.length;
p = await tank.payTick();
ok(p.sent.length === 1 && p.sent[0].stage === 2 && B.mails.length === m72 + 1 && B.mails[m72].subject === 'Last reminder: switch on payouts with @sp on InstantAdPay' && B.mails[m72].body.includes(LINK), '72 h: the last reminder, member only', JSON.stringify(p.sent));
ok(B.notices.length === 1, '72 h: no second sponsor notice');
env.now += 24 * H; p = await tank.payTick();
ok(p.sent.length === 0 && tank.payView().find(x => x.email === 'm1@x.co').done === 'reminded', 'after 72 h: done, nothing more');
ok(!/—/.test(B.chats.map(c => c.text).join(' ') + B.mails.map(m => m.subject + m.body).join(' ') + B.notices.map(n => n.subject + n.text).join(' ')), 'no em dashes in member texts');
// m3 activated on chain (MemberActivated) before the account has a memberId; m4 moved away before 24 h: both stop
B.buyer('sp2@x.co', 42);
const r3 = await tank.adopt('sp2@x.co', 'm3'); ok(r3 && r3.ok, 'second sponsor adopts m3 (setup)', JSON.stringify(r3 && r3.error));
const r4 = await tank.adopt('sp2@x.co', 'm4'); ok(r4 && r4.ok, 'second sponsor adopts m4 (setup)', JSON.stringify(r4 && r4.error));
const t3 = env.now; B.onChain.add(accounts._by.get('m3@x.co').address);
accounts._by.get('m4@x.co').sponsorRef = '';
env.now = t3 + 25 * H; p = await tank.payTick();
ok(p.sent.length === 0, 'activated on chain / sponsor changed: no reminder', JSON.stringify(p.sent));
const pv = tank.payView();
ok(pv.find(x => x.email === 'm3@x.co').done === 'activated' && pv.find(x => x.email === 'm4@x.co').done === 'moved', 'records closed as activated / moved');
ok((await tank.adminView()).payReminders.length >= 4, 'adminView lists the reminder records');
}
{ // deploy overlap: a second app copy with a stale tank-ready.json and the shared claim table sends nothing twice
const accounts = fakeAccounts(); const claims = new Set(); const env = { now: Date.now() };
const A = bench({ accounts, claims, env });
A.buyer('ov@x.co', 61); accounts.add('ovm@x.co', { address: '0x' + '6'.repeat(40) });
await A.tank.adopt('ov@x.co', 'ovm');
const stale = fs.readFileSync(path.join(A.dir, 'tank-ready.json'), 'utf8');
env.now += 25 * H;
const pa = await A.tank.payTick();
const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-ov-')); fs.writeFileSync(path.join(dir2, 'tank-ready.json'), stale);
const Bc = bench({ accounts, claims, env, dir: dir2 }); // copy B: same accounts + claims, stale state
const pb = await Bc.tank.payTick();
ok(pa.sent.length === 1 && pb.sent.length === 0 && Bc.mails.length === 0 && Bc.notices.length === 0, 'overlap: copy A sends the 24 h reminder, stale copy B sends nothing', JSON.stringify({ a: pa.sent.length, b: pb.sent.length }));
}
{ // own-downline adopter skipped
const B = bench(); const { tank, accounts, env } = B;
accounts.add('top@x.co', { address: '0x' + '1'.repeat(40) });
B.buyer('under@x.co', 21, { sponsorRef: 'top' }); B.buyer('other@x.co', 22);
await tank.readyTick(); env.now += 24 * H;
const r = await tank.readyTick();
ok(r.assigned.length === 1 && r.assigned[0].adopter === 'other@x.co', 'an adopter in the member\'s own downline is skipped', JSON.stringify(r.assigned));
}
{ // network alignment
const B = bench(); const { tank, accounts, net } = B;
accounts.add('lsboss@x.co', { memberId: 31 });
accounts.add('t1@x.co', { address: '0x' + '2'.repeat(40) }); net['t1@x.co'] = { sponsorEmail: 'lsboss@x.co', via: 'same email' };
const h = await tank.holdFor(await accounts.byEmail('t1@x.co'));
ok(h && h.aligned && (await accounts.byEmail('t1@x.co')).sponsorRef === 'lsboss', 'LinkSpin sponsor with an account here: aligned, not held', JSON.stringify(h));
ok((await tank.adminView()).aligned[0].why.includes('aligned to network sponsor @lsboss from LinkSpin'), 'alignment recorded with the reason');
accounts.add('shell@x.co', { joinedVia: 'linkspin', lastSeen: 0 });
accounts.add('t2@x.co'); net['t2@x.co'] = { sponsorEmail: 'shell@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t2@x.co'))).hold, 'sponsor only an unclaimed LinkSpin shell here: held, not aligned');
accounts.add('t3@x.co'); net['t3@x.co'] = { sponsorEmail: 'nobody@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t3@x.co'))).hold, 'sponsor with no account here: held');
// released from lsboss on purpose: never back to them
accounts.add('t4@x.co', { sponsorRef: 'lsboss' });
const rel = await tank.release('lsboss@x.co', 't4@x.co');
ok(rel && rel.ok, 'release to the tank (setup)', JSON.stringify(rel));
net['t4@x.co'] = { sponsorEmail: 'lsboss@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t4@x.co'))).hold, 'never aligned back to a sponsor who released them');
// loop: the LinkSpin sponsor sits under the tank member
accounts.add('t5@x.co'); accounts.add('child@x.co', { sponsorRef: 't5', memberId: 33 }); net['t5@x.co'] = { sponsorEmail: 'child@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t5@x.co'))).hold, 'never aligned under their own downline');
}
}
// ---------------- Part B ----------------
async function partB() {
console.log('-- Part B: local copy');
const PORT = Number(process.env.TANKHOLD_PORT || 8799);
const BASE = 'http://127.0.0.1:' + PORT; const ADMIN = 'localtest';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const LSSECRET = crypto.randomBytes(24).toString('hex'); // throwaway
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: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, LS_SYNC_SECRET: LSSECRET, LS_URL: 'http://127.0.0.1:1' }) });
let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
let browser = null;
try {
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(BASE + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + log.slice(-1500));
const api = async (p, body, hdr) => { const r = await fetch(BASE + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 20 } }, adminH);
async function signIn(email, username, extraCookie, ip) { // ip: X-Forwarded-For of its own (the code guard allows 5 sends per IP per 10 min)
const xf = ip ? { 'X-Forwarded-For': ip } : {};
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000 }, Object.assign({}, xf, extraCookie ? { Cookie: extraCookie } : {}));
const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, xf, extraCookie ? { Cookie: extraCookie } : {}), 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]).filter(c => /^iap\./.test(c) || c.includes('=')).join('; ');
if (username) await api('/api/my/profile', { username }, { Cookie: cookie });
return cookie;
}
const { ethers } = require('ethers');
async function linkWallet(cookie) {
const w = ethers.Wallet.createRandom();
const c = await api('/api/auth/challenge', { address: w.address }, { Cookie: cookie });
const signature = await w.signMessage(c.j.message);
const v = await api('/api/auth/verify', { address: w.address, signature }, { Cookie: cookie });
return { w, v };
}
// 1. tank member with a wallet
const tc = await signIn('qa-tank@example.com', 'qatankone');
const lw = await linkWallet(tc);
ok(lw.v.j && lw.v.j.linked, 'tank member links a wallet', JSON.stringify(lw.v.j));
const me = (await api('/api/me', null, { Cookie: tc })).j;
ok(me && me.tankHold && me.tankHold.until - me.tankHold.since === 24 * H, '/api/me answers tankHold with a 24-hour clock', JSON.stringify(me && me.tankHold));
ok(me && !me.sponsorId && me.sponsorBlocked === 'tankHold', '/api/me: no fallback sponsor (sponsorId ' + (me && me.sponsorId) + ')');
const sp = (await api('/api/sponsor?intent=buy', null, { Cookie: tc })).j;
ok(sp && sp.sponsorId === 1 && !sp.sponsorBlocked && !sp.tankHold, '/api/sponsor (buy) is NEVER held: falls back to the catch position #1 (Marty 2026-10-27)', JSON.stringify({ id: sp && sp.sponsorId, b: sp && sp.sponsorBlocked }));
const spa = (await api('/api/sponsor', null, { Cookie: tc })).j;
ok(spa && !spa.sponsorId && spa.sponsorBlocked === 'tankHold', '/api/sponsor without buy intent still holds (activation only)', JSON.stringify({ id: spa && spa.sponsorId, b: spa && spa.sponsorBlocked }));
const adm = (await api('/api/admin/tank', null, adminH)).j;
const row = adm && adm.waiting && adm.waiting.find(w => w.email === 'qa-tank@example.com');
ok(row && row.ready && row.holdUntil === me.tankHold.until, 'admin tank: ready with holdUntil');
// 2. joined through a link: never held, today's behaviour
const jc = await signIn('qa-kid@example.com', 'qakidone', 'iap.sponsor=qatankone');
await linkWallet(jc);
const me2 = (await api('/api/me', null, { Cookie: jc })).j;
ok(me2 && !me2.tankHold && me2.sponsorBlocked !== 'tankHold' && me2.sponsorId > 0, 'member with a sponsor link: no hold, sponsor resolves as before', JSON.stringify({ id: me2 && me2.sponsorId, b: me2 && me2.sponsorBlocked, routed: me2 && me2.sponsorRouted }));
// 3. LinkSpin knows a sponsor for this email: aligned instead of held
await signIn('qa-lsboss@example.com', 'qalsboss');
const tc3 = await signIn('qa-tank3@example.com', 'qatankthree');
const raw = JSON.stringify({ rows: [{ email: 'qa-tank3@example.com', username: 'qatankthree', sponsorEmail: 'qa-lsboss@example.com', joinedAt: Date.now() - 86400000 }] });
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', LSSECRET).update(ts + '\n' + raw).digest('hex');
const pr = await fetch(BASE + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw });
ok(pr.ok, 'LinkSpin row accepted (first-platform rule leaves the sponsor empty)');
const me3 = (await api('/api/me', null, { Cookie: tc3 })).j;
ok(me3 && !me3.tankHold && me3.sponsorBlocked !== 'tankHold', 'tank member LinkSpin knows: aligned, not held', JSON.stringify({ b: me3 && me3.sponsorBlocked, h: me3 && me3.tankHold }));
const adm3 = (await api('/api/admin/tank', null, adminH)).j;
ok(adm3 && adm3.aligned && adm3.aligned.some(x => x.email === 'qa-tank3@example.com' && x.to === 'qa-lsboss@example.com'), 'admin tank lists the alignment');
// 4. the page: Wallet tab + Getting started card
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();
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); localStorage.removeItem('iap.gs.collapsed'); } catch (e) {} });
await ctx.addCookies(tc.split('; ').filter(Boolean).map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1), url: BASE }; }));
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
await page.goto(BASE + '/my#wallet', { waitUntil: 'load' }); await page.waitForTimeout(4000);
const st = await page.evaluate(() => { const b = document.getElementById('activateBtn'); const n = document.getElementById('tankHoldNote'); const g = document.getElementById('gsNow');
return { card: !document.getElementById('activateCard').hidden, btnHidden: !!(b && b.hidden), note: n && !n.hidden ? n.textContent : null, gs: g ? g.textContent : '', gsBtn: !!document.getElementById('gsGo') }; });
ok(st.card && st.btnHidden, 'Wallet tab: Activate payouts button hidden', JSON.stringify(st));
ok(st.note && st.note.startsWith("You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).") && /Time left: \d+ h \d+ min\./.test(st.note), 'hold text with time left', st.note);
ok(/Matching you with a sponsor/.test(st.gs) && !st.gsBtn, 'Getting started: hold text, no activate button', st.gs.slice(0, 120));
await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-wallet.png') }).catch(() => {});
ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200));
// 5. one-tap link /my?activate=1#wallet (2026-10-27): IAPWallet.activate is stubbed in the page (records the sponsor id,
// never reaches a wallet); it must start only for a signed-in member with a wallet, a real sponsor and no hold
const STUB = () => { window.__act = []; let real; Object.defineProperty(window, 'IAPWallet', { configurable: true, get() { return real; },
set(v) { if (v && v.activate) v.activate = async id => { window.__act.push(id); throw new Error('qa: activation stub'); }; real = v; } });
try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} };
async function actCtx(cookie, ip) { // ip: its own address for the on-page sign-in (the code guard allows 5 sends per IP per 10 min)
const c = await browser.newContext(Object.assign({ viewport: { width: 390, height: 844 } }, ip ? { extraHTTPHeaders: { 'X-Forwarded-For': ip } } : {})); await c.addInitScript(STUB);
if (cookie) await c.addCookies(cookie.split('; ').filter(Boolean).map(x => { const i = x.indexOf('='); return { name: x.slice(0, i), value: x.slice(i + 1), url: BASE }; }));
const pg = await c.newPage(); pg.on('pageerror', e => errs.push(e.message)); return { c, pg };
}
const actState = pg => pg.evaluate(() => { const n = document.getElementById('actIntentNote'); return { act: window.__act, note: n && !n.hidden ? n.textContent : null, url: location.pathname + location.search + location.hash, hold: (document.getElementById('tankHoldNote') || {}).hidden === false }; });
{ // held tank member: never triggers, the param is dropped, the hold text shows
const { c, pg } = await actCtx(tc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s1 = await actState(pg);
ok(s1.act.length === 0 && !s1.note && s1.hold && !/activate=1/.test(s1.url), '?activate=1 on a held tank member: no activation, hold text, param dropped', JSON.stringify(s1));
await c.close();
}
{ // sponsor link to a member who never switched on payouts (walk-up / routed): no real sponsor, never triggers
ok(me2 && me2.sponsorRouted, 'setup: the link-joined member routes past an unactivated sponsor', JSON.stringify(me2 && me2.sponsorRouted));
const { c, pg } = await actCtx(jc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s2 = await actState(pg);
ok(s2.act.length === 0 && !s2.note, '?activate=1 when no real sponsor resolves: no activation', JSON.stringify(s2));
await c.close();
}
// a member with a real sponsor (#21) and a wallet: the Activate flow starts at once with #21
const pc = await signIn('qa-pay@example.com', 'qapayone', 'iap.sponsor=21', '10.78.0.1'); await linkWallet(pc);
const mp = (await api('/api/me', null, { Cookie: pc })).j;
ok(mp && mp.sponsorId === 21 && !mp.sponsorFallback && !mp.tankHold && !mp.memberId, 'setup: sponsored member, sponsor #21 resolves', JSON.stringify({ id: mp && mp.sponsorId, f: mp && mp.sponsorFallback }));
{ const { c, pg } = await actCtx(pc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4500);
const s3 = await actState(pg);
ok(s3.act.length === 1 && s3.act[0] === 21, '?activate=1: the Activate flow starts once with the sponsor prefilled (#21)', JSON.stringify(s3));
ok(s3.note === 'One free transaction switches on your payouts and locks member #21 in as your sponsor. Confirm it in your wallet.', 'explainer line above the Activate button', s3.note);
ok(/#wallet$/.test(s3.url) && !/activate=1/.test(s3.url), 'Wallet tab open, param consumed', s3.url);
await pg.reload({ waitUntil: 'load' }); await pg.waitForTimeout(3500);
ok((await actState(pg)).act.length === 0, 'a reload does not start it again');
await pg.screenshot({ path: path.join(SITE, 'qa/out/tank-activate-link.png') }).catch(() => {});
await c.close(); }
{ // signed out: sign in on the page, then the same flow carries on
const c2 = await signIn('qa-pay2@example.com', 'qapaytwo', 'iap.sponsor=21', '10.78.0.2'); await linkWallet(c2);
const { c, pg } = await actCtx(null, '10.77.' + (1 + Math.floor(Math.random() * 250)) + '.9'); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
ok((await actState(pg)).act.length === 0, 'signed out: nothing starts before sign-in');
await pg.fill('#mcEmail', 'qa-pay2@example.com'); await pg.click('#mcSendBtn');
await pg.waitForFunction(() => (document.getElementById('mcCode') || {}).value, null, { timeout: 15000 }).catch(() => {});
await pg.click('#mcVerifyBtn'); await pg.waitForTimeout(5000);
const s4 = await actState(pg);
ok(s4.act.length === 1 && s4.act[0] === 21, 'signed out -> sign in -> the Activate flow continues with #21', JSON.stringify(s4));
await c.close(); }
{ // sponsored, no wallet yet: link first (note), nothing starts; the intent waits for the link
const c3 = await signIn('qa-pay3@example.com', 'qapaythree', 'iap.sponsor=21', '10.78.0.3');
const { c, pg } = await actCtx(c3); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s5 = await actState(pg);
ok(s5.act.length === 0 && s5.note === 'Step 1: link your wallet (one free signature). Then switching on payouts with member #21 starts by itself.', 'no wallet yet: asks to link first, nothing starts', JSON.stringify(s5));
await c.close(); }
ok(!errs.length, 'no page errors (one-tap link pages)', errs.join(' | ').slice(0, 200));
} finally {
if (browser) await browser.close().catch(() => {});
try { srv.kill(); } catch (e) {}
await sleep(500);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
}
}
await partA();
if (process.argv[2] !== 'unit') await partB();
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
process.exit(fails ? 1 : 0);
+7 -3
View File
@@ -246,7 +246,8 @@ if (MODE === 'member' || MODE === 'all') {
if (/QA internal note/.test(th)) note('bug', L + 'my#help', 'INTERNAL NOTE LEAKED to the member');
flush(bag, L + 'my#help (reply seen)'); console.log('ok member sees reply, no internal note');
}
// public /support (signed out): the form, the guard, the private ticket link
// public /support (signed out): the form, the guard, the private ticket link. Members only since 2026-10-24 (962cdf0):
// a signed-out ticket needs an email that has an account (qa-walk@example.com signed up above); others get a 403
{
const pctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true });
await pctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
@@ -255,7 +256,7 @@ if (MODE === 'member' || MODE === 'all') {
await domChecks(pp, L + '/support');
if (!(await pp.$('#supForm'))) note('bug', L + '/support', 'form did not render');
else {
await pp.fill('#supName', 'QA Visitor'); await pp.fill('#supEmail', 'qa-visitor@example.com');
await pp.fill('#supName', 'QA Visitor'); await pp.fill('#supEmail', 'qa-walk@example.com');
await pp.fill('#supSubject', 'QA: cannot sign in'); await pp.fill('#supBody', 'The sign-in code never arrives. QA walk.');
await pp.click('#supSend'); await pp.waitForTimeout(3500);
const tl = await pp.$eval('#supMain a.btn[href^="/support/t/"]', e => e.getAttribute('href')).catch(() => '');
@@ -268,7 +269,10 @@ if (MODE === 'member' || MODE === 'all') {
const bad = await pp.request.get(LOCAL + '/api/support/t/' + tl.split('/').pop().slice(0, -4) + 'AAAA');
if (bad.status() !== 404) note('bug', L + '/support/t', 'a tampered token was accepted: ' + bad.status());
}
const bot = await pp.request.post(LOCAL + '/api/support', { data: { email: 'qa-bot@example.com', subject: 'x bot', body: 'bot body here', fts: Date.now(), fage: 10 } });
const nm = await pp.request.post(LOCAL + '/api/support', { data: { email: 'qa-visitor@example.com', name: 'QA', subject: 'QA: not a member', category: 'Other', body: 'Not a member, should be refused.', fage: 9000 } });
const nmj = await nm.json().catch(() => ({}));
if (nm.status() !== 403 || !nmj.membersOnly) note('bug', L + '/api/support', 'a non-member email was not refused (members-only): ' + nm.status());
const bot = await pp.request.post(LOCAL + '/api/support', { data: { email: 'qa-walk@example.com', subject: 'x bot', body: 'bot body here', fts: Date.now(), fage: 10 } });
if (bot.status() !== 400) note('bug', L + '/api/support', 'instant (form-age 10ms) post was not refused: ' + bot.status());
}
await pp.screenshot({ path: OUT + '/support-public.png' }).catch(() => {});
+125
View File
@@ -0,0 +1,125 @@
// Wallet push + nudge (walletnudge.js) against a MOCK game on localhost, throwaway data. Run: node qa/walletnudge.test.cjs
// 2026-10-27 (Marty, "build all three"): a signature-linked wallet is pushed to the game whether or not it is an on-chain
// member (memberId 0 when it is not); only players with NO linked wallet are nudged, and the nudge asks for the link step only.
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const http = require('http');
const crypto = require('crypto');
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 SECRET = 'x'.repeat(40);
const W1 = '0x' + '1'.repeat(40), W2 = '0x' + '2'.repeat(40), W3 = '0x' + '3'.repeat(40);
// a game with the same contract as the real ones: signed GET /api/iap/unpaid, signed POST /api/iap/wallet (fill empty only)
function mockGame(players) {
const pushes = [];
const srv = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x'), send = (c, j) => { res.writeHead(c, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(j)); };
if (u.pathname === '/api/iap/unpaid') {
const ts = u.searchParams.get('ts'), want = crypto.createHmac('sha256', SECRET).update('unpaid\n' + ts).digest('hex');
if (u.searchParams.get('sig') !== want) return send(401, { error: 'bad signature' });
return send(200, { ok: true, rows: Object.entries(players).filter(([, p]) => p.unpaid > 0 && !p.wallet).map(([email, p]) => ({ email, memberId: 0, username: null, unpaid: p.unpaid })) });
}
if (u.pathname === '/api/iap/wallet' && req.method === 'POST') {
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
const ts = String(req.headers['x-iap-ts'] || '');
const want = crypto.createHmac('sha256', SECRET).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex');
if (req.headers['x-iap-sig'] !== want) return send(401, { error: 'bad signature' });
const b = JSON.parse(raw), p = players[b.email]; pushes.push(b);
if (!p) return send(404, { error: 'unknown player' });
if (p.wallet && p.wallet.toLowerCase() !== b.wallet.toLowerCase()) return send(409, { error: 'a different wallet is already set' });
const changed = !p.wallet; if (!p.wallet) p.wallet = b.wallet;
send(200, { ok: true, changed, wallet: b.wallet, unpaid: p.unpaid });
});
return;
}
send(404, {});
});
return new Promise(ok => srv.listen(0, '127.0.0.1', () => ok({ srv, pushes, url: 'http://127.0.0.1:' + srv.address().port })));
}
(async () => {
for (const k of ['SD', 'GK', 'SEEK', 'DR', 'RA', 'PB', 'SW', 'PW']) { delete process.env[k + '_URL']; delete process.env[k + '_SSO_SECRET']; }
const players = {
'tank@x.test': { unpaid: 1.5 }, // linked wallet, NOT activated (holding tank): must be pushed, memberId 0
'member@x.test': { unpaid: 0.4 }, // linked + activated: pushed with its member id, as before
'nowallet@x.test': { unpaid: 0.75 }, // no linked wallet: nudged
'other@x.test': { unpaid: 0.2, wallet: null }, // game already holds a different wallet -> refused below
'rpc@x.test': { unpaid: 0.3 } // chain read fails: still pushed (stored member id, here 0)
};
const G = await mockGame(players);
process.env.GK_URL = G.url; process.env.GK_SSO_SECRET = SECRET;
const accts = {
'tank@x.test': { email: 'tank@x.test', username: 'tanky', address: W1, memberId: 0 },
'member@x.test': { email: 'member@x.test', username: 'mem', address: W2, memberId: 0 },
'nowallet@x.test': { email: 'nowallet@x.test', username: 'nw', address: null, memberId: 0 },
'other@x.test': { email: 'other@x.test', username: 'ot', address: W3, memberId: 0 },
'rpc@x.test': { email: 'rpc@x.test', username: 'rp', address: '0x' + '4'.repeat(40), memberId: 0 }
};
const chainIds = { [W2.toLowerCase()]: 77 };
const inbox = [], mail = [];
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-wn-'));
const wn = fresh('walletnudge.js');
// the 'other' player's game copy got a different wallet in between (fill-empty-only must refuse a replacement)
players['other@x.test'].wallet = '0x' + '5'.repeat(40);
players['other@x.test'].unpaid = 0.2;
// ...but then the game would not list it as unpaid-without-wallet; force it into the list once to exercise the 409 path
const origOther = players['other@x.test'];
wn.init({ dataDir: dir, site: 'https://instantadpay.com',
accounts: { byEmail: async e => accts[e] || null, byMemberId: async () => null },
chain: { memberIdByAccount: async a => { if (a === accts['rpc@x.test'].address) throw new Error('rpc down'); return chainIds[a.toLowerCase()] || 0; } },
mailer: { hasKey: () => true, send: async (to, subject, text, html) => { mail.push({ to, subject, text, html }); } },
optedIn: async () => true,
message: async (to, subject, html) => { inbox.push({ to, subject, html }); } });
let r;
await t('tick runs against the mock game', async () => { r = await wn.tick(); assert.ok(r.ok); assert.strictEqual(r.games.gemkingdom, 4); });
await t('non-activated linked wallet is pushed with memberId 0 and filled', async () => {
const p = G.pushes.find(x => x.email === 'tank@x.test'); assert.ok(p, 'no push');
assert.strictEqual(p.wallet, W1); assert.strictEqual(p.memberId, 0); assert.strictEqual(players['tank@x.test'].wallet, W1);
});
await t('activated wallet still pushed with its member id', async () => {
const p = G.pushes.find(x => x.email === 'member@x.test'); assert.ok(p); assert.strictEqual(p.memberId, 77); assert.strictEqual(players['member@x.test'].wallet, W2);
});
await t('a failed chain read still pushes the linked wallet (stored member id)', async () => {
const p = G.pushes.find(x => x.email === 'rpc@x.test'); assert.ok(p); assert.strictEqual(p.memberId, 0);
});
await t('linked players are never nudged; the no-wallet player is', async () => {
assert.deepStrictEqual(inbox.map(x => x.to), ['nowallet@x.test']); assert.deepStrictEqual(mail.map(x => x.to), ['nowallet@x.test']);
assert.strictEqual(r.pushed, 3); assert.strictEqual(r.sent, 1);
});
await t('nudge copy: link step only, the exact approved wording, /my#wallet', async () => {
const m = mail[0];
assert.strictEqual(m.subject, '0.75 POL is waiting for your wallet');
assert.ok(m.text.includes("You've earned 0.75 POL in Gem Kingdom. Link your wallet (one free signature) and it's sent automatically, including everything you've earned so far."), m.text);
assert.ok(m.text.includes('https://instantadpay.com/my#wallet')); assert.ok(inbox[0].html.includes('https://instantadpay.com/my#wallet'));
assert.ok(!/switch on|activate/i.test(m.text + inbox[0].html), 'mentions switching on payouts');
assert.ok(!/—/.test(m.text + inbox[0].html), 'em dash');
});
await t('second tick: nothing re-pushed as a change, no second nudge before 3 days', async () => {
const before = G.pushes.length; const r2 = await wn.tick();
assert.strictEqual(r2.pushed, 0); assert.strictEqual(r2.sent, 0); assert.strictEqual(G.pushes.length, before, 'filled players are no longer listed');
});
await t('a different wallet in the game is refused (409), never replaced, and not retried within the day', async () => {
// list the "other" player as unpaid with no wallet in the listing, but the game copy holds a different wallet
const realWallet = origOther.wallet;
const saved = G.srv.listeners('request')[0];
G.srv.removeAllListeners('request');
G.srv.on('request', (req, res) => {
if (req.url.startsWith('/api/iap/unpaid')) { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ ok: true, rows: [{ email: 'other@x.test', memberId: 0, unpaid: 0.2 }] })); }
return saved(req, res);
});
const before = G.pushes.length;
await wn.tick(); assert.strictEqual(G.pushes.length, before + 1); assert.strictEqual(players['other@x.test'].wallet, realWallet);
const v = wn.adminView(); assert.ok(v.pushRefused.some(x => x.email === 'other@x.test' && x.status === 'conflict'));
await wn.tick(); assert.strictEqual(G.pushes.length, before + 1, 'retried within 24 h');
});
G.srv.close(); fs.rmSync(dir, { recursive: true, force: true });
console.log((n - fails) + '/' + n + ' passed'); process.exit(fails ? 1 : 0);
})();
+32 -8
View File
@@ -10,6 +10,10 @@
//
// Settings (siteConfig): refillNotices '1'|'0' (default on), refillLowPct (80) the share of budget
// delivered that counts as "running low".
//
// 2026-10-24 (Fuel Your Offers): the bonus block names Wired Wednesday next to Five Dollar Friday, and takes
// the member's refuel-streak line from X.streakLine(owner) -> { text, html } | null when the streak is on.
// Every send is claimed first (marks.js), so the two app copies of a deploy never both write to a person.
'use strict';
const fs = require('fs');
const path = require('path');
@@ -32,6 +36,9 @@ function cfg() {
lowPct: Math.min(99, Math.max(50, Number(c.refillLowPct) || 80)),
fridayOn: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
fridayPct: Number(c.fridayBonusPct) || 20,
wedOn: String(c.wednesdayPromo == null ? '1' : c.wednesdayPromo) === '1',
wedPct: Math.max(0, Number(c.wednesdayBonusPct) || 25),
wedMinUsd: Math.max(0, Number(c.wednesdayMinCents) || 2000) / 100,
};
}
@@ -61,21 +68,34 @@ const PACKS = [
{ price: 500, credits: 70000, bonus: 40 },
];
function ladderText() {
// the day bonuses, one line each; Friday and Wednesday never fall on the same day
function dayBonusLines() {
const c = cfg(); const out = [];
if (c.fridayOn) out.push({ title: 'Five Dollar Friday', body: 'any package from $5 up, bought on a Friday (Central time), earns an extra ' + c.fridayPct + '% in credits on top of the above.' });
if (c.wedOn) out.push({ title: 'Wired Wednesday', body: 'any package from $' + c.wedMinUsd + ' up, bought on a Wednesday (Central time), earns an extra ' + c.wedPct + '% in credits, wired in the moment it settles.' });
return out;
}
async function streakLine(owner) {
if (typeof X.streakLine !== 'function' || !owner) return null;
try { return await X.streakLine(owner); } catch (e) { return null; }
}
function ladderText(sl) {
const c = cfg();
const rows = PACKS.map(p => ' $' + p.price + ' -> ' + money(p.credits) + ' credits' + (p.bonus ? ' (' + p.bonus + '% more per dollar)' : ''));
let s = 'Ad packages, and what each one adds to your balance:\n\n' + rows.join('\n')
+ '\n\nA credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.';
if (c.fridayOn) s += '\n\nFive Dollar Friday: any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.';
for (const d of dayBonusLines()) s += '\n\n' + d.title + ': ' + d.body;
if (sl && sl.text) s += '\n\n' + sl.text;
return s;
}
function ladderHtml() {
function ladderHtml(sl) {
const c = cfg();
const rows = PACKS.map(p => '<tr><td style="padding:6px 14px 6px 0"><b>$' + p.price + '</b></td><td style="padding:6px 14px 6px 0">' + money(p.credits)
+ ' credits</td><td style="padding:6px 0;color:#0E8F72">' + (p.bonus ? p.bonus + '% more per dollar' : '') + '</td></tr>').join('');
return '<p><b>Ad packages, and what each one adds to your balance:</b></p><table style="border-collapse:collapse">' + rows + '</table>'
+ '<p style="color:#556">A credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.</p>'
+ (c.fridayOn ? '<p><b>Five Dollar Friday:</b> any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.</p>' : '');
+ dayBonusLines().map(d => '<p><b>' + d.title + ':</b> ' + esc(d.body) + '</p>').join('')
+ (sl && sl.html ? '<p>' + sl.html + '</p>' : '');
}
// what one owner's batch of campaigns says in the body
@@ -112,7 +132,8 @@ async function compose(owner, list, state, credits) {
: canRelaunch
? 'You still have ' + money(Math.round(credits)) + ' credits in your balance, which is enough to put an ad back up right now without buying anything. Open Campaigns and start one: ' + SITE + '/my#campaigns'
: 'Your balance is down to ' + money(Math.round(credits)) + ' credits, so the next campaign needs a top-up first: ' + SITE + '/my#buy';
const lines = [opener, totals, next, ladderText(),
const sl = await streakLine(owner);
const lines = [opener, totals, next, ladderText(sl),
'Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger at ' + SITE + '/ledger.'];
const text = lines.filter(Boolean).join('\n\n') + '\n\nWhat each one did:\n' + describe(list) + '\n\nInstantAdPay';
const html = '<p>' + opener + '</p>' + (totals ? '<p>' + totals + '</p>' : '')
@@ -120,7 +141,7 @@ async function compose(owner, list, state, credits) {
+ '<p><b>What each one did:</b></p><ul>' + list.map(c => '<li>' + esc(c.name || ('campaign #' + c.id)) + ' (' + esc(c.type || 'ad') + '): '
+ money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'
+ (n0(c.imps) ? ', ' + money(n0(c.imps)) + ' ' + unit(c) : '') + (n0(c.clicks) ? ', ' + money(n0(c.clicks)) + ' clicks' : '') + esc(videoNote(c)) + '</li>').join('') + '</ul>'
+ ladderHtml()
+ ladderHtml(sl)
+ '<p style="color:#556">Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger.</p>';
return { subject, text, html };
}
@@ -178,7 +199,7 @@ async function followUps(all, alreadySent) {
if (credits < IDLE_MIN_CREDITS) { r.followUp = 'nocredits'; continue; }
const list = r.campaigns.map(x => all.find(c => c.id === x.id) || x);
const ok = await notify(r.owner, list, 'idle', r.id).catch(e => { console.error('refill follow-up', r.owner, e.message); return false; });
r.followUp = ok ? S.seq : 'failed';
r.followUp = ok ? S.seq : 'claimed';
if (ok) sent++;
}
if (due.length) save();
@@ -186,6 +207,9 @@ async function followUps(all, alreadySent) {
}
async function notify(owner, list, state, parentId) {
// claim before anything goes out: one copy of the app per message, ever (deploy overlap)
const claimKey = 'refill:' + (state === 'idle' ? 'idle:' + parentId : list.map(c => c.id).sort((a, b) => a - b).join(',') + ':' + state);
if (X.marks && !(await X.marks.claim(claimKey))) { if (state !== 'idle') for (const cm of list) S.sent[key(cm.id, state)] = S.sent[key(cm.id, state)] || -1; return false; }
const acct = await X.accounts.byEmail(owner); if (!acct) return false;
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(owner).catch(() => false) : false;
let credits = 0; try { credits = await X.creditsFor(owner); } catch (e) {}
@@ -281,4 +305,4 @@ function resetConversions(kinds) {
return { cleared: n };
}
module.exports = { init, tick, stats, resetConversions, PACKS };
module.exports = { init, tick, stats, resetConversions, PACKS, compose };
+414
View File
@@ -0,0 +1,414 @@
// The Monthly Refuel streak (Fuel Your Offers, Marty approved the build 2026-10-24; rules decided 2026-10-23).
// ONE streak per member across InstantAdPay and LinkSpin, kept HERE (InstantAdPay is the source of truth). LinkSpin
// reports its purchases through a signed partner call and collects its own grants and reminders from the outbox.
//
// THE RULES
// counted refuel a NEW on-chain package of $20+ on InstantAdPay (refuelMinIapCents) or $25+ on LinkSpin
// (refuelMinLsCents), bought by one of the member's own positions
// refuel day the first counted refuel starts the streak; the next is due 30 days after the last counted
// refuel (Central-time calendar days). The window opens 5 days before the due day and closes at
// the end of a 5-day grace after it. A purchase before the window is a Pit Stop, not a refuel.
// missing the grace passes with no refuel: the streak resets, unless the member's one free miss per
// 365 days covers it (the streak is kept, the month does not count, and the very next qualifying
// package counts as the next refuel)
// streak bonus purchased-grade credits on the site where bought, credit log labelled "Refuel streak":
// one engine m1 +10% m2 +15% m3 +20% m4+ +25%
// both m1 +15% m2 +20% m3 +30% m4+ +40% (+ a 100-credit Featured bonus on InstantAdPay at m4+, Marty 2026-10-24)
// both engines the other site's first qualifying package in the same cycle (any time before the next window)
// gets the both-rate, and the first site's bonus is topped up to the both-rate (difference only)
// stacking separate grants: Five Dollar Friday and Wired Wednesday still add their own on the same package
// Pit Stop a qualifying package between refuel days gets half the current streak rate, once per site per
// cycle; it is not a counted refuel
// badges 3, 6 and 12 months in a row: the InstantAdPay badge posts (one time each, like every badge)
// reminders 5 days before the refuel day, on the day, and a last call at the end of the grace: email +
// on-site notice from the site of the member's last counted refuel, from refuelReminderHour (CT)
// Refuel Day optional network bonus on the 1st of the month (refuelDayPromo, default OFF): +refuelDayPct
// on a counted refuel bought that day
// MASTER SWITCH: site setting refuelStreak (default '0'). Off: nothing is counted or granted, no reminders, the
// cards report { on:false } and stay hidden. Purchases made while it is off are never counted later.
//
// ONCE, EVERYWHERE: every purchase is decided inside a lock on the member (MySQL GET_LOCK across app copies) and
// stored by tx, so a repeat call returns the same decision. Every grant is an outbox row keyed by a unique ref
// (rf:<site>:<tx>, rftop:<site>:<tx>, rfpit:<site>:<tx>, rfday:<site>:<tx>, rffeat:<email>:<cycle>); the site
// that applies it claims 'rfg:<ref>' first (marks.js), so two copies of either app never double-grant.
'use strict';
const fs = require('fs');
const path = require('path');
let X = {}, FILE = null;
const TZ = 'America/Chicago';
const SITE = 'https://instantadpay.com';
const LS_SITE = 'https://linkspin.app';
const SINGLE = [10, 15, 20, 25];
const BOTH = [15, 20, 30, 40];
const CYCLE_DAYS = 30, EARLY_DAYS = 5, GRACE_DAYS = 5, FREE_MISS_DAYS = 365;
const BADGE_AT = [3, 6, 12];
const NAME = { iap: 'InstantAdPay', linkspin: 'LinkSpin' };
// ---- Central-time calendar days -----------------------------------------------------------------
const ctDay = ts => new Date(ts === undefined ? Date.now() : ts).toLocaleDateString('en-CA', { timeZone: TZ });
const ctHour = ts => Number(new Date(ts === undefined ? Date.now() : ts).toLocaleString('en-US', { timeZone: TZ, hour: 'numeric', hour12: false })) % 24;
const utcOf = day => { const [y, m, d] = String(day).split('-').map(Number); return Date.UTC(y, m - 1, d); };
const addDays = (day, n) => new Date(utcOf(day) + n * 86400000).toISOString().slice(0, 10);
const diffDays = (a, b) => Math.round((utcOf(b) - utcOf(a)) / 86400000); // b - a
const label = day => day ? new Date(utcOf(day) + 12 * 3600000).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' }) : null;
const rateSingle = k => SINGLE[Math.min(Math.max(k, 1), 4) - 1];
const rateBoth = k => BOTH[Math.min(Math.max(k, 1), 4) - 1];
const usd = c => ('$' + (Number(c || 0) / 100).toFixed(2)).replace(/\.00$/, '');
const money = n => Number(n || 0).toLocaleString('en-US');
const esc = s => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
function init(opts) { X = opts || {}; FILE = path.join(X.dataDir, 'refuel.json'); }
function cfg() {
const c = (X.siteConfig && X.siteConfig()) || {};
return {
on: String(c.refuelStreak == null ? '0' : c.refuelStreak) === '1',
reminders: String(c.refuelReminders == null ? '1' : c.refuelReminders) === '1',
reminderHour: Math.min(23, Math.max(0, Number(c.refuelReminderHour == null ? 9 : c.refuelReminderHour) || 0)),
dayPromo: String(c.refuelDayPromo == null ? '0' : c.refuelDayPromo) === '1',
dayPct: Math.max(0, Math.min(100, Number(c.refuelDayPct == null ? 10 : c.refuelDayPct) || 0)),
minIap: Math.max(0, Number(c.refuelMinIapCents) || 2000),
minLs: Math.max(0, Number(c.refuelMinLsCents) || 2500),
};
}
const minFor = (site, c) => site === 'linkspin' ? c.minLs : c.minIap;
const dbOn = () => !!(X.db && X.db.enabled && X.db.enabled());
// ---- storage: MySQL when there is one, else one JSON file (read and written synchronously, no await in between) ----
let tablesReady = null;
async function ensureTables() {
if (!dbOn()) return;
if (!tablesReady) tablesReady = (async () => {
await X.db.q('CREATE TABLE IF NOT EXISTS refuel_members (email VARCHAR(190) PRIMARY KEY, data MEDIUMTEXT NOT NULL, updated BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
await X.db.q("CREATE TABLE IF NOT EXISTS refuel_outbox (ref VARCHAR(160) PRIMARY KEY, site VARCHAR(12) NOT NULL, email VARCHAR(190) NOT NULL, kind VARCHAR(16) NOT NULL, payload TEXT NOT NULL, status VARCHAR(8) NOT NULL DEFAULT 'pending', created BIGINT NOT NULL, done BIGINT NULL, INDEX (site, status), INDEX (email)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
})().catch(e => { tablesReady = null; throw e; });
return tablesReady;
}
function readFile() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.members = s.members || {}; s.outbox = s.outbox || {}; return s; } catch (e) { return { members: {}, outbox: {} }; } }
function writeFile(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s)); fs.renameSync(tmp, FILE); }
async function getRec(email) {
if (dbOn()) { await ensureTables(); const r = await X.db.q('SELECT data FROM refuel_members WHERE email=?', [email]); return r.length ? JSON.parse(r[0].data) : null; }
return readFile().members[email] || null;
}
async function putRec(rec) {
if (dbOn()) { await ensureTables(); await X.db.q('INSERT INTO refuel_members (email, data, updated) VALUES (?,?,?) ON DUPLICATE KEY UPDATE data=VALUES(data), updated=VALUES(updated)', [rec.email, JSON.stringify(rec), Date.now()]); return; }
const s = readFile(); s.members[rec.email] = rec; writeFile(s);
}
async function allRecs() {
if (dbOn()) { await ensureTables(); return (await X.db.q('SELECT data FROM refuel_members')).map(r => JSON.parse(r.data)); }
return Object.values(readFile().members);
}
// an outbox row is added once per ref, whatever happens after
async function addOut(item) {
const row = { ref: item.ref, site: item.site, email: item.email, kind: item.kind, payload: item.payload, status: 'pending', created: Date.now(), done: null };
if (dbOn()) { await ensureTables(); await X.db.q('INSERT IGNORE INTO refuel_outbox (ref, site, email, kind, payload, status, created) VALUES (?,?,?,?,?,?,?)', [row.ref, row.site, row.email, row.kind, JSON.stringify(row.payload), 'pending', row.created]); return; }
const s = readFile(); if (!s.outbox[row.ref]) { s.outbox[row.ref] = row; writeFile(s); }
}
async function pendingOut(site, email, limit) {
if (dbOn()) {
await ensureTables();
const rows = email ? await X.db.q("SELECT * FROM refuel_outbox WHERE site=? AND status='pending' AND email=? ORDER BY created LIMIT ?", [site, email, limit || 200])
: await X.db.q("SELECT * FROM refuel_outbox WHERE site=? AND status='pending' ORDER BY created LIMIT ?", [site, limit || 200]);
return rows.map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind, payload: JSON.parse(r.payload), created: Number(r.created) }));
}
return Object.values(readFile().outbox).filter(r => r.site === site && r.status === 'pending' && (!email || r.email === email)).sort((a, b) => a.created - b.created).slice(0, limit || 200);
}
async function markDone(site, refs) {
refs = (refs || []).map(String).filter(Boolean).slice(0, 500); if (!refs.length) return 0;
if (dbOn()) { await ensureTables(); const r = await X.db.q("UPDATE refuel_outbox SET status='done', done=? WHERE site=? AND ref IN (?) AND status='pending'", [Date.now(), site, refs]); return r.affectedRows || 0; }
const s = readFile(); let n = 0; for (const ref of refs) { const r = s.outbox[ref]; if (r && r.site === site && r.status === 'pending') { r.status = 'done'; r.done = Date.now(); n++; } } writeFile(s); return n;
}
async function outRows(filter) {
if (dbOn()) { await ensureTables(); return (await X.db.q('SELECT ref, site, email, kind, payload, status, created, done FROM refuel_outbox ORDER BY created DESC LIMIT 2000')).map(r => Object.assign(r, { payload: JSON.parse(r.payload), created: Number(r.created) })).filter(filter || (() => true)); }
return Object.values(readFile().outbox).sort((a, b) => b.created - a.created).filter(filter || (() => true));
}
const lock = (email, fn) => X.db && X.db.withLock ? X.db.withLock('rf:' + email, fn, 15) : fn();
// ---- the record ---------------------------------------------------------------------------------
function blank(email) { return { v: 1, email, active: false, streak: 0, best: 0, firstDay: null, lastDay: null, dueDay: null, opensDay: null, graceEnd: null, home: null, cycle: null, history: [], misses: [], freeMissDay: null, txs: {}, badges: {} }; }
function archive(rec) { if (rec.cycle) { rec.history.unshift(rec.cycle); rec.history = rec.history.slice(0, 24); } rec.cycle = null; }
// walk the calendar forward to `today`: every grace that passed with no refuel is a miss
function settle(rec, today) {
let changed = false;
for (let guard = 0; rec.active && rec.graceEnd && today > rec.graceEnd && guard < 40; guard++) {
changed = true;
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, rec.graceEnd) >= FREE_MISS_DAYS;
if (freeOk) {
rec.misses.unshift({ day: rec.dueDay, free: true }); rec.freeMissDay = rec.graceEnd;
archive(rec);
rec.opensDay = addDays(rec.graceEnd, 1); // the very next qualifying package counts
rec.dueDay = addDays(rec.dueDay, CYCLE_DAYS); rec.graceEnd = addDays(rec.dueDay, GRACE_DAYS);
} else {
rec.misses.unshift({ day: rec.dueDay, free: false, streak: rec.streak });
archive(rec); rec.active = false; rec.streak = 0; rec.dueDay = rec.opensDay = rec.graceEnd = null;
}
rec.misses = rec.misses.slice(0, 24);
}
return changed;
}
function startCycle(rec, site, day, k) {
archive(rec);
rec.active = true; rec.streak = k; rec.best = Math.max(rec.best || 0, k);
rec.firstDay = rec.firstDay || day; rec.lastDay = day; rec.home = site;
rec.dueDay = addDays(day, CYCLE_DAYS); rec.opensDay = addDays(rec.dueDay, -EARLY_DAYS); rec.graceEnd = addDays(rec.dueDay, GRACE_DAYS);
rec.cycle = { n: k, startDay: day, sites: {}, pit: {}, both: false, featured: false };
}
const pctOf = (credits, pct) => Math.round((Number(credits) || 0) * pct / 100);
// classify one purchase and build its grants. Pure on (rec, purchase, config): the tests drive it directly.
function decide(rec, p, c) {
const day = ctDay(p.ts); const site = p.site; const other = site === 'iap' ? 'linkspin' : 'iap';
settle(rec, day);
const grants = [];
const g = (gs, kind, credits, note, extra) => { if (credits > 0) grants.push(Object.assign({ site: gs, kind, credits, note, ref: null }, extra || {})); };
let kind = 'none'; const firstEver = !rec.firstDay;
if (!rec.active || !rec.cycle || day >= rec.opensDay) {
// a counted refuel that opens a new cycle (first ever, after a reset, after a free miss, or in the window)
const k = rec.active ? rec.streak + 1 : 1;
startCycle(rec, site, day, k);
const pct = rateSingle(k), bonus = pctOf(p.credits, pct);
rec.cycle.sites[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus, day };
kind = 'refuel';
g(site, 'streak', bonus, 'Refuel streak month ' + k + ': +' + pct + '% on your ' + usd(p.cents) + ' package', { ref: 'rf:' + site + ':' + p.tx, pct, month: k });
} else if (!rec.cycle.sites[site]) {
// the second engine in the same cycle: both-rate here, and the first site topped up to it
const k = rec.cycle.n, pct = rateBoth(k), bonus = pctOf(p.credits, pct);
rec.cycle.sites[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus, day };
rec.cycle.both = true; kind = 'refuel';
g(site, 'streak', bonus, 'Refuel streak month ' + k + ', both engines: +' + pct + '% on your ' + usd(p.cents) + ' package', { ref: 'rf:' + site + ':' + p.tx, pct, month: k, both: true });
const o = rec.cycle.sites[other];
if (o) {
const owed = pctOf(o.credits, pct) - (o.bonus || 0);
if (owed > 0) { g(other, 'topup', owed, 'Twin Engine top-up: your month ' + k + ' refuel raised to +' + pct + '%', { ref: 'rftop:' + other + ':' + p.tx, pct, month: k }); o.bonus += owed; o.pct = pct; }
}
if (k >= 4 && !rec.cycle.featured) {
rec.cycle.featured = true;
const per = Math.max(0, Number(X.featuredBonus ? X.featuredBonus() : 100) || 100); // Marty 2026-10-24: 100 credits (was one day's Featured price, 40)
g('iap', 'featured', per, 'Twin Engine month ' + k + ': Featured bonus (' + per + ' credits)', { ref: 'rffeat:' + rec.email + ':' + rec.cycle.startDay, month: k });
}
} else if (!rec.cycle.pit[site]) {
const k = rec.cycle.n, cur = rec.cycle.both ? rateBoth(k) : rateSingle(k), pct = cur / 2;
rec.cycle.pit[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus: pctOf(p.credits, pct), day };
kind = 'pitstop';
g(site, 'pitstop', pctOf(p.credits, pct), 'Pit Stop: +' + pct + '% (half your +' + cur + '% streak rate) on your ' + usd(p.cents) + ' package', { ref: 'rfpit:' + site + ':' + p.tx, pct, month: k });
}
// the Refuel Kit: a counted refuel unlocks the kit of its Central-time month, remembered with the streak month it came at
if (kind === 'refuel') { rec.kits = rec.kits || {}; const m = day.slice(0, 7); if (!rec.kits[m]) rec.kits[m] = rec.cycle ? rec.cycle.n : 1; }
if (kind === 'refuel' && c.dayPromo && c.dayPct > 0 && day.slice(8) === '01') g(site, 'refuelday', pctOf(p.credits, c.dayPct), 'Refuel Day (the 1st): +' + c.dayPct + '% on your ' + usd(p.cents) + ' package', { ref: 'rfday:' + site + ':' + p.tx, pct: c.dayPct });
// badges: Engine Started at the first counted refuel ever (Marty 2026-10-24), then 3, 6 and 12 months in a row
const badges = [];
const opened = kind === 'refuel' && rec.cycle && rec.cycle.startDay === day && Object.keys(rec.cycle.sites).length === 1;
if (kind === 'refuel' && firstEver && !rec.badges.refuelStart) badges.push('refuelStart');
if (opened && BADGE_AT.includes(rec.streak) && !rec.badges['refuel' + rec.streak]) badges.push('refuel' + rec.streak);
for (const b of badges) rec.badges[b] = Date.now();
return { kind, day, month: rec.cycle ? rec.cycle.n : 0, grants, badges, both: !!(rec.cycle && rec.cycle.both) };
}
// ---- recording a purchase (both sites come through here) ------------------------------------------
async function record(p) {
const c = cfg(); if (!c.on) return { on: false };
const email = String(p.email || '').toLowerCase(); const site = p.site === 'linkspin' ? 'linkspin' : 'iap';
const tx = String(p.tx || ''); const cents = Number(p.cents) || 0; const credits = Number(p.credits) || 0;
if (!email || !tx) return { on: true, error: 'email and tx required' };
if (cents < minFor(site, c)) return { on: true, kind: 'below', minCents: minFor(site, c) };
const out = await lock(email, async () => {
const rec = (await getRec(email)) || blank(email);
if (rec.txs[tx]) return Object.assign({ repeat: true }, rec.txs[tx]);
const d = decide(rec, { site, tx, cents, credits, ts: Number(p.ts) || Date.now() }, c);
for (const gr of d.grants) {
const payload = { credits: gr.credits, note: gr.note, kind: gr.kind, pct: gr.pct || null, month: gr.month || null, cents, tx };
await addOut({ ref: gr.ref, site: gr.site, email, kind: 'grant', payload });
}
rec.txs[tx] = { kind: d.kind, site, day: d.day, month: d.month, both: d.both, refs: d.grants.map(x => x.ref), at: Date.now() };
const keys = Object.keys(rec.txs); if (keys.length > 400) for (const k of keys.slice(0, keys.length - 400)) delete rec.txs[k];
await putRec(rec);
return Object.assign({ badges: d.badges }, rec.txs[tx]);
});
if (!out.repeat && out.badges && X.badge) for (const b of out.badges) { try { await X.badge(email, b); } catch (e) { console.error('refuel badge', e.message); } }
// one short line in the payments feed for every counted refuel (never a Pit Stop), once per tx across app copies
if (!out.repeat && out.kind === 'refuel' && X.feed && (!X.marks || await X.marks.claim('rffeed:' + tx))) {
try { await X.feed(await feedLine(email, out)); } catch (e) { console.error('refuel feed', e.message); }
}
await drainLocal().catch(e => console.error('refuel drain', e.message));
if (out.kind && out.kind !== 'none') console.log('refuel:', site, out.kind, 'month', out.month, email.replace(/^(.).*(@.*)$/, '$1***$2'), String(tx).slice(0, 12));
return Object.assign({ on: true }, out);
}
async function whoOf(email) {
let a = null; try { a = await X.accounts.byEmail(email); } catch (e) {}
return a && a.username ? '@' + a.username : a && a.memberId ? 'member #' + a.memberId : 'a member';
}
async function feedLine(email, out) {
const who = (await whoOf(email)).replace(/[<>&]/g, '');
const what = out.both ? 'refueled both engines' : 'refueled ' + NAME[out.site];
return '⛽ <b>' + who + '</b> ' + what + ' · streak ' + out.month;
}
// Monday roundup of the week that just ended (Mon..Sun, Central), one per week across app copies
function weekOf(today) { const dow = new Date(utcOf(today)).getUTCDay(); const mon = addDays(today, -((dow + 6) % 7)); return { thisMon: mon, from: addDays(mon, -7), to: addDays(mon, -1) }; }
async function roundup(today) {
const w = weekOf(today); let members = 0, fresh = 0, longest = 0;
for (const r of await allRecs()) {
const hits = Object.values(r.txs || {}).filter(x => x.kind === 'refuel' && x.day >= w.from && x.day <= w.to);
if (hits.length) { members++; if (hits.some(x => x.month === 1)) fresh++; }
if (r.active) longest = Math.max(longest, r.streak || 0);
}
return { week: w, members, fresh, longest };
}
// an InstantAdPay chain Purchase: resolve the owner (main member or a linked position) and record it
async function onIapPurchase(ev) {
if (!ev || ev.type !== 'Purchase' || !cfg().on) return null;
let a = await X.accounts.byMemberId(ev.buyerId).catch(() => null);
if (!a && X.accounts.positionByMember) { const pos = await X.accounts.positionByMember(ev.buyerId).catch(() => null); if (pos && pos.email) a = await X.accounts.byEmail(pos.email).catch(() => null); }
if (!a || !a.email) return null;
return record({ site: 'iap', email: a.email, tx: ev.tx, cents: ev.priceCents, credits: ev.creditAmount, ts: ev.ts });
}
// ---- applying InstantAdPay's own outbox rows ---------------------------------------------------------
let draining = false;
async function drainLocal() {
if (draining) return 0; draining = true; let n = 0;
try {
for (const it of await pendingOut('iap', null, 200)) {
const mine = X.marks ? await X.marks.claim('rfg:' + it.ref) : true;
if (mine) {
if (it.kind === 'grant') {
await X.ads.addEarned(it.email, it.payload.credits, { purchased: true, log: { kind: 'bonus', note: it.payload.note, ref: it.ref.slice(0, 60) } });
try { await X.message(it.email, grantSubject(it.payload), grantHtml(it.payload, 'iap')); } catch (e) { console.error('refuel notice', e.message); }
} else if (it.kind === 'reminder') await sendReminder(it.email, it.payload, 'iap');
n++;
}
await markDone('iap', [it.ref]);
}
} finally { draining = false; }
return n;
}
function grantSubject(p) {
if (p.kind === 'topup') return 'Twin Engine top-up: +' + money(p.credits) + ' bonus credits';
if (p.kind === 'pitstop') return 'Pit Stop bonus: +' + money(p.credits) + ' credits';
if (p.kind === 'featured') return 'Twin Engine: +' + money(p.credits) + ' Featured bonus credits';
if (p.kind === 'refuelday') return 'Refuel Day bonus: +' + money(p.credits) + ' credits';
return 'Refuel counted: +' + money(p.credits) + ' bonus credits (month ' + (p.month || 1) + ')';
}
function grantHtml(p, site) {
const where = site === 'linkspin' ? 'Credits' : 'Campaigns';
return '<p>' + esc(p.note) + '. <b>' + money(p.credits) + ' bonus ad credits</b> were added to your ' + NAME[site] + ' balance, purchased-grade, so they run on any format, login ads included, and the credit log names them.</p>'
+ (p.kind === 'featured' ? '<p>Enough for two Featured days and more: book Featured links under Campaigns whenever you like, or spend them on any format.</p>' : '')
+ (p.kind === 'pitstop' ? '<p>A Pit Stop keeps an ad running between refuel days. It does not count as your monthly refuel: that is still due on your refuel day.</p>' : '')
+ '<p>See your refuel day and streak on the Refuel card (' + where + '). Bonus credits buy ad delivery only; they are never cash.</p>';
}
// ---- the LinkSpin side of the outbox --------------------------------------------------------------
async function outbox(site, email) { return pendingOut(site === 'linkspin' ? 'linkspin' : 'iap', email ? String(email).toLowerCase() : null, 200); }
async function ack(site, refs) { return markDone(site === 'linkspin' ? 'linkspin' : 'iap', refs); }
// ---- reminders ---------------------------------------------------------------------------------------
function reminderCopy(rec, kind) {
const k = rec.streak, next = k + 1, sOne = rateSingle(next), sBoth = rateBoth(next);
const due = label(rec.dueDay), grace = label(rec.graceEnd);
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, rec.graceEnd) >= FREE_MISS_DAYS;
const offer = 'A $20+ package on InstantAdPay or $25+ on LinkSpin counts. Your next refuel earns +' + sOne + '% bonus ad credits, or +' + sBoth + '% on each site when you refuel both in the same cycle.';
if (kind === 'soon') return { subject: 'Your refuel day is ' + due, text: 'Your refuel day is ' + due + ' (Central time), and your window is open from today. ' + offer + ' Keep your ' + k + '-month streak by ' + grace + ', the end of your 5-day grace.' };
if (kind === 'day') return { subject: 'Today is your refuel day', text: 'Today is your refuel day. ' + offer + ' You have until ' + grace + ' (Central time) to keep your ' + k + '-month streak.' };
return { subject: 'Last call: your refuel grace ends tonight', text: 'Today is the last day of your 5-day grace. Refuel before midnight Central to keep your ' + k + '-month streak. ' + offer
+ (freeOk ? ' If you skip it, your one free miss this year keeps the streak, and your next package counts as the refuel.' : ' Your free miss for this year is already used, so after tonight the streak starts again from month 1.') };
}
async function sendReminder(email, payload, site) {
const host = site === 'linkspin' ? LS_SITE + '/credits' : SITE + '/my#buy';
const text = payload.text + '\n\nBuy a package: ' + host;
const html = '<p>' + esc(payload.text) + '</p><p><a href="' + host + '">Buy a package</a></p><p style="color:#556">Bonus credits buy ad delivery only; they are never cash.</p>';
try { await X.message(email, payload.subject, html); } catch (e) { console.error('refuel reminder inbox', e.message); }
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(email).catch(() => false) : false;
if (!stopped && X.mailer && X.mailer.hasKey()) {
const foot = X.drip && X.drip.unsubUrl ? '\n\nStop these emails: ' + X.drip.unsubUrl(email) : '';
try { await X.mailer.send(email, payload.subject, text + foot + '\n\nInstantAdPay'); } catch (e) { console.error('refuel reminder mail', e.message); }
}
}
// the daily pass: settle misses, queue the reminders that came due today, apply our outbox
let ticking = false;
async function tick(now) {
const c = cfg(); if (!c.on || ticking) return { on: c.on };
ticking = true; let reminders = 0, settled = 0;
try {
const t = now || Date.now(); const today = ctDay(t); const hourOk = ctHour(t) >= c.reminderHour;
for (const r0 of await allRecs()) {
if (!r0.active) continue;
const res = await lock(r0.email, async () => {
const rec = await getRec(r0.email); if (!rec) return null;
if (settle(rec, today)) { await putRec(rec); settled++; }
if (!rec.active || !c.reminders || !hourOk) return null;
const kind = today === addDays(rec.dueDay, -EARLY_DAYS) ? 'soon' : today === rec.dueDay ? 'day' : today === rec.graceEnd ? 'last' : null;
if (!kind) return null;
if (rec.cycle && rec.cycle.startDay >= rec.opensDay) return null; // already refueled in this window
const ref = 'rfrem:' + rec.email + ':' + rec.dueDay + ':' + kind;
await addOut({ ref, site: rec.home === 'linkspin' ? 'linkspin' : 'iap', email: rec.email, kind: 'reminder', payload: Object.assign({ remind: kind, dueDay: rec.dueDay, graceEnd: rec.graceEnd, streak: rec.streak }, reminderCopy(rec, kind)) });
return kind;
});
if (res) reminders++;
}
await drainLocal();
// Monday after the reminder hour: last week's roundup to the payments feed (skipped when nobody refueled)
if (X.feed && new Date(utcOf(today)).getUTCDay() === 1 && ctHour(t) >= Math.max(9, c.reminderHour)) {
const ru = await roundup(today);
if (ru.members > 0 && (!X.marks || await X.marks.claim('rfweek:' + ru.week.thisMon))) {
try { await X.feed('⛽ <b>Refueled this week:</b> ' + ru.members + ' member' + (ru.members === 1 ? '' : 's') + ', ' + ru.fresh + ' new streak' + (ru.fresh === 1 ? '' : 's') + ', longest streak ' + ru.longest); } catch (e) { console.error('refuel roundup', e.message); }
}
}
} finally { ticking = false; }
return { on: true, settled, reminders };
}
// ---- what the member sees ----------------------------------------------------------------------------
async function view(email, now) {
const c = cfg(); if (!c.on) return { on: false };
email = String(email || '').toLowerCase();
const rec0 = await getRec(email); const today = ctDay(now || Date.now());
const rec = rec0 ? JSON.parse(JSON.stringify(rec0)) : blank(email);
settle(rec, today); // read-only copy: a passed grace shows as it will be stored on the next tick
const k = rec.active ? rec.streak : 0, next = k + 1;
const cy = rec.cycle;
const curRate = cy ? (cy.both ? rateBoth(cy.n) : rateSingle(cy.n)) : 0;
const windowOpen = !rec.active || !cy || today >= rec.opensDay;
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, today) >= FREE_MISS_DAYS;
const siteState = s => cy && cy.sites[s] ? { refueled: true, credits: cy.sites[s].credits, pct: cy.sites[s].pct, bonus: cy.sites[s].bonus, day: cy.sites[s].day, dayLabel: label(cy.sites[s].day) } : { refueled: false };
return {
on: true, started: !!rec.firstDay, engineUnlocked: !!rec.firstDay, active: rec.active, streak: k, best: rec.best || 0,
firstDay: rec.firstDay, lastDay: rec.lastDay, refuelDay: rec.dueDay, refuelDayLabel: label(rec.dueDay), opensDay: rec.opensDay, opensLabel: label(rec.opensDay),
graceEnd: rec.graceEnd, graceLabel: label(rec.graceEnd), today, daysToRefuel: rec.dueDay ? diffDays(today, rec.dueDay) : null, windowOpen,
cycle: cy ? { month: cy.n, startDay: cy.startDay, both: !!cy.both, iap: siteState('iap'), linkspin: siteState('linkspin'), rate: curRate } : null,
next: windowOpen ? { month: next, single: rateSingle(next), both: rateBoth(next) } : { month: cy.n, secondEngine: rateBoth(cy.n) },
pitStop: cy && !windowOpen ? { pct: curRate / 2, iap: !cy.pit.iap && !!cy.sites.iap, linkspin: !cy.pit.linkspin && !!cy.sites.linkspin, usedIap: !!cy.pit.iap, usedLinkspin: !!cy.pit.linkspin } : null,
freeMiss: { available: freeOk, usedDay: rec.freeMissDay }, misses: rec.misses.slice(0, 6), badges: Object.keys(rec.badges || {}),
kits: rec.kits || {}, goal: rec.engineGoal || null,
minUsd: { iap: c.minIap / 100, linkspin: c.minLs / 100 }, ladder: { single: SINGLE, both: BOTH }, refuelDay1: c.dayPromo ? c.dayPct : 0,
};
}
// the line the refill notices add to their bonus block
async function streakLine(email) {
const v = await view(email).catch(() => null);
if (!v || !v.on) return null;
let t;
if (!v.active) t = 'Refuel streak: a $20+ package on InstantAdPay (or $25+ on LinkSpin) starts your monthly refuel streak with +10% bonus ad credits, +15% on each site when you refuel both.';
else if (v.windowOpen) t = 'Refuel streak: you are on ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') + ', and your refuel window is open now (refuel day ' + v.refuelDayLabel + ', grace to ' + v.graceLabel + ', Central time). Refuel now for +' + v.next.single + '%, or +' + v.next.both + '% on each site with both.';
else t = 'Refuel streak: month ' + v.streak + ', next refuel day ' + v.refuelDayLabel + ' (Central time).' + (v.pitStop && (v.pitStop.iap || v.pitStop.linkspin) ? ' A top-up before then earns a Pit Stop bonus of +' + v.pitStop.pct + '% (once per site this cycle).' : '');
return { text: t, html: '<b>Refuel streak:</b> ' + esc(t.replace(/^Refuel streak: /, '')) };
}
// the member's own monthly goal for the Engine Room's goals dial (conversions from the pixel); 0 clears it
async function setGoal(email, goal) {
if (!cfg().on) return { error: 'The Engine Room is not switched on.' };
email = String(email || '').toLowerCase(); const g = Math.max(0, Math.min(100000, Math.round(Number(goal) || 0)));
return lock(email, async () => { const rec = (await getRec(email)) || blank(email); rec.engineGoal = g || null; await putRec(rec); return { ok: true, goal: rec.engineGoal }; });
}
function badgesOf(email) { return getRec(String(email || '').toLowerCase()).then(r => (r && cfg().on) ? Object.keys(r.badges || {}) : []).catch(() => []); }
// ---- admin ------------------------------------------------------------------------------------------
async function stats() {
const c = cfg(); const recs = await allRecs(); const rows = await outRows();
const by = {}; for (const r of rows) { const k = r.kind === 'grant' ? r.payload.kind : 'reminder'; const b = by[k] || (by[k] = { n: 0, credits: 0, pending: 0 }); b.n++; b.credits += Number(r.payload.credits) || 0; if (r.status === 'pending') b.pending++; }
return { settings: c, members: recs.length, active: recs.filter(r => r.active).length, both: recs.filter(r => r.cycle && r.cycle.both).length,
byMonth: recs.filter(r => r.active).reduce((m, r) => { const k = Math.min(r.streak, 12); m[k] = (m[k] || 0) + 1; return m; }, {}),
grants: by, pending: rows.filter(r => r.status === 'pending').length,
recent: rows.slice(0, 40).map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind === 'grant' ? r.payload.kind : 'reminder:' + r.payload.remind, credits: r.payload.credits || 0, status: r.status, at: r.created })) };
}
module.exports = { setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
_days: { ctDay, addDays, diffDays, label, ctHour }, SINGLE, BOTH };
+356 -49
View File
@@ -73,6 +73,9 @@ const starter = require('./starter'); // member welcome offer from the games (20
const wednesday = require('./wednesday'); // Wired Wednesday: +25% on $10+ packs, wired into a visits campaign (2026-09-29)
const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked Sat-Thu by solo + video (2026-09-26)
const refill = require('./refill');
const refuel = require('./refuel');
const kit = require('./kit');
const engine = require('./engine'); // the Engine Room: dials, warning lights, part lights, next move across both sites (Fuel Your Offers stage 4, 2026-10-24) // the Refuel Kit: monthly members-only banner sets, personalized per member (Fuel Your Offers stage 3, 2026-10-24) // the Monthly Refuel streak, one per member across InstantAdPay + LinkSpin (Fuel Your Offers, 2026-10-24); switch refuelStreak, default off
const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20)
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
@@ -82,7 +85,7 @@ const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings wit
const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16)
const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15)
const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12)
const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/presentation', '/support']);
const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation', '/support']);
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
@@ -421,7 +424,7 @@ function serveJoinPage(res, tok, angle, ang, setCookies) {
// Network Ad Space zone on the two legacy squeeze pages only (Marty, 2026-09-19): below the
// fine print, above the footer links. The regular join pages stay ad-free.
if (/^(fw|t1)-(adv|earn)$/.test(String(angle || ''))) html = html.replace('<div class="jn-foot">',
'<div class="jn-nas" style="max-width:728px;margin:34px auto 0;overflow:hidden;text-align:center"><!-- nas-legacy --><script src="https://www.networkadspace.com/showadss.php?w=728&h=90&n=1&bw=728&bh=90&c=999"></script></div>' + '<div class="jn-foot">');
'<div class="jn-nas" style="max-width:728px;margin:34px auto 0;overflow:hidden;text-align:center"><!-- nas-legacy --><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 class="jn-foot">');
const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, must-revalidate' };
if (setCookies && setCookies.length) headers['Set-Cookie'] = setCookies;
res.writeHead(200, baseHeaders(headers));
@@ -519,6 +522,7 @@ async function boot() {
marks.init({ db });
marks.ensureTable().catch(e => console.error('marks table', e.message));
lsconv.init({ db, dataDir: DATA_DIR });
auth.onSeen((email, req) => lsconv.noteSession(email, clientIp(req), req.headers['user-agent'])); // own-click tests on LinkSpin (2026-10-26)
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
chain.init({ onEvent: ev => {
// the in-memory feed is per instance and always runs
@@ -536,6 +540,7 @@ async function boot() {
Promise.all([friday.onEvent(ev).catch(e => { console.error('friday bonus', e.message); return null; }), gamepass.onEvent(ev).catch(e => { console.error('gamepass order', e.message); return null; })])
.then(([bonus, gp]) => fridayPassPerk(ev, bonus, gp)).catch(e => console.error('friday pass perk', e.message));
wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message));
refuel.onIapPurchase(ev).catch(e => console.error('refuel streak', e.message)); // its own bonus, stacked on Friday/Wednesday; no-op while refuelStreak is off
sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message));
}).catch(e => console.error('marks claim', e.message));
} });
@@ -546,7 +551,7 @@ async function boot() {
messages.init({ dataDir: DATA_DIR });
reports.init({ dataDir: DATA_DIR });
drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: 'https://instantadpay.com' });
chatbot.init({ dataDir: DATA_DIR, chain, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; } }); // pass tiers fact follows sovTiers (2026-10-22)
chatbot.init({ dataDir: DATA_DIR, chain, gameLive: slug => String(siteConfig().gamesLive == null ? 'polhunter' : siteConfig().gamesLive).split(',').map(x => x.trim().toLowerCase()).includes(slug), refuelOn: () => refuel.cfg().on, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; } }); // pass tiers fact follows sovTiers (2026-10-22)
setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000);
setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000);
setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends
@@ -555,11 +560,11 @@ async function boot() {
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
translate.init({ dataDir: DATA_DIR });
tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram, translate });
inbound.init({ tickets });
inbound.init({ tickets, accounts });
supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' });
badge.init({ publicDir: PUBLIC_DIR });
gamestats.init({ dataDir: DATA_DIR });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, publicDir: PUBLIC_DIR, games: gamestats, launchesToday: () => GAMES().filter(g => (g.soon && g.soon.opens === todayCT()) || (g.season && g.season.start === todayCT())).map(g => g.name),
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, publicDir: PUBLIC_DIR, games: gamestats, launchesToday: () => GAMES().filter(g => (g.soon && g.soon.opens === todayCT()) || (g.season && g.season.start === todayCT() && String(siteConfig().gamesLive == null ? 'polhunter' : siteConfig().gamesLive).split(',').map(x => x.trim().toLowerCase()).includes(g.slug))).map(g => g.name),
send: async (c, t, th) => { await telegramSend(c, t, th); return true; },
sendPhoto: (c, jpeg, cap, th) => telegramSendPhoto(c, jpeg, cap, th) });
fridaybank.init({ db });
@@ -570,7 +575,7 @@ async function boot() {
// Campaign refill notices: an advertiser is told when an ad is nearly out and when it has stopped,
// with the bonus ladder in the same message, and every send is watched for what they did next.
refill.init({
dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip,
dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, streakLine: email => refuel.streakLine(email),
creditsFor: async email => { const v = await adminMember.view(email); return (v && v.credits && v.credits.available) || 0; },
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
});
@@ -593,6 +598,18 @@ async function boot() {
console.log('login line: #' + c.id + ' started for ' + owner.replace(/^(.).*(@.*)$/, '$1***$2'));
});
setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login line', e.message)), 60 * 1000); // safety net: a slot that expired between changes
// the Monthly Refuel streak (refuel.js): source of truth for both sites; LinkSpin reports purchases and collects its grants
// through /api/partner/refuel/*. Feed lines go to the payments topic like other InstantAdPay feed lines.
refuel.init({ dataDir: DATA_DIR, db, marks, siteConfig, accounts, ads, mailer, drip,
featuredPerDay: () => ads.rates().featuredPerDay || 40,
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
badge: (email, key) => postBadgeOnce(email, key, 'Monthly Refuel'),
feed: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + text, sc.telegramEchoTopicId); } });
kit.init({ dataDir: DATA_DIR, program: 'iap', publicDir: PUBLIC_DIR, siteUrl: 'https://instantadpay.com',
entitled: async email => { const v = await refuel.view(email); return v && v.on ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel || null, today: v.today || null } : { on: false }; },
linkFor: async email => { const a = await accounts.byEmail(email); if (!a) return null; const tok = a.username || a.code; return tok ? { username: a.username || null, link: 'https://instantadpay.com/join/' + tok } : null; } });
setTimeout(() => refuel.tick().catch(e => console.error('refuel', e.message)), 120000);
setInterval(() => refuel.tick().catch(e => console.error('refuel', e.message)), 10 * 60 * 1000);
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000);
setInterval(() => friday.tick().catch(e => console.error('friday', e.message)), 5 * 60 * 1000);
@@ -617,14 +634,22 @@ async function boot() {
sponsorAccount: em => accounts.byEmail(em),
wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; },
activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null });
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore });
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore,
// activation hold + 24-hour safety net (2026-10-27): a tank member is never bound under the fallback position
hooks: { network: (email, address) => lsinbound.networkSponsor(email, address), isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text),
// switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap),
// the sponsor's nudge as an in-app notice (never a pop-up broadcast), stop once the wallet is on chain
claim: key => marks.claim(key), activated: a => !!(a && a.address && activationByAddress().get(String(a.address).toLowerCase())),
notify: async (email, subject, text) => { const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); } } });
// LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest
lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email));
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
walletnudge.init({ dataDir: DATA_DIR, accounts, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com',
walletnudge.init({ dataDir: DATA_DIR, accounts, chain, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com',
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); } });
setTimeout(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 3 * 60 * 1000); // past the deploy overlap window
setInterval(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 60 * 60 * 1000);
@@ -695,6 +720,8 @@ async function boot() {
setInterval(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 60 * 60 * 1000);
console.log('blog syndication:', syndicate.enabled() ? 'on (X + Instagram via Blotato)' : 'off (no blotato.key)');
setInterval(() => tankNotifyTick().catch(e => console.error('tank notify', e.message)), 15 * 60 * 1000); // new tank arrivals -> Telegram
setTimeout(() => tankReadyTick().catch(e => console.error('tank ready', e.message)), 2 * 60 * 1000); // after the LinkSpin inbound state is loaded
setInterval(() => tankReadyTick().catch(e => console.error('tank ready', e.message)), 15 * 60 * 1000); // align / 24-hour hold / safety net
geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message));
setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily
setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window
@@ -718,7 +745,7 @@ async function boot() {
// Game Pass partner helpers (2026-10-16): which secret signs for which game, signature compare, member resolution, dev clock
const GP_SECRETS = () => ({ polhunter: String(process.env.HUNT_SSO_SECRET || '').trim(), gemkingdom: GK_SECRET(), spellwheel: SW_SECRET(), spookydoors: SD_SECRET(), polywarriors: PW_SECRET(),
clutterhunt: SEEK_SECRET(), polybreak: PB_SECRET(), driprunner: DR_SECRET(), roadagent: RA_SECRET(), shardsofvalor: SOV_SECRET() });
clutterhunt: SEEK_SECRET(), polybreak: PB_SECRET(), polminer: PM_SECRET(), turkeydrop: TD_SECRET(), driprunner: DR_SECRET(), roadagent: RA_SECRET(), shardsofvalor: SOV_SECRET() });
function gpPartnerCheck(game) { if (!gamepass.GAMES.includes(game)) return { error: 'unknown game', code: 400 }; const secret = GP_SECRETS()[game] || ''; if (secret.length < 32) return { error: game + ' is not connected', code: 503 }; return { secret }; }
const gpSigOk = (want, got) => typeof got === 'string' && want.length === got.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got));
async function gpResolve(memberId, email) { // the account behind a game's player: main member id, a linked position's id, or (no wallet yet) the email
@@ -755,6 +782,10 @@ function siteConfig() {
fridayBonusPct: '20', // bonus credits on any $5+ package bought on a Friday, Central
fridayStart: '2026-09-25', // the first Five Dollar Friday
wednesdayPromo: '1', wednesdayBonusPct: '25', wednesdayMinCents: '2000', wednesdayStart: '2026-09-30', // Wired Wednesday (Marty, 2026-09-29)
refuelStreak: '0', // the Monthly Refuel streak master switch (Fuel Your Offers, 2026-10-24): '0' = nothing counted or granted, no reminders, cards hidden
refuelReminders: '1', refuelReminderHour: '9', // refuel reminders (email + on-site notice) 5 days before, on the day, last call; Central hour
refuelDayPromo: '0', refuelDayPct: '10', // optional network Refuel Day bonus on the 1st of each month (Central), off by default
refuelMinIapCents: '2000', refuelMinLsCents: '2500', // what counts as a refuel: $20+ on InstantAdPay, $25+ on LinkSpin
wednesdayNotice: '0', wednesdayKick: '0', // the Tuesday email/notice and the Wednesday Telegram kickoff stay off until Marty approves the copy
launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark
aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation
@@ -769,14 +800,15 @@ function siteConfig() {
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
// Game Pass (2026-10-16, docs/GAME-PASS.md): off until Marty flips it; caps apply from capsStartDate (Central), before it polgrant allows everything and only records
gamePassEnabled: '0', gamePassPriceCredits: 500, gamePassDays: 7, capFreeDaily: 0.30, capFreeTotal: 2.0, capPassDaily: 1.50, capPassTotal: 5.0, capsStartDate: '', passTournamentPct: 5,
// Explorer ($20) and Champion ($40) monthly passes beside the weekly one (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md): islands and looks
// Explorer and Champion monthly passes beside the weekly one (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md): islands and looks
// in Shards of Valor, never power, never more POL (same caps as the weekly pass). sovTiers = the sale switch for both (off: only ADMIN_EMAIL
// sees and can buy them, for testing; holders keep their pass). gamePass<Tier>Enabled '0' stops one tier alone. passTournamentTierSales '1'
// would add their sales to the Pass Tournament pool (off = the pool exactly as before).
// 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 / Champion $39.99 for 30 days, plus Sovereign $99.99 for 30 days and
// Legend $249.99 for 365 days (the yearly pass), all behind sovTiers. Names, perks and the rank live in gamepass.js TIER_DEFS.
sovTiers: '0', gamePassExplorerEnabled: '1', gamePassExplorerPriceCredits: 1999, gamePassExplorerDays: 30, gamePassChampionEnabled: '1', gamePassChampionPriceCredits: 3999, gamePassChampionDays: 30,
gamePassSovereignEnabled: '1', gamePassSovereignPriceCredits: 9999, gamePassSovereignDays: 30, gamePassLegendEnabled: '1', gamePassLegendPriceCredits: 24999, gamePassLegendDays: 365, passTournamentTierSales: '0',
// 2026-10-25 (Marty): prices = the one-click packages: Explorer $20, Champion $50, Sovereign $100, Legend $250 (cents below).
sovTiers: '0', gamePassExplorerEnabled: '1', gamePassExplorerPriceCredits: 2000, gamePassExplorerDays: 30, gamePassChampionEnabled: '1', gamePassChampionPriceCredits: 5000, gamePassChampionDays: 30,
gamePassSovereignEnabled: '1', gamePassSovereignPriceCredits: 10000, gamePassSovereignDays: 30, gamePassLegendEnabled: '1', gamePassLegendPriceCredits: 25000, gamePassLegendDays: 365, passTournamentTierSales: '0',
supportTelegramChat: '1289244227', // help desk pings: Marty's PRIVATE chat only (a positive user id; group/channel ids are refused). Sent with telegramBotToken, Hermes bot as fallback
supportTemplates: '', // help desk saved replies, JSON [{name, body}] (Admin > Support > Saved replies); empty = the built-in set
telegramGamesChatId: '', telegramGamesTopicId: '661565', // Game Achievements topic for the weekly Pass Tournament post (chat blank = the shared echo chat)
@@ -793,7 +825,7 @@ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': '
'.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp',
'.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2',
'.gif': 'image/gif', '.webm': 'video/webm', '.vtt': 'text/vtt; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com https://linkspin.app; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
function baseHeaders(extra) {
return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {});
@@ -1095,6 +1127,10 @@ const supportGlobal = { minute: 0, n: 0 };
const supportRecent = (k, ms) => { const now = Date.now(); const t = (supportHits.get(k) || []).filter(ts => now - ts < 86400000); supportHits.set(k, t); return t.filter(ts => now - ts < ms).length; };
const supportMark = k => { const t = supportHits.get(k) || []; t.push(Date.now()); supportHits.set(k, t); if (supportHits.size > 5000) for (const [kk, v] of supportHits) if (!v.length || Date.now() - v[v.length - 1] > 86400000) supportHits.delete(kk); };
const supportFlood = (k, n, ms) => { if (supportRecent(k, ms) >= n) return true; supportMark(k); return false; }; // signed-in and private-link replies: a plain cap
// tickets are open to platform members only (Marty, 2026-10-24, after a throwaway-address 'pentest' ticket):
// a signed-out sender's email must belong to an account on this site
const MEMBER_ONLY_TICKET_MSG = "Support tickets are for InstantAdPay members. Use the email on your InstantAdPay account, or sign in first. Not a member yet? Join free at https://instantadpay.com/join and ask from inside.";
async function memberOnlyTicket(email) { try { return (await accounts.byEmail(email)) ? null : { status: 403, body: { error: MEMBER_ONLY_TICKET_MSG, membersOnly: true } }; } catch (e) { return null; } }
function supportGuard(req, b, email) {
const now = Date.now();
const hpRaw = String(b.hp_field_x9 || '').trim();
@@ -1122,6 +1158,14 @@ function supportGuard(req, b, email) {
supportGlobal.n += 1; supportMark('ip:' + ip); supportMark('em:' + email);
return null;
}
// LinkSpin's Engine Room facts for one member (signed /api/partner/engine), cached a minute; null when LinkSpin does not answer
const lsEngineCache = new Map();
async function engineFromLinkSpin(email, fresh) {
const hit = lsEngineCache.get(email); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.v;
let v = null; try { const r = await SF.peerPost(LS_BASE(), '/api/partner/engine', { email }, 6000); v = r && r.facts ? r.facts : null; } catch (e) { v = null; }
lsEngineCache.set(email, { at: Date.now(), v }); if (lsEngineCache.size > 2000) lsEngineCache.delete(lsEngineCache.keys().next().value);
return v;
}
// LinkSpin partner calls (registry rows, help desk): one secret both ways, LS_SYNC_SECRET, as X-LS-Ts (ms) + X-LS-Sig =
// hex HMAC-SHA256(ts + newline + raw body), 10-minute window. Resolves { body } or { status, error }.
async function readLsSigned(req, maxBytes) {
@@ -1431,6 +1475,43 @@ async function tankNotifyTick() {
+ '\nAdopt from My line \u203a Holding tank: <a href="https://instantadpay.com/my#line">instantadpay.com/my</a>';
await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId);
}
// a holding-tank pickup: the live feed + one line in the shared payments topic (manual adoptions since 2026-09-12;
// the 24-hour safety net says "(auto-assigned)", 2026-10-27)
function tankPickupPost(adopterName, adopteeName, auto) {
pushFeed({ type: 'Adopted', sponsor: adopterName, member: adopteeName, ts: Date.now() });
try {
const sc = siteConfig();
const clean = t => String(t || '').replace(/[<>&]/g, '');
if (sc.telegramBotToken && sc.telegramEchoChatId)
telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>InstantAdPay</b> \u00b7 <b>' + clean(adopterName) + '</b> picked up <b>' + clean(adopteeName) + '</b> from the holding tank and is now their sponsor' + (auto ? ' (auto-assigned)' : ''), sc.telegramEchoTopicId).catch(() => {});
} catch (e) {}
}
// admin-only channels (never a member-visible topic: it names an email), the same order as the video-sweep alerts
async function tankAdminAlert(text) {
const sc = siteConfig(); const hermes = String(process.env.HERMES_BOT_TOKEN || '').trim();
const html = String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
if (hermes && sc.telegramAdminChatId) return tgSendAs(hermes, sc.telegramAdminChatId, html);
if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, html);
if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'InstantAdPay: holding tank needs an adopter', text);
console.log('tank: no admin channel configured, alert not sent:', text);
}
// holding tank every 15 min (2026-10-27): align members the network already knows, start the 24-hour clock for anyone
// who linked a wallet, run the safety net, and tell the shared payments topic once per member who became ready
async function tankReadyTick() {
const r = await tank.readyTick();
if (r.aligned || r.assigned.length || r.held || r.fresh.length || (r.reminders || []).length) console.log('tank ready tick', JSON.stringify({ fresh: r.fresh.length, aligned: r.aligned, assigned: r.assigned.length, held: r.held, payReminders: (r.reminders || []).map(x => x.stage) }));
const sc = siteConfig();
if (!r.fresh.length || !sc.telegramBotToken || !sc.telegramEchoChatId) return r;
const clean = t => String(t || '').replace(/[<>&]/g, '');
const link = 'https://instantadpay.com/my#line';
if (r.fresh.length <= 3) {
for (const w of r.fresh) await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} ' + (w.username ? '@' + clean(w.username) : 'A new member') + ' linked a wallet and is ready to switch on payouts. Adopt them from the holding tank in the next 24 hours: ' + link, sc.telegramEchoTopicId).catch(() => {});
} else { // first run after deploy (the members already linked) or a busy quarter hour: one digest, not a wall of posts
const named = r.fresh.filter(w => w.username).map(w => '@' + clean(w.username));
await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} ' + r.fresh.length + ' members linked a wallet and are ready to switch on payouts' + (named.length ? ': ' + named.slice(0, 12).join(', ') + (named.length > 12 ? ' and ' + (named.length - 12) + ' more' : '') : '') + '. Adopt them from the holding tank in the next 24 hours: ' + link, sc.telegramEchoTopicId).catch(() => {});
}
return r;
}
// one sendMessage call; never throws, never logs the token
async function telegramSend(chatId, text, threadId) {
const sc = siteConfig();
@@ -1469,7 +1550,8 @@ async function telegramSendPhoto(chatId, jpeg, caption, threadId) {
rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body);
});
}
const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'], fridays: ['Five Fridays', 'five Five Dollar Fridays in a row'], gamepass: ['Game Pass', 'Game Pass holder'] };
const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'], fridays: ['Five Fridays', 'five Five Dollar Fridays in a row'], gamepass: ['Game Pass', 'Game Pass holder'],
refuelStart: ['Engine Started', 'first monthly refuel'], refuel3: ['Refueled 3 months', 'three monthly refuels in a row'], refuel6: ['Refueled 6 months', 'six monthly refuels in a row'], refuel12: ['Refueled 12 months', 'twelve monthly refuels in a row'] };
const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
// Post a member's badge to the payments topic + General ONCE ever (the same card and caption as an unlock). Used by the
@@ -1508,7 +1590,7 @@ async function fridayPassPerk(ev, bonus, gp) {
console.log('friday pass perk', a.email, day, 'until', new Date(r.until).toISOString());
try {
const until = new Date(r.until).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Five Dollar Friday: a free Game Pass week', '<p>Your Friday package came with a free 7-day Game Pass, on top of the Friday bonus credits. It runs until ' + until + ' Central, across all nine games.</p>', 'notice');
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Five Dollar Friday: a free Game Pass week', '<p>Your Friday package came with a free 7-day Game Pass, on top of the Friday bonus credits. It runs until ' + until + ' Central, across all the games.</p>', 'notice');
} catch (e) { console.error('friday pass notice', e.message); }
try { await postBadgeOnce(a.email, 'gamepass', 'Five Dollar Friday'); } catch (e) { console.error('friday pass badge', e.message); }
return r;
@@ -1642,6 +1724,51 @@ async function pbCallback(cbUrl, receipt) {
if (!pbIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polybreak callback', e.message); return false; }
}
// -- POL Miner (2026-10-28): the dig-down mining game; its own secret POLMINER_SSO_SECRET (also on the game), same shape as PolyBreak.
// Members see nothing until 'polminer' is in site config gamesLive (Games card, strip); the hand-off, in-game sign-in and supply
// crates work as soon as the secret is set, so testers can play behind the game's own staging gate.
const PM_SECRET = () => String(process.env.POLMINER_SSO_SECRET || '').trim();
const PM_URL = () => String(process.env.POLMINER_URL || 'https://polminer.com').replace(/\/+$/, '');
const PM_ALT = () => String(process.env.POLMINER_ALT_URLS || 'https://www.polminer.com,https://polminer.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const pmSign = p => drB64u(crypto.createHmac('sha256', PM_SECRET()).update(p).digest());
function pmMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pmSign(payload); }
function pmOpen(token) {
if (PM_SECRET().length < 32) return { error: 'POL Miner is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = pmSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Go back to POL Miner and tap the supply crate again.' };
return { ok: true, claims: c };
}
const pmIsGameUrl = u => [PM_URL()].concat(PM_ALT()).some(o => String(u || '').startsWith(o + '/'));
async function pmCallback(cbUrl, receipt) {
if (!pmIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polminer callback', e.message); return false; }
}
// -- Turkey Drop (2026-10-28): the Thanksgiving season game (catch the turkeys from the WFWL 98.7 helicopter); its own secret
// TD_SSO_SECRET (also on the game), the same protocol as POL Miner. Members see nothing until 'turkeydrop' is in site config
// gamesLive (Games card, strip, games page, promo tools, Game Pass perk, chatbot), and its season window is TD_SEASON.
const TD_SECRET = () => String(process.env.TD_SSO_SECRET || '').trim();
const TD_URL = () => String(process.env.TD_URL || 'https://turkeydropgame.com').replace(/\/+$/, '');
const TD_ALT = () => String(process.env.TD_ALT_URLS || 'https://www.turkeydropgame.com,https://turkeydrop.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const TD_SEASON = { start: '2026-11-02', end: '2026-12-01' }; // Central days, end exclusive (through Nov 30)
const tdSign = p => drB64u(crypto.createHmac('sha256', TD_SECRET()).update(p).digest());
function tdMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + tdSign(payload); }
function tdOpen(token) {
if (TD_SECRET().length < 32) return { error: 'Turkey Drop is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = tdSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Go back to Turkey Drop and tap Back on the air again.' };
return { ok: true, claims: c };
}
const tdIsGameUrl = u => [TD_URL()].concat(TD_ALT()).some(o => String(u || '').startsWith(o + '/'));
async function tdCallback(cbUrl, receipt) {
if (!tdIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('turkeydrop callback', e.message); return false; }
}
// -- PolyWarriors (2026-10-05): the cyberpunk fighting game at polywarriors.com; its own secret PW_SSO_SECRET (also on the game)
const PW_SECRET = () => String(process.env.PW_SSO_SECRET || '').trim();
const PW_URL = () => String(process.env.PW_URL || 'https://polywarriors.com').replace(/\/+$/, '');
@@ -1775,8 +1902,8 @@ function doorHouseList() {
const l = ads.rates().doorHouseAds;
return (Array.isArray(l) ? l : []).filter(x => x && String(x.name || '').trim() && /^https:\/\/[^\s"'<>]+$/i.test(String(x.url || ''))).slice(0, 20);
}
async function doorHousePick(email, claimedUsername) {
const list = doorHouseList(); if (!list.length) return null;
async function doorHousePick(email, claimedUsername, skipName) {
const list = doorHouseList().filter(x => !skipName || String(x.name).toLowerCase() !== String(skipName).toLowerCase()); if (!list.length) return null;
const day = todayCT(); const prev = doorHouse.get(email) || {}; const shown = prev.day === day ? Object.assign({}, prev.shown) : {};
const pool = list.length > 1 ? list.filter(x => x.name !== prev.last) : list;
const h = pool.slice().sort((a, b) => (shown[a.name] || 0) - (shown[b.name] || 0))[0]; // never shown today sorts first, list order breaks ties
@@ -1837,6 +1964,12 @@ function GAMES() {
// PolyBreak (2026-10-13): the brick breaker; first round clears and the purple Polygon gem pay POL
{ slug: 'polybreak', name: 'PolyBreak', tag: 'Brick breaker', blurb: 'Break walls of glass jewel bricks with the classic arcade capsules, and catch the purple Polygon gem when it falls. First clears of each round pay POL.',
art: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polybreak/og-polybreak-clean.jpg', play: '/api/my/polybreak', pays: 'POL for first round clears and gem catches' },
// POL Miner (2026-10-28): dig down, beat the drill bosses, find the rare Polygon crystals (hidden until gamesLive has 'polminer')
{ slug: 'polminer', name: 'POL Miner', tag: 'Mining adventure', blurb: 'Dig down through the layers, haul ore to sell, upgrade your pick, lamp and cart, and beat a drill boss every 30 m. Rare pink Polygon crystals pay POL.',
art: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polminer/og-polminer-clean.jpg', play: '/api/my/polminer', pays: 'POL for Polygon crystals, first boss wins and depth records' },
// Turkey Drop (2026-10-28): the Thanksgiving season game, Nov 2 to 30 (hidden until gamesLive has 'turkeydrop'; gone after the season)
{ slug: 'turkeydrop', name: 'Turkey Drop', tag: 'Thanksgiving · Nov 2 to 30', blurb: 'The WFWL 98.7 helicopter is dropping turkeys over the mall. Swing the net, catch them before they splat, and keep the station on the air. Score milestones pay POL the first time you reach them, and the weekly top 3 win a POL prize.',
art: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/turkeydrop/og-turkeydrop-clean.jpg', play: '/api/my/turkeydrop', pays: 'POL for first score milestones and weekly top 3 prizes', season: { start: TD_SEASON.start, end: TD_SEASON.end } },
]);
}
// each game's member perk (the $5 welcome offer, 2026-10-05) shown on its card
@@ -1850,6 +1983,8 @@ const STRIP = () => ({
polhunter: { line: 'Find hidden codes on sites across the network. Every find drips POL.', open: 'https://polhunter.com/', host: 'polhunter.com' },
clutterhunt: { line: 'Search cozy, cluttered rooms for hidden objects. New rooms every season.', open: SEEK_URL() + '/', host: SEEK_URL().replace(/^https?:\/\//, '') },
polybreak: { line: 'Break the glass jewel wall, catch the capsules and the purple Polygon gem. First clears pay POL.', open: PB_URL() + '/', host: PB_URL().replace(/^https?:\/\//, '') },
polminer: { line: 'Dig deep, beat the drill bosses, find the rare pink Polygon crystals. Crystals pay POL.', open: PM_URL() + '/', host: PM_URL().replace(/^https?:\/\//, '') },
turkeydrop: { line: 'Thanksgiving only. Catch the turkeys from the station helicopter before they splat. Score milestones pay POL.', open: TD_URL() + '/', host: TD_URL().replace(/^https?:\/\//, '') },
spellwheel: { line: 'Swipe the letter wheel, fill the grid, solve the daily puzzle. Levels and dailies pay POL.', open: SW_URL() + '/', host: SW_URL().replace(/^https?:\/\//, '') },
polywarriors: { line: 'Recruit one-of-a-kind warriors, fight the arena, challenge members. First wins pay POL.', open: PW_URL() + '/', host: PW_URL().replace(/^https?:\/\//, '') },
});
@@ -1917,6 +2052,10 @@ const GAME_AUTH = {
mint: (a, memberId) => seekMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
polybreak: { name: 'PolyBreak', frames: false, origins: () => [PB_URL()].concat(PB_ALT()), host: () => PB_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => pbMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) },
polminer: { name: 'POL Miner', frames: false, origins: () => [PM_URL()].concat(PM_ALT()), host: () => PM_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => pmMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) },
turkeydrop: { name: 'Turkey Drop', frames: false, origins: () => [TD_URL()].concat(TD_ALT()), host: () => TD_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => tdMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) },
spellwheel: { name: 'SpellWheel', origins: () => [SW_URL()].concat(SW_ALT()), host: () => SW_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => swMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
polywarriors: { name: 'PolyWarriors', origins: () => [PW_URL()].concat(PW_ALT()), host: () => PW_URL().replace(/^https?:\/\//, ''),
@@ -2000,7 +2139,7 @@ const server = http.createServer(async (req, res) => {
} }
// -- traffic log: public page views by referring domain (admin > Traffic)
if (req.method === 'GET' && (TRAFFIC_PAGES.has(p) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']);
if (req.method === 'GET' && ((TRAFFIC_PAGES.has(p) && !(p === '/refuel' && u.searchParams.has('t'))) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']);
// -- viral links (Marty, 2026-09-21): ANY public page + ?ref=<username|code|id> is that member's
// referral link. Same 30-day last-touch sponsor cookie as /join, the view counts under the
// "page" hook in link stats. Served IN PLACE, not redirected (2026-09-21): Facebook's crawler follows
@@ -2129,7 +2268,7 @@ const server = http.createServer(async (req, res) => {
if (p === '/api/admin/wednesday/kick' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = await wednesday.kickNow(); return json(res, r.error ? 400 : 200, r); }
// -- the pages a member can turn into a viral link (promo tools > Viral links)
if (p === '/api/pages' && req.method === 'GET') {
const pages = [{ path: '/', title: 'Home page' }, { path: '/blog', title: 'Blog' }, { path: '/earning', title: 'How earning works' }, { path: '/games', title: 'Games that pay POL' }, { path: '/ledger', title: 'Live ledger' }, { path: '/leaderboard', title: 'Leaderboard' }, { path: '/contract', title: 'The contract' }, { path: '/plays', title: 'Team-building plays' }, { path: '/wallets', title: 'Wallet guide' }, { path: '/friday', title: 'Five Dollar Friday' }, { path: '/whats-new', title: "What's new" }, { path: '/shorts', title: 'Shorts' }, { path: '/presentation', title: 'The presentation (narrated video)' }];
const pages = [{ path: '/', title: 'Home page' }, { path: '/blog', title: 'Blog' }, { path: '/earning', title: 'How earning works' }, { path: '/games', title: 'Games that pay POL' }, { path: '/ledger', title: 'Live ledger' }, { path: '/leaderboard', title: 'Leaderboard' }, { path: '/contract', title: 'The contract' }, { path: '/plays', title: 'Team-building plays' }, { path: '/wallets', title: 'Wallet guide' }, { path: '/friday', title: 'Five Dollar Friday' }, { path: '/refuel', title: 'Fuel Your Offers: the Monthly Refuel guide' }, { path: '/conversion-tracking', title: 'Conversion tracking: how to set it up' }, { path: '/whats-new', title: "What's new" }, { path: '/shorts', title: 'Shorts' }, { path: '/presentation', title: 'The presentation (narrated video)' }];
try { for (const b of (await blog.listPublished()).slice(0, 40)) pages.push({ path: '/blog/' + b.slug, title: 'Article: ' + b.title, cover: b.cover || null }); } catch (e) {}
return json(res, 200, { pages });
}
@@ -2235,9 +2374,23 @@ const server = http.createServer(async (req, res) => {
}
} else if (acct && acct.sponsorRef && !sponsorId && spd.reason !== 'none') { sponsorBlocked = spd.reason; if (u.searchParams.get('intent') === 'buy') sponsorBlockedAlert(acct.email, Object.assign({ tok }, spd)); }
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; }
// holding tank (2026-10-27): a signed-in member with no sponsor and no member number is never bound under the
// fallback. Network sponsor first (LinkSpin), else the hold (the buy and activate buttons refuse on tankHold).
let tankHold = null;
if (!sponsorId && acct && !acct.sponsorRef && !acct.memberId) {
try {
const h = await tank.holdFor(acct);
if (h && h.aligned) { const a2 = await accounts.byEmail(acct.email); const sp2 = await resolveSponsorDetailed(a2 && a2.sponsorRef); if (sp2.id && !(await payoutChainBlocked(sp2.id, 2))) sponsorId = sp2.id; else tankHold = { since: null, until: null }; } // aligned: their sponsor's position (or held while it is not usable yet)
else if (h && h.hold) tankHold = h.hold;
} catch (e) { tankHold = { since: null, until: null }; }
if (tankHold) sponsorBlocked = 'tankHold';
// NEVER hold a purchase (Marty 2026-10-27): a buyer with no sponsor anywhere goes ahead under the catch position;
// the hold only stops a plain 'switch on payouts' with nothing bought. Alignment above still ran first.
if (tankHold && u.searchParams.get('intent') === 'buy') { tankHold = null; if (sponsorBlocked === 'tankHold') sponsorBlocked = null; }
}
// orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands
// the new member under the configured catch position (#1) instead of root
if (!sponsorId && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1;
if (!sponsorId && !tankHold && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1;
let name = null, avatarUrl = null, own = false;
// the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own
// sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13)
@@ -2260,7 +2413,7 @@ const server = http.createServer(async (req, res) => {
let invited = !!showTok;
if (!invited && tok) { try { invited = !(await fraud.hasAccountOnDevice(req)); } catch (e) { invited = true; } }
if (acct) invited = false; // already a member: they are not joining anybody's line
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, sponsorName: spd.name || null, invited, name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, tankHold, sponsorName: spd.name || null, invited, name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
}
if (p === '/api/stats' && req.method === 'GET') {
let members = 0; try { members = await chain.memberCount(); } catch (e) {}
@@ -2301,6 +2454,7 @@ const server = http.createServer(async (req, res) => {
const email = acct ? acct.email : String(b.email || '').trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' });
if (!acct) { const iss = await newEmailIssue(email); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } // replies must reach them
if (!acct) { const mo = await memberOnlyTicket(email); if (mo) return json(res, mo.status, mo.body); }
const guard = supportGuard(req, b, email);
if (guard) return json(res, guard.status, guard.body);
const r = await tickets.create({ source: 'public', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, subject: b.subject, category: b.category, body: b.body });
@@ -2324,7 +2478,7 @@ const server = http.createServer(async (req, res) => {
const email = acct ? acct.email : String(b.email || '').trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'Add your email so Marty can reply.', needEmail: true });
if (acct) { if (supportFlood('em:' + email, 5, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Open Help in your dashboard to add to one.' }); }
else { const guard = supportGuard(req, b, email); if (guard) return json(res, guard.status, guard.body); }
else { const mo = await memberOnlyTicket(email); if (mo) return json(res, mo.status, mo.body); const guard = supportGuard(req, b, email); if (guard) return json(res, guard.status, guard.body); }
const tr = Array.isArray(b.transcript) ? b.transcript : [];
const turns = tr.slice(-8).map(x => ((x && x.who === 'me') ? 'Me: ' : 'Assistant: ') + String((x && x.text) || '').replace(/\s+/g, ' ').trim().slice(0, 600)).filter(x => x.length > 6);
const firstQ = tr.find(x => x && x.who === 'me' && String(x.text || '').trim());
@@ -2453,7 +2607,7 @@ const server = http.createServer(async (req, res) => {
let memberId = 0;
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} }
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polminer: '/api/my/polminer', turkeydrop: '/api/my/turkeydrop', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
}
// -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies.
@@ -2633,7 +2787,9 @@ const server = http.createServer(async (req, res) => {
const s = await auth.fromRequest(req);
if (!s) return json(res, 200, { signedIn: false });
const memberId = await auth.refreshMemberId(s);
const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
let acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
// holding tank (2026-10-27): someone the network already knows is placed under that sponsor first (tank.js alignToNetwork)
if (acct && !acct.sponsorRef && !acct.memberId && !memberId) { try { if (await tank.alignToNetwork(acct)) acct = (await accounts.byEmail(acct.email)) || acct; } catch (e) {} }
const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id;
let sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason !== 'none') ? spdMe.reason : null;
let sponsorRouted = null;
@@ -2644,12 +2800,16 @@ const server = http.createServer(async (req, res) => {
}
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0;
const _defSpon = Number(siteConfig().defaultSponsorId) || 1;
if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor)
// a holding-tank member is never bound under the fallback: held for an adopter (24 h at most, then the rotation)
let tankHold = null, sponsorFallback = false; // sponsorFallback: no real sponsor resolved (the one-tap ?activate=1 flow never auto-starts then)
if (!sponsorId && !memberId && acct && !acct.sponsorRef && !acct.memberId) { try { const h = await tank.holdFor(acct); if (h && h.hold) tankHold = h.hold; } catch (e) { tankHold = { since: null, until: null }; } }
if (tankHold) sponsorBlocked = 'tankHold';
else if (!sponsorId && memberId !== _defSpon) { sponsorId = _defSpon; sponsorFallback = true; } // orphan fallback → #1 (never self-sponsor)
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'shardsofvalor'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'turkeydrop', 'shardsofvalor'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
address: s.address || (acct && acct.address) || null, memberId,
username: (acct && acct.username) || null,
refCode: (acct && acct.code) || null, sponsorId,
refCode: (acct && acct.code) || null, sponsorId, tankHold, sponsorFallback,
// profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned)
avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null,
socials: (acct && acct.socials) || null,
@@ -2677,7 +2837,7 @@ const server = http.createServer(async (req, res) => {
try {
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
const tw = tankWaitCache.list;
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok };
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok, ready: tw.filter(w => w.ready).length };
} catch (e) {}
const sc0 = siteConfig();
const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null,
@@ -2746,6 +2906,7 @@ const server = http.createServer(async (req, res) => {
if (bc >= 5) reached.push('level3');
try { if (out.memberId && friday.earnedBadge(out.memberId)) reached.push('fridays'); } catch (e) {} // five Five Dollar Fridays in a row
try { if (out.email && gamepass.flag(out.email).until) reached.push('gamepass'); } catch (e) {} // ever held a Game Pass (2026-10-22)
try { if (out.email) for (const k of await refuel.badgesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // Monthly Refuel badges (2026-10-24)
try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned
out.milestonesReached = reached;
if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached);
@@ -3135,13 +3296,7 @@ const server = http.createServer(async (req, res) => {
if (fraud.excluded(s.email)) return json(res, 403, { error: 'Adoptions are not available on this account. Contact support at instantadpay.com/support.' });
const r = await tank.adopt(s.email, b.who, b.note);
if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12)
pushFeed({ type: 'Adopted', sponsor: r.adopterName, member: r.adopteeName, ts: Date.now() });
try {
const sc = siteConfig();
const clean = t => String(t || '').replace(/[<>&]/g, '');
if (sc.telegramBotToken && sc.telegramEchoChatId)
telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>InstantAdPay</b> \u00b7 <b>' + clean(r.adopterName) + '</b> picked up <b>' + clean(r.adopteeName) + '</b> from the holding tank and is now their sponsor', sc.telegramEchoTopicId).catch(() => {});
} catch (e) {}
tankPickupPost(r.adopterName, r.adopteeName, false);
}
return json(res, r.error ? 400 : 200, r);
}
@@ -3183,6 +3338,28 @@ const server = http.createServer(async (req, res) => {
// -- reverse registry sync from LinkSpin (2026-10-15): the same signed rows LinkSpin accepts from us (HMAC LS_SYNC_SECRET
// over ts + newline + raw body, 10-minute window). New people become waiting accounts with their LinkSpin line; existing
// accounts keep their sponsor and only get empty fields filled. No mail, no notices, no chain (lsinbound.js).
// -- Monthly Refuel partner calls from LinkSpin (signed like the registry): a LinkSpin package to record (the answer carries
// LinkSpin's grants for that member), the outbox of LinkSpin grants + reminders, acks, and one member's status for its card
if (p.startsWith('/api/partner/refuel/') && req.method === 'POST') {
const sg = await readLsSigned(req, 200000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body; const op = p.slice('/api/partner/refuel/'.length);
if (op === 'purchase') {
const r = await refuel.record({ site: 'linkspin', email: b.email, tx: b.tx, cents: b.cents, credits: b.credits, ts: b.ts });
return json(res, 200, Object.assign({ ok: true }, r, { items: r.on ? await refuel.outbox('linkspin', b.email) : [] }));
}
if (op === 'outbox') return json(res, 200, { ok: true, on: refuel.cfg().on, items: refuel.cfg().on ? await refuel.outbox('linkspin') : [] });
if (op === 'ack') return json(res, 200, { ok: true, acked: await refuel.ack('linkspin', Array.isArray(b.refs) ? b.refs : []) });
if (op === 'status') return json(res, 200, Object.assign({ ok: true }, await refuel.view(b.email)));
if (op === 'goal') { const r = await refuel.setGoal(b.email, b.goal); return json(res, r.error ? 400 : 200, r); }
return json(res, 404, { error: 'unknown op' });
}
// -- the Engine Room, partner side: this site's facts for one member + the streak (LinkSpin builds its own panel from them)
if (p === '/api/partner/engine' && req.method === 'POST') {
const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const email = String(sg.body.email || '').trim().toLowerCase(); if (!email) return json(res, 400, { error: 'Which member?' });
const rv = await refuel.view(email);
return json(res, 200, { ok: true, refuel: rv, facts: rv.on ? await engine.facts({ site: 'iap', adminMember, ads, coach }, email) : null });
}
if (p === '/api/partner/registry' && req.method === 'POST') {
const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body;
@@ -3520,6 +3697,24 @@ const server = http.createServer(async (req, res) => {
const tok = pbMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null });
res.writeHead(302, { Location: PB_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- POL Miner hand-off (2026-10-28): sign the member across; the game verifies with POLMINER_SSO_SECRET
if (p === '/api/my/polminer' && req.method === 'GET') { gamestats.handoff('polminer');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polminer', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (PM_SECRET().length < 32) return json(res, 503, { error: 'POL Miner is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = pmMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null });
res.writeHead(302, { Location: PM_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- Turkey Drop hand-off (2026-10-28): sign the member across; the game verifies with TD_SSO_SECRET
if (p === '/api/my/turkeydrop' && req.method === 'GET') { gamestats.handoff('turkeydrop');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'turkeydrop', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (TD_SECRET().length < 32) return json(res, 503, { error: 'Turkey Drop is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = tdMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null });
res.writeHead(302, { Location: TD_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
if (p === '/api/my/spellwheel' && req.method === 'GET') { gamestats.handoff('spellwheel');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'spellwheel', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
@@ -3791,13 +3986,17 @@ const server = http.createServer(async (req, res) => {
if (r.error) { const g = seekOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'seek') { r = g; game = 'seek'; } }
if (r.error) { const g = swOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'spellwheel') { r = g; game = 'spellwheel'; } }
if (r.error) { const g = pbOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'polybreak') { r = g; game = 'polybreak'; } }
if (r.error) { const g = pmOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'polminer') { r = g; game = 'polminer'; } }
if (r.error) { const g = tdOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'turkeydrop') { r = g; game = 'turkeydrop'; } }
if (r.error) return json(res, 400, { error: r.error });
const c = r.claims; if (c.kind !== 'refuel' || !c.nonce || !c.email || !c.ret) return json(res, 400, { error: 'That is not a refuel link.' });
if (game === 'gemkingdom' && !String(c.ret).startsWith(GK_URL() + '/')) return json(res, 400, { error: 'That is not a Gem Kingdom link.' });
if (game === 'seek' && !seekIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a ClutterHunt link.' });
if (game === 'spellwheel' && !swIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a SpellWheel link.' });
if (game === 'polybreak' && !pbIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a PolyBreak link.' });
const G = game === 'polybreak' ? { game: 'PolyBreak', label: 'one more paddle' } : game === 'gemkingdom' ? { game: 'Gem Kingdom', label: 'continue' } : game === 'seek' ? { game: 'ClutterHunt', label: 'hint' } : game === 'spellwheel' ? { game: 'SpellWheel', label: 'hint' } : { game: 'Drip Runner', label: 'refuel' };
if (game === 'polminer' && !pmIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a POL Miner link.' });
if (game === 'turkeydrop' && !tdIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a Turkey Drop link.' });
const G = game === 'turkeydrop' ? { game: 'Turkey Drop', label: 'back on the air' } : game === 'polminer' ? { game: 'POL Miner', label: 'supply crate' } : game === 'polybreak' ? { game: 'PolyBreak', label: 'one more paddle' } : game === 'gemkingdom' ? { game: 'Gem Kingdom', label: 'continue' } : game === 'seek' ? { game: 'ClutterHunt', label: 'hint' } : game === 'spellwheel' ? { game: 'SpellWheel', label: 'hint' } : { game: 'Drip Runner', label: 'refuel' };
for (const [n, v] of refuelTokens) if (v.ts + 30 * 60000 < Date.now()) refuelTokens.delete(n);
let t = refuelTokens.get(c.nonce);
if (t && t.done) return json(res, 200, Object.assign({ done: true, ret: t.doneRet || t.ret }, G));
@@ -3805,18 +4004,24 @@ const server = http.createServer(async (req, res) => {
const email = String(c.email).toLowerCase();
const status = await ads.visitStatus(email, 'refuel'); // refuels have their own daily allowance
if (status.count >= status.cap) return json(res, 200, Object.assign({ none: true, why: 'cap', ret: c.ret }, G));
const ad = await ads.serveVisit(email, viewerGeo(req));
// 2026-10-28 (Marty): a sponsor never seen first, then one seen longest ago after the cooldown (doorRepeatDays), then a
// member video, then a house sponsor (one of Marty's programs, never the game the player is in), so the visit is never empty
const ad = await ads.serveVisit(email, viewerGeo(req), { kind: 'refuel' });
if (ad) t = { kind: 'visit', email, memberId: Number(c.memberId), id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
else { // every visit pack already visited: a member video ad instead (2026-09-30)
const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req)));
if (!v) return json(res, 200, Object.assign({ none: true, why: 'empty', ret: c.ret }, G));
t = { kind: 'video', email, memberId: Number(c.memberId), id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false };
if (!v) {
const h = await doorHousePick(email, c.username, G.game);
if (!h) return json(res, 200, Object.assign({ none: true, why: 'empty', ret: c.ret }, G));
t = { kind: 'house', email, memberId: Number(c.memberId), id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
}
else t = { kind: 'video', email, memberId: Number(c.memberId), id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false };
}
t.game = game; t.cb = c.cb || null;
refuelTokens.set(c.nonce, t);
}
if (t.kind === 'video') return json(res, 200, Object.assign({ mode: 'video', title: t.title, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G));
return json(res, 200, Object.assign({ mode: 'visit', title: t.title, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G));
return json(res, 200, Object.assign({ mode: 'visit', house: t.kind === 'house' || undefined, title: t.title, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G));
}
if (p === '/api/refuel/challenge' && req.method === 'GET') {
const t = refuelTokens.get(String(u.searchParams.get('n') || ''));
@@ -3839,13 +4044,29 @@ const server = http.createServer(async (req, res) => {
const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab
if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try again.' });
await ads.markVideoSeen(t.email, t.id); credits = tier.cost;
} else if (t.kind === 'house') { // a house sponsor: no advertiser, no pool income, but it is one of the day's refuels
const r = await ads.markHouseVisit(t.email, 'refuel');
if (r.error) return json(res, 400, { error: r.error });
credits = 0;
} else {
const r = await ads.completeVisit(t.email, t.id, { reward: false, note: t.game === 'polybreak' ? 'PolyBreak paddle' : t.game === 'gemkingdom' ? 'Gem Kingdom continue' : t.game === 'seek' ? 'ClutterHunt hint' : t.game === 'spellwheel' ? 'SpellWheel hint' : 'Drip Runner refuel' });
const r = await ads.completeVisit(t.email, t.id, { reward: false, note: t.game === 'turkeydrop' ? 'Turkey Drop back on the air' : t.game === 'polminer' ? 'POL Miner supply crate' : t.game === 'polybreak' ? 'PolyBreak paddle' : t.game === 'gemkingdom' ? 'Gem Kingdom continue' : t.game === 'seek' ? 'ClutterHunt hint' : t.game === 'spellwheel' ? 'SpellWheel hint' : 'Drip Runner refuel' });
if (r.error) return json(res, 400, r);
credits = ads.rates().visitCostPerVisit || 3;
{ const camp = await ads.campaignById(t.id).catch(() => null); if (camp && camp.house) credits = 0; } // a house ad costs nobody anything: no POL pool income (2026-10-03)
}
t.done = true;
if (t.game === 'turkeydrop') { // Turkey Drop "back on the air" (an extra life after the station pulls you off the air): signed receipt to the game's callback and on the ret page; gameplay only, never POL
const receipt = tdMint({ kind: 'td-life', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await tdCallback(t.cb, receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'Turkey Drop', label: 'back on the air' });
}
if (t.game === 'polminer') { // POL Miner supply crate: signed receipt to the game's callback and on the ret page (the crate is a gameplay boost, never POL)
const receipt = pmMint({ kind: 'pm-crate', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await pmCallback(t.cb, receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'POL Miner', label: 'supply crate' });
}
if (t.game === 'polybreak') { // PolyBreak one more paddle: signed receipt to the game's callback and on the ret page
const receipt = pbMint({ kind: 'pb-paddle', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await pbCallback(t.cb, receipt);
@@ -3964,8 +4185,9 @@ const server = http.createServer(async (req, res) => {
const out = [];
for (const g of GAMES()) {
if (g.season && day >= g.season.end) continue; // a finished season is gone
const soon = !!(g.soon && day < g.soon.opens), preSeason = !!(g.season && day < g.season.start);
const isLive = !soon && !preSeason && live.has(g.slug);
// a seasonal game shows its 'Opens' date only once it is in gamesLive (2026-10-28, Turkey Drop: nothing public before Marty launches it)
const soon = !!(g.soon && day < g.soon.opens), preSeason = !!(g.season && day < g.season.start && live.has(g.slug));
const isLive = !soon && !(g.season && day < g.season.start) && live.has(g.slug);
if (!isLive && !soon && !preSeason) continue; // not live and no date: not announced yet
out.push({ slug: g.slug, name: g.name, tag: g.tag, blurb: g.blurb, pays: g.pays, art: /^https?:/.test(g.art) ? g.art : 'https://instantadpay.com' + g.art, artPos: g.artPos || 'center', live: isLive, video: isLive && g.video ? g.video : null,
opens: soon ? g.soon.label : preSeason ? 'Opens ' + lbl(g.season.start) : null, season: g.season && isLive ? { ends: lbl(g.season.end, true) } : null, open: S[g.slug] ? S[g.slug].open : null, host: S[g.slug] ? S[g.slug].host : null });
@@ -4028,7 +4250,8 @@ const server = http.createServer(async (req, res) => {
}
if (p === '/api/my/gamepass' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay')), { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL }));
// 2026-10-25 (Marty): the member card shows every account exactly what a member sees, the admin's included; tier testing lives in Admin > Game Pass
return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay'))));
}
if (p === '/api/my/gamepass/buy' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
@@ -4036,10 +4259,26 @@ const server = http.createServer(async (req, res) => {
const b = await readBody(req);
// 2026-10-22 (Marty): no pass is ever bought with credits. Buy only opens a waiting order; a FRESH package purchase of at least the
// tier price, by one of this member's own positions, fulfils it (gamepass.onEvent), so the sponsor and team are paid as usual.
// tier: weekly (missing) | explorer | champion | sovereign | legend; every tier above weekly is refused unless sovTiers is on, except for the ADMIN_EMAIL account (testing)
const r = gamepass.buy(s.email, gpDevNow(b.devDay), b.tier, { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL });
// tier: weekly (missing) | explorer | champion | sovereign | legend; every tier above weekly is refused unless sovTiers is on, for every
// account (2026-10-25: the admin tests hidden tiers from Admin > Game Pass, POST /api/admin/gamepass/test-buy, not from the member card)
const r = gamepass.buy(s.email, gpDevNow(b.devDay), b.tier);
return json(res, r.error ? 400 : 200, r);
}
// Admin > Game Pass tier test (2026-10-25, Marty): every tier as members will see it, with the admin's OWN account's state, and a
// test buy of a tier that is not on sale yet (opens the same waiting order a member gets; a fresh package on /my fulfils it).
// Always the signed-in admin's own account (the bearer password falls back to ADMIN_EMAIL); never another member's.
if (p.startsWith('/api/admin/gamepass/') && ['/api/admin/gamepass/preview', '/api/admin/gamepass/test-buy', '/api/admin/gamepass/test-cancel', '/api/admin/gamepass/test-comp'].includes(p)) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const as = adminFromRequest(req); const me = String((as && as.email) || ADMIN_EMAIL || '').trim().toLowerCase();
if (!me) return json(res, 400, { error: 'No admin account email (ADMIN_EMAIL) is set.' });
if (p === '/api/admin/gamepass/preview' && req.method === 'GET') return json(res, 200, Object.assign({ email: me, test: true }, gamepass.view(me, gpDevNow(u.searchParams.get('devDay')), { preview: true })));
if (req.method === 'POST') {
const b = await readBody(req); const tier = String(b.tier || 'weekly').toLowerCase(); if (!gamepass.TIERS.includes(tier)) return json(res, 400, { error: 'unknown tier' });
if (p === '/api/admin/gamepass/test-buy') { const r = gamepass.buy(me, gpDevNow(b.devDay), tier, { preview: true }); if (!r.error) console.log('gamepass admin test order', tier, me); return json(res, r.error ? 400 : 200, Object.assign({ email: me, test: true }, r)); }
if (p === '/api/admin/gamepass/test-cancel') { const r = gamepass.cancelOrder(me, tier); if (r.order) console.log('gamepass admin test order cancelled', tier, me); return json(res, 200, Object.assign({ email: me }, r)); }
if (p === '/api/admin/gamepass/test-comp') { const r = gamepass.comp(me, 'admin tier test', tier); console.log('gamepass admin test comp', tier, me); return json(res, 200, Object.assign({ ok: true, email: me, test: true }, r)); }
}
}
if (!IS_PROD && p === '/api/dev/gamepass-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await gamepass.onEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: /^0x[0-9a-f]{64}$/.test(String(b.tx || '')) ? b.tx : '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email, devMinedAt: Number(b.minedAt) || 0, devNow: Number(b.now) || 0 }) }); } // local tests only (minedAt fakes the block time, now the fulfilment time, tx replays a hash)
if (p === '/api/admin/gamepass/stats' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, gamepass.adminStats()); }
if (p === '/api/admin/gamepass/comp' && req.method === 'POST') { // support: give an account a pass week without a purchase
@@ -4691,16 +4930,55 @@ const server = http.createServer(async (req, res) => {
// conversion tracking (2026-10-23): every click, the owner's own too (flagged self, so they can test), gets a click id
// on the target URL as lsclk=<id>; the row goes to LinkSpin, which matches the advertiser's goal pixel to it
let loc = target;
if (cm) { try { const ip = clientIp(req); const row = await lsconv.record(cm, req, { self: own, target, ip, country: geo.countryOf(ip) || null }); loc = lsconv.withClickId(target, row.id); } catch (e) { console.error('lsconv record', e.message); } }
// self for conversion tracking (2026-10-26): signed in as the owner, OR from a browser the owner signs in from (soft
// key). Only the conversion side; whether the click is counted and billed above stays the signed-in check.
if (cm) { try { const ip = clientIp(req); const selfConv = own || lsconv.isOwnerSk(cm.owner, lsconv.softKey(ip, req.headers['user-agent'])); const row = await lsconv.record(cm, req, { self: selfConv, target, ip, country: geo.countryOf(ip) || null }); loc = lsconv.withClickId(target, row.id); } catch (e) { console.error('lsconv record', e.message); } }
res.writeHead(302, baseHeaders({ Location: loc }));
return res.end();
}
// Campaigns > Conversion tracking: the member's goals and counts live on LinkSpin; these proxy the signed calls
// -- Monthly Refuel (2026-10-24): the member's refuel day, streak, next bonus and Pit Stop status ({ on:false } while switched off)
// -- the Refuel Kit (2026-10-24): personalized banners are public by URL (ad networks load them), rendered only for entitled members
if (p.startsWith('/kitimg/') && (req.method === 'GET' || req.method === 'HEAD')) {
const f = kit.servePath(p.slice(8)); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
res.writeHead(200, { 'Content-Type': f.mime, 'Cache-Control': 'public, max-age=86400', 'Access-Control-Allow-Origin': '*' });
return req.method === 'HEAD' ? res.end() : fs.createReadStream(f.file).pipe(res);
}
if (p === '/api/my/kits' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await kit.myKits(s.email));
}
if (p === '/api/my/kits/render' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await kit.renderFor(s.email, String(b.month || ''), String(b.size || ''), b.variant === 'gif' ? 'gif' : 'still');
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, url: r.url, abs: r.abs, size: r.size, variant: r.variant, bytes: r.bytes });
}
// -- the Engine Room (2026-10-24): InstantAdPay's facts + LinkSpin's (signed, cached a minute) + the streak, built into one panel
if (p === '/api/my/engine' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const rv = await refuel.view(s.email); if (!rv.on) return json(res, 200, { on: false });
const [own, peer] = await Promise.all([engine.facts({ site: 'iap', adminMember, ads, coach }, s.email), engineFromLinkSpin(s.email, u.searchParams.get('fresh') === '1')]);
return json(res, 200, engine.build({ site: 'iap', refuel: rv, iap: own, ls: peer, goal: rv.goal }));
}
if (p === '/api/my/engine/goal' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req); const r = await refuel.setGoal(s.email, b.goal); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/refuel' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await refuel.view(s.email));
}
if (p === '/api/my/conversions' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (!lsconv.on()) return json(res, 200, { ok: false, reason: 'off', error: 'Conversion tracking is not switched on yet. Your ads and clicks work as usual.' });
try { return json(res, 200, Object.assign({}, await lsconv.summary(s.email, u.searchParams.get('fresh') === '1'), { ok: true })); }
// cost per goal (30 days), 2026-10-26: the goals are LinkSpin's last 30 days, so the spend beside them is each
// campaign's spend over the same 30 days from the credit activity log (spend30), not its lifetime total
const since = Date.now() - 30 * 86400000; let sp = null;
try { sp = await ads.spendSince(s.email, since); } catch (e) { console.error('spendSince', e.message); }
try { return json(res, 200, Object.assign({}, await lsconv.summary(s.email, u.searchParams.get('fresh') === '1'), { ok: true, spendSince: since, spendDay: sp ? sp.day : null, spend30: sp ? sp.byCampaign : null })); }
catch (e) { return json(res, 200, { ok: false, reason: 'down', error: 'LinkSpin, the service that counts your conversions, did not answer just now. Your ads and clicks are fine. Try again in a minute.' }); }
}
if ((p === '/api/my/conversions/goal' || p === '/api/my/conversions/test') && req.method === 'POST') {
@@ -4973,6 +5251,34 @@ const server = http.createServer(async (req, res) => {
v.requester = a ? { member: true, email: a.email, username: a.username || '', memberId: a.memberId || 0, wallet: !!a.address, created: a.created || 0, lastSeen: a.lastSeen || 0 } : { member: false, email: v.ticket.email };
return json(res, 200, v);
}
// -- Refuel Kit admin: kits as data (month, theme, five base images), placeholder art from public/banners, personalization preview
if (p === '/api/admin/kits' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, { kits: kit.listKits(), sizes: kit.ORDER }); }
if (p === '/api/admin/kits' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = kit.saveKit(await readBody(req)); return json(res, r.error ? 400 : 200, r); }
if (p === '/api/admin/kits/placeholder' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, kit.usePlaceholder(String(b.month || ''))); }
if (p === '/api/admin/kits/upload' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
let buf; try { buf = await readRaw(req, 3 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large (3 MB max).' }); }
const r = kit.uploadBase(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), buf, req.headers['content-type']);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/kits/preview' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await kit.preview(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), String(u.searchParams.get('username') || 'yourname').replace(/[^a-z0-9_]/gi, '').slice(0, 24), u.searchParams.get('variant') === 'gif' ? 'gif' : 'still');
if (r.error) return json(res, 400, r);
res.writeHead(200, { 'Content-Type': { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[r.ext], 'Cache-Control': 'no-store' }); return fs.createReadStream(r.file).pipe(res);
}
if (p === '/api/admin/refuel' && req.method === 'GET') { // Monthly Refuel: settings, members on a streak, grants by kind, recent outbox rows
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.stats());
}
if (p === '/api/admin/refuel/tick' && req.method === 'POST') { // run the daily pass now (misses, reminders, outbox)
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.tick());
}
if (p === '/api/admin/refuel/member' && req.method === 'GET') { // one member's card, as they see it
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.view(String(u.searchParams.get('email') || '')));
}
if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran out, and what they did next
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, refill.stats());
@@ -5439,7 +5745,8 @@ const server = http.createServer(async (req, res) => {
if (p === '/support' || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'support.html')); // help desk (2026-10-16): the form, and the private ticket link
if (p === '/friday') return sendFile(res, path.join(PUBLIC_DIR, 'friday.html'));
if (p === '/wednesday') return sendFile(res, path.join(PUBLIC_DIR, 'wednesday.html'));
if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, 'refuel.html')); // Drip Runner refuel visit (2026-09-30)
if (p === '/conversion-tracking') return sendFile(res, path.join(PUBLIC_DIR, 'conversion-tracking.html')); // how to set up the conversion pixel, the member guide (2026-10-24)
if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, u.searchParams.has('t') ? 'refuel.html' : 'refuel-guide.html')); // ?t=<token>: the games' refuel visit (2026-09-30); no token: the Fuel Your Offers member guide (2026-10-24)
if (p === '/door') return sendFile(res, path.join(PUBLIC_DIR, 'door.html')); // Spooky Doors door visit (2026-10-02)
// per-partner kit pages (Marty, 2026-09-29): /partners/<slug> serves public/kits/<slug>.html, one file per reviewer or site owner
{ const mk = p.match(/^\/partners\/([a-z0-9-]{2,40})$/); if (mk) { const f = path.join(PUBLIC_DIR, 'kits', mk[1] + '.html'); if (fs.existsSync(f)) return sendFile(res, f); } }
+250 -13
View File
@@ -63,7 +63,8 @@ const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Numbe
const impl = () => db.enabled() ? D : J;
let ads = null;
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; J.load(); }
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; J.load();
hooks = opts.hooks || {}; RS.st = null; RS.load(); }
// every sponsor change the tank makes is deliberate: recorded (when, how, the sponsor before) so it follows to LinkSpin
// until the member is bound on a contract (sponsorfollow.js). Without the follow glue (tests) it is a plain write.
let follow = null, store = null;
@@ -85,8 +86,11 @@ async function waiting() {
const tot = ads && ads.earnedTotals ? await ads.earnedTotals(rows.map(a => a.email)) : {};
return rows.map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0,
wallet: !!a.address, activated: !!a.memberId, // in the tank "activated" is always false (payouts on = out of the tank); wallet can still be linked
earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0 }))
.sort((a, b) => (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0,
// wallet linked = ready to switch on payouts, held for an adopter (24-hour clock, autoAssign after that)
...(() => { const r = a.address ? readyRec(a.email) : null; return r ? { ready: true, readyAt: r.readyAt, holdUntil: r.readyAt + READY_MS } : { ready: false }; })() }))
// ready members first (least time left first), then newest sign-in
.sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0) || (a.ready && b.ready ? a.readyAt - b.readyAt : 0) || (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
}
// has this member bought a $20+ package themselves? (the qualifying-for-yourself buy)
@@ -113,10 +117,11 @@ async function view(email) {
const a = await accounts.byEmail(ad.adoptee);
mine.push({ id: ad.id, name: a ? nameOf(a) : mask(ad.adoptee), email: ad.adoptee, ts: ad.ts, expires: ad.expires, lastSeen: a ? (a.lastSeen || 0) : 0, wallet: !!(a && a.address), address: (a && a.address) || null, bought: !!(a && a.memberId) });
}
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, waiting: await waiting(), mine };
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, waiting: await waiting(), mine };
}
async function adopt(adopterEmail, who, note) {
async function adopt(adopterEmail, who, note, opts) {
const auto = !!(opts && opts.auto); // the 24-hour safety net (autoAssign): same path, a different record note, both sides emailed
const e = String(adopterEmail || '').toLowerCase();
const el = await eligibility(e);
if (!el.ok) return { error: el.reason };
@@ -127,21 +132,30 @@ async function adopt(adopterEmail, who, note) {
if (!target) return { error: 'That member is no longer in the tank.' };
if (target.email === e) return { error: 'That is you.' };
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
if (await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' };
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; // the safety net never leaves anyone to the company
const token = me.username || me.code || String(me.memberId);
const r = await setSponsor(target.email, token, 'adopt');
if (r.error) return r;
const now = Date.now();
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. You joined InstantAdPay without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: text });
try { await messages.sendChat(me.memberId || 0, e, target.email, text); } catch (err) {}
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: (opts && opts.recordNote) || text });
{ const rr = RS.load().ready[target.email]; if (rr && !rr.done) { rr.done = now; rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now
payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick)
const link = activateLink();
try { await messages.sendChat(me.memberId || 0, e, target.email, text + '\n\n' + chatPayLine(link)); } catch (err) {}
if (mailer && mailer.hasKey()) {
try {
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
'You joined InstantAdPay without a sponsor. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay');
'You joined InstantAdPay without a sponsor. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + '\n\n' + mailPayBlock(nameOf(me), link, !!target.wallet) + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay');
} catch (err) {}
if (auto) {
try {
await mailer.send(e, 'InstantAdPay: ' + target.name + ' from the holding tank is now in your line',
target.name + ' linked a wallet and waited 24 hours in the holding tank without anyone picking them up, so the site assigned them to you (adopters take turns). You are their sponsor now: when they switch on payouts or buy, it locks under you.\n\nWe sent them this chat from you:\n\n' + text + '\n\nSay hello and help them with their first steps: ' + siteUrl + '/my#line\n\nInstantAdPay');
} catch (err) {}
}
}
return { ok: true, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
return { ok: true, auto, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
}
// pay it forward: give one of your own free referrals to the tank
@@ -186,7 +200,8 @@ async function sweep() {
await impl().setStatus(ad.id, 'expired'); back++;
}
const r = await rescueSweep();
return { done, back, kept, warned: r.warned, rescued: r.rescued, dead: r.dead };
const au = await autoAssign().catch(e => { console.error('tank autoAssign', e.message); return { assigned: [], held: 0 }; }); // the 24-hour safety net (also every 15 min in readyTick)
return { done, back, kept, warned: r.warned, rescued: r.rescued, dead: r.dead, autoAssigned: au.assigned.length, held: au.held };
}
// pay-it-forward gift record: the sponsor already sent POL wallet-to-wallet; we
@@ -308,11 +323,233 @@ async function historyMap() {
return out;
}
// ── activation hold (Marty, 2026-10-27: "hold them for no longer than 24 hours") ──
// The contract binds a sponsor for good at the first activation or purchase. A tank member (no sponsor, no member
// number) who switched on payouts used to be bound under the fallback position (#1), which took them out of the tank
// for ever. Now, in this order:
// 1. ALIGN: someone the network already knows (LinkSpin has a sponsor for the same email or wallet) is placed under
// that sponsor, when the sponsor has a real account here and is not a sponsor this person was released or rescued
// from. Ordinary sponsor write (accounts.setSponsorRef): LinkSpin already agrees, so nothing follows anywhere.
// 2. HOLD: otherwise /api/me and /api/sponsor answer tankHold instead of the fallback and the site refuses the
// activation / first purchase. The clock starts when the member is first seen with a wallet linked ("ready").
// 3. SAFETY NET: a ready member nobody adopted within 24 hours goes to the next eligible adopter in rotation
// (least recently auto-assigned first, ties by who qualified first) through the same adopt() path. Nobody
// eligible: keep holding, alert the admin once. Never the company.
const READY_MS = 24 * 3600 * 1000; // the longest a ready member is held
const TICK_MS = 15 * 60 * 1000; // readyTick cadence: auto-assign starts one tick early so the hold never runs past 24 h
const AUTO_SEEN_MS = 7 * 86400000; // an auto-assign adopter signed in within the last 7 days
let hooks = {};
let clock = () => Date.now(); // qa/tank-hold.mjs mocks it
function setClock(fn) { clock = typeof fn === 'function' ? fn : (() => Date.now()); }
const RS = {
st: null, FILE: () => path.join(DATA_DIR, 'tank-ready.json'),
load() {
if (this.st) return this.st;
try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; }
if (!this.st || typeof this.st !== 'object') this.st = {};
this.st.ready = this.st.ready || {}; this.st.adopters = this.st.adopters || {}; this.st.aligned = this.st.aligned || [];
return this.st;
},
save() { try { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('tank-ready save', e.message); } }
};
const holdOf = rec => rec ? { since: rec.readyAt, until: rec.readyAt + READY_MS } : null;
// first time seen in the tank with a wallet linked: the 24-hour clock starts (accounts already linked at deploy start then)
function markReady(a) {
if (!a || !inTank(a) || !a.address) return null;
const st = RS.load(); const e = String(a.email || '').toLowerCase(); if (!e) return null;
const cur = st.ready[e];
if (!cur || cur.done) { st.ready[e] = { readyAt: clock(), notified: cur ? cur.notified || false : false }; RS.save(); } // back in the tank later: a fresh clock
return st.ready[e];
}
function readyRec(email) { const r = RS.load().ready[String(email || '').toLowerCase()]; return r && !r.done ? r : null; }
// sponsors this person was moved away from here on purpose (adopted then dropped, released, rescued) never count
async function previousSponsors(email) {
const e = String(email || '').toLowerCase(); const out = new Set();
for (const ad of await impl().all()) if (ad.adoptee === e && ad.adopter && !String(ad.adopter).startsWith('dead:')) out.add(String(ad.adopter).toLowerCase());
const pv = store && store.get(e); if (pv && pv.prevEmail) out.add(String(pv.prevEmail).toLowerCase());
const m = await impl().mark(e); if (m && m.sponsor) out.add(String(m.sponsor).toLowerCase());
return out;
}
async function alignToNetwork(a) {
if (!a || !inTank(a) || !hooks.network) return null;
const e = String(a.email || '').toLowerCase(); if (!e) return null;
const n = hooks.network(e, a.address || null); if (!n || !n.sponsorEmail) return null;
const spEmail = String(n.sponsorEmail).toLowerCase(); if (spEmail === e) return null;
if ((await previousSponsors(e)).has(spEmail)) return null; // never back to someone they were released or rescued from
const sp = await accounts.byEmail(spEmail);
if (!sp || (accounts.isUnclaimedShell && accounts.isUnclaimedShell(sp))) return null; // the sponsor must really be here
if (hooks.isSuspended && hooks.isSuspended(sp.email)) return null;
const token = sp.username || sp.code || (sp.memberId ? String(sp.memberId) : ''); if (!token) return null;
let cur = sp; const seen = new Set(); // never a loop (they cannot sit under their own downline)
for (let i = 0; cur && i < 60; i++) { if (cur.email === e || seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
const fresh = await accounts.byEmail(e); if (!fresh || !inTank(fresh)) return null;
const r = await accounts.setSponsorRef(e, token); if (r && r.error) return null;
const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + ' from LinkSpin (' + (n.via || 'email') + ')';
st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via: n.via || 'email', at: clock(), why });
if (st.aligned.length > 300) st.aligned = st.aligned.slice(-300);
if (st.ready[e] && !st.ready[e].done) { st.ready[e].done = clock(); st.ready[e].aligned = sp.email; }
RS.save();
console.log('tank align', e, '->', sp.email, why);
if (hooks.aligned) { try { await hooks.aligned({ email: e, name: nameOf(fresh), sponsorEmail: sp.email, sponsorName: nameOf(sp), why }); } catch (err) {} }
return { to: sp.email, toName: nameOf(sp), via: n.via || 'email', why };
}
// /api/me and /api/sponsor, when the fallback position would be used: align first, else the hold
async function holdFor(a) {
if (!a || !inTank(a)) return null;
const al = await alignToNetwork(a).catch(e => { console.error('tank align', e.message); return null; });
if (al) return { aligned: al };
const rec = markReady(a);
return { hold: rec ? holdOf(rec) : { since: null, until: null } };
}
// adopters for the safety net, in rotation order
async function rotation(excludeEmail) {
const qual = new Map(); // member # -> block of their first own $20+ purchase
for (const ev of chain.recentEvents(200000)) if (ev.type === 'Purchase' && Number(ev.priceCents) >= MIN_OWN_BUY_CENTS && ev.buyerId) { const b = Number(ev.block) || 0; const id = Number(ev.buyerId); if (!qual.has(id) || b < qual.get(id)) qual.set(id, b); }
const company = Number(hooks.companyId ? hooks.companyId() : 1) || 1; const now = clock(); const st = RS.load(); const out = [];
for (const a of await accounts.listAll(5000)) {
const id = Number(a.memberId) || 0;
if (!id || id === company || id === 1 || !qual.has(id) || a.email === excludeEmail) continue;
if (!a.lastSeen || now - a.lastSeen > AUTO_SEEN_MS) continue;
const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) continue; // suspended or fraud-flagged: the same rule as a manual adoption
out.push({ a, last: Number(st.adopters[a.email]) || 0, q: qual.get(id) });
}
out.sort((x, y) => x.last - y.last || x.q - y.q);
return out;
}
async function inDownlineOf(adoptee, adopter) { // is the adopter somewhere under the adoptee? (adopting them would close a loop)
let cur = await accounts.sponsorOf(adopter.email); const seen = new Set();
for (let i = 0; cur && i < 60; i++) { if (cur.email === adoptee || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
return false;
}
let autoBusy = null; // readyTick (15 min) and sweep (hourly) never run the safety net at the same time
function autoAssign() { if (!autoBusy) autoBusy = autoAssignRun().finally(() => { autoBusy = null; }); return autoBusy; }
async function autoAssignRun() {
const st = RS.load(); const now = clock(); const out = { assigned: [], held: 0 };
const due = [];
for (const [e, rec] of Object.entries(st.ready)) {
if (rec.done) continue;
const a = await accounts.byEmail(e);
if (!a || !inTank(a)) { rec.done = clock(); continue; } // adopted, aligned, bought or gone: the hold has lifted
if (remoteOpen(e) || !a.address) continue; // picked up on LinkSpin (the follow lands here shortly) / wallet unlinked
if (now < rec.readyAt + READY_MS - TICK_MS) continue;
due.push([e, rec, a]);
}
due.sort((x, y) => x[1].readyAt - y[1].readyAt);
let pool = null;
for (const [e, rec, a] of due) {
if (!pool) pool = await rotation(e);
let done = null;
for (const c of pool) {
if (c.a.email === e) continue;
if ((await impl().open(c.a.email)).length >= CAP_OPEN) continue;
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
if (await inDownlineOf(e, c.a)) continue;
const msg = 'Hi, I am ' + nameOf(c.a) + '. You joined InstantAdPay without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
const r = await adopt(c.a.email, a.username || e, msg, { auto: true, recordNote: 'auto-assigned after 24 hours in the tank' });
if (r && r.ok) { done = { adoptee: e, adopter: c.a.email, adopterName: r.adopterName, adopteeName: r.adopteeName }; break; }
}
if (done) {
st.adopters[done.adopter] = clock(); rec.done = clock(); rec.autoAssigned = done.adopter;
for (const c of pool) c.last = Number(st.adopters[c.a.email]) || 0;
pool.sort((x, y) => x.last - y.last || x.q - y.q);
out.assigned.push(done); RS.save();
if (hooks.assigned) { try { await hooks.assigned(done); } catch (err) {} }
} else {
out.held++;
if (!rec.noAdopterAlerted) {
rec.noAdopterAlerted = clock(); RS.save();
if (hooks.adminAlert) { try { await hooks.adminAlert('InstantAdPay holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $20+ package, fewer than ' + CAP_OPEN + ' open adoptions, signed in within 7 days, not suspended or on a no-payout chain). They stay on hold, never under the company. Adopt them from My line > Holding tank, or set their sponsor in Admin.'); } catch (err) {} }
}
}
}
RS.save();
return out;
}
// every 15 minutes (server.js): align whoever the network already knows, start the clock for new ready members,
// run the safety net. `fresh` = members who became ready and were not announced yet (server.js posts them).
async function readyTick() {
const st = RS.load(); const fresh = []; let aligned = 0;
for (const a of await accounts.listAll(5000)) {
if (!inTank(a)) continue;
if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; }
if (remoteOpen(a.email)) continue;
const rec = markReady(a);
if (rec && !rec.notified) { rec.notified = clock(); fresh.push({ email: a.email, name: nameOf(a), username: a.username || null, until: rec.readyAt + READY_MS }); }
}
RS.save();
const auto = await autoAssign();
const pay = await payTick().catch(e => { console.error('tank payTick', e.message); return { sent: [] }; });
return { fresh, aligned, assigned: auto.assigned, held: auto.held, reminders: pay.sent };
}
// ── one-tap switch on payouts after an assignment (Marty, 2026-10-27) ──
// The contract only has activate(sponsorId) from the member's OWN wallet (non-custodial), so the site cannot switch
// payouts on for them. What it can do: every assignment (manual adoption or the 24-hour safety net) carries a link to
// /my?activate=1#wallet, which starts the Activate flow with the sponsor filled in (my.js), and a member who has not
// switched on payouts gets ONE reminder email at 24 hours (and the new sponsor ONE notice), and a last email at 72 hours.
// Stops as soon as they activate or buy (memberId / MemberActivated), or the sponsor changes. State: tank-ready.json
// `pay` (adoptee email -> { at, adopter, adoptionId, auto, r1, r2, done }). Deploy overlap: each send is gated by
// hooks.claim (marks.claim, one MySQL row per key across both app copies) and the record is saved before the send.
const PAY_R1_MS = 24 * 3600 * 1000; // first reminder (member email + sponsor notice)
const PAY_R2_MS = 72 * 3600 * 1000; // last reminder (member email only)
const activateLink = () => siteUrl + '/my?activate=1#wallet';
const chatPayLine = link => 'Switch on payouts in one tap (one free transaction, it locks me in as your sponsor): ' + link;
function mailPayBlock(sponsorName, link, hasWallet) {
return 'Switch on payouts: ' + link + '\n'
+ 'One tap opens your wallet with ' + sponsorName + ' already filled in as your sponsor. It is one free transaction, no package needed, and it locks ' + sponsorName + ' in as your sponsor so every payment in your line can reach you.'
+ (hasWallet ? '' : ' No wallet linked yet? The same link shows you how (one free signature) and then carries on.');
}
function payTrack(adoptee, adopter, adoptionId, auto) {
const st = RS.load(); st.pay = st.pay || {};
st.pay[String(adoptee).toLowerCase()] = { at: clock(), adopter: String(adopter).toLowerCase(), adoptionId: adoptionId || null, auto: !!auto, r1: 0, r2: 0, done: null };
RS.save();
}
const claimOnce = async key => { if (!hooks.claim) return true; try { return !!(await hooks.claim(key)); } catch (e) { return false; } };
async function payTick() {
const st = RS.load(); st.pay = st.pay || {}; const now = clock(); const sent = [];
for (const [e, rec] of Object.entries(st.pay)) {
if (rec.done) continue;
const a = await accounts.byEmail(e);
if (!a) { rec.done = 'gone'; rec.doneAt = now; continue; }
if (Number(a.memberId) > 0) { rec.done = 'activated'; rec.doneAt = now; continue; } // switched on payouts or bought
if (a.address && hooks.activated) { let act = null; try { act = await hooks.activated(a); } catch (err) {} if (act) { rec.done = 'activated'; rec.doneAt = now; continue; } }
const sp = await accounts.byEmail(rec.adopter);
const toks = sp ? [sp.code, sp.username, sp.memberId ? String(sp.memberId) : null].filter(Boolean).map(x => String(x).toLowerCase()) : [];
if (!sp || !toks.includes(String(a.sponsorRef || '').toLowerCase())) { rec.done = 'moved'; rec.doneAt = now; continue; } // released, expired or moved
const age = now - rec.at; const link = activateLink(); const spName = nameOf(sp); const name = nameOf(a);
const noWallet = a.address ? '' : '\n\nNo wallet linked yet? The same link shows you how (one free signature) and then carries on.';
if (!rec.r1 && age >= PAY_R1_MS) {
rec.r1 = now; RS.save();
if (age >= PAY_R2_MS) rec.r1skipped = true; // already past 72 h (e.g. the app was down): one email only, the last one below
else if (await claimOnce('tankpay1:' + e + ':' + rec.at)) {
if (mailer && mailer.hasKey()) { try { await mailer.send(e, 'Reminder: switch on payouts with ' + spName + ' on InstantAdPay',
'Yesterday ' + spName + ' became your sponsor on InstantAdPay, but your payouts are not switched on yet, so nothing in your line can pay you.\n\nSwitch on payouts: ' + link + '\n\nOne tap opens your wallet with ' + spName + ' already filled in as your sponsor. It is one free transaction, no package needed, and it locks ' + spName + ' in as your sponsor.' + noWallet + '\n\nQuestions? Message ' + spName + ' in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay'); } catch (err) {} }
if (hooks.notify) { try { await hooks.notify(sp.email, name + ' hasn\'t switched on payouts yet',
name + ' hasn\'t switched on payouts yet; a nudge from you helps. They were assigned to you 24 hours ago and we sent them a reminder with a one-tap link.\n\nSend them a chat from My line (' + siteUrl + '/my#line), or pass on the same link: ' + link + '\n\nWhen they tap it, their wallet opens with you filled in as their sponsor.'); } catch (err) {} }
sent.push({ email: e, stage: 1, adopter: sp.email });
}
}
if (!rec.r2 && age >= PAY_R2_MS) {
rec.r2 = now; RS.save();
if (await claimOnce('tankpay2:' + e + ':' + rec.at)) {
if (mailer && mailer.hasKey()) { try { await mailer.send(e, 'Last reminder: switch on payouts with ' + spName + ' on InstantAdPay',
'Three days ago ' + spName + ' became your sponsor on InstantAdPay, and your payouts are still switched off, so any payment meant for you in your line cannot reach you.\n\nSwitch on payouts: ' + link + '\n\nOne tap opens your wallet with ' + spName + ' already filled in. It is one free transaction, no package needed, and it locks ' + spName + ' in as your sponsor.' + noWallet + '\n\nThis is the last reminder. Your account and your sponsor stay as they are.\n\nInstantAdPay'); } catch (err) {} }
sent.push({ email: e, stage: 2, adopter: sp.email });
}
rec.done = 'reminded'; rec.doneAt = now;
}
}
RS.save();
return { sent };
}
function payView() { return Object.entries(RS.load().pay || {}).map(([email, r]) => Object.assign({ email }, r)).sort((x, y) => y.at - x.at).slice(0, 100); }
function alignedRecent(n) { return RS.load().aligned.slice(-(n || 50)).reverse(); }
async function adminView() {
const recent = await impl().recent(200);
const names = {};
for (const ad of recent) for (const em of [ad.adoptee, ad.adopter]) if (!(em in names)) { const a = await accounts.byEmail(em); names[em] = a ? nameOf(a) : em; }
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000 };
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
}
module.exports = { init, view, adopt, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
module.exports = { init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
+1
View File
@@ -362,6 +362,7 @@ async function ingestEmail(e) {
if (!ticketId) { const r = parseRef(e.subject); if (r) { const t = await byRef(r.ref); if (t && t.email === from) ticketId = t.id; } }
const body = clean(e.text, 5000);
if (ticketId) { const r = await addMessage(ticketId, { author: 'member', body, emailMessageId: mid, via: 'email' }); return Object.assign(r, { created: false }); }
if (e.canOpen && !(await e.canOpen(from))) return { error: 'not a member (new tickets need a platform account)', created: false }; // replies above still land
const r = await create({ platform: e.platform || 'iap', source: 'email', email: from, name: e.name, subject: oneLine(e.subject, 140) || '(no subject)', category: 'Other', body, emailMessageId: mid, via: 'email', confirm: !!e.confirm });
return Object.assign(r, { created: true });
}
+8 -3
View File
@@ -80,12 +80,17 @@ async function send(input, opts) {
return { ok: true, test: true, to };
}
if (running) return { error: 'A send is already running (' + running.sent + ' of ' + running.total + '). Wait for it to finish.' };
const kind = AUDIENCES[input.audience] ? input.audience : 'optin';
// claim the slot BEFORE the slow recipient list (Sendy opt-in checks take minutes): two sends raced on 2026-10-28 and 475 members got the POL Miner email twice
running = { sent: 0, total: 0, building: true };
let kind, list;
try {
kind = AUDIENCES[input.audience] ? input.audience : 'optin';
unknownOptins = 0;
let list = await recipients(kind);
list = await recipients(kind);
if (Array.isArray(input.to) && input.to.length) { const want = new Set(input.to.map(e => String(e).toLowerCase())); const all = await R.accounts.listAll(20000); list = all.filter(a => a.email && want.has(String(a.email).toLowerCase())); } // explicit list (repairs)
if (unknownOptins && !(input.to && input.to.length)) console.log('updates: Sendy gave no answer for', unknownOptins, 'members; they were left out of this send');
if (!list.length) return { error: 'Nobody in that audience.' };
if (!list.length) { running = null; return { error: 'Nobody in that audience.' }; }
} catch (e) { running = null; throw e; }
const rec = { id: Date.now().toString(36), ts: Date.now(), subject: compose(input, null).subject, noteIds, audience: kind, total: list.length, sent: 0, skipped: 0, failed: 0, status: 'running', unknown: unknownOptins, recipients: list.map(a => a.email) };
const l = log(); l.sends.unshift(rec); l.sends = l.sends.slice(0, 50); saveLog(l); running = rec;
(async () => {
+69 -10
View File
@@ -4,6 +4,16 @@
// three touches per person: at once, at 3 days, at 10 days. In-app notice always (kind 'notice', never a pop-up
// broadcast); email only when the member opted in and outbound mail is on. Stops the moment a wallet is linked.
// State: DATA_DIR/wallet-nudge.json. The coach card reads waitingFor() to badge a direct.
// Wallet push (Marty, 2026-10-25): a game only learns the wallet on the IAP -> game hand-off, so a member who linked a wallet
// after that and keeps a remembered game session never got paid (solanaclick, 1.5 POL in Gem Kingdom). Now a row whose IAP
// account has a wallet that is an on-chain member (the same a.address the hand-off token carries) is PUSHED to that game's
// signed POST /api/iap/wallet instead of nudged; the game's own payout sweep then pays it. Idempotent on the game side (the same
// wallet twice is a no-op, a different one is refused), so the deploy overlap's two copies cannot do harm.
// Any linked wallet (Marty, 2026-10-27, "build all three"): the push no longer waits for the wallet to be an on-chain member. A
// holding-tank member can wait a day or more before switching on payouts, and their game POL sat unpaid with the nudges stopped.
// accounts.address is only ever set after a verified wallet signature (auth.verifyChallenge -> accounts.linkWallet), so that is
// the wallet every game pays. memberId goes along when the chain knows one, else 0.
// nudge: false = push only. PolyBreak, SpellWheel and PolyWarriors joined 2026-10-25 push-only; Marty turned their nudges on the same day.
const fs = require('fs'), path = require('path'), crypto = require('crypto'), https = require('https'), http = require('http');
let R = {}, DATA_DIR = '.';
const FILE = () => path.join(DATA_DIR, 'wallet-nudge.json');
@@ -11,6 +21,7 @@ const blank = () => ({ v: 1, people: {}, stats: { sent: 0, converted: 0, runs: 0
const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } };
const save = s => { try { fs.writeFileSync(FILE(), JSON.stringify(s)); } catch (e) {} };
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const now0 = () => Date.now();
const STAGES = [0, 3 * 86400000, 10 * 86400000]; // first touch now, reminder at 3 days, last word at 10 days
function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; }
@@ -21,9 +32,36 @@ function games() {
{ key: 'gemkingdom', name: 'Gem Kingdom', url: process.env.GK_URL, secret: process.env.GK_SSO_SECRET },
{ key: 'clutterhunt', name: 'ClutterHunt', url: process.env.SEEK_URL, secret: process.env.SEEK_SSO_SECRET },
{ key: 'driprunner', name: 'Drip Runner', url: process.env.DR_URL, secret: process.env.DR_SSO_SECRET },
{ key: 'roadagent', name: 'Road Agent', url: process.env.RA_URL, secret: process.env.RA_SSO_SECRET }
{ key: 'roadagent', name: 'Road Agent', url: process.env.RA_URL, secret: process.env.RA_SSO_SECRET },
{ key: 'polybreak', name: 'PolyBreak', url: process.env.PB_URL || 'https://polybreak.app', secret: process.env.PB_SSO_SECRET },
{ key: 'polminer', name: 'POL Miner', url: process.env.POLMINER_URL || 'https://polminer.com', secret: process.env.POLMINER_SSO_SECRET }, // 2026-10-28: idle until POLMINER_SSO_SECRET is set
{ key: 'turkeydrop', name: 'Turkey Drop', url: process.env.TD_URL || 'https://turkeydropgame.com', secret: process.env.TD_SSO_SECRET }, // 2026-10-28: idle until TD_SSO_SECRET is set
{ key: 'spellwheel', name: 'SpellWheel', url: process.env.SW_URL || 'https://spellwheel.com', secret: process.env.SW_SSO_SECRET },
{ key: 'polywarriors', name: 'PolyWarriors', url: process.env.PW_URL || 'https://polywarriors.com', secret: process.env.PW_SSO_SECRET }
].filter(g => g.url && g.secret && String(g.secret).trim().length >= 32);
}
// POST the wallet to the game: X-IAP-Sig = hex HMAC-SHA256(secret, 'wallet\n' + ts + '\n' + hex sha256(body)) -> { status, j }
function pushWallet(g, body) {
return new Promise(resolve => {
const raw = JSON.stringify(body), ts = String(Date.now());
const sig = crypto.createHmac('sha256', String(g.secret).trim()).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex');
let url; try { url = new URL(String(g.url).replace(/\/+$/, '') + '/api/iap/wallet'); } catch (e) { return resolve({ status: 0, j: null }); }
const mod = url.protocol === 'https:' ? https : http;
const rq = mod.request(url, { method: 'POST', timeout: 8000, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw), 'X-IAP-Ts': ts, 'X-IAP-Sig': sig, 'User-Agent': 'InstantAdPay wallet-push/1.0' } }, r => {
let d = ''; r.on('data', c => { if (d.length < 1e5) d += c; }); r.on('end', () => { let j = null; try { j = JSON.parse(d); } catch (e) {} resolve({ status: r.statusCode, j }); });
});
rq.on('timeout', () => { rq.destroy(); resolve({ status: 0, j: null }); }); rq.on('error', () => resolve({ status: 0, j: null }));
rq.end(raw);
});
}
// the wallet to push for an account: its signature-linked address, activated or not -> { wallet, memberId } | null
// memberId is the on-chain member id when there is one, else 0; a failed chain read falls back to the account's stored id.
async function linkedWallet(a) {
if (!a || !a.address || !/^0x[a-f0-9]{40}$/i.test(a.address)) return null;
let id = Number(a.memberId) || 0;
if (R.chain && R.chain.memberIdByAccount) { try { id = Number(await R.chain.memberIdByAccount(a.address)) || 0; } catch (e) { console.warn('walletnudge chain read', e.message); } }
return { wallet: a.address, memberId: id > 0 ? id : 0 };
}
function fetchRows(g) {
return new Promise(resolve => {
const ts = String(Date.now());
@@ -36,12 +74,14 @@ function fetchRows(g) {
rq.on('timeout', () => { rq.destroy(); resolve(null); }); rq.on('error', () => resolve(null));
});
}
// copy (Marty, 2026-10-27): the ask is the LINK step only (one free signature), never "switch on payouts": a linked wallet is paid
function copy(games, stage, link) {
const total = games.reduce((n, g) => n + g.unpaid, 0);
const list = games.map(g => g.unpaid.toFixed(2) + ' POL from ' + g.name).join(', ');
const parts = games.map(g => g.unpaid.toFixed(2) + ' POL in ' + g.name);
const list = parts.length > 1 ? parts.slice(0, -1).join(', ') + ' and ' + parts[parts.length - 1] : parts[0];
const subject = total.toFixed(2) + ' POL is waiting for your wallet';
const p1 = 'You have ' + list + ' sitting in your game balance' + (games.length > 1 ? 's' : '') + '. It cannot be paid out yet because no wallet is linked to your InstantAdPay account.';
const p2 = 'Link a wallet on your Wallet tab. It is one free signature, no transaction, and it cannot move funds. Your POL pays out on the next sweep, and every game pays that same wallet from then on.';
const p1 = "You've earned " + list + ". Link your wallet (one free signature) and it's sent automatically, including everything you've earned so far.";
const p2 = 'It is not a transaction and it cannot move funds. Every game pays that same wallet from then on.';
const p3 = stage >= 2 ? 'This is the last reminder about this balance. It stays yours; it just waits for a wallet.' : 'Not sure which wallet to use? SafePal is the one we recommend; MetaMask and Phantom work too. The Wallet tab has a short guide.';
const text = [p1, '', p2, '', 'Link your wallet: ' + link, '', p3].join('\n');
const html = '<p>' + esc(p1).replace(esc(list), '<b>' + esc(list) + '</b>') + '</p><p>' + esc(p2) + '</p><p><a href="' + esc(link) + '"><b>Link your wallet</b></a></p><p>' + esc(p3) + '</p>';
@@ -49,14 +89,32 @@ function copy(games, stage, link) {
}
async function tick() {
const S = load(); S.stats.runs++; S.lastRun = Date.now();
const byEmail = new Map(), snapshot = {};
const byEmail = new Map(), snapshot = {}; let pushed = 0;
S.pushes = S.pushes || {}; S.pushLog = S.pushLog || []; S.stats.pushed = S.stats.pushed || 0;
for (const g of games()) {
const rows = await fetchRows(g); snapshot[g.key] = rows ? rows.length : null; if (!rows) continue;
for (const r of rows) {
let email = String(r.email || '').trim().toLowerCase();
if (!email && r.memberId && R.accounts.byMemberId) { const a = await R.accounts.byMemberId(Number(r.memberId)); email = a ? a.email : ''; }
let email = String(r.email || '').trim().toLowerCase(), acct = null;
if (!email && Number(r.memberId) > 0 && R.accounts.byMemberId) { acct = await R.accounts.byMemberId(Number(r.memberId)); email = acct ? acct.email : ''; }
if (!email) continue;
const cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid: Math.max(0, Number(r.unpaid) || 0) }); byEmail.set(email, cur);
const unpaid = Math.max(0, Number(r.unpaid) || 0);
// the IAP account already has a linked wallet (activated or not): hand it to the game instead of asking the member for it
if (!acct) acct = await R.accounts.byEmail(email);
const act = await linkedWallet(acct);
if (act) {
const pk = g.key + ':' + email, prev = S.pushes[pk];
// a refusal (different wallet already in the game, unknown player) is retried once a day, never every hour
if (prev && prev.wallet === act.wallet && prev.status !== 'ok' && prev.status !== 'error' && now0() - prev.at < 86400000) continue;
const out = await pushWallet(g, { email, wallet: act.wallet, username: (acct && acct.username) || r.username || null, memberId: act.memberId });
const status = out.status === 200 && out.j && out.j.ok ? 'ok' : out.status === 409 ? 'conflict' : out.status === 404 ? 'unknown' : 'error';
const changed = status === 'ok' && !!out.j.changed;
S.pushes[pk] = { at: now0(), game: g.key, email, wallet: act.wallet, memberId: act.memberId, unpaid, status, code: out.status, changed };
if (changed) { S.stats.pushed++; pushed++; S.pushLog.unshift({ at: now0(), game: g.key, name: g.name, email, username: (acct && acct.username) || r.username || null, memberId: act.memberId, wallet: act.wallet, unpaid }); S.pushLog = S.pushLog.slice(0, 300); }
console.log('walletnudge push', g.key, email.replace(/^(..).*(@.*)$/, '$1***$2'), act.wallet, unpaid, status, out.status, changed ? 'FILLED' : '');
continue; // pushed (or a refusal that a nudge cannot fix: the member already has a wallet)
}
if (g.nudge === false) continue;
const cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid }); byEmail.set(email, cur);
}
}
S.lastRows = snapshot;
@@ -82,7 +140,7 @@ async function tick() {
if (ok) { p.sent.push({ ts: now, stage, total: Number(c.total.toFixed(4)) }); S.stats.sent++; sent++; }
}
save(S);
return { ok: true, sent, people: byEmail.size, games: snapshot };
return { ok: true, sent, pushed, people: byEmail.size, games: snapshot };
}
// POL a specific member has waiting across the games (0 when none, or once they linked a wallet)
function waitingFor(email) {
@@ -94,6 +152,7 @@ function adminView() {
const S = load();
const people = Object.entries(S.people).map(([email, p]) => ({ email, first: p.first, last: p.last || p.first, sent: p.sent.length, lastSent: p.sent.length ? p.sent[p.sent.length - 1].ts : 0, done: p.done || null, games: p.games, total: Number(Object.values(p.games || {}).reduce((n, v) => n + Number(v || 0), 0).toFixed(4)) }));
people.sort((a, b) => b.total - a.total);
return { stats: S.stats, lastRun: S.lastRun, lastRows: S.lastRows, games: games().map(g => ({ key: g.key, name: g.name, url: g.url })), waiting: people.filter(p => !p.done), done: people.filter(p => p.done).slice(0, 100) };
return { stats: Object.assign({ pushed: 0 }, S.stats), lastRun: S.lastRun, lastRows: S.lastRows, games: games().map(g => ({ key: g.key, name: g.name, url: g.url, nudge: g.nudge !== false })),
pushed: (S.pushLog || []).slice(0, 100), pushRefused: Object.values(S.pushes || {}).filter(x => x.status !== 'ok').sort((a, b) => b.at - a.at).slice(0, 100), waiting: people.filter(p => !p.done), done: people.filter(p => p.done).slice(0, 100) };
}
module.exports = { init, tick, waitingFor, adminView, games, STAGES };