588 Commits

Author SHA1 Message Date
martbost 1c06c58daf Network sign-in for DownlineHydra (2026-11-15): networksso NAMES downlinehydra, wallets.downlinehydra = DH_URL (default https://downlinehydra.com; staging https://dh.saasy.top until the domain switch), /go/downlinehydra. networksso.test ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:02:10 -06:00
martbost e1bee03b95 hubsync: a tank adoption-window expiry (sponsorfollow label 'expire') now reaches the hub as a sponsor change by 'expiry' (the hub's name); before, these moves were silently skipped. qa/hubsync.test.cjs 20/20 (new test fails without the fix)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 07:50:03 -06:00
martbost e17d8c4fbb 5xYourTeam The Draft on the network holding tank (Marty approved the rules 2026-11-15): signed partner routes draftpartner.js, LOCAL ONLY
POST /api/partner/draft/{pool,adopt,release,status}, HMAC DRAFT_PARTNER_SECRET over 'draft.v1.' + ts + newline + body (X-Draft-Ts /
X-Draft-Sig, 5 min), 503 until the secret is set; GET /api/admin/draft (picks + log). Every pick is tank.adopt() with opts.partner:
the signed 5x claim (positions >= 1) replaces the own-$20-buy rule for these calls only (the member's own tank button keeps it); the
coach needs an account here with a wallet linked and someone on this contract in their line (else a pick who starts here would walk
up to the company), not flagged, under the people-held cap; max 10 open picks; max 2 adoptions per person; the 24 h grace; rule 3
plus a fresh hub lock check at adopt (hub silent = refused); pool also drops spam/flagged (fraud + link-farm list), throwaway and
mistyped email domains, anyone adopted twice. Cards carry no contact data (hub ids or opaque i_ ids, door, joined, last seen,
wallet yes/no, surfing credits; games null, not tracked here). The adoption email is the only mail: no payTrack reminders, no
payments-topic post. Sponsor moves via setSponsor (sponsorfollow + hub sponsor-change, by 'adopt' / 'release').

Pick window: adoption row expires +3 days; tank.sweep skips picks (hooks.isDraftPick); draftpartner.sweep (hourly) closes them by the
pick rule: started (payouts on / purchase) = done, adopted twice or locked = kept with the coach, hub silent = wait, else back to the
tank with the original join time (no new grace). Coach release after 48 h. rid makes adopt/release idempotent. A pick closed some
other way reconciles as 'moved'. MySQL tables draft_picks + draft_log (JSON fallback locally); every call logged with a code/reason.

Tests: qa/draft-partner.test.mjs 66/66 (real tank.js, mocked clock, fake hub + a local copy's routes on 8825), in run.sh member and
run.sh draft; bash qa/run.sh member exit 0 (bugs 0); tank-cap 13/13, sponsorfollow 30/30.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 07:20:14 -06:00
martbost 7f57aedcb6 hubsync: ask the hub for ids on /v1/locked (hub id + first door per row) and expose hubInfo(email) / resolvePerson(q) for the 5xYourTeam draft pool
Read-only. A hub without hub 1e99713 ignores ids: true and the draft pool falls back to opaque i_ ids. hubsync.test 19/19.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 07:20:13 -06:00
martbost 968e60835f Network sign-in by wallet for ViralAdBlitz (2026-11-15): networksso NAMES viraladblitz, wallets.viraladblitz = VAB_URL (default https://viraladblitz.com; staging https://vab.saasy.top until the domain switch), /go/viraladblitz. qa member: ALL PASSED (bugs 0), networksso.test ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 05:41:11 -06:00
martbost 911dd623c0 Kestrel is free at level 20 in Shards of Valor (Marty approved 2026-11-14, Dallas: "The Archer should be free to everyone at level 20")
gamepass.js: HERO_DEFS kestrel freeAt 20. She is never sold here any more: buyHero refuses her ("free for every player at level 20
in Shards of Valor, so she is not for sale"), a bundle setting that names her drops her, heroOrderPrices/heroOrderOpen skip her, and a
waiting Kestrel order from before is cancelled unpaid (never fulfilled by a package). A member who bought her keeps her (the hand-off
still lists kestrel); nothing refunded. Valda, Morag, Roland, the $50 bundle of those three and every price unchanged.
Member card: Kestrel shows "Free at level 20" and "Not for sale" (my.js?v=20261114kes). Chatbot canned answer + AI fact say so.
qa/sov-heroes-store.cjs reworked for it (old Kestrel buyer kept, stale order cancelled, stats $180). iap-qa member: ALL PASSED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:21:12 -06:00
martbost 4ccdb914c7 Network sign-in: a deliberate 'Sign in with InstantAdPay/LinkSpin' tap while signed out on the provider now asks for the provider's sign-in, then finishes the trip (/sso/resume), instead of bouncing back silently (Marty 2026-11-14: VBB sign-in did nothing)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 14:31:47 -06:00
martbost 82eab8016b GET /api/admin/member-extra?email= (Marty 2026-11-14, network hub member lookup): read-only, admin Bearer; what the member card leaves out: optedOut (drip unsubscribe), updatesOptIn, tank {inTank, ready {readyAt, holdUntil}, adoptions summary}, fraud {flags, suspended, suspendedReason}. qa/member-extra.mjs in the member run (401 without/with a wrong password, 404 unknown, fields present). iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:57:33 -06:00
martbost 4787390e8b Tracked network links (Marty 2026-11-14: "make sure each of these sites is its own traffic source and link spun so we can track it"). netsites.js: /api/network-sites adds go = the LinkSpin network link for each site with ?src=iap (linkspin.app/r/nwls|nwdlb|nwvbb|nwsp|nwec, fixed codes on Marty's LinkSpin account), this site found by NETWORK_SITE_ID or the request host; common.js + netline.js footers use go (rel nofollow), plain url as fallback. Promo tools > Network sites: every kit link shows a tracked twin, credited to InstantAdPay (?src=iap) as the site that sent the visit; it lands on the same page with ?ref=<member>. Chatbot Network sites answer says so. Same netsites.js in all five sites. common.js?v=20261114ns, netline.js?v=20261114ns, netkits.js?v=20261114ns
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:39:14 -06:00
martbost d033cc7122 Network line on the six pages with their own footer (conversion-tracking, earning, friday, games, partners, wednesday): netline.js adds Terms, Earnings Disclaimer, Privacy, Contract, Ledger, Support when the footer has none, the company line, and the 'Part of the network' list from /api/network-sites (InstantAdPay current, fallback copy). netline.js?v=20261114nf. iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:02:14 -06:00
martbost efb054d916 Footer: 'Part of the network' line from the network hub (Marty 2026-11-14 trust pack). netsites.js serves GET /api/network-sites (hub GET /v1/network-sites, 10 min cache, never waits on a slow hub, built-in fallback); common.js paints the line (InstantAdPay marked as current) in the site footer and in the members-area footer; company line TrustClickz, 615 Green Valley Drive, Moody, AL 35004; footer link reads Earnings Disclaimer; the members area footer now links Terms, Earnings Disclaimer, Privacy. common.js?v=20261114nf. iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:19:13 -06:00
martbost 32f001aade Promo tools > Network sites (Marty 2026-11-14: DLB + VBB creatives "in all the places they need to go"): a new pill shows the Downline Banners and Viral Banner Blitz promo kits, read live from each site's public feed (GET <site>/api/promo-kit?u=<username>, one source: a creative or line changed on the site shows here at once). The member's username fills every link, creative HTML snippet, line, headline, email and post; usernames are network-wide, so the links work even if they never visited those sites. netkits.js (new), my.html card #promo-network, my.js setPromoSub 'network' + fillPromo hands over the username. CSP connect-src admits downlinebanners.com + viralbannerblitz.com. Chatbot: VBB + Network sites canned answers, DLB answer points at the kit, PROMO TOOLS line, KNOWLEDGE_DATE 2026-11-14. netkits.js?v=20261114nk, my.js?v=20261114nk. iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:01:41 -06:00
martbost edc484db27 One network tank (Marty 2026-11-14: IAP and LinkSpin tanks should show the same people): waiting() counts waiting accounts that never signed in here (BTC4Hits / LinkSpin arrivals) as LinkSpin does; quiet hub-made accounts stay out. The weekly email only counts the tank. hubsync test + iap-qa member ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 09:28:36 -06:00
martbost 836c7b17c2 Hub switch-on (Marty 2026-11-14). Rule 2: a hub arrival (and a sponsor climbed for it) gets person.locks.iap's sponsor when the InstantAdPay contract holds them, never the plain network sponsor; sponsor.changed stays ignored. Quiet: lssync never pushes a hub waiting account to LinkSpin (its registry route would switch payouts on and email them). Rule 3: the holding tank (waiting, release, expiry, rescue, readyTick, autoAssign) leaves out anyone the hub reports locked on any contract or sponsored; /v1/locked detail cached 10 min, last answer kept 1 h, after that held (unknown). Alignment to the hub sponsor only with HUB_TANK_ALIGN=on. Needs network-hub b44dba6. qa/hubsync.test.cjs 19/19 (mail audit with recording mailer, messages, fetch and https), iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:51:58 -06:00
martbost a01d6f2e8c Hub rule 2 (Marty 2026-11-14): every paid Purchase on the InstantAdPay contract goes to the hub's /v1/contract-spend (keyed by the position wallet so its bind is sent first, tx hash so a resend counts once, POL-in only), so when two contracts lock different sponsors the one with money spent decides the network sponsor. Still one way, only with HUB_ENABLED; needs network-hub 296aa5d. qa/hubsync.test.cjs 15/15
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:22:54 -06:00
martbost ff568d973c Network sign-in for Viral Banner Blitz (2026-11-14): vbb listed under networksso wallets (VBB_URL, default https://viralbannerblitz.com) and /go/vbb routed, so "Sign in with InstantAdPay" works on VBB the way it does on Downline Banners; NAMES gains vbb (same networksso.js as LinkSpin, DLB, VBB). iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:15:58 -06:00
martbost 5398faadee Holding-tank arrivals post shows the running total too (Marty 2026-11-14: post those totals so people know who is waiting to be adopted): '(N waiting in total)' after the new names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:06:41 -06:00
martbost a7c36a908a Earners Corner sign-in no longer fills in a website (Marty 2026-11-14): the stackpol.com link made Discourse hold every new member for approval as 'entered profile information without reading'. iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:34:54 -06:00
martbost 92288a30f5 Admin adoption for a member (Marty 2026-11-14): POST /api/admin/tank/adopt {adopter, who, note} runs the same tank.adopt as the member's button (their eligibility and cap, the adoptee's email and chat), no payments-topic post per pickup. For topping up sponsors who lost people when the contract sponsor won. iap-qa member: ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:19:15 -06:00
martbost d626469980 Admin personal notices (2026-11-13, first use: Downline Banners wallet nudge, Marty's go): POST /api/admin/notice-batch {batch, subject, html, text, items:[{email, vars}]} fills {{key}} per member, sends to the InstantAdPay inbox + email through the site mailer (opt-outs skipped, unsubscribe link added), once per member per batch (marks.claim), 400 ms apart, in the background; GET ?batch= for the result
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:04:27 -06:00
martbost e98a6ebcd8 docstore.js: claim() for once-across-copies actions (same file as Downline Banners)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:35:15 -06:00
martbost f29f6d1407 InstantAdPay data documents in MySQL (Marty 2026-11-13: 'everything database-driven'): docstore.js (same file as LinkSpin) keeps every .json/.jsonl data document in table docs of the InstantAdPay database (DOCSTORE_URL), one writer at a time, first boot imports and sets the files aside. Accounts and the other DB-mode tables are unchanged. Rehearsed on a copy with a copy of the database: 64/64 documents byte-identical, pages and APIs answer after a restart.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:33:16 -06:00
martbost 9efdfc8ee9 Data safety (2026-11-13 incident: a deploy read a half-written rotator.json, the store fell back to empty and its next save wiped 294 spin links): safefs.js makes every .json write inside DATA_DIR atomic (temp file + rename); LinkSpin's rotator refuses to start empty when rotator.json exists but will not parse
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:11:30 -06:00
martbost 4e2178d779 Refuel spots (Marty 2026-11-13, paid from the company fee share): a counted Monthly Refuel of $50+ on either site sends one signed request to Downline Banners to buy a spot for the member's main wallet (sponsor = their network sponsor's wallet), once per tx, with a member notice. Chatbot knows Downline Banners, the Banner Spin button and the refuel spot
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:55:47 -06:00
martbost f20062133f Downline Banners now lives at https://downlinebanners.com (Marty 2026-11-13): network sign-in hop default moved off new.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:35:57 -06:00
martbost 24b4ae9134 Hub gaps (Marty 2026-11-13): any later username/sponsor change (old members too) -> /v1/join, deliberate sponsor changes -> /v1/sponsor-change, MemberActivated -> /v1/contract-bind (contract iap); still one way, only with HUB_ENABLED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:22:02 -06:00
martbost 2d4fc7a9f3 Merge branch 'hub-listener' 2026-11-13 07:51:48 -06:00
martbost 00cfd09c8f Network sign-in reaches Downline Banners (Marty 2026-11-13): networksso.js vouches for a wallet site (/go/bannerline, /sso/check?r=bannerline carry the member's wallet + username); public /api/network/member lookup (username <-> linked wallet) so Downline Banners share links use the network username
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 07:35:15 -06:00
martbost 4cf3512106 Network links (Marty 2026-11-13 'yes please proceed'): every click on a link to the other site goes through /go/<peer> (InstantAdPay -> /go/linkspin, LinkSpin -> /go/iap), so a signed-in member arrives signed in; signed out it is a plain redirect. Click-time rewrite in the shared scripts (IAP common.js; LinkSpin common.js + cr-shell.js), so copied share links stay clean; data-nogo opts a link out. Browser check: path+query+hash kept, other hosts and data-nogo untouched. iap-qa member ALL PASSED. common.js/cr-shell.js ?v=20261113nl
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 05:28:11 -06:00
martbost 1f584f894f Network sign-in landing (Marty 2026-11-13, Android Chrome: signed in on LinkSpin via InstantAdPay but landed on the public home page, which always says Sign in): a hop with no page named lands on the member dashboard (LinkSpin /ads, InstantAdPay /my); LinkSpin's home page turns Sign in into 'Open my dashboard' for a signed-in visitor (home.js?v=20261113me). networksso.test + e2e ALL PASSED.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 05:16:35 -06:00
martbost ff2f668583 Network sign-in: a wallet-only session counts as signed in when its wallet belongs to an account (session carries the address, not the email), so a member who signed in with their wallet is signed in on the other site too (Marty 2026-11-13: signed in on IAP, LinkSpin's check came back 'not signed in here'). networksso.test + e2e ALL PASSED.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 05:09:53 -06:00
martbost fab7732620 Merge network sign-in (InstantAdPay <-> LinkSpin) into main for the Friday launch (Marty 2026-11-13: 'we need to get that done now'). Conflicts only in script version tags (kept today's newer assets, re-tagged ?v=20261113sso). networksso.test 'ALL PASSED' both repos, networksso.e2e ALL PASSED, iap-qa member ALL PASSED. NETWORK_SSO_SECRET set on both Coolify apps. Chatbot KNOWLEDGE_DATE 2026-11-13.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 04:53:08 -06:00
martbost 5c896cb782 Network hub listener (hubsync.js), off unless HUB_ENABLED
POST /api/hub/events: signed hub hooks (HUB_SECRET, 5-minute window), each seq applied once, 503 so the hub retries.
member.joined from another door: /v1/resolve the person (climbing to sponsors not here yet) and make waiting accounts
through lsinbound.receive (joinedVia 'hub', joinedRef 'hub:<door>'); existing accounts keep their sponsor and the
difference is listed in /api/admin/hub. wallet.connected fills waiting accounts only; sponsor.changed is a TODO.
Our own new accounts and wallet links go to /v1/join and /v1/wallet from a persisted outbox (hubsync.json), never
in the way of a sign-up. With the flag off nothing is initialised, wired, routed or written; the LinkSpin sync is
unchanged. Test: qa/hubsync.test.cjs against a local network-hub (needs /v1/resolve by id, branch hub-resolve-id).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:02:45 -06:00
martbost 74354346a3 Chasing Unicorns: the page's own ?src= (where the link was posted) rides into the join button as unicorns-<src>, so sign-ups show the channel (Marty 2026-11-12, Massifly + LeasedAdSpace posts). chasing-unicorns.js?v=20261112d
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:48:42 -06:00
martbost dbdeb5a7e6 Chasing Unicorns copy (Marty 2026-11-12): the 'free' ones (free to join until the countdown ends, then everybody gets the fee) and the small miner/gas/admin fee angle in the costs list and the pay-to-unlock card. chasing-unicorns.js?v=20261112c
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:42:16 -06:00
martbost 85d43f7483 Chasing Unicorns promo tool (Marty 2026-11-12): /chasing-unicorns, a labeled training simulation of a fake earnings dashboard where every button is one of 8 scam red flags (reveal card + scam-radar score), then PAS: what chasing unicorns costs, then how InstantAdPay works instead with a free join that keeps the sharer's ?ref=. Promo tools card with the member's link, OG image, chatbot fact, qa/chasing-unicorns.mjs (18 checks). my.js?v=20261112cu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:34:11 -06:00
martbost cedb291aaa My line: your directs' email (with copy), where they came from (referrer + ?src= tag) and how they joined, up front in 'Your line', the Activity drop-down and the three-level card; levels 2-3 never get emails (Marty 2026-11-12: 'it was kind of buried in there'). Search also matches email + source. qa/line-origin.mjs (11 checks). Chatbot fact. my.js/site.css ?v=20261112ln
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:59:09 -06:00
martbost 574a0cafb1 Join page records the ?src= tag in the first-touch source (Marty 2026-11-12: 'we need the source tag so we can know where these things come from'): joinedRef = <referrer host>/<src> or just <src> when the referrer was stripped; a tagged visit replaces an untagged 'direct' first touch; a real earlier source is kept.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (PolHunter/Drip Runner arrivals stay untagged for the bounty proof.)
2026-11-12 12:10:44 -06:00
martbost 55d3597f12 My line: search box on every member list (Your line, three-level downline, Holding tank) to find a member by name, username (with or without @), email or member number (Marty 2026-11-12). Narrows as you type, keeps focus across re-renders, restarts paging at page 1, works with sort + filter chips. Chatbot fact added. my.js/site.css ?v=20261112q
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:24:53 -06:00
martbost fe70c857be Text ads get their own network rate (Marty 2026-11-12): Network Ad Space text-ad views cost 1/synRateDivisorText (default 10, 1 credit = 100 network views) of the on-site rate; banners and partner visits keep synRateDivisor 4. Going forward only (cumulative served counter, existing NAS bookings topped up by reconcile). Admin Rates field, Campaigns table shows 1/N per type, chatbot canned + prompt updated (KNOWLEDGE_DATE 2026-11-12). my.js?v=20261112txt, admin.js?v=20261112txt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:31:10 -06:00
martbost 5585abb663 Network sign-in with LinkSpin (Marty approved 2026-11-12): signed in on one site = signed in on the other, no email code
networksso.js (same file in both repos): /go/linkspin hop for signed-in members' cross-site links; /sso/start (state cookie +
30-minute loop guard) -> LinkSpin /sso/check -> /sso/in?t=<v1 HMAC-SHA256 token, NETWORK_SSO_SECRET, 60 s, single-use nonce
(MySQL table network_sso_nonces when on the DB, else DATA_DIR file), bound to the browser's state cookie, email, audience and a
same-site relative path>. Member sessions only (admin portal never shared), ordinary 4-hour session, /my lands with ?welcome=1
so the login ad runs as after a code sign-in. An email with no account here or a waiting LinkSpin/BTC4Hits account gets the
normal email-code sign-in, email prefilled; nothing is created. Silent check on /my via public/assets/netsso.js
(/api/sso/status); never for bots/fetches; sign-out pauses it 12 hours. Engine Room + Fuel links go through /go/linkspin.
Chatbot knows it (KNOWLEDGE_DATE 2026-11-12). Off until NETWORK_SSO_SECRET (32+ chars) is set.

qa: networksso.test.cjs all passed, networksso.e2e.mjs (both servers, real browser) 31/31, run.sh member green (0 bugs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 07:00:23 -06:00
martbost db1ab8359c Admin member card: Message (inbox + email) button (Marty 2026-11-12). POST /api/admin/member/message puts a broadcast in the member's inbox and emails it through the site mailer (opt-outs and unsubscribe link kept); reports when email is skipped. admin.js?v=20261112msg; qa member passed; local route test passed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:47:52 -06:00
Marty Bostick 3eae242dc3 BTC4Hits import, round 2: tank cap 10 at one time (setting tankAdoptCap), BTC4Hits wording in the adoption note/email/auto-assign message, lssync rows carry origin btc4hits (not hashed), chatbot knows the import + the cap (KNOWLEDGE_DATE 2026-11-11). qa: tank-cap 13/13, tank-hold all passed, sponsorfollow 30/30, sponsorfollow-e2e 24/24
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:08:58 -06:00
Marty Bostick 5e8dee7517 Holding tank: an adopter may hold up to 6 people at one time (open adoptions not yet switched on payouts; setting tankAdoptCap, default 6; was 2 open adoptions), clear message at the cap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 07:49:03 -06:00
Marty Bostick ffcc0c6339 BTC4Hits import: joinedVia 'btc4hits' accounts are waiting accounts like LinkSpin's (left out of every sweep that mails, counts or adopts until their owner signs in); listAll's limit now counts members, not waiting accounts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 07:23:35 -06:00
martbost 0013416af7 Forum reward lookup (Marty 2026-11-10: 1 POL for an introduction, ongoing, linked wallet + payouts on): GET /api/forum/member?email= signed with the forum secret (HMAC of email.ts, 5-minute window) returns found/username/activated (member id > 0)/address/suspended for the earnerscorner.com reward service. qa/forumsso 17/17.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 09:22:27 -06:00
martbost 52eaa20171 Member menu: Earners Corner link (opens earnerscorner.com/session/sso, one-tap sign-in with this account) after Games (Marty 2026-11-10). Member walk 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:50:51 -06:00
martbost e00c820d2f Earners Corner invites credit the inviter (Marty 2026-11-10): /forum/join/<username>[?to=/path] sets the member as sponsor exactly like /join/ (30-day cookie, last touch wins, first-touch source earnerscorner.com, link view recorded) and forwards to the forum (?to= must be an on-forum path); /forum/invite shows a signed-in member their link. The forum's Log In carries a shared thread's ?u= through this route. qa/forumsso 14/14 (incl. a new sign-up landing under the inviter); member walk 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:29:00 -06:00
martbost ef28c16502 qa/chatbot-parse: price route matched 'Five packages, priced' but the ladder is seven packages now; match the answer, not the count. 38/38 pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:20:18 -06:00
martbost 3991a5eb79 Chatbot: Earners Corner forum (canned answer + prompt fact), ahead of the forum announcement (Marty 2026-11-10)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:14:32 -06:00
martbost d06394a3d3 tools/export-knowledge.js: export the chatbot's canned answers as Markdown for the Earners Corner forum assistant (Marty 2026-11-10); rerun and re-upload whenever KNOWLEDGE_DATE is bumped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:13:41 -06:00
martbost 2e4d18d77d Stack POL Pro owned state (Marty 2026-11-10): a Pro owner sees '⭐ You own Stack POL Pro', the unlock date and an 'Open my Pro page' button instead of a one-line note; the Stack POL pane re-checks when the member returns to the tab, so a purchase made while it was open shows without a manual refresh. my.js ?v=20261110proown. Member walk 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 07:37:28 -06:00
martbost f20e845cf1 Earners Corner forum sign-in (Marty 2026-11-10): InstantAdPay is the DiscourseConnect identity provider for earnerscorner.com. /forum/sso verifies Discourse's HMAC-signed request (return URL must be on the forum), a signed-out visitor signs in on /my (request kept in a 30-minute cookie, my.js hands back via /api/my/forum), then a signed payload goes back: email, external id, username, Stack POL page as website, groups network_members (on-chain position) and wallet_linked. Suspended accounts are refused. Env FORUM_SSO_SECRET + FORUM_URL. qa/forumsso.mjs 9/9; member walk 0 bugs; my.js ?v=20261110forum.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 06:51:34 -06:00
martbost 5f38c1486d Chatbot KNOWLEDGE_DATE 2026-11-10: the Stack POL launch release note (scheduled 5 AM CT Nov 10) is already covered by the canned answer + prompt (free page on by default, Pro via any $10+ package)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:20:11 -06:00
martbost 87ea24b8f0 Stack POL Pro: ANY $10+ package unlocks it automatically (Marty 2026-11-09: "Any $10 package or higher unlocks it"). No Get Pro order step; the member's own on-chain package of $10+ switches Pro on for good, rides along with a Game Pass or hero order the same package fulfils (never takes it from them), only packages from the Pro launch (21:30 UTC) count, credits never. Promo tools shows Buy a $10+ package; chatbot updated; my.js ?v=20261109pro4; qa/stackpro rewritten (11 pass).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:40:48 -06:00
martbost 1da37f05ab Admin: grant Stack POL Pro for a $10+ package bought without a Pro order first (Marty 2026-11-09, Orlando). POST /api/admin/stackpro/grant {memberId, tx}: the tx must be an on-chain Purchase of $10+ by that member; recorded as a package sale with its tx, marks the Stack POL page Pro and posts the badge once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:30:34 -06:00
martbost 054ce10985 Stack POL pages ON by default (Marty 2026-11-09: "Everyone's should be enabled by default"): every paid member has stackpol.com/<username>; only an explicit switch-off hides it. Promo tools copy, note and chatbot updated; my.js ?v=20261109pro3; qa/stackpro expects on by default. Pro features stay Pro-only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 15:41:21 -06:00
martbost bafeff9bf4 Stack POL Pro (Marty 2026-11-09): a one-time unlock for the member's stackpol.com page, new money only. Promo tools > Stack POL > Get Pro opens an order; the member's next ad package of $10 or more (mined after the order, by their own position) fulfils it, one package fulfils one order, credits never count (gamepass.js order book, persisted map 'stackpro', durable). The fulfilment marks pro[username] in stack-optin.json for the stackpol.com indexer. New Stack POL Pro achievement badge (badge-stackpro.jpg, ribbon 0.855), celebrated and posted like Game Pass. /my#promo?s=stackpol deep-links the tab (the Pro page's Unlock Pro button). Chatbot canned answer + prompt carry Pro. qa/stackpro.mjs 16/16; member walk 0 bugs; qa/gamepass.mjs has the same 7 date-based failures on the untouched HEAD.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 15:29:48 -06:00
martbost 627341e8ad Chatbot: the Stack POL answer needs its match pattern (re); without it seeds() threw 'reading source' at boot and the 2aa98bd deploy rolled back
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 14:50:34 -06:00
martbost 2aa98bdbd2 Promo tools > Stack POL: 'Show my Stack POL page' switch (GET/POST /api/my/stackpol, DATA_DIR/stack-optin.json read by the stackpol.com indexer); chatbot knows Stack POL (KNOWLEDGE_DATE 2026-11-09); my.js v=20261109sp
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 14:39:25 -06:00
martbost 03284aa281 Conversion linkage, InstantAdPay side (Marty 2026-11-07, "Yes ship these"): a LinkSpin click stays with the account, and its sign-up, wallet link and each package purchase are reported to LinkSpin. Reporting only: no sponsor, payout, credit or chain path changes; accounts.js only gains a notification after a wallet is linked.
lsreport.js. A click id (lsclk or lsid) arriving on any page is kept in a first-party cookie iap.lsclk, 30 days, last click wins, like the sponsor cookie. The join page also sends its own copy with the code request and verify (the cookie is refused in traffic-exchange frames and never crosses browsers, the 2026-09-29 lesson) and it is remembered per email. It is stored in its own table ls_account_clicks when the account is created or a waiting LinkSpin shell is claimed, on /api/signup, email sign-in and in-game sign-in (a game may pass lsclk; none does yet).

Reports queue in ls_events, whose primary key is the idempotency key (join:<hash>, wallet:<hash>, purchase:<tx>:<log index>), so two app copies in a deploy cannot double a row, and LinkSpin dedupes on the same key. A background loop sends them signed, retrying up to every 5 minutes; a sign-up or a purchase never waits on LinkSpin. The purchase hook runs after the existing ev: claim and its value is the USD price on the chain event. A first purchase finds its buyer through the contract's wallet for that member id, since member_id may not be stored yet. Linked positions count as the account's purchases. Past 30 days from the sign-up nothing is queued (LinkSpin's window is from the click).

Campaigns > Conversion tracking lists everything the member's clicks led to, and joins, wallets and purchases on each campaign row. Guide, privacy page and chatbot (CANNED + FACTS) updated; common.js, join.js and my.js tags bumped.

QA: bash qa/run.sh netconv (54 checks: local InstantAdPay + local LinkSpin + a mock Polygon RPC, a real Purchase log through the real event fan-out, LinkSpin down, two copies racing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 07:48:36 -06:00
martbost bfbea142b6 Holding tank: 24-hour sign-up grace plus a Who invited you card (Marty 2026-11-07: "24-hour grace plus the prompt"). On Nov 2 a sponsorless sign-up was adopted five hours after joining, before he could say who invited him.
Grace: for 24 hours from an account's created time nobody can adopt the person by hand. They stay on the waiting list after the open ones with an Opens in badge and no Adopt button, and adopt() refuses in plain words. Only sign-up counts, so someone back in the tank later has no grace. Auto-assign does not wait for it: the 24-hour hold still runs from the wallet link and is not stretched. No notice tells people to adopt someone they cannot adopt yet: the wallet-ready post waits for the grace and says the time really left, is skipped when the rotation takes them in that tick, the arrivals post moves to when the grace ends (marks.claim per member), and the Overview note and weekly email count only people who are open.

Prompt: a member with no sponsor and no member number sees the card at the top of Overview, types a username, confirms in an in-page box, and that person becomes their sponsor through setSponsor as a deliberate change with by 'invited', so it follows to LinkSpin and clears the hold. Refused: self, unknown username, already sponsored, member number or wallet already on the contract, a chain loop, a suspended sponsor, a no-payout chain, and a line with nobody on the contract (they would walk up to the company). The network sponsor is tried first. Nobody invited me hides it and a small link brings it back. Not an adoption: status 'invited', no 7-day window, not counted toward the two. The named sponsor gets the referral email and an on-site notice. Switch-on-payouts reminders track the named sponsor.

Chatbot canned + systemPrompt, KNOWLEDGE_DATE 2026-11-07. my.js, admin.js, admin-sponsorcheck.js ?v=20261107tg. qa/tank-hold.mjs, qa/sponsorfollow.test.cjs and qa/sponsorfollow-e2e.mjs extended (SF_E2E_PORT overrides the ports).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 07:04:18 -06:00
martbost 973fc80570 Shards of Valor testing: the Games card and the chatbot say all testing progress is wiped at launch (Marty 2026-11-06: "we're just testing for bugs right now")
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 09:56:25 -06:00
martbost a845155c88 Shards of Valor open for testing from the Games tab (Marty 2026-11-06, Dallas ready for players): card tagged Open testing, Pays "Nothing yet. No POL until we set a launch date", strip line, card art; chatbot says it is open testing with no POL and no date (KNOWLEDGE_DATE 2026-11-06). Shows once gamesLive has 'shardsofvalor'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 09:43:04 -06:00
martbost abfb3e3199 Shards of Valor bonus heroes sold one time (Marty approved 2026-11-05): Kestrel, Valda, Morag, Roland $20 each, $50 bundle (Valda + Morag + Roland), behind heroSales (OFF)
Paid exactly like a pass: no credits, no POL. POST /api/my/heroes/buy opens a waiting order (kind hero); a fresh package of at least the
price from one of the member's own positions fulfils it in gamepass.onEvent (one package, one order: the highest-priced it covers, pass
or hero; each tx once). Ownership is permanent on the passes record (heroes, heroBundle), never in bought, so hero sales never feed the
Pass Tournament pool. No double charge: an owned hero is refused, a bundle is refused once any of its heroes is owned, and waiting orders
made pointless by a purchase are cancelled.
Settings (Admin > Settings): heroSales '0', heroPrice<Kestrel|Valda|Morag|Roland>Cents 2000 (0 = free for every account),
heroBundlePriceCents 5000, heroBundleHeroes 'valda,morag,roland', heroBundleCap '' (unset: the bundle is heroes only, no cap change).
Hand-off: sovMint (and GET /api/partner/player for shardsofvalor) carries heroes, heroBundle, heroSale { free, bundle, each, bundlePrice },
and heroBundleCap only when set. TIER_DEFS perks: Champion no longer lists the Druid, Sovereign no longer the Necromancer (dropped),
Legend every bonus hero while active. Member Game Pass card: a Bonus heroes block (shown while heroSales is on or to an owner);
Admin > Game Pass: hero test on the admin's own account (test buy / cancel / give / remove) and /api/admin/heroes/stats.
Chatbot: canned sov-bonus-heroes answer + heroesFact following heroSales; KNOWLEDGE_DATE 2026-11-05. my.js?v=20261105hr, admin.js?v=20261105hr.
QA: qa/sov-heroes-store.cjs (39 checks, in member and sov-passes); sov-passes-local expects the hero test panel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:04:47 -06:00
martbost e61475f89b Zealy quest checks for the games (Marty 2026-11-05: game quests are important): /api/quest/zealy/game passes once the account has earned any network-game reward (gamepass.activity = grants and POL in the ledger), /api/quest/zealy/gamepass passes while a Game Pass is active (gamepass.flag). Read-only, same key and 200/400 contract as the other checks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 06:19:17 -06:00
martbost 2e935b3081 Quest-site checks for Zealy (Marty 2026-11-04): POST /api/quest/zealy/account|wallet|member reads accounts.email or accounts.wallet from Zealy's API task call, checks X-Api-Key against QUEST_API_KEY, answers 200 (claimable) or 400 with a message that tells the member what to do (join link martbost, link a wallet, get a package). Read-only lookups; 503 until the key is set
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:38:17 -06:00
martbost 769c04e639 Share domain is instantadpay.link (Marty 2026-11-04: ctbgo.com confuses people; a branded domain, bought on NameSilo $8.39): SHARE_HOSTS default instantadpay.link,ctbgo.com,mylinehq.com so every old ctbgo.com link keeps working; shareDomain default instantadpay.link; chatbot short-banner example on the new domain; my.js?v=20261104il, KNOWLEDGE_DATE 2026-11-04
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 06:18:01 -06:00
martbost fb2383ffae Tell members when the free game allowance is used up (Marty 2026-11-03): the polgrant answer carries waiting (every game's progress POL held for the account), the member view carries caps.lifetime.done/waiting, lastCapHit records lifetime. The Overview card says "You have used your free 2 POL in the games", what the Pass gives and the POL held, with a Get the Game Pass button, and shows to anyone whose allowance is used (not only after a recent cap hit). Chatbot knows both messages. Short banner links fall back to this page's origin (http locally) when no share domain is set; my.js and promo.js ?v=20261103gp. QA member 0 bugs; gamepass the 7 known date-pinned failures, nothing new
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:15:29 -06:00
martbost 0865a4967b Short banner links remember a missing file for one minute, not ten (Road Agent's banners were uploaded 2026-11-03 right after Michael asked for them and stayed 404 on the short link)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:35:23 -06:00
martbost 7d28ec7b5f Short banner image URLs (Michael Camire via Marty, 2026-11-03): the Spaces CDN links in the Games and BixPay kits ran about 105 characters and exchange / safelist image fields cut them off, so the banners never showed. /b/<slug>/<file> on instantadpay.com and the share hosts (https://ctbgo.com/b/turkeydrop/728x90.png) serves the same game-banners CDN file in place (no redirect, HEAD works, 300-file six-hour cache); promo.js builds every game and BixPay banner URL on the share domain; chatbot banner-image answer; promo.js?v=20261103b, KNOWLEDGE_DATE 2026-11-03
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-03 07:36:55 -06:00
martbost c0a435343a Chatbot: every game is gated now (guests earn nothing, free accounts a quarter of progress rewards under the 2 POL allowance, Game Pass the full table); per-game specifics for ClutterHunt, POL Miner, PolyWarriors paid mints and Turkey Drop prizes
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 17:04:54 -06:00
martbost c6b4a84abc Free allowance across the games (Marty 2026-11-02, "cap these so if they want to keep playing they spend a tiny amount"): an account with no Game Pass receives at most capFreeLifetime POL of game rewards ever, across every game (2 POL default, site setting). After that a free account's room for the day is zero: progress rewards defer until a pass is active, repeatable rewards drop, carry waits too. Grant answers and partner caps carry lifetimeHit / freeUsed / lifetime; chatbot facts; QA block for the allowance
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 17:01:27 -06:00
martbost 7f3f057db0 Chatbot: the game tiers (2026-11-02): PolHunter free tier (one hunt a day on 0.02 to 0.10 POL; Game Pass holders five at the full draw, the weekly prizes and the Mystery Hunt Box), SpellWheel ladder (guests one place, free account two, Game Pass from the Mountain Lodge on and for daily/streak POL), and a GAME TIERS fact so unlisted games get an honest answer
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 13:31:39 -06:00
martbost ae3a08b991 Gem Kingdom Royal Charter: /gk/shop charges a paidOnly order from purchased credits only (never the earned pool); chatbot and promo copy carry the new ladder (guests chapters 1-2, free account for 3, $5 Charter for 4-6, taste rewards then Charter-only rewards capped at what the player paid in)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 11:27:00 -06:00
martbost 4bcc867679 Daily growth snapshot also posts to the InstantAdPay support topic: the 'support' target has been in snapshotTargets since 2026-09-24 but post() only knew feed and echo (Marty, 2026-11-02); POST /api/admin/snapshot/send takes {target} for a one-off post to one destination
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 08:23:40 -06:00
martbost 27d7215f0f Merge light and dark themes into main (Marty 2026-11-02 after the Turkey Drop launch): token sets, the Light/Dark/Auto switch saved on the account, the theme head script and its CSP hash, contrast and QA tooling; chatbot answers theme questions; KNOWLEDGE_DATE 2026-11-02 (covers the Turkey Drop note) 2026-11-02 06:32:07 -06:00
martbost 0aaffc308e 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-11-02 04:33:54 -06:00
martbost 4ae7a318da QA for the themes: contrast check in both themes, QA_THEME walks, theme-switch assertions
qa/theme-contrast.mjs (bash qa/run.sh theme) mirrors LinkSpin's: signs in one account per theme (the account value wins at sign-in), walks every member pane, 24 public pages and the admin panes in light and dark with Playwright, samples the main text/background pairs with composited ancestor backgrounds and gradient averages, injects one probe per variant so every pair is measured even when a page has no live example, and reports the ratio per pair with pass/fail at 4.5:1 (3:1 for large text). Result today: 8,169 pairs, 0 fails, worst 4.76:1 (the ok badge in light), worst dark 5.76:1.

qa/walk.mjs honours QA_THEME=light|dark|auto (localStorage iap.theme set before the first navigation; screenshots carry a -<theme> suffix so both sets survive), asserts the header and Profile switch (applies at once, saves to the account, repaints the other control, never touches the username), screenshots the public home, the member's wall and the join page from the local copy, and returns to /my with waitUntil load (a signed-in member area keeps polling, so networkidle never settles). Requests the page cancels by navigating away (net::ERR_ABORTED) no longer count as failures, and the local-only /api/qr 404 (no qrcode module in a checkout) is ignored for images. Both QA_THEME walks: 0 bugs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 12:03:38 -06:00
martbost 1aec9caf6c Theme switch: auto | light | dark, stored in localStorage iap.theme and on the account, applied before first paint on every page
themehead.js is the one source of the tiny inline head script (and of AUTO_DEFAULT, the one constant Marty decides later: 0 = nothing stored keeps the page's current look, dark everywhere on InstantAdPay; 1 = follow the device). It mirrors LinkSpin's themehead.js with only the storage key (iap.theme), the global (window.IAPTheme) and the event name (iap-theme) changed. The script sets data-theme on <html> from iap.theme (auto follows prefers-color-scheme and tracks changes live). tools/stamp-theme-head.cjs writes it into all 28 static site.css pages before the first stylesheet with data-theme-base="dark" on <html>; the blog, the leaderboard, what's-new, the badge page, the unsubscribe page and the wall 404 read the module directly. The site CSP allows inline scripts by hash only, so themehead.CSP_HASH joins script-src (without it the script is silently blocked).

Account side: accounts.theme (JSON store and MySQL, alterSafe theme VARCHAR(8)), in the public account JSON and /api/me; POST /api/my/profile {theme} rides the existing profile save path, never touches the username, and does not tap changed() (appearance is not mirrored to LinkSpin, same as LinkSpin's side). common.js owns the client side for every page: paints every .theme-seg, saves a click to the account, and IAP.themeSync lets the account value win over the local one at sign-in (a local choice is pushed up when the account has none yet); my.js calls it from render(). The Light / Dark / Auto segmented control sits in the member-area header (#boTheme) and in a Profile pane "Appearance" card, and in the admin header for the same session. shorts.html pins the dark ink set on its black video stage; view.html stops reading an undefined --bg. ?v= tags bumped on every changed stylesheet and script (20261101th): site.css on all 28 pages, common.js on 25, welcome.js on 17, support.js, my.js, engine-room.js, admin.js, admin-kits.js, blog-page.js.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 11:55:06 -06:00
martbost fdc95b5ed6 Light and dark themes as token sets (Marty 2026-11-01: LinkSpin got light and dark for vision-impaired readers and people who struggle with bright or dark screens, and InstantAdPay gets the same treatment)
site.css keeps its near-black mint look as the dark set and gains :root[data-theme="light"]: light mint-grey ground (#E8F0EC), white panels, dark ink (#0B1A14), muted #50665C, the mint family darkened to a teal that reads as text on white (#0A6B56, hover #075744), white ink on mint buttons, cyan/violet/amber/gold/ok/warn/bad retuned so every text-on-fill pair clears WCAG AA 4.5:1 (qa/theme-contrast.mjs: 8,169 pairs, 0 fails, worst 4.76:1). New tokens, same names as LinkSpin where the role matches: mint-deep/pale/faint/soft-2/line/line-2, ok/ok-ink/ok-soft, warn, bad-soft, gold/gold-2/gold-ink/gold-soft/gold-faint/gold-line, amber-soft/line/ink, cyan-soft/line, violet-soft/line, muted-soft/line, ink-faint, line-soft, ground-soft, field-bg, nav-bg, side-bg, pill-bg, panel-grad, panel-grad-deep, plate-grad, sh-lg, plus color-scheme. A .seg segmented control (pill, mint when on) for the theme switch.

Audit of stray literals: every raw hex/rgba that encoded a surface, text, border or soft fill in site.css now reads a token (nav and sidebar backings, menu hover/on fills, chips, badges, split strip, spend banner, pager, pipeline columns, tank/line chips, toolkit tiers, chat bubbles, the genViz diagram strokes, the Shorts report link that was white at 45 percent on black). Scripts that draw UI read tokens: my.js charts take their colours from getComputedStyle at draw time (CH proxy), the wallet check, tank badges, ledger deltas, Game Pass badges (gold with gold-ink), Friday bank dots and promo errors use var(--ok)/(--warn)/(--gold)/(--bad); admin.js ticket thread fills, welcome.js pop-up card, support.js ticket styles, engine-room.js lamps, admin-kits.js preview border and blog-page.js bar likewise.

Left as literals on purpose: button glows and drop shadows, the modal and ad-viewer backdrops, the ticker mask, iframe/video/QR backings that must stay white or black, the hero arc and isometric art, the welcome pop-up's brand mint button gradient (dark text on a fixed mint fill passes in both themes), the game return bars and ribbons (game-brand colours), canvas-drawn share images, var() fallbacks, print styles, the sticky-note yellow (#fde68a/#7c2d12, 8.5:1 in both themes), and the refuel rail / Spooky Doors / Gem Kingdom shop pages that carry their own palettes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 11:54:47 -06:00
martbost ce33d71427 Nov 1 season turnover: chatbot says Spooky Doors is closed (Candy Crunch top 10 share 27 POL after admin sign-off, unpaid ladder POL pays once a wallet is linked, Turkey Drop opens Nov 2) and ClutterHunt is in its Harvest Farmhouse season (six rooms, Nov 1 to 30); ClutterHunt promo kit carries the Harvest copy and share image; KNOWLEDGE_DATE 2026-11-01
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 06:07:10 -06:00
martbost b4989ab59f EnjoyBestGames arcade kit in Promo tools > Games (Marty 2026-10-31): member link enjoybestgames.com/?r=<username> (30-day ebg_ref cookie), share image, 4 posts, 11 banner sizes on the game-banners CDN, and a note that the site is an engagement site where only the featured Polygon games pay; generic game panel gains an optional note line; chatbot canned answer + prompt updated, KNOWLEDGE_DATE 2026-10-31
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-31 08:14:49 -05:00
martbost 47ce40b858 Coach nudges never guess from a failed chain read, and the site owner is never coached (Marty 2026-10-31): a chain.member() failure cached null for 60 s, rungFor() then classed the member as "payouts on, no purchase" and mailed the rung-2 "See a payout land: your first package" nudge to the owner (memberId 1, 4 purchases, 7 buyers). describe() now reports unknown and stalled requires a known state; nudgeTick skips adminEmail.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-31 07:44:22 -05:00
martbost f0811ecf70 Policy test follows the new link-farm report wording (new / still watched / left the list)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-31 07:29:01 -05:00
martbost 53978476bb Link-farm scan reports only changes: new candidates since the last run and accounts that left the list (wallet linked, bought, deleted), with the still-watched count; candidates carry firstSeen (Marty 2026-10-31: watch, do not delete yet)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-31 07:26:33 -05:00
martbost 2f2cf24946 Legend pass perk: every new hero as it ships (Marty 2026-10-30: Dallas's $100/year tier idea folded into Legend, no new tier, level caps unchanged)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-30 13:20:34 -05:00
martbost fda27ad43f Merge warpwares-integration: Warp & Wares hand-off, sponsor dock visit kind (dockCapPerDay 10), Games tab card, promo entry, chatbot, walletnudge, qa (gated by gamesLive); conflicts resolved: KNOWLEDGE_DATE 2026-10-30 kept, my.js tag 20261030ww, ads.js dock changes re-applied onto the prohibited-content version (git saw the file as binary)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-30 11:23:31 -05:00
martbost 012250360e Wall profile rendering: a purchase alone decides (a quarantined account that buys a package gets its bio and links back, as the quarantine notice promises)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-30 07:33:19 -05:00
martbost 337d4f9e8f Link-farm hardening (2026-10-30 incident: 106 free accounts used casino bios and website links as backlinks; Google indexed the text through /wall pages)
Public walls: profile fields (bio, avatar, socials, intro video) render only for a paying member (memberId > 0 or a registered position), on /api/wall and in the OG image; a free account's wall shows the name, the line's ads and the join call. The meta/og description is a fixed site sentence with the handle, never the bio. Outbound profile links are rel="sponsored ugc noopener" target="_blank". A deleted or unknown name is a real 404 with X-Robots-Tag noindex (was a bare "Banner wall" page at 200, a soft 404 that stayed indexed).

Policy (prohibited.js, byte-for-byte copy on LinkSpin): bios may not carry a URL or a domain token ("Links go in the social fields, not the bio"); gambling, adult, pharma, weapons and link-selling terms (Unicode aware, Vietnamese and Portuguese terms included) are refused in bios, social URLs, line banner targets, wall offers and every campaign field, with the refusal logged. lssync applies it on the way out and lsinbound on ingest.

Quarantine rule: a brand-new free account (no wallet, no sponsor, under 24 h) whose first profile save plants a link is saved with profileQuarantined (JSON + MySQL column), never rendered publicly, and told "Your profile links will appear after your first ad package"; the admin member card shows the flag.

Daily link-farm scan (spamscan.js, same copy on LinkSpin): in-app job at 06:30 Central, claimOnce per day, lists memberId-0 walletless accounts with a link plus a farm signal (prohibited term, sign-in over within 15 min, no sponsor), skips the spamScanAllow setting (seeded), writes DATA_DIR/wall-spam-scan.json and sends one Telegram to the private admin chat only when there are candidates. Admin > Members > Link-farm list: rows with "also on LinkSpin", Delete selected (existing DELETE /api/admin/member, on-chain refused, no cascade) and Allow.

Terms section 8 "Prohibited content", bio hint in the profile editor, chatbot canned answer "What content is not allowed?", KNOWLEDGE_DATE 2026-10-30. Test: qa/profile-policy.test.cjs (unit + local copy; runs in qa/run.sh member and policy).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-30 07:29:11 -05:00
martbost ec4ada08d7 Five Dollar Friday notice, email and kickoff mention the Game Pass perk correctly: a $5+ Friday pack earns +20% credits (600 from the $5 pack) AND includes the free 7-day Game Pass automatically (fridayPassPerk, since 2026-10-23); Marty 2026-10-30 asked for the tie-in
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-30 05:16:12 -05:00
martbost a058fd515d Warp & Wares integration, gated (2026-10-29): the 30-day Trade Wars-style season game, same protocol as POL Miner and Turkey Drop. WW_SSO_SECRET / WW_URL (default https://warpwares.saasy.top, staging for now) / WW_ALT_URLS / WW_SEASON_START + WW_SEASON_END (default 2026-11-30..2026-12-30, Central, end exclusive) with wwMint/wwOpen/wwIsGameUrl/wwCallback (code defaults only, no env set); GAME_AUTH warpwares (in-game sign-in kit); /api/my/warpwares hand-off + iap.return + my.js redirect; a new visit kind 'dock' in ads.js VISIT_KINDS with its own daily cap (dockCapPerDay, default 10; repeats after the cooldown like refuels; house visits count toward it) and the refuel rail serving game 'warpwares' with that kind (label 'sponsor dock', receipt kind ww-dock, note 'Warp & Wares sponsor dock', refuel.js done text 'Your bonus turns are waiting on the bridge'); GAMES() card with the season window (hidden until 'warpwares' is in gamesLive, its 'Opens' date shown only once live, gone after the season) and STRIP line; growth snapshot counts a season start only when live; walletnudge entry (idle until the secret is set); gamestats + gamepass GAMES/NAMES + GP_SECRETS; Game Pass perks row 'the Season Pass' shown only while the game is in the public games list (gpShown, the Turkey Drop pattern); cap-nudge names; promo tools Games entry (warpwares.saasy.top/?ref=, 3 posts) shown only while live; chatbot CANNED warpwares + fact follow gamesLive and the season window (coming-soon and season-over answers, KB answer kept out of the prompt unless live), KNOWLEDGE_DATE 2026-10-29b; my.js?v=20261029ww, promo.js?v=20261029ww, refuel.js?v=20261029ww. qa/warpwares.mjs (bash qa/run.sh warpwares): 21 checks on a local copy with a mock game (card gating, the hand-off token, a sponsor dock open/challenge/done with receipt + callback, the dock cap separate from refuels, chatbot gating), all passing. Not merged, not deployed.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 16:43:49 -05:00
martbost c621fecb54 BixPay sign-up warning (Marty 2026-10-29: bizventures registered through our correct partner link but BIX recorded referrer N/A): the invite token lives only in BIX's URL and their security check often fails inside app webviews, so members who reopen BIX elsewhere lose their sponsor. Guide, Wallet card and Overview card now say: sign up on the page the button opens, no app first, no portal Sign Up menu; in-app browsers (Gmail/Telegram/Facebook webviews, iOS web views) get a notice with the link to copy into Chrome or Safari (no native dialogs); chatbot card answer carries the same; my.js + bixpay-guide.js ?v=20261029bz
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 11:46:46 -05:00
martbost 13e0644355 QA: syntax gate in every run.sh mode (node --check on every server and public script) after LinkSpin's /traffic-guide shipped with a parse error
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 10:49:06 -05:00
martbost ed6febe0b8 BixPay card integration, phase 1 (Marty approved the copy 2026-10-29; docs/BIXPAY-INTEGRATION.md): gated by site config bixpayLive (off by default). Profile > BixPay card field (partner link validated: bix.ibportal.io/auth/register, e= token, a=1; the appId=3 card-customer link is refused with a message), bixpay.js resolver own > sponsor chain (10 levels) > company link (bixCompanyLink, seeded with Marty's partner link), every surface says whose link it is. Wallet tab card, one-week Overview announcement (24 h snooze), one sentence in TierPaid payout emails and the games' wallet nudges, Promo tools > BixPay tab (3 posts, email swipe, 4 text-only banners on the Spaces CDN, tracked link + per-member clicks), public guide /bixpay with masked app screenshots, chatbot canned answers + facts gated to 'coming soon' while off (KNOWLEDGE_DATE 2026-10-29). Clicks per surface via /go/bixpay in the admin Traffic tab; admin Overview counts members with a link; member card shows it; signed /api/partner/bixpay and the lssync profile row carry it for LinkSpin/CTB. accounts.bix_partner_link column (db.js alterSafe). Tests: qa/bixpay.test.cjs (17) + walk.mjs BixPay block; my.js/promo.js/admin.js ?v=20261029bx.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 07:56:49 -05:00
martbost 6e1ab102f1 Holding-tank Telegram notice: a wallet that predates the tank visit says 'already linked (last seen <date>)' instead of 'linked a wallet' (Marty 2026-10-29: @teamearning, dormant since Sep 18, was returned by a sponsor and the notice read as a live member); digest wording to match; readyTick carries lastSeen + linkedNow
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 07:16:47 -05:00
martbost 01154c0856 Member update emails: claim the send slot before building the recipient list (the Sendy opt-in checks take minutes). On 2026-10-28 a retried POL Miner launch email raced the first one: both passed the 'already running' check, 475 members got it twice; stopped by a restart, the rest went out once. A second send now gets 'A send is already running' immediately.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:34:31 -05:00
martbost 7d134e55a2 Game refuel visits never come up empty (Marty 2026-10-28): after every sponsor has been seen, a member video, then a house sponsor (one of Marty's programs, never the game the player is in; 0 credits, no pool income) and, after the doorRepeatDays cooldown, a sponsor seen before again (a real, paid repeat visit, visit_repeat kind refuel). Repeats and house visits count toward the 20-a-day refuel cap. Applies to every game using /refuel (supply crates, paddles, continues, refuels, hints). Earn stays once-ever. Chatbot fact updated. qa/refuel-fallback.mjs (10 checks); member + earn qa clean; qa/door.mjs prints the callbacks on its pre-existing credits failure (admin-seeded packs are house ads, 0 credits, fails on main too)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:23:46 -05:00
martbost 8b28d028a6 All-games promo posts no longer name a game count (said 'Eight games'); list adds the brick breaker and the mining game; promo.js?v=20261028q
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:28:33 -05:00
martbost f1482deb12 POL Miner joins the Game Pass (2026-10-28, Marty): gamepass.GAMES/NAMES += polminer (polgrant accepts it with POLMINER_SSO_SECRET); pass copy "nine games" -> "ten games" (my.js card + perks table, chatbot pass/Friday/tiers answers, friday.html, Friday pass email); GP_PERKS + chatbot perk line "POL Miner: daily crystal limit 1.5 POL instead of 0.5, plus one free supply crate every day" (PolyBreak gem precedent + Gem Kingdom free-continue precedent); Games card art -> Spaces CDN og-polminer-clean.jpg; promo tools Games entry (link polminer.com/?ref=, og + 11 CDN banners, 4 posts) shown only once polminer is in the public games list; my.js?v=20261028pp, promo.js?v=20261028p. qa member 0 bugs (2 old warnings), qa public 0 bugs (1 old /shorts warning), qa/gamepass.mjs same 5 date-based failures as without this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:11:29 -05:00
martbost 6096bf38c6 POL Miner integration, gated (2026-10-28): POLMINER_SSO_SECRET / POLMINER_URL / POLMINER_ALT_URLS with pmMint/pmOpen/pmIsGameUrl/pmCallback; GAME_AUTH polminer (in-game sign-in kit); /api/my/polminer hand-off + iap.return + my.js redirect (my.js?v=20261028pm); refuel game 'polminer' (label "supply crate", receipt kind pm-crate, note "POL Miner supply crate"); GAMES() card (art polminer.com/og-polminer.jpg) and STRIP line, both hidden until 'polminer' is in site config gamesLive; walletnudge entry (idle until the secret is set); gamestats name; chatbot CANNED + systemPrompt fact follow gamesLive (coming-soon answer and fact until launch, its KB answer kept out of the prompt), KNOWLEDGE_DATE 2026-10-28. qa member: 0 bugs (2 old admin warnings), qa public: 0 bugs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:07:26 -05:00
martbost 1089942bca Game POL pays to any LINKED wallet (Marty approved "build all three", 2026-10-27)
- walletnudge.js: the hourly push hands the member's signature-linked wallet (accounts.address, only set by
  auth.verifyChallenge -> accounts.linkWallet) to every game holding an unpaid balance, activated or not; memberId is the
  on-chain id when there is one, else 0 (a failed chain read falls back to the stored id instead of skipping the row).
  Holding-tank members waiting to switch on payouts no longer have their game POL stuck. Game side unchanged contract:
  signed POST, fill-empty-only (different wallet = 409, retried once a day), idempotent.
- Nudge copy (no linked wallet only): "You've earned X POL in <game>. Link your wallet (one free signature) and it's sent
  automatically, including everything you've earned so far." + /my#wallet; never mentions switching on payouts.
- The IAP -> game /auth tokens already carried wallet: a.address regardless of activation (no change).
- chatbot.js: game-pol-wallet canned answer (ahead of the per-game entries) + GAME POL TO ANY LINKED WALLET prompt fact
- qa/walletnudge.test.cjs (mock game: non-activated push with memberId 0, activated push, chain-read failure, nudge copy,
  409 refusal + daily retry), wired into qa/run.sh member + walletnudge; chatbot-parse routing cases for the new answer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-16 08:18:09 -05:00
martbost d0cc45eadb AI calls: reasoning off (deepseek-v4-flash began thinking by default and used the whole max_tokens, so chatbot and Copy Engine answers came back empty)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:30:23 -05:00
martbost 0db7c94728 Plan lab: honest licence booking, licence levels kept after the replay, unsponsored joins under the top position, sponsor leg obeys the gap toggle, pool-only members no longer count as paid
- Licence value now books the money each leg actually moved for it (its own share of the level), not the full level price; labelled "licence value funded" with a note on what a licence-granted level costs the system
- gStartRun: after replaying an org, money counters reset but members keep every level they hold, licence-won ones included, and keep what they actually paid in
- Joins with no recruiter go to the top position (spread placement) instead of the earliest member with one recruit, which qualified members who never brought a second
- Sponsor-leg licences respect the gap toggle (skip vs fund), like the depth leg
- "Paid" counts cash or entry share only; pool-only members are reported apart
- The climb and the drawn tree are labelled as simplified depth-only illustrations; headline numbers come from the month-by-month run
- Cache tag bumped

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 17:10:12 -05:00
martbost be268beb66 Presentation sponsor card: a capped bio ends on a whole word with an ellipsis
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:57:13 -05:00
martbost bb11f8183d Chatbot: Road Agent (live 10-15) and its fuel-stop visits, from today's two release notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:52:50 -05:00
martbost 7aec7d5169 Presentation page + Build Wide 'wide' join angle
- /presentation: the narrated InstantAdPay presentation (video on Spaces
  training/iap-presentation.mp4, poster .jpg), caption pills for
  en/it/fr/es/de/pt (VTTs served from /captions, text/vtt MIME added),
  sponsor card from /api/sponsor ("Shared with you by @name" + Join to
  /join/<ref>?v=wide, or the plain join link). Works framed: join and
  sign-in open a new tab, internal links carry ?ref.
- Site menu + footer: Presentation. Sitemap, Traffic pages and the viral
  page list include it. Promo tools: "Share the presentation" strip copies
  instantadpay.com/presentation?ref=<username>.
- 'wide' join angle (Width unlocks depth.): server JOIN_ANGLES with the
  buildwide poster as og:image, join.js angle (portrait video on phones,
  16:9 otherwise, files promo/buildwide*), link stats row, promo VIDEOS
  first entry with a per-entry file override, front-door list entry.
- Chatbot: presentation canned answer + facts, ?v=wide in the angle lists,
  KNOWLEDGE_DATE 2026-10-15.
- common.js/my.js/promo.js/join.js cache tags bumped; qa/walk.mjs PUBLIC
  gains /presentation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:51:04 -05:00
martbost d86f2fbcf8 Reverse registry sync: LinkSpin-first members arrive on InstantAdPay as waiting accounts
POST /api/partner/registry (same HMAC LS_SYNC_SECRET scheme LinkSpin accepts from us, 10-minute window) feeds
lsinbound.js: an email already on InstantAdPay keeps its sponsor and only gets empty fields filled (username if free
and allowed, wallet if no other account or linked position holds it, profile); a new email becomes a waiting shell
(joinedVia linkspin) under its LinkSpin sponsor, building the sponsor's shell upward from known rows (25 levels),
remembering a sponsor whose row has not arrived and binding it later, refusing sponsor loops. No mail, notices or chain.

Unclaimed shells are left out of accounts.listAll by default (tank, coach nudges, Friday/Wednesday broadcasts, member
update audiences, leaderboard, 1,000-member milestone count); the admin members table and lssync ask for them. The first
sign-in claims the shell: the sign-up anti-fraud checks run then, a sponsorless shell takes the link used, lastSeen set.

Loop guard: lssync mutes an email while its LinkSpin row is applied, then records the result as already pushed when it
equals what LinkSpin sent; touch() now skips rows whose hash is unchanged. Status: GET /api/admin/lsinbound (also under
/api/admin/lssync as inbound).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:44:53 -05:00
martbost ae72a06a85 Mail: every non-transactional email carries an unsubscribe link and honours opt-outs
instantadpay.com landed on the Spamhaus DBL. Only the drip and the admin update
tool had an unsubscribe link; the Wednesday/Friday broadcasts, coach nudges and
digests, milestone, refill, reach, wallet nudges and sponsor notices had none,
and several did not check opt-outs. The rule now lives in mailer.send, so new
senders inherit it: skip anyone who unsubscribed, append the signed link (unless
the body already has one) and add RFC 8058 one-click List-Unsubscribe headers.
Exempt (transactional): sign-in codes, mail to ADMIN_EMAIL, purchase receipts
and payout notices. /unsubscribe now accepts the one-click POST too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 06:34:40 -05:00
martbost 4759cabf09 Game art off the adrotate.xyz host: ad blockers filter 'adrotate', so the PolyBreak card showed no image (Games tab, public games page) and promo banner previews went blank; serve from the Spaces CDN instead
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 08:28:31 -05:00
martbost 2df64f6247 Angle pages: each hook angle shares with its own video frame as the preview image; Share sends one message with the link inside the text (Telegram dropped the separate url)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:51:58 -05:00
martbost ba811e48f8 Angle page 'play': /join/<member>?v=play shows the 'If you have time to play' video, three points and a Play the free games button (games page with the member's ref) above the free sign-up; listed in Promo tools angle pages; the video's matched link now opens this page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:43:46 -05:00
martbost 375ddf75bd Promo tools Videos: 'If you have time to play' angle (games as a trust tool), matched link + caption point at the member's games page ({{GAMES}})
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:29:37 -05:00
martbost 7a79b4a930 Chatbot: fix a broken string in the PolyBreak answer (crashed startup; Coolify rolled back)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:32:37 -05:00
martbost c40b7ccb5c Promo tools: PolyBreak card shows once the game is in the live games list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:16:24 -05:00
martbost c43f166418 Chatbot: PolyBreak canned answer + facts, Games roster, KNOWLEDGE_DATE 2026-10-13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:15:46 -05:00
martbost ab83e37d23 PolyBreak on the network rails (hand-off, in-game sign-in, one-more-paddle refuel receipts, Games card, strip line, return routing) + Promo tools PolyBreak card, 600x300 traffic-exchange size for every game and InstantAdPay's own 600x300 banner
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:06:57 -05:00
martbost 06f2665809 PolyWarriors pass mint: visible 'Minting now' hand-back page with a Back to PolyWarriors button and a 2 s auto-return (a silent redirect chain left Zachary's iPad on the mint form)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 13:45:48 -05:00
martbost 8d3fc12862 RPC breaker: bench a provider only for health failures (timeouts, connection errors, rate limits, 5xx); request errors such as invalid block range just move to the next provider
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 11:40:15 -05:00
martbost f417d416da RPC circuit breaker for InstantAdPay: bench a failing provider for 10 min, 4 s timeout on eth_call, log provider failures; log any request over 3 s (members felt slow sign-ins; the sticky index was paying the 15 s timeout on every call when a node hung)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 11:29:31 -05:00
martbost a63f6206a3 Chatbot: fix PolyWarriors regex word boundaries (backspace bytes from the heredoc)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 10:05:33 -05:00
martbost 10617df866 Chatbot: PolyWarriors + SpellWheel canned answers and facts, Games tab roster, /games page, KNOWLEDGE_DATE 2026-10-12
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 10:02:31 -05:00
martbost 0f56d3c7bb PolyWarriors launch trailer: Promo tools game card (player, 16:9 + vertical downloads, poster, caption, share) and the public games card plays it; poster replaces the coming-soon art
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 09:41:35 -05:00
martbost a5acf0c848 Promo tools: PolyWarriors card copy for the live game (24 rivals, fusion, mint passes, Telegram line)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 07:56:29 -05:00
martbost 1287f94669 Bare /join: use the viral-link token when the handler already consumed ?ref= 2026-10-11 18:36:12 -05:00
martbost b796a7a64e Bare /join: honour ?ref= before the sponsor cookie 2026-10-11 18:29:22 -05:00
martbost 041a3d41ae Bare /join redirects to the sponsored join page (cookie sponsor, else company); games page links /join/<ref> directly
Diann: "Join free" on /games?ref=diannt landed on "Not found". /join, /join?ref=
and the Friday/Wednesday /join?v= links all 404ed because only /join/<token>
was routed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 18:26:24 -05:00
martbost 9cf039270e Telegram feed: name a freshly activated member by wallet when the chain id is not mapped yet
The "switched on payouts" line read a bare "#200" although the member had a
username (roodtriaan07): names are looked up by chain id, which the account only
gets after the index links it. Fall back to the activating wallet's account.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 06:48:35 -05:00
martbost a6c523c6aa LinkSpin sync: carry the member profile (avatar, bio, social links) with each row
Marty 2026-10-11: members should not re-type their profile on LinkSpin. Rows now
include profile {avatarUrl (absolute https), bio, socials}; it is part of the row
hash so every profiled member re-syncs once, and a profile edit touches the sync.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 06:40:05 -05:00
martbost 23da5b61ba PolyWarriors mint bar: 4 h cookie (was 7 days), cleared on every exit, x to hide
Members who tapped Mint, saw the price and went back to the game kept the blue
"PolyWarriors mint" bar on the dashboard for a week. The cookie now lives 4 h,
is cleared by Back to PolyWarriors / Cancel (new /pw/mint/leave), by the
mint-pass success redirect, and by an x on the bar (/pw/mint/dismiss). The
waiting order itself is untouched: a later package still completes the mint.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 06:28:53 -05:00
martbost 7b4c2ef9e5 Games page featured strip: tags at the card foot
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 18:20:38 -05:00
martbost 1ffca3030c Games page: featured PolyWarriors listings come through a same-origin proxy (/api/public/pw-featured, 60 s cache); the page CSP blocked the direct call
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 18:13:09 -05:00
martbost ef6c6b584e Games page: a strip of featured warriors from the PolyWarriors market (rarest listings, forged art, links into the market)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 18:07:32 -05:00
martbost 84d54eda16 Games page in Promo tools (All games entry with the member's referral, three posts), in the viral-link page list and the chatbot; a generic games banner (1200x630 + 1080 square) as the /games share image instead of the two-games launch art (Marty 2026-10-10)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 14:18:55 -05:00
martbost fcb9edd2eb Public games page at /games (Marty 2026-10-10: a page to send people): every game, open ones first, dated ones after, with play links to each game's site, OG tags, and a join call that keeps ?ref; data from the new public /api/public/games/all
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 14:06:55 -05:00
martbost f8e55413ee Mint passes survive deploys: durable persisted maps (passes, prizes, game orders) are restored whatever their age, pass records carry ts; the admin member card shows PolyWarriors mint passes
The open-tokens loader kept only entries newer than 2 hours, meant for short-lived earn tokens; pass balances had no ts, so every deploy wiped them (Orlando's were lost on 2026-10-10).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 09:51:06 -05:00
martbost 310992e40f 1,000-member POL drop (Marty 2026-10-10): snapshot of activated members at the milestone, 1 POL each from a dedicated wallet, notices for paid and missed
milestone.js watches the account count (site config milestoneMode off|dry|armed, milestoneTarget 1000, milestonePol 1). At the target it freezes the eligibility list: wallet activated on chain (member record with activated flag), not on the no-payout list, not suspended, one payment per wallet. Payments go one at a time from IAP_MILESTONE_KEY with tx hashes per row and never twice; the Telegram start post waits for the wallet to hold the full amount. Paid members get an in-app notice + email with their Polygonscan link; everyone else gets the missed-it nudge (link a wallet / switch on payouts), email only with the newsletter opt-in. One start and one finish Telegram post (Discord mirrored), the total logged in the P&L as a rewards cost against Receiver A. Admin: /api/admin/milestone (view, mode, snapshot, recheck, pay, settle, notify-missed, reset-before-payment).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 09:35:50 -05:00
martbost 4b7b1c5d95 Two-games launch short (35 s vertical, SpellWheel + ClutterHunt gameplay, Marty's voice) hosted for social posts
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 07:09:09 -05:00
martbost 69b7395387 Two-games launch banner (SpellWheel + ClutterHunt, 2026-10-10) in 1200x630 and 1080x1080 for social posts
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 06:39:58 -05:00
martbost d8a31ddd40 Games tab: a coming-soon card stops carrying its soon object once the opening day arrives (SpellWheel's button read '[object Object]' on 2026-10-10); SpellWheel card art switches to the game's live OG image
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 06:16:15 -05:00
martbost f7c4d34a35 PolyWarriors mint pass: the button shows Minting... and the redirect no longer waits on the game callback (Marty's phone sat on the form on 2026-10-09 while the mint had already gone through)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 18:30:26 -05:00
Marty Bostick 1c9db665b3 Discord relay: wrap button links in <> so Discord shows no preview cards under every post
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 15:16:36 +00:00
martbost 7d20cd2c35 Login ad: frame the sponsor's page inside the gate under the timer bar (open-in-tab link, dashboard button), new-tab fallback only when the site refuses framing (Brian Holland: no timer, no way out on the ad tab)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 09:17:48 -05:00
Marty Bostick efb6020e40 Mirror Telegram group posts into the Crypto Team Build Discord
Discord relaunch 2026-10-09: the shared discord-relay.cjs fans every post that goes to the
community group out to the matching Discord channel (achievements topic -> #achievements,
payments topic -> #payment-proofs) through DISCORD_WEBHOOK_* webhooks. Telegram HTML is
converted to Discord markdown, buttons become links, cards post as images. DMs and alert
chats are not mirrored. Fire-and-forget; off when the env is unset.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 13:57:29 +00:00
martbost f53bd67d30 Dwell timers no longer stall on phones: a focused ad frame or a touch device counts as an active tab (Brian Holland 2026-10-09: no timer, no close on the welcome tour and verified ads on mobile)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 08:44:27 -05:00
martbost 75339757e5 Promo kit: October Five Dollar Friday banners (bright porch, 1200x630 + 1080x1080) at the top of the Friday band
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 04:48:36 -05:00
martbost d4b0e74829 Archived card shows what each campaign actually returned (Yoshi: 'credits released' read as a refund on 7 fully delivered campaigns)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 13:40:31 -05:00
martbost af5a53b833 Daily snapshot gains a Games block: members handed into each game (counted at hand-off, per hour) and payouts read from each game wallet on Polygon in the last 24 h, launches of the day called out
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 09:13:44 -05:00
martbost d07a32a837 Game return bars say what happens: buy a package and you go straight back to the game when it settles
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 08:31:49 -05:00
martbost 67cb82eef3 Game purchases return to the game automatically once settled (PolyWarriors mint, Gem Kingdom Crowns, Spooky Doors costumes); status toast lifts above the game return bar so results are readable
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 08:28:18 -05:00
martbost 7131adfc42 Games tab: Play opens the game in a new tab so the dashboard keeps its place (Marty 2026-10-08)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 07:51:45 -05:00
martbost 5f6ab1b35c accounts.onChange hook (restores production boot)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 07:30:56 -05:00
martbost a61a4f8745 LinkSpin registry sync module + account change hooks (restores production: server.js required lssync before the module was committed)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 07:23:59 -05:00
martbost d93d26f2e3 Signed /api/partner/registry: InstantAdPay pushes member rows live; new people become shell accounts with their line, existing shells gain username/wallet/sponsor
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 07:14:39 -05:00
martbost 7e949c86ec Cross-promo strip entries for SpellWheel and PolyWarriors (shown once each is in gamesLive)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 04:57:02 -05:00
martbost 468def461c Tester view of a coming-soon game drops the soon object so the Play button renders (showed [object Object])
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 17:30:57 -05:00
martbost 8285e31fbd Game testers (env GAMES_TESTERS) see the Play button on a coming-soon game from the Games tab before it opens (Road Agent testers, Marty 2026-10-07)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 17:17:33 -05:00
martbost b82f63f803 Road Agent card shows 'Opens Thursday, Oct 15' to every member until launch day; Promo tools gain the Road Agent entry on launch day
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 14:10:20 -05:00
martbost dfd0b9dbed Destination reachability: refuse a link whose host has no DNS record at save time; daily sweep pauses live ads whose host is dead two days running, notices the owner (in-app + opt-in email), one admin alert; Admin API /api/admin/reach (+/run, dry) (campaign #163 served lmgnow.co after the domain vanished)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 13:24:50 -05:00
martbost 04fad66dab Road Agent hooks: per-game door round trip (fuel stops under RA_SSO_SECRET, callbacks to RA_URL), /api/my/roadagent hand-off, registry + strip entries (not live), wallet nudges ask Road Agent, door page words itself as a fuel stop
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 12:30:41 -05:00
martbost 616bd37142 Wallet-link nudges: hourly job asks each game (signed with the shared secret) for players with POL waiting and no wallet, sends up to three notices per person (now, 3 days, 10 days) in-app and by opt-in email, stops when a wallet is linked; coach directs badge "POL waiting, no wallet"; admin view and run endpoint
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 10:35:16 -05:00
martbost ca065e456e Coach directs: Pay it forward is offered to any direct with a linked wallet who has not bought a package yet, including directs who already switched payouts on (the gift funds the first package, not the activation)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 10:14:41 -05:00
martbost 2a96d5c672 Wired Wednesday and Five Dollar Friday Telegram kickoffs at 5 AM CT (kickHour setting, was hard-coded 9 AM)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 06:41:34 -05:00
martbost 5c31f4540c Sign-in guard: measure form age on the visitor's own clock (fage) so a device with a fast clock is not refused forever
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 04:26:58 -05:00
martbost 28b90dcae4 Chatbot knows the Platform facts page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:31:05 -05:00
martbost 98c24c2e6b Platform facts page (/facts) and /llms.txt: verified contract split, credits, refunds, anti-fraud and games; footer link on every page; sitemap entry
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:25:26 -05:00
martbost 6191c07fa5 Count Polygon RPC calls by method (DATA_DIR/rpc-count.json every 5 min) for a 24 h measurement
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:47:11 -05:00
martbost ef8b256172 Promo tools: one Games tab (picker for all 7 games; PolHunter and Spooky Doors kits live inside it; link, share image, posts and 10 banner sizes per game); SpellWheel link fixed to spellwheel.com
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:16:12 -05:00
martbost 5a39b2599f Promo tools: Game banners section (7 games x 10 standard sizes on banners.adrotate.xyz, embed code linked to the member)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 07:52:17 -05:00
martbost 9142efef01 PolyWarriors mint passes go to the NEWEST waiting order (an old forgotten order took Marty's); admin endpoint to credit/remove passes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 07:30:56 -05:00
martbost 8251c0e693 Broadcasts: a pop-up when sent (how many members) and when not sent (why); an expired sign-in keeps the draft and offers Sign in again (Brian 2026-10-05)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:57:06 -05:00
martbost ba5cdfdf4b Network labeling: InstantAdPay is the Polygon hub of the Crypto Team Build Network (footers, dashboard footer, Games tab)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:48:25 -05:00
martbost a32c1ab3c9 PolyWarriors weekly season prizes: signed game claim -> earned credits (setting pwWeeklyPrize 1000,500,250), once per week+place
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:38:18 -05:00
martbost e3b2c7b579 PolyWarriors mints: every $5 of packages bought while a mint waits earns one mint pass (bigger packages earn more, kept on the account); one-tap 'use a pass'; members keep the ad credits; existing credits never pay for mints (replaces the 100-credit checkout)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:15:30 -05:00
martbost ec57a926fc Welcome back bonus: +250 earned credits on the first sign-in after 7+ days away (settings comebackBonus/comebackDays)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:28:54 -05:00
martbost 503a252fc8 P&L: Game marketing category for game wallet top-ups (old top-ups moved once from Player rewards); counted in Advertising and promotion
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:22:06 -05:00
martbost 18813a4127 PolyWarriors paid mints: /pw/mint checkout, 100 credits from package credits only (earned never counts)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:56:44 -05:00
martbost d1a638b66b Games tab: PolyWarriors coming-soon card (opens Monday Oct 12); sign-in kit's one-tap link carries the inviter's ref
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:32:13 -05:00
martbost f9299e5ef3 One-tap game links keep the inviter's ?ref for signed-out visitors (PolyWarriors, SpellWheel, ClutterHunt, Drip Runner, PassiveDrip; Gem Kingdom and Spooky Doors already did)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:25:36 -05:00
martbost c99896c131 Member welcome offer from the games: starter.js (+100 purchased-grade credits on a first $5+ package after a game visit within 14 days, once per account; setting starterBonusCredits), /api/starter + /api/starter/public, /my?from=<game>#buy banner with the way back to the game perk, Members get <perk> on game cards, admin Traffic 'Games to members' table
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:26:03 -05:00
martbost f09ff71c56 PolyWarriors hookups: in-game sign-in (game 'polywarriors', PW_SSO_SECRET), one-tap /api/my/polywarriors, sign-in return route
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:34:37 -05:00
martbost e09babc1ff SpellWheel hookups: in-game sign-in (game 'spellwheel', SW_SSO_SECRET), one-tap /api/my/spellwheel, sponsor-visit hints through the shared refuel flow (sw-hint receipts)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:56:40 -05:00
martbost 376a4b04f2 Chatbot: ClutterHunt pays POL now (fixed per-room rewards, no caps, no promises)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:38:40 -05:00
martbost 1ac5e1d206 Coming-soon card: no ribbon (the art says it and it covered the title)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:28:38 -05:00
martbost 5a4b27f50e Games tab: SpellWheel coming-soon card (date, no Play until Oct 10); ClutterHunt card now says it pays POL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:27:11 -05:00
martbost a453366964 Games cards: frame matches the 1200x630 art (no side crop); limited-time ribbon top-right so it no longer covers the title
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:02:19 -05:00
martbost 9b904b1a64 Audit: visit counters are proven by our viewer + repeat door visits + PassiveDrip deliveries; flag only counts above their proof (37 false alarms)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 07:56:20 -05:00
martbost 4e35a83fdd Tax summary: real block timestamps for sale dates (the 2 s estimate drifted weeks), cached
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 07:24:17 -05:00
martbost eb3cfebf1f P&L: Cost lines with tax categories (advertising, player rewards, software, other), outside-wallet source, duplicate-tx guard; Tax summary (income vs advertising/promotion, own sales excluded, CSV)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 07:22:21 -05:00
martbost ca7a579990 Admin: stop a member campaign on every rail (pause + archive, releases unspent budget) and grant refunds as purchased-grade credits (Shift AI closed)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 07:06:42 -05:00
martbost 3f758cdd38 Framed pages: the new tab's sign-in link carries the page's sponsor (?ref, /join/<tok>, /wall/<tok>)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 19:39:18 -05:00
martbost 563ece9896 Traffic exchanges: inside another site's frame, sign-in/join and off-site links open in a new tab (sign-in cookies are refused in frames)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 19:23:04 -05:00
martbost b53de647b9 PolHunter door: a signed-out visitor keeps the share link's ?ref through to /my sign-in (framed traffic-exchange visits lost the sponsor)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 19:15:52 -05:00
martbost 1932b625ac Chatbot: ClutterHunt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:11:47 -05:00
martbost a3905a0b5a ClutterHunt: SEEK_SSO_SECRET tokens, in-game sign-in (game seek), one-tap hand-off, hint visits via the refuel flow, Games card + strip entry
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:10:03 -05:00
martbost 7775ed87ef Member update emails can carry one linked header image: a simple HTML part alongside the plain text (same paragraphs, footer, unsubscribe)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:19:49 -05:00
martbost 067460c0e6 Chatbot: Gem Kingdom free revive, Hero Bundle, Kingdom Pass, hero looks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:10:04 -05:00
martbost 56eb1f2d4f Gem Kingdom continues ride the refuel flow (GK token, gk-continue receipt + callback, game-aware page, in-game overlay message); house-ad visits report 0 credits so no game pool books income nobody paid
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 15:47:51 -05:00
martbost 22407fe9ae Game purchases report the purchased part (paid): earned viewing credits are not money, so game POL pools grow only from purchased credits (Gem Kingdom + Spooky Doors receipts carry paid)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 15:36:33 -05:00
martbost 0fd67b407a In-game sign-in carries the paid-traffic source: joinedRef = <game host>/<src>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 11:30:23 -05:00
martbost 0112422c72 Cross-promo strip: /api/public/games (live list, Spooky Doors while in season), /g/<slug> counted hop (signed-in straight into the game), shared /assets/game-strip.js; Drip Runner card says 0.10 POL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 10:19:39 -05:00
martbost 30c95026f9 In-game sign-in for the games: /api/game/auth/{start,verify,username} (CORS for the game origins, same code guard and one-account checks), /api/game/enter for signed-in nudges, shared kit /assets/game-signin.js
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 10:01:34 -05:00
martbost e484025d6d Retire the PolHunter launch card: launch announcements show 7 days after launchAt, then stop
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:41:22 -05:00
martbost 737ed28e1d Overview announcement cards: the x hides a card for 24 hours (was until next sign-in, so they stacked up at every login)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:32:29 -05:00
martbost 8f61d11d43 Chatbot: PassiveDrip is live on the Earn tab for every member (canned answer + prompt facts)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 07:51:04 -05:00
martbost 217802d577 Spooky Doors promo card link uses ?ref= (consistent with the other programs)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:07:09 -05:00
martbost 2c2d93b2dc Chatbot: empty doors now show a house ad (smaller treat), not Nobody's home
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 15:57:11 -05:00
martbost a5a991d024 Spooky Doors launch pack (IAP side): door packs + Golden Doors, Promo tools card, season from Oct 4
- Visit packs get a placement: 'all' (as before), 'doors' (Behind Spooky Doors, doorPackCost 4/door) or
  'golden' (Golden Spooky Door, goldenDoorCost 6/door). campaigns.placement column (alterSafe) + JSON store.
- Doors serve golden packs first, then door packs, then the existing chain; each pack at most once per
  player per Central day. Door-only packs never reach the Earn tab, refuels or the PassiveDrip listing
  until rates.sdSeasonEnd ('2026-11-01'); from then on they behave as 'all'.
- Door payloads: credits = per-door price actually charged (3/4/6); Golden Doors add golden: true and
  bonus: goldenBonusCandy (2) to /api/door/open, done, callback and receipt. Gold variant of /door.
- Campaign list: Spooky Doors / Golden Door chip, doors opened + unique players, Buy more doors at the
  door price. Composer: placement choice with live cost. Admin rates labels + house pack placement.
- Promo tools: Spooky Doors card (spookydoors.com/r/<username>, copy, share image, two posts) on the same
  season window as the Games card (seasonState helper).
- Season start moved up to 2026-10-04 (Games card + promo card + chatbot).
- qa/door.mjs covers all of the above.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 15:55:19 -05:00
martbost 9809953ae0 Spooky Doors house ads: an empty street serves one of Marty's programs instead of "Nobody's home"
When a door finds no visit pack and no video, /api/door/open serves a house ad from rates.doorHouseAds
(RM Circle, Drip Runner, Gem Kingdom, PolHunter by default; ref templates carry the player's IAP username
where the program takes a share link). Rotation: never the same program twice in a row, else the one least
recently shown to that member today. Same dwell + Halloween icon check. No advertiser charge and no campaign
imps, but it counts toward doorCapPerDay (visit_repeat row with campaign 0). Callback and receipt add
house: true and program, with credits 0, host null, campaignId 0. doorHouseAds = [] restores none=1.
Admin rates table keeps text columns as text so the list survives a save. qa/door.mjs covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 15:06:53 -05:00
martbost dbbce34202 Spooky Doors: doors may repeat a visit campaign after doorRepeatDays (7) via visit_repeat; Earn and refuels stay once-ever
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 14:51:10 -05:00
martbost 3b57bbc9cf Spooky Doors door check uses Halloween icons (pumpkin, ghost, bat, candy...) instead of the generic set
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:10:41 -05:00
martbost 27c9d51fde Spooky Doors (Halloween season game): hand-off, door visits, costume shop, seasonal Games card
- SD_SSO_SECRET / SD_URL (default https://spookydoors.com); sdMint/sdOpen same token shape as Drip Runner
- GET /api/my/spookydoors sign-in hand-off (?ref pass-through; iap.return spookydoors + sdshop whitelisted)
- /door page (Halloween copy of /refuel, door art backdrop) + /api/door/open|challenge|done as visit kind 'door';
  signed callback to SD_URL/api/door/callback (X-SD-Ts/X-SD-Sig) + 24 h door-receipt on ret&ok=1&r=;
  ret&none=1 when nothing to serve, ret&cap=1 at the daily cap; host = campaign owner's username
- /sd/shop (+ topup/resume/confirm) costume checkout via ads.gamePurchase('Spooky Doors: <label>'), sd-receipt
- Games tab: generic season window (Central days, admin preview before start, hidden after end) + pink
  limited-time ribbon; progress from SD_URL/api/partner/player (signed); my.js ?v bumped
- Chatbot canned answer + prompt facts; qa/door.mjs (bash qa/run.sh door) end-to-end on a throwaway local copy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 09:40:08 -05:00
martbost b6850d4342 Visit kinds generalized: 'door' (Spooky Doors) gets its own daily cap doorCapPerDay (15)
earn/refuel/door each count only their own visit_seen rows; earn and refuel behave exactly as before
(reward:false without a kind is still a refuel). markRefuelVideo takes an optional kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 09:40:07 -05:00
martbost 6804a26c5d Games cards: optional artPos crop anchor; Drip Runner share image anchored left so its headline isn't cropped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 08:47:36 -05:00
martbost bc713f57b0 Games tab: Drip Runner card uses its share image
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 08:45:59 -05:00
martbost 5c54bd3905 Games tab: Gem Kingdom card uses the share image
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 08:18:39 -05:00
martbost 4a38d9ce79 Member menu: drop the standalone PolHunter link (it lives in the Games tab now)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 08:17:22 -05:00
martbost 0414560ecb chatbot.js: restore CRLF line endings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 07:58:50 -05:00
martbost 9212128b0d Chatbot + Games card: Gem Kingdom pays POL for first clears (six chapters, boss ladder to 10 POL, pool-funded, no referral bonus)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 07:58:39 -05:00
martbost da7e421daf Chatbot: Gem Kingdom is live in the Games tab (pays no POL; Crowns bought with ad credits); the Games tab no longer says every game pays POL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 06:43:23 -05:00
martbost be102a4b16 Gem Kingdom sign-in carries a feed post's ?ref through to IAP sign-up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:00:39 -05:00
martbost 0e32a57424 Gem Kingdom shop: Paid! page with refresh back to the game (CSP form-action blocked the cross-site 302)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:29:48 -05:00
martbost be313e6202 Gem Kingdom: sign-in hand-off (/api/my/gemkingdom), Games card (admin preview until gamesLive), Crown shop checkout (/gk/shop: confirm, short -> top-up detour with dashboard banner back, confirm spends credits via ads.gamePurchase, signed receipt redirect + server callback); game purchases skip refill notices and the campaign list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:36:03 -05:00
martbost 513c713292 PassiveDrip moves from Games to an Earn-tab card (it is an earning site); members see it when site config passivedripLive=on, admin preview until then
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:11:19 -05:00
martbost f56f363090 Chatbot: Drip Runner is live at driprunner.app
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 09:38:53 -05:00
martbost 5a522f0ede Weekly member email as sectioned HTML (plain-text twin kept); PassiveDrip one-tap hand-off (inert until PD_SSO_SECRET)
- coach.js: weeklyDigest() builds one card per topic (credits, streak, contest, tank, team) with the key number up front and one button; mailer.send takes optional html
- server.js: /api/my/passivedrip mints a signed hand-off (memberId, email, username, verified wallet, sponsor email); Games card for PassiveDrip (admin preview until gamesLive includes passivedrip) with the member's own coins line via the bridge 'member' lookup; sign-in return path
- my.js: card button label, return redirect; v=20261001b

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 08:43:22 -05:00
martbost dd53d132d6 Games hub: one Games menu entry and pane with a card per game (registry in server.js, live list = site config gamesLive, default polhunter; admin sees unlaunched games as previews), Drip Runner card with the player's own progress via a signed read; chatbot knows Games + Drip Runner (KNOWLEDGE_DATE 2026-10-01); QA walk covers the pane
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:36:49 -05:00
martbost 5fe6058e76 Drip Runner video refuels: when a player has visited every running visit pack, the refuel plays a member video ad (advertiser charged one view as on the Watch tab, player gets fuel not credits, counts toward the refuel cap, one refuel per video per person); timer runs only while the video plays and the page is in front
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:52:52 -05:00
martbost 5d0e89be6f Drip Runner refuels get their own daily allowance (refuelCapPerDay 20): visit_seen.kind earn|refuel, each kind capped separately, once-per-page-per-person still spans both; clearer refuel cap / no-packs copy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:44:59 -05:00
martbost 2b2e131c3e Drip Runner referrals: /join/<ref>?from=driprunner returns newcomers to the game once they have a username, first-touch source driprunner.saasy.top, hand-off carries sponsorRef/joinedRef
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:14:05 -05:00
martbost f1b37e0c4a Drip Runner return path: signed-out hand-off sets iap.return=driprunner and the email sign-in answers next=/api/my/driprunner (straight back into the game); refuel page dead ends keep a Back to Drip Runner button
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 14:01:47 -05:00
martbost 587272673b Drip Runner trial (2026-09-30): /api/my/driprunner hand-off, /refuel verified-visit page for the game (advertiser charged, viewer gets fuel not credits, signed callback + receipt), completeVisit(opts)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 13:33:37 -05:00
martbost 3ae9ab55e9 Balances: show earned and bonus credits that live campaigns already hold (Jim's Wired Wednesday bonus read as +0 earned); PassiveDrip bridge PD_SYNC_APPLY=0 read-only mode while pointed at staging
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 08:08:50 -05:00
martbost 972421fbbe PassiveDrip PTC bridge: visit campaigns listed on PassiveDrip's paid-to-click page (signed sync every 5 min), delivered visits read back and applied to the pack (read, never derived); admin status + run routes
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 07:57:47 -05:00
martbost a2d7bede82 Refill: 7-day idle follow-up (unanswered out notice, >=100 credits, nothing running; once per record, tracked as state idle); ad click relay ignores an advertiser opening their own ad
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 04:34:38 -05:00
martbost f7d9fd65cb Wired Wednesday: admin route to post the kickoff now (marks the day sent so 09:00 does not repeat it)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 04:26:24 -05:00
martbost 75d084c4b7 Refill notices: video campaigns report watches, watch length and per-watch price so the relaunch maths is clear
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 04:17:51 -05:00
martbost a7a15615ec Sponsor survives a lost cookie: join page sends its own token with the code request, server remembers it per email for 30 days, framed visitors offered a full window
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 09:48:06 -05:00
martbost b5baaf27e8 Partner kit pages at /partners/<slug>; first one for Jamie (@cryptojaime)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 09:36:25 -05:00
martbost b197d74234 docs: reviewer partner kit for Jamie (@cryptojaime), code CRYPTOJAIME
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 09:30:36 -05:00
martbost a60905a9fb Tank, roster and downline: sortable/filterable lists with last seen, surf earnings and wallet/payout state; admin Members table loads 5000 accounts
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 09:25:55 -05:00
martbost 58dc3864cd Friday Bonus Hunts card: say plainly when an unopened inbox ad is what blocks today
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 08:50:12 -05:00
martbost 37a78de339 Wired Wednesday: page, kit, chatbot and banners say $20 and up
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 08:10:48 -05:00
martbost 43463366ec Wired Wednesday floor is $20 (Activation pack and up): there is no $10 package
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 08:07:21 -05:00
martbost d43836a892 Shiny-objects article: widescreen art as the cover and in the kit
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 07:32:02 -05:00
martbost 9c90a95f4c Shiny-objects article art in the promo kit (cover, square, portrait) with a share-the-article link
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 07:27:09 -05:00
martbost a765b97421 Bridge pages: banner keeps its aspect ratio on phones (height:auto)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 05:46:58 -05:00
martbost 8a6029cd90 Wired Wednesday: bonus is wired into the balance (purchased-grade, any format), no forced visits campaign; all copy corrected
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 05:42:08 -05:00
martbost 5b54debf72 Wired Wednesday: configurable Tuesday notice hour + optional Tuesday Telegram heads-up
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 05:27:50 -05:00
martbost 79023e5f46 Wired Wednesday wrap-up names the biggest lines of the day, like Friday's
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 05:06:22 -05:00
martbost 04fd4db9ca Wired Wednesday: +25% on $10+ packs wired into a verified-visits campaign; /wednesday bridge page, banners, kit, cards, chatbot (notice + kickoff off until approved)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 04:49:34 -05:00
martbost 7ce7aeffa4 home: platform-overview embed points at the 48 kHz re-encode
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 16:17:43 -05:00
martbost 61be49c303 plan-lab: knob for levels bought up front by your position, net of what you paid
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 10:41:58 -05:00
martbost e6b5a9fb22 plan-lab: long runs paint every month with progress and can be interrupted; O(recruiters) placement and picks
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 10:01:47 -05:00
martbost b55388c83b plan-lab: activity pool (15% company + 5% pool), money-flow bar, three example members, the mix table
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 09:32:36 -05:00
martbost 39951cfac5 plan-lab: each leg funds licences at its own share, so join-and-pay members keep their path
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 08:58:35 -05:00
martbost 257b06d6d2 plan-lab: sponsor leg, entry split, Fast Start switches; builders vs join-and-pay mix; 0 ladder
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 08:55:41 -05:00
martbost 34e9d32a8a plan-lab: how-to-read section for reviewers; Start over zeroes every counter
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 08:26:56 -05:00
martbost fd7b5d7ed7 plan-lab: fresh script version tag on every build
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 08:16:03 -05:00
martbost 06a83a0b97 plan-lab: forward-only wording, no comparisons to other programs
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 08:12:19 -05:00
martbost c20a5ed56b plan-lab: spread placement is the decided default
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 07:17:05 -05:00
martbost ab2431be11 Email an update: release notes are optional when there is an intro
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 05:22:24 -05:00
martbost a9cffb87d4 Email an update: a refresh never re-ticks release notes; a saved draft decides which notes go
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 04:50:59 -05:00
martbost 927b13a7cf Admin > Email an update loads at once; audience counts fill in from the background
The panel waited on a Sendy pass over every member (minutes, and the cache
empties on each deploy), so it showed blank. Counts are now a snapshot with
a background refresh, and the form no longer depends on them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 04:43:42 -05:00
martbost 53f0970209 plan-lab: spillover placement and zero-recruit cash switches; tenure and team-funded metrics
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 20:00:17 -05:00
martbost d562d61cbc My line: how pay it forward actually works here, and a confirmation before every PIF
Wallet-to-wallet gift in good faith, unlike platforms that buy the position
out of an account balance. The site holds nothing, cannot reverse or recover
it, and nothing obliges the recipient to buy. Same wording in the chatbot.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 15:14:51 -05:00
martbost 30f84c6aa2 plan-lab: month-by-month run from the real InstantAdPay org; the full-matrix climb becomes the ceiling view
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:50:23 -05:00
martbost 273715dc17 plan-lab: admin fee is a running total from zero; entry fees stated once at the start
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:37:54 -05:00
martbost e1309d43b7 plan-lab: exactly one route, admin-fee label says whole-org
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:19:57 -05:00
martbost 6e3f631cc6 plan-lab: one route (the builder had appended it three times), clearer admin-fee label
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:09:04 -05:00
martbost 8e419f95e8 plan-lab: the climb story first, tree and rules folded away
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:04:57 -05:00
martbost a2d5706d8e Unlisted /plan-lab: Reach Ladder simulator for the planning group
The working simulator for the new matrix plan, served by link only
(noindex, no menu entry, no sitemap). Engine in /assets/plan-lab.js because
the CSP blocks inline scripts.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 12:38:43 -05:00
martbost 7ef8094a4d Top-ups: check the ad's own position, say where the free credits are, offer to pay from another
Bug: topUpCampaign read the position from the owner's campaign list, which
does not carry memberId, so every top-up was checked against the member's
MAIN position (Jim Watts: every ad said 19 free). It now reads the ad's row.

When the ad's position is short, the error names it and lists the member's
other positions with their free credits; the dashboard offers to pay from
the best one. Moving an ad settles any charges its old position already ran
up (a burn on the old member id) before switching, so the new position only
pays for views after the move.

Weekly email: unspent credits are broken down by position with the advice to
start a campaign from the largest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 06:05:19 -05:00
martbost 5059d46bcb Video views never charge past the budget; audit reads scheduled and uncharged campaigns correctly
chargeVideoView charged a full view even when the budget had less left (#39:
602 of 600). It now charges only what is left, and nothing once the budget is
gone; the viewer is still credited and the view still counted, so views keep
matching the watch log.

Audit: featured bookings are judged from their start time, not creation (#275
was flagged hours before its scheduled start); clicks-over-views only flags
campaigns that charged the buyer (#146, a placeholder video paused by the
source sweep, never spent a credit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 05:28:03 -05:00
martbost 917e87cd32 Reserve company and staff usernames; Terms: usernames must not mislead
setUsername refuses names containing our brands (instantadpay, polhunter,
rmcircle, cryptoteambuild, linkspin, dripoffers, adrevlnks...) and staff or
authority words on their own (admin, support, official, staff, moderator,
owner, ceo, payouts...). Terms section 3 gains the matching rule.
Prompted by #170 'instantadpay' and #172 'admin' (same person), 2026-09-27.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 05:02:35 -05:00
martbost 7873d752d3 My line: section pills and 10-row pages on every list
A sticky pill row at the top of My line jumps to each section (built from
the cards marked data-jump; hidden cards get no pill; the one in view is
lit). Every list on the page pages at 10: your line, downline levels,
holding tank, coach directs, prospects, both link-stats tables; upline
messages at 5. qa/line-pager.mjs checks it in a real browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 18:56:20 -05:00
martbost cf5a9674a2 Friday Bonus Hunts: InstantAdPay counts the banked days
Each day Saturday through Thursday (Central) that a member opens an inbox ad
and watches a video banks one extra PolHunter hunt for the following Friday.
If their inbox had no unread solo ad that day, the video alone counts, so
nobody is blocked by an empty inbox. These are the two slowest-delivering ad
types (about 6-7 views per campaign per day against 40-50 for banners), so
the game sends attention exactly where advertisers are short of it.

fridaybank.js counts from video_seen and solo_inbox.read_ts with DST-safe
Central midnights. /api/my/friday-bank feeds a card on the Earn tab (week
chips, today's two steps with links to the right sub-tab);
/api/hunt/friday-bank answers PolHunter, HMAC-signed with the existing
HUNT_SSO_SECRET, 5-minute window. QA member walk: 0 bugs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 15:20:51 -05:00
martbost 9116368ffe Telegram sender says what happened
Success logs tg-ok with the chat, thread and message id; a refusal logs
tg-fail with Telegram's own description; network errors and timeouts are
logged instead of swallowed. Without this a feed that fails is
indistinguishable from a quiet day, which is how the first grouped
purchase posts could not be confirmed from the log on 25 September.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 07:26:01 -05:00
martbost d2a3f162d0 Proof feed: one message per purchase, and it says InstantAdPay
Marty, reading the feed on 25 September: "I see the level 1 payout, I see
a level 2 payout, but I don't see who purchased something and what they
bought." And in the main Crypto Team Build group the same lines carried no
product name at all, so nobody knew what they were from.

feedgroup.js composes one message from every event of a purchase
transaction: the buyer and the package on top, the level payouts under it
with their dollar equivalents, then who was passed over and why. It is
triggered on AdminPaid, the last event the contract emits for a purchase,
which is how the missed-payout notice already knows the whole transaction
is indexed. Tier payouts and purchases are no longer posted one line at a
time. In payouts mode a purchase that paid no member (root or unsponsored
buyer) stays silent, as before. Every post now opens with the InstantAdPay
header in the main group as well as the payments topic.

Composed against three real transactions from the live index before
shipping: three tiers, a double pass-up, and a root purchase. QA member
walk: 0 bugs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 07:02:59 -05:00
martbost 742c271469 Chain-event side effects happen once across running instances
A Coolify deploy starts the new container and stops the old one only once
the new one is healthy, so for about half a minute two copies of this app
watch the chain. On 25 September, 06:26 CT, both saw Marty's $5 purchase:
two confirmation emails, and the Five Dollar Friday bonus granted twice
(+100 and +100, nineteen seconds apart). Every dedupe until now lived in
process memory or a JSON file on the volume; a second process shares
neither in time.

marks.js is the shared version: a row in MySQL that only one INSERT IGNORE
can win. The chain-event fan-out claims 'ev:<tx>:<logIndex>' before the
email, Telegram post, Friday bonus and sponsor sync; the in-memory feed
stays per instance. The Friday scheduler claims its Thursday email, kickoff
and wrap-up the same way, with the file marker kept as the second line of
defence and the thing an operator can edit by hand. Without a database it
degrades to a per-process Set, which is exactly the old single-instance
behaviour.

Proven on the production MySQL before deploy: first insert 1 row, second 0.
Marty's duplicate 100 credits reversed with a labelled adjust row; no other
member was double-granted.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 06:40:11 -05:00
martbost 18aabb3cb2 /friday: status script as a file (CSP blocks inline), and the page in the real sitemap
The first deploy shipped the status strip stuck on Checking: the site CSP has no
unsafe-inline, so the inline script never ran. Moved to /assets/friday.js. The
sitemap list lives in blog.js, not the pages list I edited in server.js; /friday
is in it now.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 06:29:09 -05:00
martbost 5b694c8ab4 Five Dollar Friday bridge page, with the member's link on it
Marty's ask: use the Friday promo as a tool where the sponsor gets the
credit, and as a bridge-page entry point. The sponsor part already worked
(any public page + ?ref sets the sponsor cookie, 2026-09-21); what was
missing was a page that is ABOUT the offer, so a click on a "20% bonus
credits today" image did not land on the general pitch and leak.

/friday: the banner as the hero, the live state from /api/friday (live now
with today's pack count and bonus credits issued, or the next date with a
countdown to midnight Central found by scanning minutes so DST cannot put it
an hour out), three steps, the email-first join with a new `friday` angle so
it shows as its own row in Admin > Traffic, and the credit definition. No
attribution logic added: last touch, walk-up, as everywhere.

Promo tools: a {{FRIDAY}} token that turns the member's invite link into
/friday?ref=<username>; posts for X, Facebook and Telegram and a text that
carry it; the three new banners (loft 1200x630, dark 1200x630, square
1080x1080) as a group in the kit with a copy-my-Friday-link button on it.
Chatbot answer points at the page and drops the stale "first one is
September 25" line. /friday in the traffic list, the sitemap and the QA
public walk. Cache tags bumped on my.js, promo.js and site.css.

QA member walk: 0 bugs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 06:26:11 -05:00
martbost 1b72a9a18c Screen every advertiser destination against Google Safe Browsing
Google marked instantadpay.com "deceptive pages" on 24 September. The probable
cause was campaign #225: a verified-visits ad that opened llclickpro.com from
our pages, and llclickpro.com carries exactly that flag. We put other people's
destinations in front of members, so their reputation becomes ours, and
nothing was checking it.

sbcheck.js screens the destination when a campaign is saved (member and house
paths both) and re-screens every live campaign daily, pausing the ones on a
flagged host and alerting the admin channel with the campaigns and owners.
POST /api/admin/sbcheck {dry} runs a pass by hand.

Verdicts are three-valued on purpose: flagged, clean, unknown. A guard that
reads "could not check" as "clean" is the failure mode this whole day has been
about; one that reads it as "flagged" would refuse every advertiser whenever
Google rate-limits us. So flagged refuses and pauses, clean passes, unknown
passes at save time but is logged and retried by the sweep until it resolves.

Uses the official Lookup API v4 when SAFE_BROWSING_KEY is set (full-URL,
batched). Until a key exists it reads the Transparency Report site-status
record, decoded against Google's own test site rather than guessed:
status 1 is clean, status 3 with any true flag is listed, anything else is
no data. That endpoint rate-limits by answering HTML, hence the 4-second pace.

videosweep's inline alert is hoisted into videosweepAlert so both sweeps use
the same admin-only channel: these messages name members and their emails.

QA: member walk 0 bugs, public walk 0 bugs. Verified by hand that
llclickpro.com is refused, rmcircle.team passes, and our own host is skipped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:38:35 -05:00
martbost f2a999edd0 Search Console verification for instantadpay.com
Google Safe Browsing has the site marked "some pages on this site are unsafe"
(social engineering) as of 24 September. The only place that names the pages,
and the only place a review can be requested, is Search Console, and the site
was never verified there. Meta tag on the home page plus the HTML-file
fallback; both are Marty's own account.

The likeliest trigger is already paused: campaign #225 was a verified-visits
ad opening llclickpro.com from our pages, and llclickpro.com carries the same
flag. A guard for that class of problem is the next commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:26:22 -05:00
martbost 3f9dc3cc94 A session pop-up that says what InstantAdPay actually is
The dashboard card was too easy to scroll past, so this is a real overlay: once
per browser session, on every page that loads common.js, dismissed with the X,
Escape or the backdrop.

It leads with the mechanic rather than the promotion, because the ask was to
remind people what the site is about: the ad spend in your line pays you, in the
same transaction. Five Dollar Friday rides underneath as the reason to act, and
the copy is driven by the live /api/friday, so it reads "tomorrow", "today" or
nothing at all without anyone editing text on a Friday morning.

Not shown on /join or /admin: an overlay in the middle of signing up costs
sign-ups, and staff do not need reminding what the product is.

QA: the overlay appears after an async fetch, so hiding it at load time missed
it and every click in the harness timed out. The harness now pre-sets the same
sessionStorage flag a real dismissal uses, before page scripts run. Green again,
0 bugs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 15:54:33 -05:00
martbost fd08af36ba Admin alerts arrive from Marty's own Hermes bot
Operational alerts should come from @CoolifyHermes_Bot, where his other pings
land, not from the member-facing InstantAdPay bot. The token is supplied as
HERMES_BOT_TOKEN in the app environment and never appears in the repo.

Still admin-only, and it falls back to the IAP bot then email rather than to any
member-visible channel: these alerts name a member's campaign and their email.

Also: the sweep swallowed a failed pause in an empty catch, which is precisely
the failure mode the module exists to prevent. It reports now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 14:05:55 -05:00
martbost 170d9963f7 Video sweep alert: admin channels only
The alert names a member's campaign and their email address. It fell back to the
shared payments topic when no admin chat was configured, which would have put a
member's broken ad in front of the whole team. Admin chat or email, or it logs
and stays quiet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 13:58:17 -05:00
martbost 2854e2a7ba Video sources: check the house path too, and re-check the live ones
Two holes left by videoCheck, which only ever ran when a campaign was saved.

The house-ad route never called it at all. It guarded /api/my/campaigns and not
/api/admin/campaigns, so a bad source pasted into a house video would hand every
viewer a black player exactly as #146 did.

And nothing re-checked anything after it went live. #146 pointed at
https://yourdomain.com/ from 16 September; the check shipped on the 22nd and the
campaign sat live for another two days, burning a daily video slot for everyone
who drew it, until Marty hit it himself and asked why nothing played. A save-time
check can never catch a campaign that predates it, or a link that rots later.

videosweep re-checks every live video source daily. A source that fails is
PAUSED, never deleted: the advertiser keeps every unspent credit, because the
reservation is computed rather than deducted, and can restart it once the link is
fixed. It reports what it paused to the admin channel rather than doing it
quietly, since a guard nobody hears from is how the first one went unnoticed.
POST /api/admin/videosweep runs it on demand, with { dry: true } to look first.

QA green, 0 bugs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 13:56:28 -05:00
martbost 3d4b07a8ab Real cover art, and a third milestone destination
The cover was a drawn arc and a hoop I built out of rectangles. It looked like
it. Replaced with a kie.ai generated photograph, a basketball sitting untouched
on a wet floodlit court at night with the hoop in shadow behind it, which is the
whole argument of the post in one frame. The type is still set here rather than
prompted, because image models cannot letter.

Milestones and the daily snapshot now post to three places instead of two: the
main Crypto Team Build group, the InstantAdPay support topic (634443) and the
shared payments topic. The RM Circle proof channel is deliberately excluded,
that channel is RM Circle only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 08:07:09 -05:00
martbost 78892421bb Blog cover: the shot that lands short
Cover for "You Miss One Hundred Percent of the Ads You Never Run". The arc is
the argument: a shot that rises, falls and stops short of the rim, next to the
73,181 credits our members are holding and have never spent on an ad.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 07:58:51 -05:00
martbost 869eee809e Milestones post a card, and a dead target stops being silent
The 600-member milestone went out as plain text into the shared payments topic
and Marty scrolled straight past it. Every hundred now posts a picture.

The cards are pre-rendered for the whole ladder (600 through 10,000) and carry
no live figures on purpose: a number baked into an image rendered weeks early is
wrong by the time the mark is reached, so the numbers stay in the caption. The
send falls back to plain text if the card for a mark is missing or the caption
runs past Telegram's 1024.

Separately: a target listed in snapshotTargets with no chat id was skipped
without a word, so the "feed" half of every milestone and every daily snapshot
has been going nowhere for weeks while the log said it sent. It now warns.
telegramChatId is still unset, so feed is still dark until Marty says where it
should point, but at least it says so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 07:45:27 -05:00
martbost 6ff21f76ee P&L: account for money the chain cannot explain
The P&L took revenue from AdminPaid events and holdings from eth_getBalance,
so anything else moving through a receiver was invisible. Receiver A has earned
10,871.89 POL and holds 4,561.19; nothing explained the difference, and the gap
would have widened every time Marty drew from it. "Why would I ever keep a
receiver wallet that I never take anything out of? That's stupid, so I need to
be able to account for it."

Three kinds, because three different things move through that wallet and only
one is profit. Revenue is outside income, a ClickBaitPays withdrawal paid in
POL, and counts toward profit. A draw is house profit spent on something, such
as funding RM Circle #139's Culmen to Apex upgrade; it leaves the wallet but is
not a cost of running InstantAdPay. A transfer is Marty's own capital parked in
the Tangem receiver for safekeeping, and moves the balance only: counting it as
revenue would report his savings as earnings.

The pane now states earned, plus revenue, less draws, against what is actually
held, and names any unexplained drift rather than hiding it in a balance.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 18:10:56 -05:00
martbost 8656f7ce4d Admin members: resolve sponsors against every account, not the page's 500
The Members page loads the newest 500 accounts and built its sponsor name
lookup from that same list. Once the site passed 500 accounts every sponsor who
joined before that window became unfindable, so the page labelled them "dead
link: <name>" with a tooltip saying the member would fall into the holding
tank. It was doing that to 144 of the 500 rows, including cryptoassets 76
times, and not one token on the whole site is genuinely unresolvable.

Sponsorship itself was never affected: assignment at purchase time looks each
token up directly rather than scanning a list.

accounts.identities() returns the identity columns for every account with no
limit, which stays cheap at any size, and the page uses that for the lookup
while still showing 500 rows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 11:25:38 -05:00
martbost 5c08be1c30 Campaign actions: a centred, even stack with a squarer corner
The column is narrow so these buttons stack. Left-aligned pills of different
widths read as a ragged edge, and a label that wraps inside a 999px radius
becomes a tall oval, which is what "Buy more views" was doing.

They are now centred, the same width, and cornered at 10px, so each label sits
on one line. Scoped to this table: everything else keeps the pill. The phone
card shares a row rather than stacking, as it did before, so that layout is
left alone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 09:10:50 -05:00
martbost 02d60d6ee1 Archive button: it had no text colour, and no room beside its neighbours
I gave it the class "ghost", which on PolHunter is a button and here is the
giant faded wordmark in the footer. That class sets color:transparent, so the
label was not dark, it was invisible. It now uses a new "quiet" variant, grey
on a muted outline, which reads clearly and sits below the mint actions rather
than competing with them.

The campaign actions also had no spacing on desktop. The mobile layout already
gapped them; the wide one leaned on a plain space between tags, so they sat
flush against each other.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 08:57:56 -05:00
martbost f0a6a93f8b Campaigns: archive a finished one, get the credits back, keep the numbers
A member asked for a delete button. Deleting would orphan the credit ledger,
the hourly view rows and the P&L, and throw away the figures they actually
want, so a campaign is archived instead: out of the working table, listed in
full underneath with its views, clicks and spend, and restorable.

The credits are the real point. Reserved budget is computed from campaigns
that are active or paused, so a paused campaign quietly holds credits the
member cannot spend anywhere else. Archiving releases them the moment the
status changes, with nothing to refund and nothing that can double-refund.

Only a paused or finished campaign can be archived, so pause stays the
deliberate first step, and restoring brings it back paused rather than live.
The syndication rails are stopped on the way in.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 08:40:17 -05:00
martbost 891eac1626 Overview: the PolHunter return card goes first
Marty's call: someone arriving from PolHunter stays on the dashboard rather
than being bounced back, because that is where the business is. That makes the
return card their only way back, and it was sitting third, below the launch
announcement for the site they had just come from and the Friday promotion.

It is hidden for everyone who did not arrive that way, so no other member's
page changes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 06:35:33 -05:00
martbost 489d832546 Sign-in: stop telling a fast returning member off for being fast
The email-code endpoint refuses a request that arrives within two seconds of
the page loading, because a script fills a form instantly and a person does
not. A member whose email is already filled in by the browser has nothing to
type, taps straight away, and gets "Give the page a second, then tap again."

The page now waits out the remainder itself and sends when the window has
passed, so the person sees the normal sending state instead of an error.
The server check is untouched, so anything posting at the endpoint without a
page behind it still fails exactly as before.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 05:50:34 -05:00
martbost 286ac9207a Hand the sponsor to PolHunter, and put its payouts in the P&L
PolHunter now pays a bounty when a hunter brings someone who turns up and
hunts, and the person who gets it has to be the one that member actually
joined under here. The sign-in payload carries sponsorRef and the join date
across so PolHunter is never guessing from a cookie.

Its payouts are real POL from its own faucet and none of it passes through the
ad contract, so the P&L could not derive it. It now reads the figures across,
cached and fail-soft, and shows finds, bounties and matches as their own card.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 04:36:02 -05:00
martbost ce9f3e6904 Videos: reject a source that does not load, and stop stranding the viewer
Michael Camire reported the video tab locking up after the fifth watch each
day. Three separate faults behind it.

A campaign could go live with a video address that resolves nowhere, because
the form only checked the shape of the URL. One has been sitting there since
11 September pointing at the example host, serving every Tier 1 member a black
player it could never finish. The create route now fetches the address and
refuses a host that does not answer, a 404, or a page that is not a video.

The Watch tab holds the landscape videos and Shorts holds the upright ones,
but they share one daily count. A member who cleared the tab was told to come
back tomorrow while clips were still waiting one tap away. When the other
surface still has something, the done screen now says so and links to it.

When a browser refused to autoplay, the button offered "Tap to play" but was
wired to fetch a different video, so the loaded one was thrown away and the
next also would not start. On a phone the clip could never be played at all.
The button now starts what is already loaded.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 16:54:31 -05:00
martbost 68a92c39ff Milestones: a recorded mark stays done whatever its stamp
The done-check read the stored value, so a mark recorded as 0 counted as never
celebrated. Seeding the already-passed hundreds that way would have made the
site announce "400 members" to a channel watching 528. It now tests that the
mark is present at all. Caught before it posted; the live state has been
re-stamped either way.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 10:19:12 -05:00
martbost f255d096ad Milestones: celebrate every 100 members, not just the big marks
Marty, 2026-09-22. The ladder was 500 / 1000 / 2500 / 5000 / 10000, so most of
the year would pass with nothing to cheer. It is now every 100, with the fuller
write-up kept for the half-thousands and thousands and a short cheer in
between, so the small ones do not read as a repeated speech. Both are laid out
in short lines for a phone, like the daily snapshot. The hundreds already
passed are recorded as done on the live volume, so the next post is 600.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 10:15:02 -05:00
martbost 5c11bfa502 Daily snapshot: lay the numbers out so a phone can read them
The post was one paragraph per subject, and on a phone every line wrapped into
a block of text with nothing to catch the eye. It is now a heading and two or
three short lines per subject, with a blank line between, the date under the
title, and no line long enough to wrap on a narrow screen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 09:58:07 -05:00
martbost c47905d89a Overview announcements: let a member put one away for the session
The PolHunter launch card, the Five Dollar Friday card and the "you came from
PolHunter" card repeat on a timer, so anyone who has read one had no way to
clear it. Each now carries a small close control in its heading: the card
stays hidden for the rest of that browser session and comes back at the next
sign-in, so a message nobody acted on is never lost for good.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 06:29:49 -05:00
martbost 67fb8193bd Refill conversions: only count a genuine response. An unrelated ad already running is not a relaunch, and a still-running low campaign is not a conversion at all; adds a reset lever to re-decide verdicts
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 05:26:20 -05:00
martbost 635844a12b Campaign refill notices: tell an advertiser when an ad is nearly out and when it has stopped, one email per owner with what it delivered, their balance and the bonus ladder; every send recorded and watched for the relaunch, top-up or purchase that follows
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 05:21:57 -05:00
martbost 9df669fa7c Sponsor pre-check alert: only the checkout call may alert (the dashboard's display-only call never does), and the alert says what it is: a heads-up before the sale, nothing paid yet
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 10:55:09 -05:00
martbost a403ce3520 Promo tools > PolHunter: the two vertical spots with download, caption carrying the member's link, share buttons and the platform guide
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 09:59:58 -05:00
martbost 260daaf9d0 Viral links served in place, not redirected: Facebook follows redirects and og:url, so every share was losing the member's name; og:url now carries the ref, canonical stays clean; QA walk updated
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 08:07:12 -05:00
martbost c6c26b8073 PolHunter in the member menu from launch morning (the Overview reveal still waits for launchAt); Promo tools > PolHunter kit: share link, posts, swipe, banners, both videos; reveal card says tap to copy
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 07:36:37 -05:00
martbost e5cbecbdb2 Viral link builder: dropdown only (the paste box only ever accepted the site's own pages, which the dropdown already lists)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 06:13:25 -05:00
martbost 269247c871 Blog renderer: bump blog-page.js tag so articles load the viral-link bar now, not after the cache
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 05:56:21 -05:00
martbost e2f88dad42 Viral links: any public page + ?ref=<username|code|id> sets the same last-touch sponsor cookie as /join, counts under a 'page' hook in link stats, then redirects to the clean URL; Promo tools > Viral links builder (pages list + paste any address, copy + share); blog posts show a signed-in member's own link; chatbot answer; QA walk proves redirect + cookie
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 05:54:55 -05:00
martbost 337d5dd556 Walk-up feed post moves to the activation event (a member who activates first and buys later was never posted); the Purchase branch no longer posts it
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 04:41:11 -05:00
martbost 6f5b5dbae6 Earning guide: adds the POL side (50/20/10 split, payouts on, qualification at 2 and 5, pass-ups, sponsor lock, where to see it); title and meta cover both kinds of earning
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 04:27:27 -05:00
martbost 91456ae0ce Promo tools: Five Dollar Friday banner set (1200x630, 1080x1080, 728x90, 300x250)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-20 14:06:16 -05:00
martbost 68b08ab8cc Five Dollar Friday: +20% purchased-grade credits on any $5+ package bought on a Friday (Central), live wave on the landing strip and Overview card, Telegram every ten packs + Friday kickoff + midnight wrap-up, Thursday notice + email, Five Fridays badge, promo posts + swipe, chatbot; first Friday 2026-09-25
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-20 13:59:15 -05:00
Marty Bostick de5bdfefaf SocialPix gate: /from/socialpix bridge page (advertiser copy by default, ?seg=earn), chatbot knows the new page
socialpix.club was being used as a free ad board by posting bots; its signup/onboarding/post flows
now redirect here. No legacy credits for these arrivals. Referrer tagging (traffic.js) already covers /from/*.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-20 09:26:40 -05:00
martbost 9fafd0bf43 Training: feature 'polhunter' entries appear at the launch moment; launch card links the feeder video
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-20 05:27:10 -05:00
martbost 9a531538ed Launch-day surprise: PolHunter card on the Overview and the menu entry appear at siteConfig.launchAt (self-flipping, nothing visible before)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-20 05:16:30 -05:00
martbost 7ea7a5f409 PolHunter return loop: ?from=polhunter sets iap.return (landing + join links), /api/me carries returnTo, Overview card sends them back once a wallet is linked, wallet link answers next=/api/my/polhunter, hand-off clears the cookie
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 20:00:55 -05:00
martbost ad539d5fae Ledger: a NAS zone under the payout feed (mission pages must carry ad inventory)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 16:40:07 -05:00
martbost 5fe3dfa625 Dashboard: PolHunter menu entry removed until it opens (the hand-off route and the ledger embed stay; neither is visible)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 16:15:26 -05:00
martbost 49a92461f0 CSP: put polhunter.com after 'self' in connect-src (the previous edit produced an invalid source list)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 14:26:43 -05:00
martbost 240a928323 CSP: connect-src allows polhunter.com so the PolHunter embed can fetch its code
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 14:23:57 -05:00
martbost af710f68b8 PolHunter hand-off, nav entry, and the ledger embed
/api/my/polhunter signs a member across to polhunter.com with a five-minute single-use HMAC
token (memberId, email, wallet, username); PolHunter has no sign-up and no mailer, this is the
only way in. A PolHunter entry in the dashboard nav. The PolHunter embed on the public ledger
with one slot beside the payout feed; CSP allows polhunter.com.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 14:20:16 -05:00
martbost 0d2621defd missed: list each tier's skips in walk order
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 13:16:03 -05:00
martbost c00ec64cf8 Missed-payout notice shows the whole chain, one message per purchase
Marty (2026-09-19): show every missed qualification so the whole chain is visible. The old
notice fired once per passed-up tier and showed only that tier. AdminPaid is the last event of
every purchase transaction (119 of 119 in the index), so the notice now fires there, gathers
every PassedUp and TierPaid of the tx, and missed.js composes one message: each tier's walk,
every person passed over with their buyer count, who finally caught it (or that the company
kept it), and the total POL that walked past how many people on that one sale.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 13:14:12 -05:00
martbost d90f08d54a Milestone posts: a celebratory Telegram post the moment membership crosses 500 (then 1k, 2.5k, 5k, 10k), once per mark
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 10:52:21 -05:00
martbost a85ee4cacf Login slots: 1,000 credits, at most 3 member slots live; viewer gets an open-in-tab link
Marty (2026-09-19): cap the login-ad slots. About 124 members sign in a day and every live
slot shares those views, so a fourth slot only thins the other three. Member slots only;
house login ads now step aside whenever a member slot is running (JSON: filtered out of the
pool; MySQL: ORDER BY house ASC). The 14 slots already running keep their term; new buys are
refused until one ends. Format label and chatbot updated.

mindfulmojo (email, 2026-09-19): the viewer frames the advertiser's page and both controls
meant "back"; some sites refuse to load inside a frame and signing up is easier in a full tab.
The viewer bar now carries "Open site in a new tab", set from the ad's target URL.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 07:46:12 -05:00
martbost f282e328b5 Snapshot: where the credits came from (handed out / earned / spent), last 24h
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 07:23:04 -05:00
martbost 415a5f3848 Partner-code credits arrive as a drip; unclaimed installments expire
Marty (2026-09-19): partner codes keep working with no monthly cap, but the credits stop
being a dump. A fifth is paid the day the code is redeemed, then a fifth on each day the
member finishes their daily ad set, five days in all, and whatever is unclaimed 30 days after
redemption is never paid. Same headline number for the partner to promote; paid only to
people who show up. 49 of the 52 PARTNER redemptions were still sitting on 500+ unspent.

Every redemption now records the site the ?promo= link was opened from (iap.promoref cookie
set from the Referer at link-open), so a code's traffic can be attributed to the partner page
it was supposed to come from. Member-funded codes charge the funder one installment at a
time; a short funder leaves the installment due, not lost.

Pre-drip redemptions were paid in full up front and are marked paid=credits at start-up, so
nothing is paid twice. Covered by a module test (13 checks: per-day cadence, gaps, rounding,
expiry, pre-drip rows, declined payer) and an end-to-end HTTP test on a local copy (9 checks).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 06:24:14 -05:00
martbost 5ebe890760 Paged lists: 25 rows, then a clearly marked next page
Marty (2026-09-19): once a membership gets large, My line and the other lists scroll forever.
One helper, pageList(), pages what each pane already renders: rows past the current page are
hidden and a solid-mint control bar (row range, Previous/Next 25, page count) goes under the
list. Row markup and bindings are untouched, so it goes on every growing list at once: My
line per level (the Activity drawer pages with its row, and a chip drill-down opens on the
right page), the Overview roster, the Campaigns table and its credit ledger, each Pipeline
column, and the Messages thread list. Asset tags bumped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 06:02:28 -05:00
martbost 70c4053201 Network Ad Space zone on the Faucet Wave and Tier One Ads landing pages
Marty asked for a NAS zone on the two legacy squeeze pages (2026-09-19). Injected server-side
in serveJoinPage for the fw-*/t1-* angles only, below the fine print and above the footer
links; the regular join pages stay ad-free. script-src now allows networkadspace.com, which
it did not, so the tag would otherwise have died silently under the CSP.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 05:50:02 -05:00
martbost 39572c0ff5 Sign-up deny list beside the allow list
fraud-allow.json says "never block this person". There was nothing for the opposite case.
fraud-block.json: an address on it cannot open an account through /api/signup or the
email-code door, and the admin fraud report carries the list with a matching
/api/admin/fraud/block route. Existing accounts are untouched; Suspend covers those.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 05:46:04 -05:00
martbost b061053ccf Daily rules run on Central time, and the sign-in bonus gets a hard floor
today() was a UTC day, which rolls over at 7 PM Central. Sign in at 6:55 PM and again at
7:05 PM and those were two different days, so the once-per-day sign-in bonus paid twice,
ten minutes apart. On the live ledger 83 of the first 364 sign-in bonuses landed less than
24 hours after the previous one, one pair 24 minutes apart, worth 618 credits.

The same boundary governs the daily-credit claim, the claim streak, each campaign's daily
spend cap and the login-ad daily meter, all of which could turn over twice in one Central
evening.

ctDay() puts every member-facing daily rule on America/Chicago, which tracks CST/CDT on its
own. Reporting slices elsewhere are left alone rather than re-bucketing chart history.

The bonus also records login_ts now and refuses to pay again inside 20 hours, whatever the
day string says. 20 rather than 24 so signing in at the same time each morning never skips.

Safe to deploy between midnight and 7 PM Central, when the two day strings agree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-19 05:19:44 -05:00
martbost 0a50d07658 Login ads become a flat 30-day slot
The daily meter charged 100 credits for every day a campaign was shown,
with no end date. It produced 74-day queues, and worse, each new campaign
added 100/day of charges while adding no inventory: on 18 September, 15
campaigns were charged 1,500 credits against a platform that had produced
367 login impressions in its entire life. That had stopped being a pricing
inefficiency and become members paying for delivery that did not exist.

Now: 3,000 credits buys 30 days of unlimited impressions, charged once at
purchase, with no delivery promise — the model Marty wanted, matching how
ClickBaitPays sells theirs. The price is deliberately identical to 30 days
at the old daily rate, so nobody pays more than before; they just get a
known end instead of an open-ended drain.

It reuses the `featured` shape, which was already a flat up-front buy that
runs to `expires`. Both daily meters — MySQL and JSON — now skip any
campaign with an expiry, so a slot can never be metered. The existing
sweep closes it on day 30 and returns anything unspent.

qa/login-slot.mjs, 9 checks, including that the slot price still equals
30 days at the old rate and that neither meter can touch a slot campaign.
Member walk clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 16:18:27 -05:00
martbost ccc372152d Sessions last 4 hours, and we say why
Marty's call. Sign-ins expired after 24 hours, which meant a member passed
the login gate roughly once a day — and that gate is the entire inventory
behind the login-ad product. The platform has served 356 login impressions
in its life while members have bought 20,526 credits of them.

Four hours, env-tunable via SESSION_TTL_HOURS.

Said out loud in three places rather than left to feel like a glitch:
the login gate itself now explains it, the chatbot has a canned answer for
"why do I keep getting logged out", and the same fact is in the assistant's
system prompt so the AI never calls it a bug. Wording throughout is
Marty's: to keep resources optimised we do not keep anyone signed in
longer than 4 hours, and nothing about the account, credits or line is
affected.

The canned pattern was checked against the neighbours it sits beside —
seven phrasings reach it, and withdraw / pyramid / earnings / second
account / payout answers are all untouched. CANNED is first-match-wins,
so that check matters.

Member walk clean, chatbot suite 35 green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 13:31:52 -05:00
martbost c5a846bd91 Keep the notifications worth interrupting for
Splitting system messages out of the modal was right for payout receipts,
but it would have silenced two that a member genuinely loses money by
ignoring:

  - "@someone is trying to buy. Link your wallet so it pays you" — a sale
    is blocked right now, and the referral is lost permanently once it
    routes to someone else.
  - "You missed 43 POL on InstantAdPay" — a payout passed them by, and the
    message explains exactly how to stop the next one doing the same.

So the dividing line is not system-versus-human, it is "does this need you
to do something". Those two become kind 'alert' and still interrupt; the
receipts stay kind 'notice' and stay in the inbox.

The modal no longer credits an alert to a person either. It was saying "A
message from @martbost" over machine-generated text, because system mail
is sent by member 1 at ADMIN_EMAIL. Alerts now read "Action needed on your
account".

Also reclassified "X is now in your line for good" as a notice — it is
good news about a referral the member gained, with nothing at stake.

qa/messages-notice.mjs now covers both lanes: 14 checks, including that an
alert interrupts and a flood of 25 receipts does not.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 08:25:08 -05:00
martbost a2c77d01d1 Stop payout notices interrupting members who are earning
Marty hit this viewing daily ads: a popup after every single return to
the dashboard, each one a different payout notice.

Two causes, both fixed.

The channel was shared. "You just got paid 40.8923 POL" and "Welcome to
my line, here are your first three moves" were stored identically, as
kind 'broadcast' — the kind the sign-in modal is meant to interrupt for.
Dismissing one just promoted the next unread notice, so a backlog became
a carousel. System messages are now kind 'notice': they land in the
inbox, count toward its badge, and never pop. Only a message a person
actually wrote can interrupt.

The modal also had no memory. loadDashboard() runs on far more than
sign-in — after every ad view, campaign edit and chat close — and it
re-popped each time. It now shows at most once per page load and never
twice for the same message.

The 79 existing machine-generated rows are retagged by a migration in
ensureSchema, 15 of them unread and currently popping. Matched on
subject rather than sender on purpose: these come from member 1 at
ADMIN_EMAIL, which is also Marty's own member address, so his genuine
broadcasts sit under the same sender and must be left alone. Verified
against the live data first — "Credits returned: a counting error on our
side" and the broken-banner note are his, and stay as broadcasts.

qa/messages-notice.mjs covers it: a flood of 25 notices produces no
interruption, the human message still does, and chat stays in its own
lane. Member walk clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 08:09:50 -05:00
martbost a84b851272 Correct the DripOffers capacity figure and tighten the cap
I read campaigns.received_today as a per-day counter and told Marty the
platform delivers about 2,700 clicks a day. It doesn't. That column is
only a daily figure while the nightly cron resets it, and that reset has
stopped running, so the value is an accumulation since it last ran.

The permanent click ledger is unambiguous: roughly 40 to 50 clicks a day
across the whole platform. It also agrees exactly with ordered-minus-
remaining on every campaign, which is a good independent check that the
read-never-derive design is reading the right thing.

So MAX_CLICKS drops from 10,000 to 2,500. At the real volume a 10,000-click
booking would hold the top of the offerwall for most of a year.

The pack-2 placement is working as intended and is already measurable: the
three backfilled campaigns took 14 of the platform's 17 clicks today.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 07:04:20 -05:00
martbost 71ab9555e2 Give a syndicated offer a title a stranger can read
A campaign's name is the member's own internal label, and some of them are
two characters ("MG"). DripOffers rejects anything under five, and more to
the point a click-earner scanning the offerwall learns nothing from "MG".

So the ad's own headline comes first, then the label, and a very short
label is qualified with the destination host — "MG (mailer.gold)" — rather
than dropped or dressed up in marketing copy we invented on the member's
behalf. Nothing usable at all returns null instead of a made-up title.

Found by the backfill: campaign 88 failed on it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 06:52:24 -05:00
martbost d4e2f59f9b Member campaigns now go out as click offers on DripOffers
Third syndication rail. The first two send impressions; this one sends
clicks — a real person picks the offer off the offerwall, goes to the
member's link, and has to stay the dwell time before anyone is paid.

Two things it does that the other rails can't:

- It carries geo-targeted campaigns. DripOffers filters on an explicit
  country list, so a campaign aimed at Tier 1 finally reaches an outside
  audience instead of staying on our own site. Tier-3-only campaigns are
  skipped rather than quietly sent worldwide, because an inclusion list
  can't express "everywhere except the other tiers" and widening it would
  deliver exactly the traffic the owner chose to exclude.
- Delivery is counted, not derived. It reads rows from the platform's
  permanent click ledger. It never computes delivery as ordered minus
  remaining, and pausing never zeroes remaining — that pair is what
  charged members for impressions that never ran on Network Ad Space.

Also fixes two live bugs found while wiring it: the AdRevLinks pause was
nested inside the Network Ad Space check in both the end sweep and
setStatus, so with NAS switched off an ended or paused campaign kept
running on AdRevLinks. Each rail is now checked on its own.

Caps: 1,000 credits minimum, 10,000 clicks maximum per campaign. Not for
cost — Marty owns the platform and these placements are free — but because
the whole site delivers around 2,700 clicks a day, and one campaign
booking 50,000 would sit in the list for weeks.

Inert unless DRIPOFFERS_BRIDGE_URL and _KEY are set. 26 checks green
against the live endpoint; member walk clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 06:27:33 -05:00
martbost dc0f0d056d Syndicate member campaigns to AdRevLinks as Tier 1 popup ads
Second delivery surface for member campaigns, and deliberately the opposite shape to the
Network Ad Space rail: that one is Tier 3 heavy, this one only has prices configured for
US, CA, GB, AU, NZ and UM, so its traffic is Tier 1 by construction.

The AdRevLinks database is not reachable from this server, so rather than opening a
database port to the internet there is a narrow authenticated endpoint on that box which
does the insert locally. Five actions, no general query surface: a leaked key can only
create or remove popup campaigns. The secret lives outside that server's webroot and is
compared in constant time; Apache there strips Authorization, so it travels as
X-Bridge-Key.

adrevlnks.js mirrors nas.js, with two rules carried over from this morning's billing bug:
- DELIVERY IS READ, NEVER DERIVED. status returns the rotator's own per-country counters.
  Nothing is computed from a figure a stop could overwrite, which is exactly what charged
  16 members for undelivered impressions on the NAS side.
- EVERY WRITE IS IDEMPOTENT. Each campaign carries ref "iap:<id>", so a retry after a
  timeout returns the existing campaign instead of booking a second one.

Capped on purpose. That server serves roughly 5,500 popup impressions a DAY in total,
shared by every active campaign, and its rotator favours whichever has delivered least. So
syndicating everything unchecked would starve what is already running, Marty's own ads
included. Hence a credit floor and a per-campaign view cap. Cost is not the reason: he owns
the platform and treats the placements as free. Finite shared inventory is the reason.

Hooked into create, pause/resume and the scheduled end sweep so both networks stay in step.
Inert unless ADREVLNKS_BRIDGE_URL and _KEY are set, and a bridge hiccup can never block a
campaign going live.

qa/adrevlnks-bridge.mjs (15 assertions) drives the REAL endpoint: under-floor campaigns
skipped, full credit value booked, Tier 1 targeting, retry returns the same campaign,
delivery read back, pause/resume mirrored, then deleted and confirmed gone. Creates only
paused campaigns so no live traffic is spent, and leaves nothing behind.

nas-served 8, fraud-allow 12, sponsor-note 5, chatbot-parse 35, qa/run.sh member 0 bugs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 05:53:38 -05:00
martbost 3fb123393a Admin credit grants carry their reason into the member's Credit activity
A correction that reads 'granted by admin' explains nothing to the member looking at
their ledger. The note now travels with the grant, so a credit-consumption correction
names itself where they will actually see it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 19:59:13 -05:00
martbost cb6da01e1c Stop billing members for syndicated impressions that were never delivered
Network Ad Space has no stop flag. Its serving query only picks rows with remaining>0,
so zeroing that counter is the only way to halt an ad. But delivery is derived as
assigned - remaining, so the moment an ad was stopped it read back as 100% DELIVERED.

That was not only a reporting error. reconcileNas() runs every five minutes, had no
status filter, and CHARGES member credits off that figure. So pausing a campaign, or
ending one, made the next reconcile pass bill the member for the entire unspent budget
as though it had all been served.

Measured on production before the fix: 23 member campaigns across 16 members, every
single one charged to exactly 100% of budget, 11,437 credits in total, against on-site
delivery evidence of roughly 4,700 impressions. A naturally exhausted ad also ends at
remaining=0, so the two cases cannot be told apart after the fact, which is why the
true figure has to be captured before the stop.

Three changes:
- nas.deactivate() now reads the real served count BEFORE zeroing and returns it.
- a new ads.stopNas() helper is the only path to a stop, and it persists that figure as
  the campaign's final delivery. No caller touches nas.deactivate() directly any more.
- reconcileNas() only processes campaigns with status='active'. A stopped ad delivers
  nothing further, so there is never anything legitimate left to charge for.

qa/nas-served.mjs (8 assertions) stubs the NAS layer and drives the real code: pausing
records the true 3,000 rather than the 10,000 allocation, a paused campaign is never
charged afterwards and its figure never jumps to the allocation, and an active campaign
still reconciles and is charged normally so the guard did not break delivery.

fraud-allow 12, sponsor-note 5, chatbot-parse 35, qa/run.sh member 0 bugs.

Historical delivery is not recoverable: the stop overwrote the only record of it.
Refunding the 11,437 credits to the 16 affected members is Marty's call, pending.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 19:52:12 -05:00
martbost e95f9df13a Approved exceptions: people you have okayed to hold more than one account
Marty approves specific people for multiple accounts (partners, staff, a spouse on a
shared machine) and needed a way to say so without the guard fighting him.

Admin > Members > Duplicate signals now carries an "Approved exceptions" list: add an
email with a note, see who is on it and when, remove one. It sits directly under the
signals so the two are read together.

An exception can be added against the address they ALREADY have, not just the new one.
That matters because the usual case is approving a person before their second address
exists, and at sign-up time the new address is unknown to us. checkSignup now tracks
every account the sign-up collided with, and clears the block if either side is approved.

Clearing the HARD flags matters as much as clearing the block. Those flags are what
silently drop an account off the leaderboard and bar it from adopting out of the holding
tank, so an approved person would have been "allowed" in name only. They now keep both.
The account is tagged 'allowlisted' instead, so the admin sees why it went through, and
the server logs the exception by name.

Suspension still wins. An exception is permission to hold several accounts, not immunity
from being suspended for something else.

qa/fraud-allow.mjs (12 assertions) boots its own server and walks the real flow: first
account created, second blocked with the Qualified Start redirect, exception added,
second account now created, no hard flag left on it, exception visible in the admin
report, removing it blocks again, malformed address refused, endpoint admin-only.
qa/sponsor-note.mjs 5, qa/run.sh member 0 bugs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 10:42:31 -05:00
martbost 2dfccf0039 Sign-in no longer tells an existing member they are joining somebody's line
Marty signed in and was told "You're joining the line of @bliss". He is member #1.

Cause: the last-touch sponsor cookie lives 30 days, and /api/sponsor set invited
purely from that cookie. So any member who had ever clicked a teammate's invite link
was greeted on the sign-in screen as though logging in would place them under that
person. Untrue, and alarming in exactly the wrong place: their sponsor locked at their
first purchase and nothing on that screen can move it. Anyone seeing that would
reasonably worry their line was about to change.

The greeting now shows when someone actually arrived through a link (?ref= in the URL),
or when the cookie is present AND this browser has never had an account, which is the
genuine "came back later to finish joining" case. A browser that already has an account,
or a signed-in session, never sees it.

Attribution is deliberately untouched: the cookie still resolves, the sponsor id is
still returned, and placement still works exactly as before. Only the greeting changed.

fraud.hasAccountOnDevice(req) is the new signal, reusing the device cookie the
one-account-per-person checks already set.

qa/sponsor-note.mjs (5 assertions) boots its own throwaway server and creates a REAL
account so the case is proven rather than assumed: still greeted with ?ref=, still
greeted from the cookie on a browser with no account, NOT greeted on the browser that
has one, and attribution still resolving. qa/run.sh member: 0 bugs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 08:41:46 -05:00
martbost f27388a322 Chatbot: catch the PIF question when nobody says "PIF", and stop inventing references
Follow-on to the risk rewrite. Two gaps it exposed.

Members ask this without the word PIF: "should I fund their first package", "can I
buy it for them", "can I front someone the $20". Those were falling through to the
AI, which answered reasonably but told the member to "read the full warning on your
training page" - a page section that does not exist and that they would go looking
for. The pattern now also matches a paying verb plus an explicit for-someone-else
phrase, so these get the full canned answer with the risk in it. It deliberately
needs BOTH halves: "which package should I buy" must not be stolen.

The prompt now forbids sending anyone to a warning, guide or page section that is
not in the PAGES list, and requires plain ASCII (the model was emitting non-breaking
hyphens in "Wi-Fi").

Fixed two first-match-wins routing bugs, one of them mine from the previous commit:
"what do I get for buying a package" was returning the commission split, because I
had widened the earnings pattern to "what do I get" when it should only ever have
been "what do I get paid". And "should I buy the $20 package" previously matched
nothing at all and burned an AI call on a question we have a written answer for.

CANNED is an ordered list, so any pattern edit can silently steal a neighbour. The
suite now pins a 19-case routing table across PIF, price, earnings and the tank, so
the next person to widen a regex finds out immediately. qa/chatbot-parse.mjs is 35
assertions. qa/run.sh member: 0 bugs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 05:41:54 -05:00
martbost 3867b28bd4 Chatbot: the PIF risk is the answer, not a footnote
Marty: the answer has to cover what a member is risking when they send POL to
somebody they have not spoken to and have no commitment from.

The canned answer now leads the advice with "do not send anything until you have
actually talked to that person and they have told you they will use it", then says
plainly: the transfer is wallet to wallet and irreversible, there is no refund and
no chargeback, support cannot pull it back, the gift is theirs whatever they do with
it, and they are free to go quiet or spend it on something else without breaking any
rule. It names the worst case for what it is, which is that a tank member joined
with nobody working with them and may never have engaged, so an unanswered PIF is
the easiest money on this site to lose.

It gives the arithmetic both ways rather than only the upside: a gift that works
costs about half, because the contract pays the sponsor 50 percent when they buy;
a gift to someone who never answers costs all of it. It ends on never gift money
you need and never borrow to do it.

The same guidance goes into the AI prompt as a standing rule, so PIF is never sold
as a tactic on any phrasing that misses the canned pattern, and a "should I PIF
someone from the tank" question starts with talk to them first, not the mechanics.

qa/chatbot-parse.mjs is now 16 assertions: the 9 response-shape cases plus 7 that
pin each risk line, so a future rewrite cannot quietly drop them.
qa/run.sh member: 0 bugs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 05:36:42 -05:00
martbost 6c8cc0ede2 Chatbot: the PIF and holding-tank answers, and no more dead ends on a provider hiccup
Marty hit "I hit a snag answering that one" on "Should I pif someone from the
holding tank". Two separate problems behind it.

The real bug: OpenRouter pads a slow upstream with keepalive lines before the JSON,
and when the provider gives up it can close having sent ONLY that padding. HTTP 200,
no body. JSON.parse threw and EVERY non-canned question died the same way, not just
this one. Now we find the actual JSON object in the stream, treat an empty answer as
a failure rather than sending a blank reply, retry once (the usual cause is one
provider dropping the request), and if both attempts fail we say plainly that it was
our side, not their question, and point at a person.

The content gap: PIF and the holding tank were in the system prompt but had no canned
answers, so they depended on the AI being up. Both are now canned and instant. The PIF
answer leads with the thing the question gets wrong, which is that you cannot PIF
somebody still in the tank: adopt first, they link a wallet, then the button appears.
It is honest that nothing obliges them to buy, that crypto transfers are irreversible,
and that the 50 percent coming back only happens if they actually purchase.

Also fixes a pre-existing routing bug found while testing: "how much do I earn"
returned the PACKAGE PRICE ladder, because the price pattern matches "how much do"
and the commission pattern only caught "how much earn".

qa/chatbot-parse.mjs (9 assertions) drives the real parse branch against a stub
server for every response shape: keepalive-only, keepalive-then-JSON, plain JSON,
SSE comments, empty content, non-JSON. qa/run.sh member: 0 bugs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 05:27:18 -05:00
martbost 8ad2e01a74 Admin: a linked wallet can no longer be misread as an active position
The member card showed the wallet address on its own, directly above "Registered:
no (payouts off)". That reads as "he is set up" when he is not, and it caused a
real misread today on @mcbit1: wallet linked, memberId 0 on chain, every sale in
his line walking up to his sponsor while the row looked healthy.

Linking a wallet is a free signature that tells the site which address is theirs.
Switching on payouts is a separate transaction that creates the position. Only the
second one makes them payable, so the two states now say so:

  Main wallet  0x30a7…5703  payouts OFF
  Registered   no  wallet linked, but payouts were never switched on, so no
               position exists. Sales in their line walk up to their sponsor and
               lock there.

and the no-wallet case says "no wallet linked yet" instead of the same text.

qa/run.sh member: 0 bugs (the 2 warnings are pre-existing and unrelated).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 05:03:29 -05:00
martbost a2cea3a2be Anti-fraud refusals redirect to Qualified Start (the sanctioned way to hold extra positions); chatbot says the same
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:52:46 -05:00
martbost aab18e28ca Sign-up: hand out the device cookie on every code-request response, including guard refusals
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:40:54 -05:00
martbost 34c62b9d3a Anti-fraud: one account per person enforced at sign-up (device cookie + IP), flags, admin duplicate signals, suspend switch
Marty, 2026-09-16, after @megamol created megamol2/megamol3 under his own link and bought $20 on each
to fake his two qualifying buyers. fraud.js records sign-up IP/UA/browser id (iap.dev cookie set with
the code request) and last-seen on sign-in. New accounts: dup-device (browser already has an account)
and sponsor-device are refused, ip-burst (> fraudMaxSignupsPerIpDay, default 2, per 24h) is refused;
sponsor-ip and shared-ip are flagged only. Flagged/suspended accounts never count on the leaderboard
and cannot adopt from the tank; suspended accounts are signed out everywhere (auth.fromRequest
wrapper) and refused at sign-in. Admin > Members: Duplicate signals card (shared browser / IP,
flagged, suspended), flags badge, Suspend/Unsuspend; GET /api/admin/fraud; PATCH members {suspend,
reason, flags}. Telegram admin alert on every block/flag. Privacy page + chatbot prompt updated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:39:13 -05:00
martbost 125be174e3 Terms: one account per person (duplicate accounts and self-referral prohibited; Qualified Start linked wallets are the only sanctioned extra positions); chatbot canned + prompt
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:29:54 -05:00
martbost 9b3a79561b Chatbot: repair the price pattern (shell had turned \b into backspace bytes), full package ladder in the answer, ranked above the credits answer
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:19:17 -05:00
martbost 2b4050d410 Chatbot: exact page map (no invented URLs), tighter price/credit patterns, canned answer for the unactivated-sponsor walk-up
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:14:37 -05:00
martbost 27f2742c31 Chatbot: banner-image questions get the creative rule, not the Promo tools kit answer
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:12:49 -05:00
martbost 362526d007 Chatbot brought fully current + knowledge guard
Audit against the live site: removed stale text (featured links and visit packs marked "coming",
Pipeline "coming soon", the superseded sponsor-hold rule, a non-existent home-page calculator,
"earned credits spend on banner and text only", "Coaching pane"); added live featured and visit-pack
rules with prices and limits, the video cap and rewards, the sign-in bonus and claim ladders,
report-an-ad, the public missed-payout posts, the walk-up gain notice, the four-minute overview
video, the promo Videos and Toolkit tabs; new canned answers for featured links, visit packs and
"what is this". KNOWLEDGE_DATE constant + qa/chatbot-sync.mjs (run in public/all QA) fails when a
release note is newer than the chatbot's knowledge.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 14:10:00 -05:00
martbost 5641582709 Banner creatives must be images: server-side image check (extension or image/* HEAD), form hint, chatbot note
Campaign #134 (NAS ad 2806) had the member's join-page link in the image field and served a broken
banner 141 times on the network; #102 did the same with an imgbb page link. imageCheck() accepts
/uploads/ and instantadpay.com/banners files and image extensions outright, otherwise HEADs the URL
(one redirect) and requires image/*. Wired into member and house campaign creation for banners and
login-ad creatives. Form placeholder + hint point at Promo tools > Banners > Copy image URL.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 13:56:30 -05:00
martbost d6bc79c9d6 Home: 'Watch the 4-minute overview' CTA + inline overview video section (Spaces training/platform-overview.mp4)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 13:42:23 -05:00
martbost b811b96e33 Payments feeds: post who missed a share and who got it (on-chain pass-ups and off-chain walk-ups)
Marty, 2026-09-16: make missing a payout visible. On a TierPaid with hops>0 the PassedUp events of the
same tx name the skipped positions, with the reason and how many qualifying buyers they had; the post
says the amount and who received it instead. On a Purchase whose buyer was routed past an unactivated
sponsor (movedByTx set by sponsorSyncOnEvent), the post names the sponsor who missed the whole sale
and the upline who now owns that buyer for good. Both go to the main feed and the shared payments
topic unless the events mode is 'none'.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 13:25:31 -05:00
martbost 230c250c64 Earnings pane: Trace a payment card sits at the top
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 12:30:46 -05:00
martbost a727ab1ce5 Payment trace: self-serve "who was paid, who was skipped and why" per purchase (Earnings tab + admin member card)
Marty, 2026-09-16, after the third "why didn't my sponsor get paid" thread of the day (livedreams / gracie25,
Morten / Terry's linked wallets). GET /api/my/trace?who=<#|username> (yourself, anyone up to 3 levels
below you, or your own 3 uplines) and GET /api/admin/trace?who= list every purchase the member was
part of, newest first: buyer, sponsor, package, then levels 1-3 with the recipient, the skipped
positions and the reason ("not qualified: had N of 2 qualifying buyers then"), the platform share, and
a verify link. Linked extra wallets are named after their owner. Earnings tab card "Trace a payment";
admin member card gets a "Payment trace" section; chatbot canned answer + AI prompt route the
question there.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 12:24:53 -05:00
martbost dffcaa113b Never hold a sale for an unactivated sponsor: walk up to the first payable upline, referral follows the money
Marty, 2026-09-16: a purchase must never wait on a sponsor who has not linked a wallet / switched on
payouts. /api/sponsor and /me now walk the site's sponsor line upward to the first upline that is
activated with payouts on (not on the no-payout list) and the buy proceeds under them; nobody
activated -> the catch position (#1). The buyer sees a one-line notice and carries on; admin gets a
heads-up. When the position is created on-chain (MemberActivated), sponsorSyncOnEvent re-points the
buyer's stored sponsor to whoever was paid (#1 included), so the referral leaves the skipped
sponsor's line for good, then sends the pointed notices: the skipped sponsor(s) are told they lost
this referral permanently and how to switch on payouts; the sponsor who was paid is told the
referral is theirs for good and to coach the one who missed it (teach-forward). Admin lookup:
GET /api/admin/sponsor-resolve?ref=. Only a transient chain error still pauses a buy.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 11:18:14 -05:00
martbost a85a198e95 Chain index keeps the full event history (was a 600-event window); one-time rescan from the deploy block
Hugh's Earnings page showed no payouts, referrals or purchases: /api/my/activity read the last 600
events and the window had moved past his Sept 9-10 activity. Ten other readers (dashboard earned
total, leaderboard, holding-tank own-buy check, admin member view, growth snapshot, P&L, burner
match) treated the same list as complete. KEEP_EVENTS 600 -> 250000; chain.rescan() rebuilds from
deployBlock without re-firing onEvent (no repeat Telegram/email), keeps real ts for known events and
estimates ts by block height for backfilled ones; runs once at boot when a filled window is found;
admin routes POST /api/admin/chain/rescan and GET /api/admin/chain/status. State file only rewritten
when events changed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 10:36:28 -05:00
martbost dda8c976b0 No native dialogs: Shorts report prompt -> inline reason buttons; admin drip confirms -> IAP.confirmBox
Same class of bug as the campaign #27 false report: the Shorts report was a prompt() pre-filled with
'inappropriate'. Members now tap a reason button on purpose or cancel. Script tags bumped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 10:23:00 -05:00
martbost 616f328db5 Report-an-ad dialog: site dialog with no default reason (was a native prompt pre-filled with "broken")
Campaign #27 (house AdRevSplit text ad) was reported "broken" with no note while the target framed
and loaded fine; the report dialog was prompt() with 'broken' as the default value, so one stray OK
filed it. Now IAP.ask with an explicit, validated reason and an optional note; common.js tag bumped
on all pages.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 10:21:53 -05:00
martbost 69d672665c Credit activity ledger: every earn and spend logged with a reason, listed under Campaigns
Hugh earned a 10-credit sign-in bonus, then bought a 280-credit extension; earned credits spend
first, so Earned read 0 and the bonus looked lost. There was no record a member could check.
Now every real credit movement writes a credit_log row (JSON store in file mode): welcome, sign-in
bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone/leaderboard
bonuses, partner codes, admin/team grants, AI Copy Engine charges + refunds, flat buys (featured
run, extension, visit pack, more visits), login-ad days, and metered delivery rolled up per
campaign per day; on-chain purchased-credit spends are marked. GET /api/my/credits/activity;
dashboard shows the last 40 under Campaigns (also when there are no campaigns) with a link from
Earn credits. Chatbot canned answer + AI prompt updated; my.js tag bumped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 08:41:43 -05:00
martbost ffacf741da Extend run / visits top-up: budget = charged + this buy (release parked credits); featured row shows days left
Hugh extended his featured link and his balance fell 1,133 -> 0: the row still carried the 1,400
parked by the old add-credits button, and reactivating it reserved that budget again. Both flat
paths now set budget to spent + accrued + cost. Featured Run column shows "N of M days left"
(Hugh: "says 14 but it's actually 7") and "M days done" after the run.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 08:19:33 -05:00
martbost 28bce75913 Featured links: Extend run (book more days) replaces Buy more views; visit packs top up by visits; campaign rows say paid up front and runs through
Hugh and Michael both added credits to a featured run expecting more days. Featured is a flat
daily buy, so the credits sat unspent until the run ended and their balance read 0 meanwhile.
Now: /api/my/campaigns/:id/extend books extra days after the current run (or from today if it
ended) and charges them at once; top-up refuses featured; a visits top-up buys more visits at the
pack rate, charged now; rows show paid up front + day count + runs through <date> / run ended;
explainer under the campaign table; chatbot canned answer + AI prompt updated; my.js v tag bumped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 07:38:37 -05:00
martbost b1a1cbff5e Achievement badge image rendered on the server with ffmpeg (a phone canvas sent a blank card); admin re-post route
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 03:30:01 -05:00
martbost 84d9f49d4b Held purchase: nudge the sponsor automatically (email + on-site) to link a wallet and switch on payouts, once an hour at most
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 23:43:11 -05:00
martbost b7cc06b28c Overview: click a chip in Your line at a glance to open that member's Activity panel on My line
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 18:54:00 -05:00
martbost 0da7c796b8 Campaigns: visit packs show 'paid up front' and delivered-of-total instead of a spent bar (Michael's 3,000-credit pack looked used up)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 16:13:26 -05:00
martbost 4d578fadac Lead with the $20 activation language; free-member POL earning no longer volunteered (Marty); chatbot answers truthfully only when asked point-blank
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 15:00:01 -05:00
martbost 310384cdad Credits versus POL spelled out: level 1 needs payouts on (no purchase), free members earn credits; home page block, earning page, join step 3, chatbot (Clinton's question)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 14:29:39 -05:00
martbost 66b3c83d3d Burner: when a campaign's pinned position is dry on-chain, settle the spend from another funded position on the same account (credits are pooled per account)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 12:49:16 -05:00
martbost 92e7304882 Daily growth snapshot to the Telegram payments feed and shared topic (sign-ups, purchases, POL paid, campaigns, viewing, lifetime totals); admin preview/send-now routes and settings
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 12:43:19 -05:00
martbost 8ca019a5b3 Pipeline advice follows the main wallet's buyer count (what the contract pays on); card states the linked-positions rule; chatbot knows it
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 12:26:02 -05:00
martbost 560d758ed9 Pipeline: count linked positions' buyers on member cards, the way My line and badges do; show the main/positions split on the card
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 12:22:25 -05:00
martbost 02f742f90a Pipeline: sponsor follow-up board (stages from the ledger, notes/follow-ups/tags, stage messages into chat), gated by pipelineMode with a coming-soon card until launch; training cards can wait on the same switch
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 11:01:03 -05:00
martbost 56aa7418ad Payment and missed-payment notices also land in the on-site inbox (login pop-up + Messages card), with who bought, share in POL and dollars, and the transaction link
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 10:44:48 -05:00
martbost d6d771d93e Missed-payout email: tell the skipped member who bought, what they missed in POL and dollars, buyers needed, and how to close the gap
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 10:39:12 -05:00
martbost 87fa837165 Campaigns table: click sources stacked so the Clicks column stays narrow, card layout up to 900px; audit alert-day persisted, rounding-scale diffs ignored
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 07:31:16 -05:00
martbost 653c6d486e Launch checklist: launch graphics (wide + square), five day-by-day posts and a DM with link and FOUNDER code, copy buttons
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 07:12:23 -05:00
martbost c5e4dc423b Launch checklist: four promoter swipe emails with the member's link and the FOUNDER code, copy buttons
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 07:05:57 -05:00
martbost e03dbbffcf Audit: ignore history already refunded and campaigns older than the hourly log; login daily fee capped at remaining budget
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 05:45:57 -05:00
martbost 84a9063bbe Admin > Reports: counters audit (views vs delivery logs, login days charged vs shown, featured views, clicks vs views, spend vs budget), daily with Telegram alert
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 05:32:13 -05:00
martbost 86a7f83874 Login ads: charge the daily fee only on days the ad was actually shown (last_shown_day); featured views counted
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 05:26:16 -05:00
martbost 7423347c95 Featured strip: count impressions (one per viewer per campaign per hour) so featured advertisers see views and the by-hour chart
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 05:21:58 -05:00
martbost a19a3fc31e Campaigns list: stacked cards on phones with the buttons at the bottom, no sideways scroll (Jim, 2026-09-15)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 04:37:43 -05:00
martbost f155a8cc24 Sponsor hold: a named sponsor that cannot be paid (payouts off, chain lookup failed, unknown) blocks the first purchase and activation with a message and alerts the admin, instead of silently crediting the company
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 21:00:27 -05:00
martbost 1533d377cc Member updates: paced + retried Sendy opt-in checks (unknowns never cached as declines), explicit recipient list for repairs, recipients recorded on the send log
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 14:24:27 -05:00
martbost 6e8f1ccf9d Member updates: closing text after the notes (sign-off placement)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 14:21:13 -05:00
martbost 14868753c0 Member updates: saved draft (loads into the admin card, Save draft button)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 14:11:51 -05:00
martbost 024170e7f8 Member updates: audience defaults to newsletter opt-ins (Sendy list status), explicit 'everyone' option; sendy.status()
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 13:47:13 -05:00
martbost 7bb956e896 Admin > Releases: email an update to members (pick notes, intro, audience, preview, test, send; opt-outs honoured; send log)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 13:40:01 -05:00
martbost 203ebdb4bf Dashboard payload carries lineBannerUrl so the Overview launch mark counts the banner item (was 7 of 8 vs 8 of 8 on /launch)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 12:17:12 -05:00
martbost 119644d688 Line at a glance + My line: every level shows who made their $20+ buy and how many qualifying buyers of their own they have (Clinton); 60s member cache for line views
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 11:29:10 -05:00
martbost 0a19e77e7f Badges count qualifying buyers across linked positions (never regress); line chips light on any of a member's positions; buyers tile notes linked-position buyers
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 10:44:36 -05:00
martbost 1fad5bdab2 No-payout positions (siteConfig.noPayoutIds, default 25): linkage only. Buy-from picker disables them, purchases from them refused, joins routed away from them and their upline chain
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 10:30:58 -05:00
martbost e699513636 My line: show who sponsored each person on every row, all three levels
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 10:15:44 -05:00
martbost f2c155a6d2 My line: sixth grid column so the Activity button sits on the row
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 09:58:47 -05:00
martbost 201d249738 My line: Activity drop-down on every row, all three levels (last seen, stage, ads today, campaigns, link views, line, wallet, badges, Working/Quiet); Video Maker font override for local runs
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 09:56:14 -05:00
martbost 32028b1e8e Video Maker: live progress bar (stage labels + ffmpeg -progress percent, queue position), page polls every 2.5s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 09:04:38 -05:00
martbost d57fc40299 Toolkit: render the Spark/Circuit/Nexus sections for members below Surge too (early return skipped them); log toolkit errors
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 08:43:35 -05:00
martbost 96760158df Video Maker: size every end-card line to the frame width; two-line headline and footer in portrait
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 07:18:51 -05:00
martbost 9316dfc0db Toolkit: ship the rest of the ladder (Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops, grants, co-brand, partner code)
- Spark: one-tap banner/text campaign templates aimed at the member's link (POST /api/my/toolkit/template); printable QR handout at /handout/<username>
- Circuit: videomaker.js renders every promo video/short with the member's end card + QR via ffmpeg (Dockerfile adds ffmpeg + ttf-dejavu), hosted in Spaces; split tester compares join angles
- Nexus: Leader Ops (three-level triage, stalled flags, one-click nudges), AI team broadcast kind + Send to my team, credit grants from the leader's earned pool, co-branded join page (sponsor bio for level-3 sponsors), member-funded partner code (promo_codes.funder; redemption charges the funder) + /partners?ref=<username>
- toolkit ladder all live; chatbot updated; my.js v20260914e, site.css v20260914c, join.js/partners.js v20260914a

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 07:15:43 -05:00
martbost 0f030a4943 Copy Engine: scrub en dashes too
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 06:44:11 -05:00
martbost c1f58b2acf Promo toolkit by badge + AI Copy Engine at Surge: posts, DMs, follow-ups, objection replies, emails, stories in the member's name; monthly free allowance by badge (20/60/150), then ad credits per generation; admin usage view
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 06:42:55 -05:00
martbost b09e5dce8b Overview: Getting-started stepper (username, link wallet, switch on payouts, first package) with one guided button per step; soft nudge, collapsible, never a gate
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 05:53:02 -05:00
martbost 825d0de6c3 Header: Leaderboard link
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 05:40:26 -05:00
martbost 6233d112e0 Leaderboard: company account excluded from rankings. Weekly member email: credits unspent, streak, contest rank, tank, line (sponsors by default; memberWeeklyEmail=1 for everyone)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 05:26:23 -05:00
martbost b0ef3b3a58 Leaderboard + referral contest: /leaderboard (week/month/all, read from chain, own positions excluded), Overview card with own rank, weekly and monthly winners recorded at rollover with credit ladders granted automatically and announced to Telegram
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 05:22:39 -05:00
martbost b3523e9dc4 Release notes + roadmap: /whats-new page, Overview What's new card, Admin > Releases editor
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 04:54:43 -05:00
martbost f7b911bab6 Badge share sheet: Massifly option (copies the post, opens the feed composer)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 17:23:57 -05:00
martbost 8e415c3cf4 Badge share sheet: public badge page with preview image (/b/<user>/<badge>), X/Facebook/Telegram/WhatsApp/LinkedIn/native share, copy link, save image
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 17:13:18 -05:00
martbost e63bc57a99 Badge posts: manual Post to Telegram is admin-only; members' badges still post automatically on unlock
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 17:09:59 -05:00
martbost 964a02a342 Achievement badges: personalised badge image auto-posted to the Telegram payments topic and main group on unlock (once per badge), Post to Telegram button, feed toast
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 16:55:43 -05:00
martbost 0c58b80184 Holding tank: no releasing an adoptee within 3 days of pickup, dropped adoptions count toward the two-adoption limit, releases posted to the feed and Telegram
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 13:50:28 -05:00
martbost b9a70dba1a Sponsor chat: composer grows with the message (up to 45% of the screen) and can be dragged taller
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 13:41:18 -05:00
martbost 34098e5565 Watch videos: green-check done screen when the day's videos are finished, like Watch ads
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 08:56:13 -05:00
martbost 6589930945 Join page names the owner of the link it was opened with, and tells a member when they are previewing their own page
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 07:54:29 -05:00
martbost 6ca287042f Member labels: resolve a brand-new buyer by on-chain wallet so purchase emails name the username, not member #
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 07:49:08 -05:00
martbost b5eb03456c Wallet tab: Ad credits card counts earned credits too (promo credits looked like 0)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 07:29:24 -05:00
martbost 53f87f79ba Blog syndication: publishing an article posts it to X and Instagram through Blotato (cover via media upload, once per article, retry button, status column)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 07:20:47 -05:00
martbost 0ad974ca59 Admin traffic: conversion columns (visit to signup, signup to registered, signup to buyer), stacked centered headers
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 07:03:04 -05:00
martbost 4efba20d4e Earn: video stops when leaving the tab/pane, 'all watched today' message, open earn tokens survive a redeploy; admin member search matches as you type, clearer old-site line; QA earn harness follows the done screen
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 06:46:08 -05:00
martbost 0c7f957db4 Admin: member search + drilldown card (identity, chain, credits, line, purchases, payouts, campaigns) with username/sponsor/wallet/credits/delete actions; sortable + filterable admin tables; Earn tab zero-credit button wording
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 06:27:07 -05:00
martbost 1faa43780e Wallet guide + chatbot: Phantom ships with Polygon switched off (Settings > Active Networks)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 05:07:54 -05:00
martbost 4caa0ef5a8 Sign-up guard: honeypot is read-only until a trusted focus and ignores browser autofill (own email); masked value logging
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 04:57:51 -05:00
martbost 2bd612d9ba Admin blog: Save draft / Publish buttons keep the solid style (chips wrapper made them transparent)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 18:56:10 -05:00
martbost 49a98e7ee3 Blog: admin-written coaching articles, server-rendered public /blog with SEO metadata, sitemap, RSS, robots
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 18:42:56 -05:00
martbost 1a83f4f2ff Earn tab: progress hint shows at every stage (the claim-ready hint was unreachable); member guide /earning
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 17:41:13 -05:00
martbost a6dcd02999 Earn: claim streak (5/7/10, 25 every 7th day), after-set prompts for verified visits and launching a campaign
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 17:30:02 -05:00
martbost 9d14af0898 Top menu: 'How it works' and 'Ad packages' anchor to homepage sections (#how, #packages); sections clear the sticky nav
The Ad packages link pointed at /#ladder, an id that did not exist on the homepage.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 16:54:55 -05:00
martbost 5b4fe133eb Homepage ticker: speed scales with text length (~70 px/s), pauses on hover/touch; CSS fallback 120 s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 16:40:23 -05:00
martbost 99f6c1f8c6 Dialogs: Cancel used the site's giant .ghost display class by mistake; use the secondary button style
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 16:23:39 -05:00
martbost 6395ad3a7e Dashboard: community toasts for joins, tank arrivals, adoptions, purchases, payouts and qualifications
A second, quieter toast (bottom-left, one per 4 s) shows site-wide activity from the
live feed for every signed-in member; personal payout toasts are unchanged. The server
pushes Joined (at first username, with tank flag) and Adopted events onto the feed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 16:03:43 -05:00
martbost a9f10f861d Wallet tab: 'Wallet connected' with a green check next to the address; explicit 'No wallet connected yet' otherwise
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 15:39:46 -05:00
martbost a385fbf4c2 Username is required: blocking first step on every sign-in until one is saved
showOnboard(required) has no skip and no dismiss; a suggestion from the email
prefix is prefilled (GET /api/my/username-suggest, made unique); the member
area does not render until the username exists. Welcome tour and login ad still
run once for invite arrivals afterwards. Wallet-only sessions are unaffected.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 15:32:42 -05:00
martbost 6996186061 Partner page + kit: 'I've been running ad sites for years' (present tense)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 14:19:27 -05:00
martbost 2a96403ffd Site-owner partner page at /partners: kit content, the explainer video, ?name and ?promo personalisation, company placement CTA
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 13:32:03 -05:00
martbost fb709ddde9 Join page: ?name=First greets the visitor; on /join/company it says the top spot is reserved for them
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 13:25:21 -05:00
martbost 3c81df2167 Holding tank: adoption posts to the Telegram payments topic naming the sponsor
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 13:18:59 -05:00
martbost 65ef42fc24 Docs: partner kit: the top spot is claimed by activating with at least the $20 package
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 12:43:07 -05:00
martbost d6b85f0ce9 Join alias: /join/company and /join/top place partners under member #1 (the company position)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 12:32:26 -05:00
martbost c2402c4e0e Docs: partner kit promises top placement under the company via the company link
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 12:30:42 -05:00
martbost 551b860c67 Docs: partner kit mentions the WalletConnect integration
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 12:19:52 -05:00
martbost 9898e3f47f Docs: partner kit retoned for site owners who know Marty and already run a builder
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 11:49:49 -05:00
martbost 6498d85b20 Docs: partner kit links the explainer video
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 11:38:12 -05:00
martbost eaaa87281f Docs: site-owner partner kit (plain-text copy of the shareable page)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 11:21:32 -05:00
martbost fc55714757 Partner promo codes: reusable codes that add free ad credits, tracked per redemption
promos.js (promo_codes + promo_redemptions, JSON fallback): create/update codes with
credits, partner, optional cap and expiry, on/off. Redeemed once per account either
from a join link ?promo=CODE (cookie, applied at signup) or the Overview box
'Have a promo code?' (/api/my/promo/redeem). Admin > Traffic gets a Partner promo
codes card (create, toggle, uses, recent redemptions). Chatbot line added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 10:53:17 -05:00
martbost 9b60e6414e Referral purchase email names the buyer: @username in subject and body
memberLabel() resolves @username, or the owner's username for a linked
position, else member #id. Subject: '@name just bought a $20 ad package'.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 10:37:45 -05:00
martbost ebac2fcb32 Member area: in-page dialogs replace every browser prompt/confirm
Mobile Safari shows a red 'Suppress dialogs' option on the second native pop-up
in a row and, once tapped, swallows every later prompt on the site until reload
(Hugh, 2026-09-12, campaign top-up). IAP.ask / IAP.confirmBox in common.js render
a modal-card dialog (Enter/Escape, focus, backdrop cancel); all nine call sites in
my.js use them (top-up credits, link insert x2 with selection restore, pay it
forward, adopt note, release, unlink, add position, Trust Wallet check).
Version tags bumped on every page that loads common.js.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 09:31:43 -05:00
martbost 261f90d843 QA: walk the Traffic and P&L admin panes too
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 07:59:40 -05:00
martbost 0cfbe67196 Admin: register the Traffic pane in the title map (the menu click was a no-op); bump script version tags
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 07:57:43 -05:00
martbost ef088601c3 Admin Traffic tab: referring domains, landing pages, angles, by day
traffic.js logs public page views by referring domain (30 s buffered; page_hits
table or traffic.json), coach exposes all join-page views, and
/api/admin/traffic merges page views, join-page views, signups, registrations
and $20+ buyers by first-touch source for 7/30/90/365-day ranges.
Also: line-tree chips no longer truncate own-position labels.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 07:51:01 -05:00
martbost abc76c47c8 Line tree: gold outline follows the chain's BuyerCounted events, plus a legend
The Overview tree painted gold on the first N chips (N = buyer count) instead of
the members the contract actually counted, so a non-buyer listed first showed as
qualified (Hugh's line, 2026-09-12). /api/my/line now flags each member with
qualified from BuyerCounted events for the account's ids; the tree uses that flag
and shows a legend for gold / plain / open chips.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 07:42:24 -05:00
martbost e46780f872 Legacy bridge: optional src tag (old-domain splash) recorded on the account source
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 07:33:36 -05:00
martbost eae2a04dc0 Legacy bridge pages, welcome-back credits, holding-tank alerts
- /from/faucetwave and /from/tieroneads (?seg=advertiser): the squeeze page with
  brand copy and no video, sponsor cookie cleared so arrivals land in the holding
  tank, angle + a legacy:<brand> source recorded on the account.
- legacy.js: private list DATA_DIR/legacy.json (email -> brand, segment); listed
  emails get a one-time credit grant at account creation (legacyCreditsAdvertiser
  500 / legacyCreditsEarner 150, admin-editable), recorded in legacy-grants.json.
- Holding-tank alerts: dashboard payload carries who is waiting (Overview notice
  with usernames + adopt link), and a 15-minute tick posts new arrivals to the
  shared Telegram payments topic.
- Chatbot prompt lines + admin setting labels.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 07:25:32 -05:00
martbost b844a227d3 My line: show payouts from an email-only session and across all owned positions
refreshMemberId falls back to the account's on-chain id when the session has no
wallet address (phone sign-in by email code), without caching it into the
session. /api/my/line now sums TierPaid events to every position the account
owns (main id + linked positions), so each direct's 'paid you so far' is right
from any device.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-12 04:46:22 -05:00
martbost 1fd61eca56 Telegram: echo payouts into a shared cross-program topic
telegramOnEvent now builds the line once per target: the existing proof feed
(telegramChatId) and a new echo target (telegramEchoChatId + telegramEchoTopicId,
telegramEchoEvents). AwardPaid events are now posted too. Echo lines carry an
InstantAdPay prefix since RM Circle shares the topic. Admin labels added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 18:51:03 -05:00
martbost 024027a2da Campaign form: show the banner size and image rows at load (banner is the default type), not only after a type change
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 15:25:46 -05:00
martbost 63bedddc94 Sign-up guard: a filled honeypot triggers the icon check instead of a silent drop (form-filler extensions fill hidden fields)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 14:17:29 -05:00
martbost cd26161db5 Country-tier targeting for campaigns: DB-IP lite lookup, tier lists in Settings, Show-to tiers on every format, geo-restricted ads kept off the network, per-country serve stats
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 12:02:40 -05:00
martbost 0f855292f5 Sign-up guard: honeypot field renamed so browser autofill cannot trip it; log every guard rejection; clearer stale-page message
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 10:30:11 -05:00
martbost fbd83bf933 Wall: center the sponsor block on phones
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 09:25:28 -05:00
martbost 78e4c76a89 Wall: optional intro video (YouTube, Vimeo or .mp4) from Profile, embedded under the bio
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 09:24:10 -05:00
martbost c9f7a50b30 Admin Members: show the sponsor's username, note share-code joins, flag dead sponsor links
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 09:06:13 -05:00
martbost ab306937e1 MoonPay fallback: use the working /buy/matic page (the /buy/pol slug 404s)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 09:01:17 -05:00
martbost 8b16d52ca6 Wallets guide: website, App Store, Google Play and extension links per wallet; MoonPay button
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 08:47:30 -05:00
martbost fe1edd945c Banner kit: 17 new member banners by angle (1200x630 set, leaderboards, rectangles)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 08:40:06 -05:00
martbost b97e139ef8 Hotfix: quote reserved column name lead in lead_marks (MySQL 8 boot failure)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 08:10:19 -05:00
martbost 09dc6ed368 Dormant-lead rescue: 10-day warning, 14-day move to the holding tank, Contacted-them reset, dead sponsor links to the tank
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 08:06:40 -05:00
martbost 9709ce782d Holding tank: unsponsored free members, first-come adoption (own $20 buy required, 2 open, 7-day window, twice max), release to tank, admin view; PIF wallet-to-wallet POL gift with logging
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 07:57:44 -05:00
martbost 9939c0487f Admin tables: action column keeps its width, email wraps, shorter dates; no sideways scroll needed
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 07:41:50 -05:00
martbost 6a21b4dc62 Admin tables: scroll instead of clipping the last column; Joined stays on one line
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 07:32:29 -05:00
martbost cdb580c1f4 Launch checklist: read buyer count and referrals from the dashboard endpoint
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 07:29:01 -05:00
martbost 48dcd71290 Founding week: /launch leader checklist (8 live-read items incl. the level-3 leader play), dashboard launch-ready mark, launchAt setting
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 07:16:54 -05:00
martbost bf5371ab20 Campaign scheduling (start/end, solo send-from), scheduled NAS push + end sweep, views-by-hour chart
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 06:53:53 -05:00
martbost 159e19dcdf Sign-up code guard: honeypot, form age, per-IP + global limits, progressive icon check, burst alert
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 06:30:03 -05:00
martbost f9b198a49b Your links: collapsed band per angle; Share button only where a share sheet exists
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 06:05:02 -05:00
martbost f7c840dee4 Training: Wallets and buying POL guide (/wallets), guide link on Buy packages, chatbot answers
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 17:20:31 -05:00
martbost 496133b99e Angle join pages are squeeze pages: hook, video, one capture card, three points; full page stays on the plain link
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 16:09:03 -05:00
martbost fe9661ec33 Join page: keep the Sign in link clear of the byline on narrow screens
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 16:04:16 -05:00
martbost 129e4d0946 Angle join pages: matching hook video + three angle points replace the worked example
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 16:02:25 -05:00
martbost 00f85fde08 README: sponsor attribution is last touch 2026-09-10 15:51:19 -05:00
martbost 04e42e94ff Sponsor attribution: last touch (30-day cookie), locked at account creation; 'Joining under' line at the code step; chatbot answer
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 15:49:40 -05:00
martbost 4addf7718e Your links: URLs are tappable, plus an Open button per angle
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 15:41:05 -05:00
martbost f5fb195927 Promo tools: 'Your links' block with the invite link + five angle links (who each is for, copy, share)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 15:30:10 -05:00
martbost b4b9ac8680 Promo tools: banner kit as collapsed accordions per size group
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 14:32:16 -05:00
martbost cac78133ca Never charge a campaign past its budget (on-site batches vs network reconcile overlap)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 11:42:46 -05:00
martbost 4487a90d16 Balances: one reservation rule (earned first) + purchased-grade credited pool
- balances(): live campaign budgets are set aside up front, earned pool first then
  purchased, so dashboard numbers never move per impression; new 'in campaigns' line
- earned pool gains a purchase_grade portion for refunds/comps: shows under Purchased
  as 'credited to you' and funds login ads (daily login charge draws on it first)
- viewing credits always spend before credited purchased money
- dashboard/donut/spend banner/earn pane/positions show purchased, credited, earned, in campaigns
- chatbot canned answer + AI prompt: the balance rule

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 11:16:40 -05:00
martbost af6d2db711 Burner: in-flight sends persisted to the volume and checked directly against contract logs before any resend
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 10:47:22 -05:00
martbost 38366e0beb Credits: Welcome label shows only the welcome amount; login ads explain they spend purchased credits only
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 10:42:16 -05:00
martbost 82269eccc8 NAS: syndicated ads click through our redirect so network clicks count and carry the source site
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 10:16:22 -05:00
martbost ecdee89be1 Traffic sources: referring domain on join-link visits and joins (per-member table), click sources per campaign (surface or outside host)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 10:12:13 -05:00
martbost 6e187c4f41 Campaigns: optional daily cap on banner/text paces spend on-site and hands Network Ad Space one day's allowance at a time
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 10:03:57 -05:00
martbost abf7415c83 Burner: on-chain ref = burn id; recognise already-mined burns from CreditsConsumed and hold in-flight sends, so a lost RPC response can never double-burn
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 09:49:20 -05:00
martbost 94910275c0 Positions policy: cap of five per account, refuse wallets registered under anything but the main member, admin members shows positions; Qualified Start card states the rule
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 09:42:06 -05:00
martbost f6490c9444 Promo tools: hook video cards (matched links, downloads, captions, share buttons)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 08:55:29 -05:00
324 changed files with 39055 additions and 962 deletions
+1
View File
@@ -1,4 +1,5 @@
FROM node:22-alpine
RUN apk add --no-cache ffmpeg ttf-dejavu
WORKDIR /app
COPY package.json ./
RUN npm install --omit=dev --no-audit --no-fund
+8 -1
View File
@@ -8,7 +8,7 @@ Node server (RM Circle pattern): static pages + JSON API + SSE ledger.
- `server.js` — http server: pages, `/api/*`, `/join/<id>` sponsor links, SSE feed
- `chain.js` — contract reader + persistent event indexer (free public RPCs)
- `auth.js` — SIWE wallet sign-in (EIP-4361), sessions in the volume
- `accounts.js` — site-side records only (free members, first-touch sponsor
- `accounts.js` — site-side records only (free members, last-touch sponsor
attribution, handles). The CHAIN is the source of truth for money/credits.
- `public/` — landing, live ledger, member area; no client libraries
@@ -30,3 +30,10 @@ PORT=3100 node server.js # DATA_DIR defaults to ./data
Admin API auth: `Authorization: Bearer $ADMIN_PASSWORD`.
Spec: `../CONTRACT-SPEC.md` (v1.0.3-frozen). Contracts: `../contracts/`.
## Chatbot knowledge is part of every change
`chatbot.js` answers members two ways: `CANNED` regex answers and `systemPrompt()` for the AI. Any
change that a member could ask about (a new pane, a rule, a price, a limit, a fix they noticed) is not
done until both are updated in the same commit, and `KNOWLEDGE_DATE` in `chatbot.js` is bumped. The QA
runner (`bash qa/run.sh public`) fails when a release note on the live site is newer than that date.
+103 -20
View File
@@ -33,11 +33,15 @@ function newCode(taken) {
return c;
}
const pub = a => a ? { email: a.email, sponsorRef: a.sponsorRef || '', code: a.code || null,
username: a.username || null, memberId: a.memberId || 0, joinedVia: a.joinedVia || null,
username: a.username || null, memberId: a.memberId || 0, joinedVia: a.joinedVia || null, joinedRef: a.joinedRef || null,
lineBannerUrl: a.lineBannerUrl || null, lineTargetUrl: a.lineTargetUrl || null, wallOffers: a.wallOffers || null,
avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials: a.socials || null,
bixPartnerLink: a.bixPartnerLink || null, // BixPay partner link (bixpay.js, 2026-10-29): one identity, follows the member to LinkSpin/CTB
profileQuarantined: !!a.profileQuarantined, // 2026-10-30: first profile save of a brand-new free account planted a link; stored, never rendered publicly (spamscan.js)
chatAvailable: a.chatAvailable === false ? false : true, lastSeen: a.lastSeen || 0,
theme: a.theme || null, // 2026-11-01 appearance: auto | light | dark, follows the member across browsers (common.js IAP.themeSync)
address: a.address || null, created: a.created } : null;
const THEMES = new Set(['auto', 'light', 'dark']);
const USER_RE = /^[a-zA-Z0-9_]{3,20}$/;
const normUser = u => String(u || '').trim().toLowerCase();
@@ -75,11 +79,11 @@ const J = {
if (!a || !a.pass || !checkPassword(password, a.pass)) return { error: 'Wrong email or password.' };
return { ok: true, account: pub(a) };
},
async ensure(e, ref, via) {
async ensure(e, ref, via, joinedRef) {
let created = false;
if (!this.db.byEmail[e]) {
const code = newCode(c => this.db.byCode[c]);
this.db.byEmail[e] = { email: e, pass: null, sponsorRef: ref, code, address: null, created: Date.now(), joinedVia: via || null };
this.db.byEmail[e] = { email: e, pass: null, sponsorRef: ref, code, address: null, created: Date.now(), joinedVia: via || null, joinedRef: joinedRef || null };
this.db.byCode[code] = e;
created = true;
this.save();
@@ -116,16 +120,19 @@ const J = {
acct.wallOffers = json || null; this.save();
return { ok: true, account: pub(acct) };
},
async setProfile(e, avatarUrl, bio, socials) {
async setProfile(e, avatarUrl, bio, socials, quarantined) {
const acct = this.db.byEmail[e];
if (!acct) return { error: 'No such account.' };
if (avatarUrl !== undefined) acct.avatarUrl = avatarUrl || null;
if (bio !== undefined) acct.bio = bio || null;
if (socials !== undefined) acct.socials = socials || null;
if (quarantined !== undefined) acct.profileQuarantined = !!quarantined;
this.save();
return { ok: true, account: pub(acct) };
},
async setBixLink(e, link) { const acct = this.db.byEmail[e]; if (!acct) return { error: 'No such account.' }; acct.bixPartnerLink = link || null; this.save(); return { ok: true, account: pub(acct) }; },
async touchSeen(e) { const a = this.db.byEmail[e]; if (a) { a.lastSeen = Date.now(); this.save(); } },
async setTheme(e, t) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.theme = THEMES.has(t) ? t : null; this.save(); return { ok: true, account: pub(a) }; },
async setChatAvailable(e, v) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.chatAvailable = !!v; this.save(); return { ok: true, available: !!v }; },
async getMutes(e) { const a = this.db.byEmail[e]; return (a && Array.isArray(a.chatMutes)) ? a.chatMutes : []; },
async setMute(owner, target, muted) {
@@ -168,6 +175,10 @@ const J = {
return { ok: true, account: pub(acct) };
},
async listAll(limit) { return Object.values(this.db.byEmail).sort((a, b) => (b.created || 0) - (a.created || 0)).slice(0, limit).map(pub); },
// every account's identity, never a page of them: a lookup built from a capped list silently
// calls every older member unreachable (the admin table labelled 144 live sponsors 'dead link'
// once the site passed 500 accounts, Marty 2026-09-23)
async identities() { return Object.values(this.db.byEmail).map(a => ({ email: a.email, username: a.username || null, code: a.code || null, memberId: a.memberId || 0 })); },
async setSponsorRef(e, ref) {
const acct = this.db.byEmail[e];
if (!acct) return { error: 'No such account.' };
@@ -194,20 +205,38 @@ const J = {
},
async setPositionMember(a, id) { const p = this.db.positions[a]; if (p && p.memberId !== id) { p.memberId = id; this.save(); } },
async positionOwner(a) { const p = this.db.positions[a]; return p ? { address: a, email: p.email, memberId: p.memberId || 0 } : null; },
async positionByMember(id) { const e = Object.entries(this.db.positions).find(([, p]) => p.memberId === Number(id)); return e ? { address: e[0], email: e[1].email, memberId: e[1].memberId } : null; },
async removePosition(e, a) {
const p = this.db.positions[a];
if (!p || p.email !== e) return { error: 'No such position.' };
if (p.memberId) return { error: 'That position is already registered on-chain and cannot be unlinked.' };
delete this.db.positions[a]; this.save(); return { ok: true };
},
// admin only: point the account at a different main wallet (or none); the caller re-reads the member id
async adminSetAddress(e, a) {
const acct = this.db.byEmail[e]; if (!acct) return { error: 'No such account.' };
if (a) {
if (this.db.byAddress[a] && this.db.byAddress[a] !== e) return { error: 'That wallet is the main wallet of another account.' };
if (this.db.positions[a]) return { error: 'That wallet is a linked position on ' + (this.db.positions[a].email === e ? 'this' : 'another') + ' account.' };
}
if (acct.address) delete this.db.byAddress[acct.address];
acct.address = a || null; if (a) this.db.byAddress[a] = e; this.save(); return { ok: true, account: pub(acct) };
},
async positionByAddress(a) { const p = this.db.positions[a]; return p ? { address: a, email: p.email, memberId: p.memberId } : null; },
async removeAccount(e) {
const acct = this.db.byEmail[e]; if (!acct) return { error: 'No such account.' };
if (acct.address) delete this.db.byAddress[acct.address]; if (acct.code) delete this.db.byCode[acct.code];
for (const [a, p] of Object.entries(this.db.positions)) if (p.email === e) delete this.db.positions[a];
delete this.db.byEmail[e]; this.save(); return { ok: true };
},
};
// ---- MySQL mode ----
const rowPub = r => r ? pub({ email: r.email, sponsorRef: r.sponsor_ref, code: r.code,
username: r.username, memberId: r.member_id || 0, joinedVia: r.joined_via || null,
username: r.username, memberId: r.member_id || 0, joinedVia: r.joined_via || null, joinedRef: r.joined_ref || null,
lineBannerUrl: r.line_banner_url, lineTargetUrl: r.line_target_url, wallOffers: r.wall_offers || null,
avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials,
chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0),
avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials, bixPartnerLink: r.bix_partner_link || null, profileQuarantined: !!r.profile_quarantined,
chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), theme: r.theme || null,
address: r.address, created: Number(r.created) }) : null;
const D = {
async signup(e, password, ref) {
@@ -228,12 +257,12 @@ const D = {
if (!rows.length || !rows[0].pass || !checkPassword(password, rows[0].pass)) return { error: 'Wrong email or password.' };
return { ok: true, account: rowPub(rows[0]) };
},
async ensure(e, ref, via) {
async ensure(e, ref, via, joinedRef) {
const code = newCode();
let created = false;
try {
await db.q('INSERT INTO accounts (email,pass,sponsor_ref,code,address,created,joined_via) VALUES (?,NULL,?,?,NULL,?,?)',
[e, ref, code, Date.now(), via || null]);
await db.q('INSERT INTO accounts (email,pass,sponsor_ref,code,address,created,joined_via,joined_ref) VALUES (?,NULL,?,?,NULL,?,?,?)',
[e, ref, code, Date.now(), via || null, joinedRef || null]);
created = true;
} catch (err) {
if (err.code !== 'ER_DUP_ENTRY') throw err;
@@ -261,13 +290,16 @@ const D = {
await db.q('UPDATE accounts SET wall_offers=? WHERE email=?', [json || null, e]);
return { ok: true, account: await this.byEmail(e) };
},
async setProfile(e, avatarUrl, bio, socials) {
async setProfile(e, avatarUrl, bio, socials, quarantined) {
if (avatarUrl !== undefined) await db.q('UPDATE accounts SET avatar_url=? WHERE email=?', [avatarUrl || null, e]);
if (bio !== undefined) await db.q('UPDATE accounts SET bio=? WHERE email=?', [bio || null, e]);
if (socials !== undefined) await db.q('UPDATE accounts SET socials=? WHERE email=?', [socials || null, e]);
if (quarantined !== undefined) await db.q('UPDATE accounts SET profile_quarantined=? WHERE email=?', [quarantined ? 1 : 0, e]);
return { ok: true, account: await this.byEmail(e) };
},
async setBixLink(e, link) { const r = await db.q('UPDATE accounts SET bix_partner_link=? WHERE email=?', [link || null, e]); if (!r || !r.affectedRows) return { error: 'No such account.' }; return { ok: true, account: await this.byEmail(e) }; },
async touchSeen(e) { await db.q('UPDATE accounts SET last_seen=? WHERE email=?', [Date.now(), e]); },
async setTheme(e, t) { await db.q('UPDATE accounts SET theme=? WHERE email=?', [THEMES.has(t) ? t : null, e]); return { ok: true, account: await this.byEmail(e) }; },
async setChatAvailable(e, v) { await db.q('UPDATE accounts SET chat_available=? WHERE email=?', [v ? 1 : 0, e]); return { ok: true, available: !!v }; },
async getMutes(e) {
const r = await db.q('SELECT chat_mutes FROM accounts WHERE email=?', [e]);
@@ -315,6 +347,10 @@ const D = {
return { ok: true, account: await this.byEmail(e) };
},
async listAll(limit) { const rows = await db.q('SELECT * FROM accounts ORDER BY created DESC LIMIT ?', [Number(limit) || 500]); return rows.map(rowPub); },
// identity columns for EVERY account, no limit: small enough to stay cheap at any size, and a
// sponsor lookup must never be built from a page of members (see the JSON note above)
async identities() { const rows = await db.q('SELECT email, username, code, member_id FROM accounts');
return rows.map(r => ({ email: r.email, username: r.username || null, code: r.code || null, memberId: Number(r.member_id) || 0 })); },
async setSponsorRef(e, ref) {
const r = await db.q('UPDATE accounts SET sponsor_ref=? WHERE email=?', [ref, e]);
if (!r.affectedRows) return { error: 'No such account.' };
@@ -342,12 +378,25 @@ const D = {
const r = (await db.q('SELECT * FROM positions WHERE address=?', [a]))[0];
return r ? { address: r.address, email: r.email, memberId: r.member_id || 0 } : null;
},
async positionByMember(id) { const r = await db.q('SELECT address, email, member_id FROM positions WHERE member_id=? LIMIT 1', [Number(id)]); return r[0] ? { address: r[0].address, email: r[0].email, memberId: r[0].member_id } : null; },
async removePosition(e, a) {
const r = (await db.q('SELECT * FROM positions WHERE address=? AND email=?', [a, e]))[0];
if (!r) return { error: 'No such position.' };
if (r.member_id) return { error: 'That position is already registered on-chain and cannot be unlinked.' };
await db.q('DELETE FROM positions WHERE address=?', [a]); return { ok: true };
},
async adminSetAddress(e, a) {
if (a) {
const o = (await db.q('SELECT email FROM accounts WHERE address=?', [a]))[0]; if (o && o.email !== e) return { error: 'That wallet is the main wallet of another account.' };
const pos = (await db.q('SELECT email FROM positions WHERE address=?', [a]))[0]; if (pos) return { error: 'That wallet is a linked position on ' + (pos.email === e ? 'this' : 'another') + ' account.' };
}
await db.q('UPDATE accounts SET address=? WHERE email=?', [a || null, e]); return { ok: true, account: await this.byEmail(e) };
},
async positionByAddress(a) { const r = (await db.q('SELECT * FROM positions WHERE address=?', [a]))[0]; return r ? { address: r.address, email: r.email, memberId: r.member_id || 0 } : null; },
async removeAccount(e) {
await db.q('DELETE FROM positions WHERE email=?', [e]);
const r = await db.q('DELETE FROM accounts WHERE email=?', [e]); return r.affectedRows ? { ok: true } : { error: 'No such account.' };
},
};
const impl = () => db.enabled() ? D : J;
@@ -360,10 +409,15 @@ async function signup(email, password, sponsorRef) {
return impl().signup(e, String(password), String(sponsorRef || ''));
}
async function login(email, password) { return impl().login(normEmail(email), String(password || '')); }
async function ensure(email, sponsorRef, via) {
// change listener (2026-10-08): LinkSpin's registry sync hears about created / named / wallet-linked / re-sponsored accounts
let changeFn = null; function onChange(fn) { changeFn = fn; } const changed = e => { try { if (changeFn) changeFn(e); } catch (err) {} };
let walletFn = null; function onWalletLinked(fn) { walletFn = fn; } // reporting only (lsreport.js, 2026-11-07): told after a main wallet is linked, never in the way of it
async function ensure(email, sponsorRef, via, joinedRef) {
const e = normEmail(email);
if (!EMAIL_RE.test(e)) return { error: 'That email address does not look right.' };
return impl().ensure(e, String(sponsorRef || ''), String(via || '').toLowerCase().slice(0, 20) || null);
const r = await impl().ensure(e, String(sponsorRef || ''), String(via || '').toLowerCase().slice(0, 20) || null, String(joinedRef || '').toLowerCase().slice(0, 80) || null);
if (r && !r.error) changed(e);
return r;
}
async function byEmail(email) { return impl().byEmail(normEmail(email)); }
async function byAddress(address) { return impl().byAddress(normAddr(address)); }
@@ -372,11 +426,24 @@ async function byUsername(u) {
const n = normUser(u);
return USER_RE.test(n) ? impl().byUsername(n) : null;
}
// Usernames that pass a member off as the company, its staff or its other sites (Marty, 2026-09-27:
// member #170 took "instantadpay" and a second account of theirs took "admin", then adopted
// holding-tank members under the company's name). Anything that contains a brand, or is a staff
// or authority word on its own (with digits, underscores or team/desk/help around it), is refused.
const BRANDS = ['instantadpay', 'instant_ad_pay', 'instantadspay', 'polhunter', 'rmcircle', 'cryptoteambuild', 'linkspin', 'dripoffers', 'adrevlnks', 'adrevsplit', 'faucetwave', 'tieroneads', 'tier1ads'];
const ROLE_RE = /^[_\d]*(the_?|iap_?|ctb_?|team_?|official_?)?(admin|admins|administrator|sysadmin|root|system|support|helpdesk|help|staff|official|moderator|mod|mods|owner|ceo|founder|cofounder|company|house|security|billing|payout|payouts|payment|payments|compliance|legal|noreply|no_reply|info|contact|service|verify|verification|iap|ctb)[_\d]*(_?(team|desk|help|official|staff|support|center|centre))?[_\d]*$/;
function reservedUsername(n) {
const u = String(n || '').toLowerCase();
const flat = u.replace(/_/g, '');
if (BRANDS.some(b => flat.includes(b.replace(/_/g, '')))) return true;
return ROLE_RE.test(u);
}
async function setUsername(email, username) {
const n = normUser(username);
if (!USER_RE.test(n)) return { error: 'Usernames are 3 to 20 letters, numbers, or underscores.' };
if (/^\d+$/.test(n)) return { error: 'Usernames need at least one letter.' }; // keep /join/<number> unambiguous
return impl().setUsername(normEmail(email), n);
if (reservedUsername(n)) return { error: 'That username is reserved. Names that suggest you are InstantAdPay, our staff or one of our sites are not allowed. Please pick another.' };
const r = await impl().setUsername(normEmail(email), n); if (r && !r.error) changed(normEmail(email)); return r;
}
async function setMemberId(email, id) { return impl().setMemberId(normEmail(email), Number(id) || 0); }
async function namesForMembers(ids) { return impl().namesForMembers([...new Set(ids)].filter(n => n > 0)); }
@@ -408,13 +475,23 @@ async function downline(email, depth = 3) {
async function linkWallet(email, address) {
const a = normAddr(address);
if (!/^0x[0-9a-f]{40}$/.test(a)) return { error: 'Bad wallet address.' };
return impl().linkWallet(normEmail(email), a);
const r = await impl().linkWallet(normEmail(email), a); if (r && !r.error) { changed(normEmail(email)); try { if (walletFn) walletFn(normEmail(email)); } catch (err) {} } return r;
}
async function count() { return impl().count(); }
// admin: newest-first account list, and re-pointing a member's sponsor (a
// username, share code, or numeric member id: the same tokens join links use)
async function listAll(limit = 500) { return impl().listAll(limit); }
async function setSponsorRef(email, ref) { return impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)); }
// A waiting account made from a LinkSpin registry row (lsinbound.js, 2026-10-15) that its owner has not signed in to yet.
// It exists so the LinkSpin line is already in place; it is not a member yet, so the sweeps that mail, count or adopt
// members (listAll by default) leave it out. It becomes an ordinary account the first time its owner signs in (lastSeen).
// BTC4Hits members imported 2026-11-11 (btc4hits-migration, joinedVia 'btc4hits') are the same kind of waiting account.
// Network hub members who joined at another door (hubsync.js, 2026-11-12, only while HUB_ENABLED) arrive as joinedVia 'hub'.
const SHELL_VIAS = new Set(['linkspin', 'btc4hits', 'hub']);
const isUnclaimedShell = a => !!a && SHELL_VIAS.has(a.joinedVia) && !a.lastSeen && !a.memberId;
// the limit counts members, not waiting accounts: newest-first LIMIT before the filter let thousands of waiting accounts push
// older real members out of the sweeps that read listAll(5000) (tank, coach, leaderboard, Friday, Wednesday)
async function listAll(limit = 500, opts) { if (opts && opts.shells) return impl().listAll(limit); const all = await impl().listAll(1e7); return all.filter(a => !isUnclaimedShell(a)).slice(0, limit); }
async function identities() { return impl().identities(); }
async function setSponsorRef(email, ref) { const r = await impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)); if (r && !r.error) changed(normEmail(email)); return r; }
// resolve a member's DIRECT sponsor account (the token they joined under)
async function sponsorOf(email) {
@@ -438,12 +515,17 @@ async function getChatSettings(email) {
return { available: a ? a.chatAvailable !== false : true, mutes: await impl().getMutes(String(email || '').toLowerCase()) };
}
module.exports = { init, signup, login, ensure, byEmail, byAddress, byCode, byUsername, listAll, setSponsorRef,
setUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, count,
module.exports = { init, signup, login, ensure, onChange, onWalletLinked, isUnclaimedShell, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, identities, setSponsorRef,
setUsername, reservedUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, count,
setLineBanner: (e, b, t) => impl().setLineBanner(String(e || '').toLowerCase(), b, t),
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
setProfile: (e, a, bio, socials) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials),
setProfile: async (e, a, bio, socials, quarantined) => { const r = await impl().setProfile(String(e || '').toLowerCase(), a, bio, socials, quarantined); if (!(r && r.error)) changed(String(e || '').toLowerCase()); return r; }, // profile edits reach LinkSpin too
setBixLink: async (e, link) => { const r = await impl().setBixLink(normEmail(e), link ? String(link).slice(0, 300) : null); if (!(r && r.error)) changed(normEmail(e)); return r; }, // the BixPay partner link rides to LinkSpin in the profile row (lssync.js)
touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()),
setTheme: (e, t) => impl().setTheme(String(e || '').toLowerCase(), t), // appearance only: no changed() tap, LinkSpin does not mirror it either (its accounts.js says the same)
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null),
positionByAddress: a => impl().positionByAddress(normAddr(a)),
removeAccount: e => impl().removeAccount(String(e || '').toLowerCase()),
setChatAvailable: (e, v) => impl().setChatAvailable(String(e || '').toLowerCase(), v),
getMutes: e => impl().getMutes(String(e || '').toLowerCase()),
setMute: (o, t, m) => impl().setMute(String(o || '').toLowerCase(), String(t || '').toLowerCase(), m),
@@ -452,5 +534,6 @@ module.exports = { init, signup, login, ensure, byEmail, byAddress, byCode, byUs
addPosition: (e, a) => { const x = normAddr(a); return /^0x[0-9a-f]{40}$/.test(x) ? impl().addPosition(normEmail(e), x) : Promise.resolve({ error: 'Bad wallet address.' }); },
setPositionMember: (a, id) => impl().setPositionMember(normAddr(a), Number(id) || 0),
positionOwner: a => impl().positionOwner(normAddr(a)),
positionByMember: id => impl().positionByMember(Number(id) || 0),
removePosition: (e, a) => impl().removePosition(normEmail(e), normAddr(a)),
byMemberId: id => impl().byMemberId(id) };
+109
View File
@@ -0,0 +1,109 @@
// Admin member card (Marty, 2026-09-13): one lookup that gathers everything known about a member so
// the admin can search, drill down and act without digging through pages. Read side only; the
// edits live in server.js (/api/admin/member PATCH/DELETE) and accounts.js.
const fs = require('fs');
const path = require('path');
const db = require('./db');
let R = null; // { accounts, ads, chain, tank, legacy, promos, messages, dataDir }
function init(refs) { R = refs; }
const nameOf = a => a ? (a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : a.email) : null;
// resolve a search token: email, @username, member #, share code, or wallet address
async function resolve(q) {
const { accounts } = R;
let t = String(q || '').trim(); if (!t) return null;
if (t.includes('@') && t.indexOf('@') > 0) { const a = await accounts.byEmail(t.toLowerCase()); if (a) return a; }
const u = t.replace(/^@/, '');
if (/^0x[0-9a-f]{40}$/i.test(t)) {
const a = await accounts.byAddress(t.toLowerCase()); if (a) return a;
const pos = accounts.positionByAddress ? await accounts.positionByAddress(t.toLowerCase()) : null;
if (pos && pos.email) return accounts.byEmail(pos.email);
}
if (/^#?\d+$/.test(t)) {
const id = Number(t.replace('#', ''));
const a = await accounts.byMemberId(id); if (a) return a;
const pos = await accounts.positionByMember(id); if (pos && pos.email) return accounts.byEmail(pos.email);
}
let a = await accounts.byUsername(u.toLowerCase()); if (a) return a;
a = await accounts.byCode(u.toLowerCase()); if (a) return a;
return null;
}
async function view(email) {
const { accounts, ads, chain, tank, legacy, promos, messages } = R;
const acct = await accounts.byEmail(String(email || '').toLowerCase());
if (!acct) return null;
const out = { account: acct };
// sponsor + upline chain (site-side sponsorship, up to 5 levels)
const up = []; let cur = acct; const seen = new Set([acct.email]);
for (let i = 0; i < 5 && cur; i++) {
const s = await accounts.sponsorOf(cur.email).catch(() => null);
if (!s || seen.has(s.email)) break; seen.add(s.email);
up.push({ email: s.email, name: nameOf(s), memberId: s.memberId || 0 }); cur = s;
}
out.upline = up; out.sponsorName = up[0] ? up[0].name : null;
// positions (extra wallets) + every on-chain id this account owns
const positions = await accounts.positions(acct.email).catch(() => []);
out.positions = positions;
const ids = new Set([acct.memberId, ...positions.map(p => p.memberId)].filter(Boolean));
out.ids = [...ids];
// on-chain
out.chain = null;
if (acct.memberId) {
try { const m = await chain.member(acct.memberId); out.chain = { memberId: acct.memberId, sponsorId: m.sponsorId, buyerCount: m.buyerCount, activated: m.activated, account: m.account,
level: m.buyerCount >= 5 ? 3 : m.buyerCount >= 2 ? 2 : 1 }; } catch (e) { out.chain = { memberId: acct.memberId, readError: true }; }
}
const purchases = [], received = [], qualified = new Set(); let receivedWei = 0n, spentWei = 0n, spentCents = 0;
if (ids.size) {
for (const ev of chain.recentEvents(1e9)) {
if (ev.type === 'Purchase' && ids.has(ev.buyerId)) { purchases.push({ ts: ev.ts, buyerId: ev.buyerId, priceCents: ev.priceCents, paidWei: ev.paidWei, credits: ev.creditAmount, tx: ev.tx }); spentWei += BigInt(ev.paidWei || 0); spentCents += Number(ev.priceCents || 0); }
if (ev.type === 'TierPaid' && ids.has(ev.recipientId)) { received.push({ ts: ev.ts, buyerId: ev.buyerId, tier: ev.tier, amountWei: ev.amountWei, tx: ev.tx }); receivedWei += BigInt(ev.amountWei || 0); }
if (ev.type === 'BuyerCounted' && ids.has(ev.sponsorId) && ev.newBuyerId) qualified.add(ev.newBuyerId);
}
}
purchases.sort((a, b) => b.ts - a.ts); received.sort((a, b) => b.ts - a.ts);
out.purchases = purchases; out.received = received.slice(0, 50);
out.totals = { purchases: purchases.length, spentCents, spentWei: spentWei.toString(), receivedWei: receivedWei.toString(), payoutsIn: received.length };
const buyerNames = await accounts.namesForMembers([...new Set([...purchases.map(p => p.buyerId), ...received.map(r => r.buyerId)])]).catch(() => ({}));
out.names = buyerNames;
// credits
try { out.credits = await ads.balances([...ids], acct.email); } catch (e) { out.credits = null; }
try { out.earnedSplit = await ads.earnedSplit(acct.email); } catch (e) {}
// campaigns
try { out.campaigns = (await ads.listCampaigns(acct.email)).map(c => ({ id: c.id, type: c.type, status: c.status, name: c.name || c.title || '', budget: c.budget, spent: c.spent, created: c.created, views: (Number(c.imps) || 0) + (Number(c.impsNas) || 0), pack: c.type === 'visits' ? (Number(c.body) || 0) : 0, clicks: c.clicks })); } catch (e) { out.campaigns = []; }
// line (3 levels) with wallet / bought / qualified per person
const levels = await accounts.downline(acct.email, 3).catch(() => []);
const boughtIds = new Set(chain.recentEvents(1e9).filter(ev => ev.type === 'Purchase').map(ev => ev.buyerId));
out.line = levels.map(L => ({ level: L.level, members: L.members.map(m => ({ email: m.email, name: nameOf(m), username: m.username, memberId: m.memberId || 0, wallet: !!m.address, joined: m.created, lastSeen: m.lastSeen || 0,
bought: !!(m.memberId && boughtIds.has(m.memberId)), qualified: !!(m.memberId && qualified.has(m.memberId)) })) }));
out.lineCounts = out.line.map(L => L.members.length);
// tank / adoptions
try {
const tv = await tank.adminView();
out.tank = { waiting: !!tv.waiting.find(w => w.email === acct.email),
adoptedBy: tv.adoptions.filter(a => a.adoptee === acct.email).map(a => ({ name: a.adopterName, email: a.adopter, created: a.created, status: a.status || a.state || '' })),
adopted: tv.adoptions.filter(a => a.adopter === acct.email).map(a => ({ name: a.adopteeName, email: a.adoptee, created: a.created, status: a.status || a.state || '' })) };
} catch (e) { out.tank = null; }
// legacy + promo + drip + earning + messages
try { const rec = legacy.lookup(acct.email); let g = null; try { g = JSON.parse(fs.readFileSync(path.join(R.dataDir, 'legacy-grants.json'), 'utf8'))[acct.email] || null; } catch (e) {} out.legacy = rec ? { brand: rec.b, seg: rec.s === 'a' ? 'advertiser' : 'earner', grant: g } : null; } catch (e) { out.legacy = null; }
try {
if (db.enabled()) out.promos = await db.q('SELECT code, credits, via, ts FROM promo_redemptions WHERE email=? ORDER BY ts DESC', [acct.email]);
else out.promos = (await promos.adminView()).recent.filter(r => r.email === acct.email);
} catch (e) { out.promos = []; }
try { out.drip = db.enabled() ? (await db.q('SELECT step, next_at, started, stopped, ref, angle FROM drips WHERE email=?', [acct.email]))[0] || null : null; } catch (e) { out.drip = null; }
try { const vs = await ads.viewStatus(acct.email); out.earning = { today: vs.views || vs.viewsToday || 0, claimed: !!vs.claimed, streakDay: vs.streakDay || 0 }; } catch (e) { out.earning = null; }
try {
if (db.enabled()) {
const since = new Date(Date.now() - 14 * 86400000).toISOString().slice(0, 10);
const dv = await db.q('SELECT day, views, claimed, video_count FROM daily_views WHERE email=? AND day>=? ORDER BY day DESC', [acct.email, since]);
out.days = dv; out.activeDays14 = dv.filter(d => d.views > 0 || d.video_count > 0).length; out.claims14 = dv.filter(d => d.claimed).length;
const mc = await db.q('SELECT COUNT(*) n FROM sponsor_messages WHERE from_email=? OR to_email=?', [acct.email, acct.email]); out.messageCount = Number(mc[0].n) || 0;
const vv = await db.q('SELECT COUNT(*) n FROM visit_seen WHERE email=?', [acct.email]).catch(() => [{ n: 0 }]); out.visits = Number(vv[0].n) || 0;
const vw = await db.q('SELECT COUNT(*) n FROM video_seen WHERE email=?', [acct.email]).catch(() => [{ n: 0 }]); out.videos = Number(vw[0].n) || 0;
}
} catch (e) {}
return out;
}
module.exports = { init, resolve, view, nameOf };
+118
View File
@@ -0,0 +1,118 @@
// Syndicate member campaigns to AdRevLinks as popup ads.
//
// The AdRevLinks database is NOT reachable from this server (port 3306 on that box is
// closed to us), so we talk to a narrow authenticated endpoint that runs there and does
// the insert locally. It exposes exactly five actions and no general query surface, so a
// leaked key can only create or remove popup campaigns.
//
// FEATURE-FLAGGED: inert unless ADREVLNKS_BRIDGE_URL and ADREVLNKS_BRIDGE_KEY are set.
//
// Two things learned from the Network Ad Space integration, deliberately repeated here:
//
// 1. DELIVERY IS READ, NEVER DERIVED. `status` returns the rotator's own per-country view
// counters. We never compute "served" from a number that a stop or cancel could
// overwrite, which is exactly what charged members for undelivered impressions there.
//
// 2. EVERY WRITE IS IDEMPOTENT. Each campaign carries ref "iap:<id>". A retry after a
// timeout returns the existing campaign instead of booking a second one.
//
// Capacity note (2026-09-18): that server serves roughly 5,500 popup impressions a day in
// TOTAL, shared by every active campaign, and its rotator favours campaigns with the least
// delivered. So syndicating everything would starve what is already running, including
// Marty's own ads. Hence MAX_VIEWS_PER_CAMPAIGN and MIN_CREDITS below. Cost is not the
// reason for the caps - Marty owns the platform and treats the placements as free - the
// reason is that inventory there is finite and shared.
'use strict';
const https = require('https');
const { URL } = require('url');
// Tier 1 only. These are the sole countries with a configured popup price on that server;
// anything else is refused by the bridge rather than silently accepted.
const TIER1 = ['US', 'CA', 'GB', 'AU', 'NZ'];
const WORLDWIDE = ['all'];
const MIN_CREDITS = Number(process.env.ADREVLNKS_MIN_CREDITS || 1000); // below this, not worth a slot
const MAX_VIEWS_PER_CAMPAIGN = Number(process.env.ADREVLNKS_MAX_VIEWS || 50000);
const TRAFFIC_SOURCE = Number(process.env.ADREVLNKS_TRAFFIC_SOURCE || 1);
const USER_ID = Number(process.env.ADREVLNKS_USER_ID || 2);
function enabled() {
return !!(process.env.ADREVLNKS_BRIDGE_URL && process.env.ADREVLNKS_BRIDGE_KEY);
}
function call(action, payload, timeoutMs) {
return new Promise((resolve, reject) => {
if (!enabled()) return reject(new Error('adrevlnks-disabled'));
const u = new URL(process.env.ADREVLNKS_BRIDGE_URL);
const body = JSON.stringify(Object.assign({ action }, payload || {}));
const req = https.request({
hostname: u.hostname, path: u.pathname + u.search, method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body),
'X-Bridge-Key': process.env.ADREVLNKS_BRIDGE_KEY },
timeout: timeoutMs || 25000
}, res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => {
let j = null;
try { j = JSON.parse(d); } catch (e) {}
if (!j) return reject(new Error('adrevlnks ' + res.statusCode + ': ' + d.slice(0, 120)));
if (j.error) return reject(new Error(j.error));
resolve(j);
});
});
req.on('error', reject);
req.on('timeout', () => req.destroy(new Error('adrevlnks timeout')));
req.end(body);
});
}
const refFor = campaignId => 'iap:' + Number(campaignId);
// How many popup views a campaign's credits are worth. 1 credit = 1 view, capped so a
// single large campaign cannot swallow the whole server's daily inventory.
function viewsFor(credits) {
const v = Math.max(0, Math.floor(Number(credits) || 0));
return Math.min(v, MAX_VIEWS_PER_CAMPAIGN);
}
// Push a campaign. Returns null when it is not worth syndicating, rather than throwing,
// so the caller can treat "too small" and "disabled" the same quiet way.
async function push(campaign, opts) {
if (!enabled()) return null;
const credits = Number((campaign.budget || 0) - (campaign.spent || 0) - (campaign.accrued || 0));
if (credits < MIN_CREDITS) return null;
const views = viewsFor(credits);
if (views < 1000) return null;
const title = String(campaign.name || campaign.title || 'InstantAdPay').slice(0, 250);
const url = String(campaign.targetUrl || campaign.target_url || '').trim();
if (!/^https?:\/\//i.test(url)) return null;
const countries = (opts && opts.worldwide) ? WORLDWIDE : TIER1;
return await call('create_popup', {
title, url, views, countries,
traffic_source: TRAFFIC_SOURCE,
user_id: USER_ID,
ref: refFor(campaign.id),
activate: !(opts && opts.paused)
});
}
// Real delivery, straight from the rotator's counters. Never derived.
async function readServed(campaignId) {
if (!enabled()) return null;
try { return await call('status', { ref: refFor(campaignId) }); }
catch (e) { if (/not found/i.test(e.message)) return null; throw e; }
}
async function pause(campaignId) { return enabled() ? call('pause', { ref: refFor(campaignId) }) : null; }
async function resume(campaignId) { return enabled() ? call('resume', { ref: refFor(campaignId) }) : null; }
async function remove(campaignId) {
if (!enabled()) return null;
try { return await call('delete', { ref: refFor(campaignId) }); }
catch (e) { if (/not found/i.test(e.message)) return null; throw e; }
}
module.exports = { enabled, push, readServed, pause, resume, remove, viewsFor, refFor,
TIER1, WORLDWIDE, MIN_CREDITS, MAX_VIEWS_PER_CAMPAIGN };
BIN
View File
Binary file not shown.
+89
View File
@@ -0,0 +1,89 @@
// Counter audit (Marty, 2026-09-15: "buyers will lose confidence if they feel cheated"). Every ad format's
// recorded impressions are reconciled against the log that proves delivery, and login/featured charging is
// checked against actual shows. Runs on demand from Admin > Reports and once a day; any issue alerts the admin.
// DB mode only (production); JSON mode reports "not checked".
const db = require('./db');
const fs = require('fs'); const path = require('path');
let R = null; // { notify(text), dataDir }
function init(refs) { R = refs; }
// credits already returned for past counting errors: subtract them so history that was made right does not keep flagging
function refunded() { const out = {}; try { for (const f of fs.readdirSync(R.dataDir)) if (/^refunds-.*\.json$/.test(f)) for (const i of (JSON.parse(fs.readFileSync(path.join(R.dataDir, f), 'utf8')).items || [])) out[i.id] = (out[i.id] || 0) + Number(i.credits || 0); } catch (e) {} return out; }
async function run() {
const out = { checkedAt: Date.now(), checks: [] };
if (!db.enabled()) { out.checks.push({ name: 'Counters', ok: true, detail: 'JSON mode: not checked', issues: [] }); return out; }
const camps = await db.q("SELECT id, name, type, status, imps, clicks, spent, accrued, budget, created, starts, house, expires FROM campaigns WHERE house=0 OR house IS NULL");
const back = refunded(); for (const c of camps) if (back[c.id]) c.spent = Math.max(0, Number(c.spent) - back[c.id]); // already made right
const logStart = (await db.q('SELECT MIN(day) d FROM camp_hours'))[0].d; const logStartMs = logStart ? Date.parse(logStart + 'T00:00:00Z') : 0;
const byType = t => camps.filter(c => c.type === t);
const add = (name, issues, detail) => out.checks.push({ name, ok: !issues.length, detail, issues });
// 1. per-view formats: campaign.imps must equal the rows in the log that paid for them
for (const [type, table, label] of [['video', 'video_seen', 'completed watches'], ['visits', 'visit_seen', 'verified visits'], ['solo', 'solo_inbox', 'inbox deliveries']]) {
const rows = await db.q('SELECT campaign_id, COUNT(*) n FROM ' + table + ' GROUP BY campaign_id'); const logN = {}; for (const r of rows) logN[r.campaign_id] = Number(r.n);
// visits are proven by three logs (2026-10-04: 37 false alarms): our viewer (visit_seen), repeat door knocks on Spooky Doors
// (visit_repeat), and visits delivered on PassiveDrip's PTC page (pdsync.json, read from PassiveDrip, never derived).
// A counter BELOW its proof is the advertiser getting a visit free; only a counter ABOVE its proof can overcharge them.
let extra = {};
if (type === 'visits') {
for (const r of await db.q('SELECT campaign_id, COUNT(*) n FROM visit_repeat GROUP BY campaign_id')) extra[r.campaign_id] = (extra[r.campaign_id] || 0) + Number(r.n);
try { const pd = JSON.parse(fs.readFileSync(path.join(R.dataDir, 'pdsync.json'), 'utf8')).served || {}; for (const [id, n] of Object.entries(pd)) extra[id] = (extra[id] || 0) + Number(n || 0); } catch (e) {}
}
const issues = []; let tot = 0, logTot = 0, under = 0;
for (const c of byType(type)) {
const l = (logN[c.id] || 0) + (extra[c.id] || 0); tot += Number(c.imps); logTot += l;
if (type === 'visits') { if (Number(c.imps) > l) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' counted vs ' + l + ' proven (' + (Number(c.imps) - l) + ' not proven)'); else if (Number(c.imps) < l) under++; }
else if (Number(c.imps) !== l) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' views vs ' + l + ' ' + label);
}
add(type + ' views vs ' + label, issues, tot + ' views recorded, ' + logTot + ' ' + label + (type === 'visits' ? ' (our viewer + repeat door visits + PassiveDrip)' + (under ? '; ' + under + ' campaign(s) got a visit or two free' : '') : ''));
}
// 2. banner/text: imps must equal the hourly log (both bumped on serve)
{
const rows = await db.q('SELECT campaign_id, SUM(n) n FROM camp_hours GROUP BY campaign_id'); const h = {}; for (const r of rows) h[r.campaign_id] = Number(r.n);
const issues = [];
// only campaigns that started after the hourly log did
for (const c of camps.filter(c => ['banner', 'text'].includes(c.type) && Number(c.created) >= logStartMs)) { const l = h[c.id] || 0; if (Math.abs(Number(c.imps) - l) > Math.max(5, Math.round(0.02 * Math.max(Number(c.imps), l)))) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' views vs ' + l + ' in the hourly log'); }
add('banner/text views vs hourly log', issues, camps.filter(c => ['banner', 'text'].includes(c.type) && Number(c.created) >= logStartMs).length + ' campaigns compared (started since the hourly log began ' + (logStart || '') + ')');
}
// 3. login: days charged vs days shown (a day may only be charged after the ad was shown)
{
const rows = await db.q('SELECT campaign_id, COUNT(DISTINCT day) d FROM camp_hours WHERE n>0 GROUP BY campaign_id'); const shown = {}; for (const r of rows) shown[r.campaign_id] = Number(r.d);
const issues = [];
for (const c of byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status))) { /* a reservation in the login-ad line is paid up front and has no end date yet (2026-10-23) */ const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
add('login ads: days charged vs days shown', issues, byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status)).length + ' per-day campaigns compared (30-day slots are paid up front)');
}
// 4. featured: a live booking older than two hours must have views
{
const issues = []; const now = Date.now();
// counted from when the booking STARTS: a paid booking scheduled for later has no views yet by design
// (#275 was flagged on 2026-09-27 hours before its 7 PM start)
for (const c of byType('featured').filter(c => c.status === 'active' && now - Math.max(Number(c.created), Number(c.starts) || 0) > 2 * 3600e3)) if (!Number(c.imps)) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': live with 0 views');
add('featured: live bookings have views', issues, byType('featured').filter(c => c.status === 'active').length + ' live bookings');
}
// 5. clicks can only exceed views where a click precedes the counted view (visits, login)
{
const issues = [];
// only where the buyer was charged: this check protects buyers, and a campaign that never spent a credit
// cannot have overcharged anyone (#146: a placeholder video that never played, paused by the source
// sweep, clicks on its button while the player failed, 0 credits spent)
for (const c of camps.filter(c => !['visits', 'login'].includes(c.type) && Number(c.spent) + Number(c.accrued || 0) > 0 && Number(c.clicks) > Number(c.imps) + 5)) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ' (' + c.type + '): ' + c.clicks + ' clicks vs ' + c.imps + ' views');
add('clicks vs views', issues, 'campaigns with more clicks than views, where that cannot happen');
}
// 6. budgets: spent can never pass budget
{
const issues = camps.filter(c => Number(c.spent) + Number(c.accrued || 0) > Number(c.budget) + 1).map(c => '#' + c.id + ' ' + c.name.slice(0, 30) + ': spent ' + (Number(c.spent) + Number(c.accrued || 0)) + ' of ' + c.budget);
add('spend never exceeds budget', issues, camps.length + ' campaigns');
}
return out;
}
// the "once a day" memory lives on the volume: a redeploy restarts the process, and Marty got an alert after every deploy (2026-09-15)
const STATE = () => path.join(R.dataDir, 'audit-state.json');
function lastAlertDay() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')).lastAlertDay || ''; } catch (e) { return ''; } }
function setAlertDay(d) { try { fs.writeFileSync(STATE(), JSON.stringify({ lastAlertDay: d })); } catch (e) {} }
async function dailyTick() {
try {
const r = await run(); const bad = r.checks.filter(c => !c.ok); const day = new Date().toISOString().slice(0, 10);
if (bad.length && lastAlertDay() !== day && R && R.notify) { setAlertDay(day); R.notify('⚠️ InstantAdPay counter audit found ' + bad.length + ' issue' + (bad.length === 1 ? '' : 's') + ': ' + bad.map(c => c.name + ' (' + c.issues.length + ')').join('; ') + '. Admin > Reports > Counters audit.'); }
return r;
} catch (e) { console.error('audit', e.message); return null; }
}
module.exports = { init, run, dailyTick };
+23 -4
View File
@@ -14,7 +14,13 @@ let IS_PROD = false;
let SITE = 'instantadpay.com';
const CHALLENGE_TTL = 10 * 60 * 1000;
const SESSION_TTL = 24 * 60 * 60 * 1000; // 24h — forces a daily re-login so the login ad shows each day
// 4 hours (Marty, 2026-09-18). Two reasons, and we say both of them out loud rather than
// letting it feel like a glitch: it keeps resources tidy, and it is what makes the login-ad
// slot worth buying — an advertiser paying for a 30-day run needs members to actually pass
// the gate more than once a day. Members are told the length up front, on the sign-in screen,
// in the training and by the chatbot, so nobody is surprised by it.
const SESSION_TTL = Number(process.env.SESSION_TTL_HOURS || 4) * 60 * 60 * 1000;
const SESSION_HOURS = SESSION_TTL / 3600000;
const challenges = new Map(); // addressLower -> {message, exp}
// ---- JSON session fallback ----
@@ -140,13 +146,26 @@ 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 || !sess.address) return (sess && sess.memberId) || 0;
if (!sess) return 0;
if (!sess.address) {
if (sess.memberId) return sess.memberId;
// email-only session (phone sign-in with no wallet connected): read the account's
// on-chain id instead, so read-only views (My line, earnings, P&L) work from any
// device. Not cached into the session: a session without an address stays wallet-less.
if (sess.email) { try { const a = await require('./accounts').byEmail(sess.email); if (a && a.memberId) return a.memberId; } catch (e) {} }
return 0;
}
try {
const id = await chain.memberIdByAccount(sess.address);
if (id && id !== sess.memberId) await updateSession(sess.token, { memberId: id });
@@ -158,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 };
+42
View File
@@ -0,0 +1,42 @@
// Achievement badge image, rendered on the server with ffmpeg (Marty, 2026-09-16).
// The browser used to compose it on a canvas and upload the JPEG; a phone that ran short of canvas
// memory (cryptomonk's Spark post) sent a mostly blank card to the group. Now the server draws the
// member's name onto the badge art itself, the same way the Video Maker draws end cards, so every
// badge looks the same no matter what device unlocked it. The browser upload stays as a fallback.
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
let PUBLIC_DIR = null;
const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 }, stackpro: { file: 'badge-stackpro.jpg', ribbonY: 0.855 }, 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;
FONT = process.env.BADGE_FONT || null;
if (FONT) return FONT;
const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/DejaVuSans-Bold\.ttf$/i.test(f)) return f; } return null; };
for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } }
if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf';
return FONT;
}
const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%');
function init(opts) { PUBLIC_DIR = opts.publicDir; }
// returns a JPEG buffer, or null when ffmpeg or the font is missing (caller falls back to the upload)
function render(key, who) {
return new Promise(resolve => {
const a = ART[key]; const F = font(); if (!a || !F) return resolve(null);
const src = path.resolve(PUBLIC_DIR, 'badges', a.file); if (!fs.existsSync(src)) return resolve(null);
const name = String(who || '').slice(0, 28);
// a Windows font path carries a drive colon that the filter parser trips on: run from the font's folder instead
const winPath = /:/.test(F);
const fontFile = winPath ? path.basename(F) : F;
// 1080-wide art: 59px bold gold text with a dark outline, centred on the ribbon (matches the old canvas layout)
const vf = name ? 'drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=#ffd15c:fontsize=59:borderw=7:bordercolor=0x04140f@0.9:x=(w-text_w)/2:y=" + a.ribbonY + '*h-text_h/2' : 'null';
const p = spawn('ffmpeg', ['-v', 'error', '-i', src, '-vf', vf, '-frames:v', '1', '-q:v', '3', '-f', 'image2pipe', '-vcodec', 'mjpeg', 'pipe:1'], { stdio: ['ignore', 'pipe', 'pipe'], cwd: winPath ? path.dirname(F) : undefined });
const chunks = []; let err = '';
p.stdout.on('data', c => chunks.push(c)); p.stderr.on('data', c => { err += c; });
p.on('error', () => resolve(null));
p.on('close', code => { const buf = Buffer.concat(chunks); if (code === 0 && buf.length > 2000 && buf[0] === 0xff && buf[1] === 0xd8) resolve(buf); else { console.error('badge render failed', code, err.slice(0, 200)); resolve(null); } });
});
}
module.exports = { init, render, font, ART };
+120
View File
@@ -0,0 +1,120 @@
// BixPay card integration, phase 1 (Marty approved 2026-10-29; spec docs/BIXPAY-INTEGRATION.md).
// BIX is a separate company: a self-custody wallet with a Visa card spent from USDT/USDC. We only carry each member's
// PARTNER link (bix.ibportal.io/auth/register?e=<token>&a=1) so anyone who gets a card through their pages is credited to
// them in the BIX portal. Nothing is settled on our side: the portal tracks directs and levels itself.
//
// One identity, sponsor follows (feedback-one-identity-sponsor-follows): the link a visitor gets is the member's own,
// else the first sponsor up the chain (10 levels) with one, else the company link (site config bixCompanyLink). Every
// surface says WHOSE link is in play ("you" / "@sponsor" / "network") so members add their own and sponsors get their
// teams signed up.
//
// Everything is gated by site config bixpayLive ('0' = nothing shows; the admin flips it in Admin > Settings).
// Clicks: every surface links through /go/bixpay?s=<surface>[&m=<member>] which counts here (DATA_DIR/bixpay-clicks.json)
// and 302s to the resolved partner link. Counts per surface land in the admin Traffic tab, per member on the Promo tab.
const fs = require('fs');
const path = require('path');
let R = {}; // { dataDir, accounts, siteConfig, refAccount }
const HOST = 'bix.ibportal.io';
const PATH = '/auth/register';
const MAX_LEN = 300;
const MAX_LEVELS = 10;
// Marty's own PARTNER link (IB12143793): the company fallback until Admin > Settings bixCompanyLink says otherwise
const DEFAULT_COMPANY_LINK = 'https://bix.ibportal.io/auth/register?e=XqwU9T1aJ5N0UJ0yr9x0TGUiSQTsVCkTM01MIovVNnc&a=1';
const SURFACES = ['wallet', 'overview', 'email', 'nudge', 'promo', 'guide', 'chat'];
const CUSTOMER_LINK_MSG = "That's the card-customer link. Paste the Partner link from your BIX portal profile instead.";
const ANNOUNCE_MS = 7 * 86400000; // the Overview announcement card shows for the first week after the switch is flipped
function init(opts) { R = opts || {}; }
const cfg = () => { try { return (R.siteConfig && R.siteConfig()) || {}; } catch (e) { return {}; } };
function live() { return String(cfg().bixpayLive == null ? '0' : cfg().bixpayLive) === '1'; }
function companyLink() { const v = validate(cfg().bixCompanyLink); return v.ok ? v.link : DEFAULT_COMPANY_LINK; }
// the Overview announcement runs a week from bixpayLiveSince (stamped by the admin settings route when the switch is flipped on)
function announcing() { if (!live()) return false; const t = Date.parse(String(cfg().bixpayLiveSince || '')); return !(t > 0) || Date.now() - t < ANNOUNCE_MS; }
// A pasted partner link -> { ok: true, link } (normalised to e= and a=1 only) or { error }.
// The card-customer link carries appId=3 (it makes a card customer, not a partner): refused with the message members see.
function validate(input) {
const s = String(input == null ? '' : input).trim();
if (!s) return { error: 'Paste your BixPay partner link first.' };
if (s.length > MAX_LEN) return { error: 'That link is too long. Copy the Partner link from your BIX portal profile.' };
let u; try { u = new URL(s); } catch (e) { return { error: 'That is not a full link. It starts with https://bix.ibportal.io/auth/register?e=' }; }
if (u.protocol !== 'https:' || u.hostname.toLowerCase() !== HOST) return { error: 'A BixPay partner link lives on https://bix.ibportal.io. Copy it from your BIX portal profile (Profile > Partner).' };
if (u.pathname.replace(/\/+$/, '') !== PATH) return { error: 'That is not the register link. It looks like https://bix.ibportal.io/auth/register?e=...&a=1' };
if (u.searchParams.has('appId') || u.searchParams.has('appid')) return { error: CUSTOMER_LINK_MSG };
const e = String(u.searchParams.get('e') || '').trim();
if (!/^[A-Za-z0-9_-]{16,128}$/.test(e)) return { error: 'The link is missing its e= token. Copy the whole Partner link from your BIX portal profile.' };
if (String(u.searchParams.get('a') || '').trim() !== '1') return { error: 'The link needs a=1 on the end. Copy the whole Partner link from your BIX portal profile.' };
return { ok: true, link: 'https://' + HOST + PATH + '?e=' + e + '&a=1' };
}
const nameOf = a => a ? (a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'your sponsor') : null;
// bixLinkFor(member): own link, else the first sponsor up the chain with one (10 levels), else the company link.
// -> { link, whose: 'you' | 'sponsor' | 'network', name, email } (name/email = the sponsor whose link it is)
async function resolve(acct) {
if (acct && validate(acct.bixPartnerLink).ok) return { link: validate(acct.bixPartnerLink).link, whose: 'you', name: nameOf(acct), email: acct.email };
if (acct && R.accounts && R.accounts.sponsorOf) {
const seen = new Set([String(acct.email || '').toLowerCase()]);
let cur = acct;
for (let i = 0; i < MAX_LEVELS && cur; i++) {
let s = null; try { s = await R.accounts.sponsorOf(cur.email); } catch (e) { s = null; }
if (!s || seen.has(String(s.email).toLowerCase())) break;
seen.add(String(s.email).toLowerCase());
const v = validate(s.bixPartnerLink);
if (v.ok) return { link: v.link, whose: 'sponsor', name: nameOf(s), email: s.email };
cur = s;
}
}
return { link: companyLink(), whose: 'network', name: null, email: null };
}
// the same for a public page: the referrer token (?ref / the sponsor cookie) resolves like the member it names
async function resolveRef(tok) {
let a = null; try { a = tok && R.refAccount ? await R.refAccount(tok) : null; } catch (e) { a = null; }
return resolve(a);
}
// the line every surface shows under the button
function usingLine(r) { return r.whose === 'you' ? 'Using: your link.' : r.whose === 'sponsor' ? 'Using: ' + r.name + "'s link. Add yours in Profile." : 'Using: the network link. Add yours in Profile.'; }
// tracked link for a surface (+ the member it belongs to: the sharer on promo/guide/email, the viewer on the dashboard cards)
const SITE = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
function goLink(surface, token) { return SITE() + '/go/bixpay?s=' + encodeURIComponent(surface) + (token ? '&m=' + encodeURIComponent(String(token)) : ''); }
// one sentence for payout emails and the games' wallet nudges (text), only while live
function emailLine(token) { return live() ? 'Want to spend it? A BixPay Visa card turns POL into everyday purchases: ' + goLink('email', token) : ''; }
function nudgeLine(token) { return live() ? 'Want to spend it? A BixPay Visa card turns POL into everyday purchases: ' + goLink('nudge', token) : ''; }
// ---- clicks ----
const FILE = () => path.join(R.dataDir || '.', 'bixpay-clicks.json');
const blank = () => ({ v: 1, total: {}, days: {}, members: {} });
let S = null;
function load() { if (S) return S; try { S = Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { S = blank(); } return S; }
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(S)); } catch (e) {} }
const day = ts => new Date(ts).toISOString().slice(0, 10);
function click(surface, email) {
const s = SURFACES.includes(surface) ? surface : 'other';
const st = load();
st.total[s] = (st.total[s] || 0) + 1;
const d = day(Date.now()); st.days[d] = st.days[d] || {}; st.days[d][s] = (st.days[d][s] || 0) + 1;
const e = String(email || '').trim().toLowerCase();
if (e) { const m = st.members[e] = st.members[e] || { total: 0 }; m.total++; m[s] = (m[s] || 0) + 1; m.last = Date.now(); }
// bounded: 400 days
const cutoff = day(Date.now() - 400 * 86400000); for (const k of Object.keys(st.days)) if (k < cutoff) delete st.days[k];
save();
return { surface: s, email: e || null };
}
function memberClicks(email) {
const m = load().members[String(email || '').trim().toLowerCase()];
if (!m) return { total: 0 };
return Object.assign({}, m);
}
function adminView(days) {
const st = load(); const n = Math.min(365, Math.max(1, Number(days) || 30));
const since = day(Date.now() - n * 86400000);
const bySurface = {}; let total = 0;
for (const [d, row] of Object.entries(st.days)) if (d >= since) for (const [s, c] of Object.entries(row)) { bySurface[s] = (bySurface[s] || 0) + c; total += c; }
const daily = Object.entries(st.days).filter(([d]) => d >= since).sort((a, b) => a[0] < b[0] ? 1 : -1).map(([d, row]) => ({ day: d, clicks: Object.values(row).reduce((x, y) => x + y, 0) }));
const members = Object.entries(st.members).map(([email, m]) => ({ email, total: m.total || 0, last: m.last || 0, promo: m.promo || 0 })).sort((a, b) => b.total - a.total).slice(0, 50);
return { days: n, total, allTime: Object.values(st.total).reduce((x, y) => x + y, 0), bySurface, daily, members, surfaces: SURFACES };
}
function _reset() { S = null; }
module.exports = { init, live, announcing, validate, resolve, resolveRef, usingLine, companyLink, goLink, emailLine, nudgeLine, click, memberClicks, adminView, SURFACES, CUSTOMER_LINK_MSG, DEFAULT_COMPANY_LINK, MAX_LEVELS, _reset };
+164
View File
@@ -0,0 +1,164 @@
// Public blog (Marty, 2026-09-12): coaching and teaching articles on instantadpay.com, written in
// Admin > Blog, server-rendered so crawlers see real HTML with real metadata. Storage: MySQL
// blog_posts, or DATA_DIR/blog.json. Public: /blog (paged index), /blog/<slug>, /blog/feed.xml,
// /sitemap.xml, /robots.txt. SEO per post: title, description, canonical, Open Graph, Twitter
// card, article dates, BlogPosting JSON-LD, breadcrumb JSON-LD, internal links, related posts.
const fs = require('fs');
const path = require('path');
const db = require('./db');
const themehead = require('./themehead'); // light/dark theme head script (2026-11-01)
let DATA_DIR = null;
const SITE = 'https://instantadpay.com';
const AUTHOR = 'Marty Bostick';
const PER_PAGE = 10;
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const slugify = s => String(s || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
const words = html => String(html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
const readMinutes = html => Math.max(1, Math.round(words(html).split(' ').length / 220));
const fmtDate = ts => new Date(ts).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'America/Chicago' });
// article HTML from the admin editor: keep a small whitelist of tags, http(s) links and safe images
function sanitize(html) {
const src = String(html || '').replace(/ /g, ' ').replace(/<(script|style|iframe|object|embed|form)\b[\s\S]*?<\/\1\s*>/gi, '').replace(/<(script|style|iframe|object|embed|form|input)\b[^>]*>/gi, '').replace(/<!--[\s\S]*?-->/g, '').replace(/\son[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
const ALLOW = new Set(['p', 'br', 'hr', 'h2', 'h3', 'h4', 'ul', 'ol', 'li', 'b', 'strong', 'i', 'em', 'u', 'a', 'img', 'blockquote', 'pre', 'code', 'figure', 'figcaption', 'table', 'thead', 'tbody', 'tr', 'th', 'td']);
const safeSrc = s => /^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|\/banners\/[a-z0-9._-]+\.(png|jpg|webp|gif)|https:\/\/[^\s"'<>]+)$/i.test(s);
return src.replace(/<\s*(\/?)\s*([a-zA-Z0-9]+)((?:[^>"']|"[^"]*"|'[^']*')*)>/g, (m, close, tag, attrs) => {
tag = tag.toLowerCase();
if (!ALLOW.has(tag)) return '';
if (close) return '</' + tag + '>';
if (tag === 'a') {
const hm = /href\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attrs || ''); const href = (hm && (hm[1] || hm[2])) || '';
if (!/^(https?:\/\/|\/)[^\s"'<>]*$/i.test(href)) return '';
const internal = href.startsWith('/') || href.startsWith(SITE);
return '<a href="' + href.replace(/"/g, '%22') + '"' + (internal ? '' : ' target="_blank" rel="noopener"') + '>';
}
if (tag === 'img') {
const sm = /src\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attrs || ''); const s = (sm && (sm[1] || sm[2])) || '';
const am = /alt\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attrs || ''); const alt = (am && (am[1] || am[2])) || '';
return safeSrc(s) ? '<img src="' + s.replace(/"/g, '%22') + '" alt="' + esc(alt) + '" loading="lazy">' : '';
}
if (tag === 'br' || tag === 'hr') return '<' + tag + '>';
return '<' + tag + '>';
});
}
// ---- storage ----
const J = {
db: { v: 1, posts: {} },
FILE() { return path.join(DATA_DIR, 'blog.json'); },
load() { try { this.db = Object.assign(this.db, JSON.parse(fs.readFileSync(this.FILE(), 'utf8'))); } catch (e) {} },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
async all() { return Object.values(this.db.posts); },
async get(slug) { return this.db.posts[slug] || null; },
async put(p) { this.db.posts[p.slug] = p; this.save(); return p; },
async remove(slug) { delete this.db.posts[slug]; this.save(); },
async bumpViews(slug) { const p = this.db.posts[slug]; if (p) { p.views = (p.views || 0) + 1; this.save(); } }
};
const D = {
async all() { return (await db.q('SELECT * FROM blog_posts ORDER BY COALESCE(published_at, created) DESC')).map(row); },
async get(slug) { const r = await db.q('SELECT * FROM blog_posts WHERE slug=?', [slug]); return r[0] ? row(r[0]) : null; },
async put(p) {
await db.q(`INSERT INTO blog_posts (slug,title,excerpt,body,cover,tags,status,author,created,updated,published_at,views) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
ON DUPLICATE KEY UPDATE title=VALUES(title), excerpt=VALUES(excerpt), body=VALUES(body), cover=VALUES(cover), tags=VALUES(tags), status=VALUES(status), author=VALUES(author), updated=VALUES(updated), published_at=VALUES(published_at)`,
[p.slug, p.title, p.excerpt, p.body, p.cover || null, (p.tags || []).join(','), p.status, p.author, p.created, p.updated, p.publishedAt || null, p.views || 0]);
return this.get(p.slug);
},
async remove(slug) { await db.q('DELETE FROM blog_posts WHERE slug=?', [slug]); },
async bumpViews(slug) { await db.q('UPDATE blog_posts SET views=views+1 WHERE slug=?', [slug]); }
};
const row = r => ({ slug: r.slug, title: r.title, excerpt: r.excerpt || '', body: r.body || '', cover: r.cover || '', tags: r.tags ? String(r.tags).split(',').filter(Boolean) : [], status: r.status, author: r.author || AUTHOR, created: Number(r.created), updated: Number(r.updated), publishedAt: r.published_at ? Number(r.published_at) : null, views: Number(r.views) || 0 });
const impl = () => db.enabled() ? D : J;
let EXTRA_PAGES = () => []; // sitemap entries that follow a switch (the /bixpay guide while bixpayLive, 2026-10-29)
function init(opts) { DATA_DIR = opts.dataDir; if (typeof opts.extraPages === 'function') EXTRA_PAGES = opts.extraPages; if (!db.enabled()) J.load(); }
async function listAll() { return (await impl().all()).sort((a, b) => (b.publishedAt || b.created) - (a.publishedAt || a.created)); }
async function listPublished() { return (await listAll()).filter(p => p.status === 'published' && (p.publishedAt || 0) <= Date.now()); }
async function get(slug) { return impl().get(slugify(slug)); }
async function save(input, existingSlug) {
const title = String(input.title || '').trim().slice(0, 140);
if (!title) return { error: 'Give the post a title.' };
let slug = slugify(input.slug || title); if (!slug) return { error: 'Slug needs letters or numbers.' };
const prev = existingSlug ? await impl().get(existingSlug) : null;
if (!prev && await impl().get(slug)) return { error: 'That slug is already used. Pick another.' };
if (prev && prev.slug !== slug) { if (await impl().get(slug)) return { error: 'That slug is already used.' }; await impl().remove(prev.slug); }
const now = Date.now();
const status = input.status === 'published' ? 'published' : 'draft';
const body = sanitize(input.body);
const excerpt = String(input.excerpt || '').trim().slice(0, 300) || words(body).slice(0, 200);
const post = { slug, title, excerpt, body, cover: /^(\/uploads\/|\/banners\/|https:\/\/)/.test(String(input.cover || '')) ? String(input.cover).slice(0, 300) : '', tags: String(input.tags || '').split(',').map(t => t.trim().toLowerCase()).filter(Boolean).slice(0, 8),
status, author: AUTHOR, created: prev ? prev.created : now, updated: now,
publishedAt: status === 'published' ? (prev && prev.publishedAt ? prev.publishedAt : (input.publishedAt ? Number(new Date(input.publishedAt)) || now : now)) : (prev ? prev.publishedAt : null), views: prev ? prev.views : 0 };
return { ok: true, post: await impl().put(post) };
}
async function remove(slug) { await impl().remove(slugify(slug)); return { ok: true }; }
async function bumpViews(slug) { try { await impl().bumpViews(slug); } catch (e) {} }
// ---- rendering ----
function head(o) {
const url = SITE + o.path;
const img = o.image ? (o.image.startsWith('http') ? o.image : SITE + o.image) : SITE + '/banners/iap-hero-1200x630.png';
return '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
+ '<title>' + esc(o.title) + '</title><meta name="description" content="' + esc(o.desc) + '"><link rel="canonical" href="' + esc(url) + '">'
+ '<meta name="robots" content="index,follow,max-image-preview:large"><meta name="theme-color" content="#043b2f">'
+ '<meta property="og:type" content="' + (o.article ? 'article' : 'website') + '"><meta property="og:site_name" content="InstantAdPay"><meta property="og:title" content="' + esc(o.title) + '"><meta property="og:description" content="' + esc(o.desc) + '"><meta property="og:url" content="' + esc(url) + '"><meta property="og:image" content="' + esc(img) + '">'
+ (o.article ? '<meta property="article:published_time" content="' + new Date(o.article.publishedAt || o.article.created).toISOString() + '"><meta property="article:modified_time" content="' + new Date(o.article.updated).toISOString() + '"><meta property="article:author" content="' + esc(AUTHOR) + '">' + (o.article.tags || []).map(t => '<meta property="article:tag" content="' + esc(t) + '">').join('') : '')
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + esc(o.title) + '"><meta name="twitter:description" content="' + esc(o.desc) + '"><meta name="twitter:image" content="' + esc(img) + '">'
+ '<link rel="alternate" type="application/rss+xml" title="InstantAdPay blog" href="' + SITE + '/blog/feed.xml"><link rel="icon" type="image/png" href="/logo-icon.png">'
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
+ '<style>.bl{max-width:760px}.bl h1{font-size:clamp(30px,4.6vw,44px);line-height:1.12;margin:10px 0 12px}.bl .meta{color:var(--muted);font-size:14px;margin:0 0 22px}.bl .cover{width:100%;border-radius:14px;border:1px solid var(--line);margin:0 0 26px;display:block}.bl article{font-size:17.5px;line-height:1.7}.bl article p{margin:0 0 18px;max-width:68ch}.bl article h2{font-size:26px;margin:36px 0 12px}.bl article h3{font-size:20px;margin:28px 0 10px}.bl article ul,.bl article ol{margin:0 0 18px 22px;max-width:66ch}.bl article li{margin:6px 0}.bl article blockquote{border-left:4px solid var(--mint);margin:0 0 18px;padding:8px 18px;color:var(--muted);font-style:italic}.bl article img{max-width:100%;border-radius:12px;border:1px solid var(--line)}.bl article a{color:var(--mint)}.bl article pre{background:var(--ground-soft);border:1px solid var(--line);border-radius:10px;padding:14px;overflow:auto;font-size:14px}.bl article table{border-collapse:collapse;width:100%;font-size:15px}.bl article th,.bl article td{border-bottom:1px solid var(--line);padding:8px 10px;text-align:left}.tags a{display:inline-block;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--mint);border:1px solid var(--mint-line);border-radius:999px;padding:3px 10px;margin:0 6px 6px 0;text-decoration:none}.post-card{display:block;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:20px 22px;margin:0 0 14px;color:inherit;text-decoration:none}.post-card:hover{border-color:var(--mint)}.post-card h2{font-size:22px;margin:0 0 6px}.post-card p{margin:0;color:var(--muted);font-size:15px;max-width:70ch}.post-card .meta{margin:8px 0 0;font-size:13px}.author{display:flex;gap:14px;align-items:center;border:1px solid var(--line);border-radius:14px;padding:16px 18px;margin:36px 0 0;background:var(--panel)}.author img{width:56px;height:56px;border-radius:50%;object-fit:cover}.author b{display:block}.author span{color:var(--muted);font-size:14px}.share a{margin-right:14px;font-size:14px}.pager{display:flex;justify-content:space-between;margin:26px 0}.related{margin-top:40px}.related h3{margin-bottom:10px}</style>'
+ '</head><body><div class="wrap bl">';
}
function tail() {
return '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
}
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="InstantAdPay"><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="" loading="lazy" style="width:100%;border-radius:10px;margin:0 0 12px">' : '') + '<h2>' + esc(p.title) + '</h2><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '</p></a>';
function renderIndex(posts, page, tag) {
const all = tag ? posts.filter(p => p.tags.includes(tag)) : posts;
const pages = Math.max(1, Math.ceil(all.length / PER_PAGE)); page = Math.min(Math.max(1, page || 1), pages);
const slice = all.slice((page - 1) * PER_PAGE, page * PER_PAGE);
const title = (tag ? esc(tag) + ' · ' : '') + 'Blog | InstantAdPay';
const desc = 'Coaching and teaching articles from Marty Bostick on building a line, advertising that pays, and doing the simple work every day.';
const p = tag ? '/blog/tag/' + encodeURIComponent(tag) : '/blog' + (page > 1 ? '/page/' + page : '');
let h = head({ title, desc, path: p });
h += '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">' + (tag ? 'Tag: ' + esc(tag) : 'The InstantAdPay blog') + '</p><h1>Notes on building a line, <em>one honest day at a time</em>.</h1><p class="lead">' + esc(desc) + '</p></section>';
h += slice.length ? slice.map(cardHtml).join('') : '<p class="muted">Nothing published yet. Check back soon.</p>';
if (pages > 1) h += '<div class="pager">' + (page > 1 ? '<a href="/blog' + (page - 1 > 1 ? '/page/' + (page - 1) : '') + '">&larr; Newer</a>' : '<span></span>') + (page < pages ? '<a href="/blog/page/' + (page + 1) + '">Older &rarr;</a>' : '<span></span>') + '</div>';
h += '<script type="application/ld+json">' + JSON.stringify({ '@context': 'https://schema.org', '@type': 'Blog', name: 'InstantAdPay blog', url: SITE + '/blog', publisher: { '@type': 'Organization', name: 'InstantAdPay', logo: SITE + '/logo.png' } }) + '</script>';
return h + tail();
}
function renderPost(p, related) {
const url = SITE + '/blog/' + p.slug;
let h = head({ title: p.title + ' | InstantAdPay', desc: p.excerpt, path: '/blog/' + p.slug, image: p.cover, article: p });
h += '<p class="eyebrow" style="margin-top:44px"><a href="/blog" style="color:var(--mint);text-decoration:none">Blog</a>' + (p.tags[0] ? ' · <a href="/blog/tag/' + encodeURIComponent(p.tags[0]) + '" style="color:var(--mint);text-decoration:none">' + esc(p.tags[0]) + '</a>' : '') + '</p>';
h += '<h1>' + esc(p.title) + '</h1><p class="meta">By ' + esc(AUTHOR) + ' · ' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read</p>';
if (p.cover) h += '<img class="cover" src="' + esc(p.cover) + '" alt="' + esc(p.title) + '">';
h += '<article>' + p.body + '</article>';
if (p.tags.length) h += '<p class="tags" style="margin-top:22px">' + p.tags.map(t => '<a href="/blog/tag/' + encodeURIComponent(t) + '">' + esc(t) + '</a>').join('') + '</p>';
h += '<p class="share" style="margin-top:18px"><a href="https://x.com/intent/tweet?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(p.title) + '" target="_blank" rel="noopener">Share on X</a><a href="https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url) + '" target="_blank" rel="noopener">Share on Facebook</a><a href="https://t.me/share/url?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(p.title) + '" target="_blank" rel="noopener">Telegram</a></p>';
h += authorBox();
if (related.length) h += '<div class="related"><h3>Keep reading</h3>' + related.map(cardHtml).join('') + '</div>';
h += '<p class="muted small" style="margin-top:34px">InstantAdPay sells advertising. Nothing here is investment advice, no income is guaranteed, and cryptocurrency involves risk of loss.</p>';
h += '<script type="application/ld+json">' + JSON.stringify({ '@context': 'https://schema.org', '@type': 'BlogPosting', headline: p.title, description: p.excerpt, image: p.cover ? (p.cover.startsWith('http') ? p.cover : SITE + p.cover) : SITE + '/banners/iap-hero-1200x630.png', datePublished: new Date(p.publishedAt || p.created).toISOString(), dateModified: new Date(p.updated).toISOString(), wordCount: words(p.body).split(' ').length, keywords: p.tags.join(', '), author: { '@type': 'Person', name: AUTHOR, url: SITE + '/blog' }, publisher: { '@type': 'Organization', name: 'InstantAdPay', logo: { '@type': 'ImageObject', url: SITE + '/logo.png' } }, mainEntityOfPage: { '@type': 'WebPage', '@id': url } }) + '</script>';
h += '<script type="application/ld+json">' + JSON.stringify({ '@context': 'https://schema.org', '@type': 'BreadcrumbList', itemListElement: [{ '@type': 'ListItem', position: 1, name: 'Blog', item: SITE + '/blog' }, { '@type': 'ListItem', position: 2, name: p.title, item: url }] }) + '</script>';
return h + tail();
}
function relatedFor(p, posts) {
const scored = posts.filter(x => x.slug !== p.slug).map(x => ({ x, s: x.tags.filter(t => p.tags.includes(t)).length }));
return scored.sort((a, b) => b.s - a.s || (b.x.publishedAt || 0) - (a.x.publishedAt || 0)).slice(0, 3).map(r => r.x);
}
function rss(posts) {
const items = posts.slice(0, 30).map(p => '<item><title>' + esc(p.title) + '</title><link>' + SITE + '/blog/' + p.slug + '</link><guid>' + SITE + '/blog/' + p.slug + '</guid><pubDate>' + new Date(p.publishedAt || p.created).toUTCString() + '</pubDate><description>' + esc(p.excerpt) + '</description></item>').join('');
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', '/refuel', '/conversion-tracking', '/presentation'].concat(EXTRA_PAGES() || []);
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>';
}
const robots = () => 'User-agent: *\nAllow: /\nDisallow: /my\nDisallow: /admin\nDisallow: /api/\nDisallow: /view/\nSitemap: ' + SITE + '/sitemap.xml\n';
module.exports = { init, listAll, listPublished, get, save, remove, bumpViews, renderIndex, renderPost, relatedFor, rss, sitemap, robots, slugify, sanitize };
+64 -6
View File
@@ -4,8 +4,24 @@
// and members never sign or pay gas for it: the engine wallet pays.
let ethers = null; try { ethers = require('ethers'); } catch (e) { /* optional dependency */ }
const fs = require('fs');
const path = require('path');
// in-flight sends survive a restart: written to the volume before every send, cleared on receipt
const INFLIGHT_FILE = () => path.join(process.env.DATA_DIR || path.join(__dirname, 'data'), 'burner-inflight.json');
function loadInflight() { try { return JSON.parse(fs.readFileSync(INFLIGHT_FILE(), 'utf8')); } catch (e) { return {}; } }
function saveInflight(o) { try { fs.writeFileSync(INFLIGHT_FILE(), JSON.stringify(o)); } catch (e) {} }
let chain = null, ads = null;
let chain = null, ads = null, accounts = null;
// another of the same account's positions that can cover this burn on-chain (credits are pooled per account)
async function fundedAlternative(b) {
if (!accounts) return null;
const owner = await ads.burnOwner(b.ref); if (!owner) return null;
const acct = await accounts.byEmail(owner); if (!acct) return null;
const ids = [acct.memberId, ...(await accounts.positions(owner)).map(p => p.memberId)].filter(id => id && id !== b.memberId);
for (const id of [...new Set(ids)]) {
try { const bal = await chain.creditBalance(id, 0); const held = await ads.unburnedFor(id); if (bal - held >= b.amount) return id; } catch (e) {}
}
return null;
}
const ABI = ['function consume(uint32 memberId_, uint8 creditType, uint256 amount, bytes32 campaignRef)', 'function engineSigner() view returns (address)'];
const state = { enabled: false, address: null, signer: null, balanceWei: '0', lastRun: 0, lastError: null, burned: 0, lastTx: null, mismatch: false, skipped: {} };
let running = false;
@@ -37,6 +53,30 @@ async function setup() {
} catch (e) { state.lastError = 'engineSigner read: ' + e.message; }
}
function refToBytes32(ref) { return ethers.zeroPadBytes(ethers.toUtf8Bytes(String(ref || '').slice(0, 32)), 32); }
// the on-chain ref IS the burn id, so a burn that already mined can always be recognised
// from its CreditsConsumed event, even when the RPC lost the response (a lost response
// double-burned member #5's campaign 30 on 2026-09-10)
function alreadyMined(b) {
const want = refToBytes32(b.id).toLowerCase();
const hit = chain.recentEvents(1e9).find(e => e.type === 'CreditsConsumed' && e.memberId === Number(b.memberId) && String(e.ref || '').toLowerCase() === want);
return hit ? hit.tx : null;
}
// ask the chain directly (not the index) whether this burn's ref already appears in a
// CreditsConsumed log for this member over roughly the last two hours
const TOPIC_CONSUMED = '0x97f58994fda6236f3659a1d723c3d42e81841551eae9243477a2948eac6aec46';
async function minedOnChain(b) {
const want = refToBytes32(b.id).toLowerCase();
const latest = parseInt(await chain.rpc('eth_blockNumber', []), 16);
const from = Math.max(0, latest - 3600);
const member = '0x' + Number(b.memberId).toString(16).padStart(64, '0');
const logs = await chain.rpc('eth_getLogs', [{ address: chain.getConfig().contract, fromBlock: '0x' + from.toString(16), toBlock: 'latest', topics: [TOPIC_CONSUMED, member] }]);
for (const lg of logs || []) {
const d = String(lg.data || '').slice(2);
const ref = '0x' + d.slice(128, 192);
if (ref.toLowerCase() === want) return lg.transactionHash;
}
return null;
}
async function tick() {
if (!state.enabled || state.mismatch || running || !ethers) return { burned: 0 };
@@ -53,15 +93,33 @@ async function tick() {
try {
// Polygon nodes reject low priority fees and some public RPCs answer fee
// queries with 500s: set the fees ourselves from the server's estimate
const mined = alreadyMined(b);
if (mined) { await ads.markBurned(b.id, mined); burned += 1; state.burned += 1; continue; }
state.inflight = Object.assign(loadInflight(), state.inflight || {});
if (state.inflight[b.id]) {
// a send whose answer we lost (or a restart mid-send): ask the chain itself before doing anything
let tx = null; try { tx = await minedOnChain(b); } catch (e) { state.lastError = 'chain check: ' + e.message; break; }
if (tx) { await ads.markBurned(b.id, tx); delete state.inflight[b.id]; saveInflight(state.inflight); burned += 1; state.burned += 1; continue; }
if (Date.now() - state.inflight[b.id] < 10 * 60000) continue; // give the network time; re-check next tick
}
// dry-run first: a revert here (usually "Insufficient credits", the member's on-chain
// balance is below what the engine metered) costs no gas and is left for the admin
try { await ctr.consume.staticCall(Number(b.memberId), 0, BigInt(b.amount), refToBytes32(b.ref)); }
catch (e) { state.skipped[b.id] = String(e.reason || e.shortMessage || e.message).slice(0, 120); continue; }
try { await ctr.consume.staticCall(Number(b.memberId), 0, BigInt(b.amount), refToBytes32(b.id)); }
catch (e) {
const why = String(e.reason || e.shortMessage || e.message).slice(0, 120);
// the pinned position is dry: settle from another funded position on the same account
const alt = /insufficient credits/i.test(why) ? await fundedAlternative(b) : null;
if (!alt) { state.skipped[b.id] = why + (alt === null && /insufficient credits/i.test(why) ? ' (no funded position on the account)' : ''); continue; }
try { await ctr.consume.staticCall(Number(alt), 0, BigInt(b.amount), refToBytes32(b.id)); }
catch (e2) { state.skipped[b.id] = String(e2.reason || e2.shortMessage || e2.message).slice(0, 120); continue; }
await ads.reassignBurn(b.id, alt); b.memberId = alt; delete state.skipped[b.id];
}
const g = await chain.suggestedFees();
const overrides = { gasLimit: 120000n, maxPriorityFeePerGas: BigInt(g.maxPriorityFeePerGas), maxFeePerGas: BigInt(g.maxFeePerGas) };
const tx = await ctr.consume(Number(b.memberId), 0, BigInt(b.amount), refToBytes32(b.ref), overrides);
state.inflight[b.id] = Date.now(); saveInflight(state.inflight);
const tx = await ctr.consume(Number(b.memberId), 0, BigInt(b.amount), refToBytes32(b.id), overrides);
const rc = await tx.wait(1);
if (rc && rc.status === 1) { await ads.markBurned(b.id, tx.hash); burned += 1; state.burned += 1; state.lastTx = tx.hash; state.lastError = null; }
if (rc && rc.status === 1) { await ads.markBurned(b.id, tx.hash); delete state.inflight[b.id]; saveInflight(state.inflight); burned += 1; state.burned += 1; state.lastTx = tx.hash; state.lastError = null; }
else { state.lastError = 'consume reverted for burn ' + b.id; break; }
} catch (e) {
state.lastError = 'burn ' + b.id + ': ' + String(e.shortMessage || e.message).slice(0, 160);
@@ -76,5 +134,5 @@ async function tick() {
return { burned };
}
function status() { return Object.assign({}, state, { hasEthers: !!ethers, keyPresent: !!keyHex() }); }
function init(opts) { chain = opts.chain; ads = opts.ads; setup().catch(e => { state.lastError = e.message; }); }
function init(opts) { chain = opts.chain; ads = opts.ads; accounts = opts.accounts || null; setup().catch(e => { state.lastError = e.message; }); }
module.exports = { init, tick, status };
+96 -26
View File
@@ -46,11 +46,16 @@ const SEL = {
const CHUNK = 9000;
const POLL_MS = 30000;
const KEEP_EVENTS = 600;
// 2026-09-16: was 600. Eleven consumers (member Earnings page, dashboard earned total, leaderboard,
// holding-tank own-buy check, admin member view, growth snapshot, P&L) read this list as if it
// were the whole history; once the contract passed 600 events (Sept 12) every older member's
// purchases and payouts silently vanished from all of them. Keep the full history; rescan() rebuilds it.
const KEEP_EVENTS = 250000;
let cfg = null;
let state = null;
let busy = false;
let dirty = false;
let onEvent = null;
function getConfig() {
@@ -72,13 +77,19 @@ function getConfig() {
function reloadConfig() { cfg = null; return getConfig(); }
// ---- JSON-RPC with fallback rotation ----
// RPC call counter (2026-10-06, Marty: measure 24 h of Polygon traffic before choosing a paid endpoint): counts every request
// this module sends, by method, and writes DATA_DIR/rpc-count.json every 5 minutes. Read-only bookkeeping; no behaviour change.
const RPC_COUNT = { since: Date.now(), m: {} };
const rpcCount = method => { RPC_COUNT.m[method] = (RPC_COUNT.m[method] || 0) + 1; };
setInterval(() => { try { fs.writeFileSync(path.join(DATA_DIR, 'rpc-count.json'), JSON.stringify(Object.assign({ at: Date.now() }, RPC_COUNT))); } catch (e) {} }, 300000).unref();
let rpcIdx = 0;
function rpcOnce(url, method, params) {
function rpcOnce(url, method, params, timeoutMs) {
rpcCount(method);
return new Promise((resolve, reject) => {
const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
const u = new URL(url);
const req = https.request({ hostname: u.hostname, path: u.pathname + u.search, method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 15000 },
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: timeoutMs || 15000 },
res => { let d = ''; res.on('data', c => d += c); res.on('end', () => {
try { const j = JSON.parse(d); if (j.error) reject(new Error(j.error.message)); else resolve(j.result); }
catch (e) { reject(e); } }); });
@@ -86,20 +97,28 @@ function rpcOnce(url, method, params) {
req.end(body);
});
}
async function rpc(method, params) {
// Circuit breaker (2026-10-12, ported from RM Circle): a provider that fails or hangs is benched for RPC_BENCH_MS so the next
// calls skip it instead of each paying the full timeout in turn (a dead node at the sticky index was stalling every member
// lookup, which members felt as slow sign-ins). eth_call reads use a 4 s timeout; logs/blocks keep 15 s. Failures are logged.
// bench only for provider-health failures (timeouts, connection errors, rate limits, 5xx). A deterministic JSON-RPC reply such as
// "invalid block range" or "query returned more than N results" is about the request, so the next provider is tried without benching.
const benchable = e => /timeout|timed out|abort|ECONN|EAI_AGAIN|ENOTFOUND|EPIPE|socket|hang up|429|too many|rate.?limit|temporar|internal error|service unavailable|50[234]/i.test(String(e && e.message || e));
const RPC_BENCH_MS = 10 * 60 * 1000; const rpcBenched = new Map(); // url -> benched until (ms)
const ETH_CALL_TIMEOUT_MS = 4000;
async function rpc(method, params, timeoutMs) {
const urls = getConfig().rpcs;
let last;
// 3 rounds over the RPC pool with backoff — the public Amoy nodes routinely
// return transient "Temporary internal error. Please retry" on eth_call, and a
// single miss was silently surfacing as 0 credits / chainReadError on the
// dashboard. Retry so a real read isn't lost to a momentary node hiccup.
for (let round = 0; round < 3; round++) {
for (let i = 0; i < urls.length; i++) {
const url = urls[(rpcIdx + i) % urls.length];
try { const r = await rpcOnce(url, method, params); rpcIdx = (rpcIdx + i) % urls.length; return r; }
catch (e) { last = e; }
// two passes: healthy providers first (round-robin from the last good one), benched ones only as a last resort; a short
// backoff before the second pass covers the public nodes' transient "Temporary internal error" replies.
for (let round = 0; round < 2; round++) {
const now = Date.now(); const order = [], benched = [];
for (let i = 0; i < urls.length; i++) { const url = urls[(rpcIdx + i) % urls.length]; ((rpcBenched.get(url) || 0) > now ? benched : order).push(url); }
order.push(...benched);
for (const url of order) {
try { const r = await rpcOnce(url, method, params, timeoutMs); rpcIdx = urls.indexOf(url); rpcBenched.delete(url); return r; }
catch (e) { last = e; const bench = benchable(e); if (bench) rpcBenched.set(url, Date.now() + RPC_BENCH_MS); console.warn('rpc', method, 'failed on', url, '->', String(e && e.message || e).slice(0, 80), bench ? '(benched 10 min)' : '(request error, next provider)'); }
}
if (round < 2) await new Promise(r => setTimeout(r, 400 * (round + 1)));
if (round < 1) await new Promise(r => setTimeout(r, 400));
}
throw last || new Error('all RPCs failed');
}
@@ -120,7 +139,7 @@ function decodeString(data, wordIdx) {
}
async function call(sel, args) {
const data = sel + (args || []).map(a => pad(a)).join('');
return rpc('eth_call', [{ to: getConfig().contract, data }, 'latest']);
return rpc('eth_call', [{ to: getConfig().contract, data }, 'latest'], ETH_CALL_TIMEOUT_MS);
}
// ---- reads ----
@@ -130,7 +149,16 @@ async function memberIdByAccount(addr) {
}
async function memberCount() { return toNum(word(await call(SEL.memberCount), 0)); }
async function productCount() { return toNum(word(await call(SEL.productCount), 0)); }
// member reads are cached 15 s (2026-10-20): dashboards ask for the same members many times a minute and every read is
// an RPC round trip; sponsor never changes and a buyer count up to 15 s old is fine for display
const memberCache = new Map();
async function member(id) {
const hit = memberCache.get(Number(id)); if (hit && Date.now() - hit.at < 15000) return hit.v;
const v = await memberRead(id); memberCache.set(Number(id), { at: Date.now(), v });
if (memberCache.size > 5000) memberCache.clear();
return v;
}
async function memberRead(id) {
const r = await call(SEL.members, [id]);
return { account: toAddr(word(r, 0)), sponsorId: toNum(word(r, 1)), buyerCount: toNum(word(r, 2)),
activated: toNum(word(r, 3)) === 1, countedAsBuyer: toNum(word(r, 4)) === 1 };
@@ -143,15 +171,16 @@ async function product(id) {
async function quoteWei(id) { try { return toBig(word(await call(SEL.quoteWei, [id]), 0)); } catch (e) { return null; } }
async function creditBalance(id, type) { return Number(toBig(word(await call(SEL.creditBalance, [id, type || 0]), 0))); }
async function catalog() {
// products and quotes are read side by side, not one after another (2026-10-19: 15 sequential reads took ~6 s
// and every dashboard waited on them)
const n = await productCount();
const out = [];
for (let i = 1; i <= n; i++) {
const p = await product(i);
if (!p.exists || !p.active) continue;
const q = await quoteWei(i);
out.push(Object.assign(p, { costWei: q === null ? null : q.toString() }));
}
return out;
const ids = Array.from({ length: n }, (_, k) => k + 1);
const rows = await Promise.all(ids.map(async i => {
const [p, q] = await Promise.all([product(i), quoteWei(i)]);
if (!p.exists || !p.active) return null;
return Object.assign(p, { costWei: q === null ? null : q.toString() });
}));
return rows.filter(Boolean);
}
// ---- event decode ----
@@ -223,17 +252,54 @@ async function tail() {
const ev = decodeLog(lg);
if (!ev) continue;
ev.ts = Date.now(); // indexed-at time: powers honest time-series charts
state.events.push(ev);
state.events.push(ev); memberCache.clear(); // a new chain event can change any member: drop the 15 s read cache
tally(ev);
if (onEvent) { try { onEvent(ev); } catch (e) { console.error('chain onEvent', e.message); } }
}
if (state.events.length > KEEP_EVENTS) state.events = state.events.slice(-KEEP_EVENTS);
state.lastBlock = to;
dirty = true;
}
saveState();
if (dirty) { saveState(); dirty = false; }
} catch (e) { console.error('chain tail', e.message); }
busy = false;
}
// Full history rebuild from the deploy block. Does NOT fire onEvent (no repeat Telegram/email
// posts) and keeps the real indexed-at ts of events already known; backfilled events get a ts
// estimated from their block height so day/week windows stay honest enough.
async function rescan() {
let waited = 0; while (busy && waited < 120000) { await new Promise(r => setTimeout(r, 500)); waited += 500; }
if (busy) return { error: 'indexer busy' };
busy = true;
try {
const c = getConfig();
const tip = await bestTip(); const latest = tip.block;
const known = new Map(state.events.map(e => [e.tx + ':' + e.li, e]));
const oldest = state.events.find(e => e.ts && e.block);
const spb = oldest && latest > oldest.block ? Math.max(1000, Math.min(4000, (Date.now() - oldest.ts) / (latest - oldest.block))) : 2150; // ms per block
const evs = [];
for (let from = c.deployBlock; from <= latest; from += CHUNK) {
const to = Math.min(from + CHUNK - 1, latest);
const range = [{ address: c.contract, fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }];
let logs;
try { logs = await rpcOnce(tip.url, 'eth_getLogs', range); } catch (e) { logs = await rpc('eth_getLogs', range); }
for (const lg of logs) {
const ev = decodeLog(lg); if (!ev) continue;
const old = known.get(ev.tx + ':' + ev.li);
ev.ts = old && old.ts ? old.ts : Math.round(Date.now() - (latest - ev.block) * spb);
evs.push(ev);
}
}
state.events = evs.slice(-KEEP_EVENTS);
state.lastBlock = latest;
state.totals = null; for (const ev of state.events) tally(ev);
state.full = true;
saveState();
console.log('chain rescan: ' + evs.length + ' events, blocks ' + c.deployBlock + '-' + latest);
return { ok: true, events: evs.length, fromBlock: c.deployBlock, toBlock: latest };
} catch (e) { console.error('chain rescan', e.message); return { error: e.message }; }
finally { busy = false; }
}
function recentEvents(n) { return state ? state.events.slice(-(n || 100)).reverse() : []; }
// running totals for the public counters — every number provable on-chain
@@ -254,6 +320,9 @@ function init(opts) {
getConfig(); loadState();
tail();
setInterval(tail, POLL_MS);
// one-time migration: a state that filled the old 600-event window has lost history; rebuild it.
// (Fresh/test servers have an empty state and never trigger this.)
if (!state.full && state.events.length >= 600) setTimeout(() => { rescan().catch(() => {}); }, 8000);
}
// Recommended EIP-1559 fees straight from the network. Polygon Amoy's Bor nodes
@@ -273,4 +342,5 @@ async function suggestedFees() {
}
module.exports = { init, getConfig, reloadConfig, memberIdByAccount, memberCount, member,
product, productCount, quoteWei, creditBalance, catalog, recentEvents, totals, rpc, decodeLog, suggestedFees };
product, productCount, quoteWei, creditBalance, catalog, recentEvents, totals, rpc, decodeLog, suggestedFees, rescan,
eventCount: () => (state ? state.events.length : 0), historyComplete: () => !!(state && state.full) };
+468 -46
View File
@@ -4,15 +4,29 @@
//
// HOUSE RULE: whenever a site feature changes, update BOTH the CANNED
// answers and FACTS below in the same commit.
//
// KNOWLEDGE BASE (2026-10-20, kb.js): CANNED below and kb-seed.js SEED the knowledge base, which is
// the one source the assistant answers from. Each CANNED regex becomes its entry's instant-answer
// pattern (same order, first match wins), and for everything else the best-matching entries go into
// the system prompt. Admin > Knowledge base edits entries; an edited entry is no longer refreshed from
// the code. If the KB store fails, the in-code CANNED list still answers.
const fs = require('fs');
const path = require('path');
const https = require('https');
const http = require('http');
const kb = require('./kb');
const kbSeed = require('./kb-seed');
let DATA_DIR = null;
let chain = null;
let HERO_SALE = null; // () => gamepass.cfg().heroes + names (server.js): the bonus-hero fact follows heroSales (2026-11-05)
let PASS_TIERS = null; // () => the live pass tiers (server.js, from gamepass.cfg): the tier fact follows the sovTiers switch
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; }
function init(opts) {
if (opts && typeof opts.gameLive === 'function') GAME_LIVE = opts.gameLive;
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn;
if (opts && typeof opts.bixLive === 'function') BIX_LIVE = opts.bixLive; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; HERO_SALE = typeof opts.heroSale === 'function' ? opts.heroSale : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
function key() {
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
@@ -20,90 +34,468 @@ function key() {
function enabled() { return !!key(); }
// ---- canned answers: instant, free, always in voice ----
const KNOWLEDGE_DATE = '2026-11-14'; // bump whenever the canned answers / prompt are brought up to date
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
const CANNED = [
{ re: /(pyramid|ponzi|scam|scheme)/i,
// network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js)
{ id: 'network-signin', title: 'One sign-in for InstantAdPay and LinkSpin', q: ['Do I have to sign in again on LinkSpin?', 'Why was I signed in on LinkSpin without a code?', 'Is it one sign-in for both sites?'], tags: ['sign in', 'network sign-in', 'linkspin', 'code', 'single sign-on'],
re: /(((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password).{0,40}(linkspin|both sites|other site)|(linkspin|both sites|other site).{0,40}((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password)|single sign|sso|one sign.?in|network sign.?in)/i,
a: 'One sign-in covers both sites. While you are signed in on InstantAdPay, any link inside your account that opens LinkSpin (the Engine Room, Refuel and the other LinkSpin links) lands you there signed in, with no code. It works the other way too, and if you open the sign-in screen on either site while you are signed in on the other, it signs you in by itself. Both sites use the same email. The one exception: if your account on the other site is not set up yet (for example you joined minutes ago, or it is waiting for your first visit), you get the usual email code that one time, with your email already filled in. Signing out signs you out of that site only, and it stays signed out there until you sign in again or follow a link from the other site. A session still lasts 4 hours on each site. This sign-in never moves money: buying, payouts and wallet actions work exactly as before.' },
// Stack POL (2026-11-09): stackpol.com, every POL payout across the network on one page; members opt in to a page in Promo tools
// Earners Corner (2026-11-10): earnerscorner.com, the network's forum; sign-in is the InstantAdPay account (DiscourseConnect)
{ id: 'earners-corner', title: 'Earners Corner forum', q: ['What is Earners Corner?', 'Is there a forum?', 'How do I sign in to the forum?'], tags: ['earners corner', 'forum', 'earnerscorner', 'community', 'discussion'],
re: /\b(earners ?corner|earnerscorner(\.com)?|forum)\b/i,
a: 'Earners Corner (https://earnerscorner.com) is our forum for people who earn online: business opportunities, paid to click, traffic exchanges and mailers, crypto earning and wallets, affiliate marketing and tools, with its own section for InstantAdPay, LinkSpin, the games and Stack POL. Anyone can read it. To post, tap Log In there and sign in with your InstantAdPay account, no new password. A new account\'s first post is reviewed before it shows, and referral links belong in the Promote Your Program category. Members with an on-chain position can post links from day one. It also has an assistant that answers questions about the network and finds related threads.' },
{ id: 'stack-pol', title: 'Stack POL', q: ['What is Stack POL?', 'How do I get my Stack POL page?', 'What is stackpol.com?'], tags: ['stack pol', 'stackpol', 'payouts', 'ledger', 'promo tools', 'stack pol pro', 'pro'],
re: /\b(stack ?pol|stackpol(\.com)?)\b/i,
a: 'Stack POL (https://stackpol.com) adds up every POL payout in the network: InstantAdPay and LinkSpin referral payments and the rewards from every game that pays POL. It shows the network total, one page per program, and a public ledger of the latest payouts with the username and a Polygonscan link for every payment. It refreshes every 5 minutes. Every member who has been paid has a page by default at stackpol.com/your-username (Promo tools > Stack POL shows the link and the switch "Show my Stack POL page"). It appears at stackpol.com/your-username within 5 minutes and carries your referral link on every program card. Link a wallet so your payouts can be added up. Switch it off any time. Stack POL Pro is a one-time upgrade: your page then shows your own LinkSpin Banner Spins in its ad spots and your spin links, a purple QR code that opens your page, and blog articles opened from your page show your banners and use your referral links on every button. Any ad package of $10 or more unlocks it automatically, one time, yours for good: Pro switches on when that package settles on chain, and you keep every credit of the package. Credits never unlock it. Pro owners also get the Stack POL Pro badge. The totals are what members were paid, not a promise of what anyone will earn.' },
// Shards of Valor bonus heroes (2026-11-05, Marty approved): sold one time. The prices and whether they are on sale live in settings, so
// this answer names neither; heroesFact() gives the AI the live state.
{ id: 'sov-bonus-heroes', title: 'Shards of Valor bonus heroes', q: ['What are the bonus heroes in Shards of Valor?', 'How do I get Kestrel, Valda, Morag or Roland?', 'Is the hero a subscription?'], tags: ['shards of valor', 'heroes', 'bonus heroes', 'kestrel', 'valda', 'morag', 'roland', 'party'],
re: /\b(bonus heroe?s?|kestrel|valda|morag|roland|paladin|barbarian|druid hero|archer hero|hero bundle)\b/i,
a: 'Shards of Valor has four bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin. Kestrel is free for every player: she joins for good once a hero in your party reaches level 20, and she is not sold. Valda, Morag and Roland are each a one-time purchase, yours for good, with no subscription, and there is a bundle of those three. Like a Game Pass, a hero is paid by a new package purchase of at least its price (your sponsor and team are paid as usual and you keep the package credits for your ads); credits you already hold never buy one. When they are on sale they show on the Game Pass card in Members > Games (https://instantadpay.com/my#games) with each price; if you do not see them there, they are not on sale yet. In the game three heroes fight at a time and you pick which three at an inn, a rest spot or a dungeon camp; heroes waiting in the roster keep their gear and level and earn half experience. A bonus hero joins at your party level (at most 20) and is never stronger than the free heroes. The whole story stays free with Aldric, Sylwen and Borin.' },
{ 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.' },
// BixPay Visa card (2026-10-29, docs/BIXPAY-INTEGRATION.md). Sits ahead of the Level 4 entry because that one also matches "3%".
// While site config bixpayLive is off, answer() swaps every bixpay-* hit for BIX_SOON_ANSWER. Never BIX's marketing claims (user
// counts, spend per day, valuations) as facts; the only fee we state is 3% per purchase, no load fee, see BIX's terms for the rest.
{ id: 'bixpay-link', title: 'Where to put my BixPay partner link', q: ['Where do I put my BixPay partner link?', 'How do I add my BIX link?', 'Which BixPay link do I paste, referral or partner?'], tags: ['bixpay', 'bix', 'partner link', 'profile', 'ib portal'],
re: /(bix|bixpay).*(partner link|my link|referral link|ib ?portal|paste|where do i (put|add|enter)|profile)|(partner link|ib ?portal).*(bix|bixpay)/i,
a: 'Members > Profile > BixPay card. Paste your PARTNER link there: in your BIX portal (bix.ibportal.io) open Profile and copy the link in the second box, the one labelled Partner. It looks like https://bix.ibportal.io/auth/register?e=...&a=1. The first box, the Bix referral link (it ends in appId=3), only makes a card customer, so the field refuses it and asks for the Partner one. Once saved, your Wallet card, your promo kit, the /bixpay guide opened from your links and the line in your payout emails all carry your link, and LinkSpin will read the same one.' },
{ id: 'bixpay-credit', title: 'Who gets the BixPay credit', q: ['Who gets credit when someone signs up for BixPay through my page?', 'Whose BixPay link is on my pages?', 'What does "Using: the network link" mean?'], tags: ['bixpay', 'bix', 'credit', 'sponsor', 'network link'],
re: /(bix|bixpay).*(credit|whose|who gets|sponsor.s link|network link|using:|my sponsor|upline)|(whose|who gets).*(bix|bixpay)/i,
a: 'The BixPay link on your pages is yours when you have saved your partner link in Profile. If you have not, it is the first sponsor up your line (up to ten levels) who has one, and if nobody has, it is the network link. Every BixPay card says which one is in play: "Using: your link", "Using: @name’s link" or "Using: the network link". Sign-ups are credited inside the BIX portal to whoever owns that link, directs and levels included; InstantAdPay does not count or pay BixPay sign-ups itself. Add your own link in Members > Profile > BixPay card so the credit is yours.' },
{ id: 'bixpay-load', title: 'Loading the BixPay card from POL', q: ['How do I load my BixPay card from POL?', 'Can I send POL to BixPay?', 'How do I fund the BixPay card?'], tags: ['bixpay', 'bix', 'fund', 'load', 'usdt', 'usdc', 'polygon', 'cash app'],
re: /(bix|bixpay).*(load|fund|top ?up|deposit|send pol|from pol|usdt|usdc|swap|cash ?app)|(load|fund|top ?up).*(bix|bixpay)/i,
a: 'The BixPay card spends USDT or USDC, so the step is POL to USDT or USDC first. Three ways: (1) swap your POL for USDT or USDC on any exchange or on-ramp you already use, then send it to your BixPay wallet on the Polygon network (open the BIX app, Wallet > Receive, pick USDT or USDC, and use the Polygon address); (2) in the US, Cash App can send crypto straight to the BixPay wallet; (3) BIX has said an in-app swap is coming, and we will add it here when it ships. Once the USDT or USDC is in the wallet, tap TOPUP on the card. No load fee; 3% per purchase; see BIX’s terms for other charges. The full walk-through with screenshots is at https://instantadpay.com/bixpay.' },
{ id: 'bixpay-card', title: 'How to get the BixPay card', q: ['How do I get the BixPay card?', 'How do I sign up for BixPay?', 'Is BixPay available in my state?'], tags: ['bixpay', 'bix', 'visa card', 'virtual card', 'sign up', 'states'],
re: /(bix|bixpay).*(get|sign ?up|join|order|apply|virtual|plastic|metal|state|country|available|how much|cost|price|\$9)|(get|sign ?up for|order).*(bix|bixpay)/i,
a: 'Open the BixPay card in your Wallet tab (Members > Wallet) and tap Get your BixPay card. That opens a partner sign-up link, so you join as a partner and the card and the referral plan come with it: 1) register in the BIX portal ON THE PAGE THE LINK OPENS (if you are reading this inside Gmail or Telegram, open the page in Chrome or Safari first; do not install the app first and do not use the portal’s own Sign Up menu, or your sponsor is lost and BIX shows the referrer as N/A), 2) download the BIX app and create your wallet, 3) in the app open Settings > Scan QR and scan the code in your portal profile to link the two, 4) Cards > Create Card for the $9.99 virtual Visa (plastic, metal and gold cards cost more). KYC is required for the card. In the US it is open in 31 states so far; not in your state yet? You can still get the wallet and build. Elsewhere availability varies by country. Guide: https://instantadpay.com/bixpay.' },
{ id: 'bixpay', title: 'What BixPay is', q: ['What is BixPay?', 'What is the BIX card?', 'Can I spend my POL with a Visa card?'], tags: ['bixpay', 'bix', 'visa', 'card', 'spend pol', 'wallet'],
re: /(bix|bixpay|bix card|visa card|debit card|spend (my )?(pol|crypto|earnings)|crypto card)/i,
a: 'BixPay is a self-custody wallet with a Visa card, made by BIX, a separate company. You send USDT or USDC to it on Polygon, load the card, and spend wherever Visa is accepted, including Apple Pay and Google Pay. Virtual cards from $9.99. 3% per purchase, no load fee; see BIX’s terms for other charges. InstantAdPay is not the card issuer; members who join BixPay as partners get their own partner link, and anyone who gets a card through their pages is credited to them in the BIX portal, up to ten levels deep. Where to find it: Members > Wallet (the card), Members > Profile (your partner link), Promo tools > BixPay (posts and banners), and the guide at https://instantadpay.com/bixpay. Crypto assets can lose value.' },
{ id: 'level4-override', title: 'The Level 4 override (3%)', q: ['What is the Level 4 override?', 'Do I earn from my fourth level?', 'How does the 3% override work?'], tags: ['override', 'level 4', 'fourth level', 'commission', 'payouts'],
re: /(level ?(4|four)|4th level|fourth level|override|3 ?%|three percent)/i,
a: 'The Level 4 override is 3% of every package bought four levels below you, paid by the company on top of the three levels the contract pays. It goes to the buyer’s 4th sponsor up if that member has 5 or more qualifying buyers (direct referrals who bought $20 or more, the same bar as level 3). If they do not have 5 yet, it moves up the line to the next member who does, up to 25 steps, and each purchase pays one override to one person. It is paid weekly in POL from a company wallet, every Monday after 9 AM Central for the Monday to Sunday week before, through the contract’s award function, so every payment has a Polygon link, and it shows in your Earnings as "Level 4 override". Weekly totals under 0.01 POL carry over to the next week. It counts purchases from the start date on, not earlier ones. It comes from the platform’s 20% share, so the 50/20/10 split does not change. What you earn depends on real purchases in your line; nothing is guaranteed.' },
{ id: 'game-pass', title: 'Game Pass and daily POL caps', q: ['What is the Game Pass?', 'Why did I hit the daily POL cap in the games?', 'Does a boss reward carry over to the next day?'], tags: ['games', 'game pass', 'daily cap', 'tournament'],
re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i,
a: 'The Game Pass is $5 for 7 days and covers every game in the network on your InstantAdPay account (linked positions included). Since Nov 2 free play is a taste and the Pass is where the games pay: 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 hunts a day at the full 0.05 to 1 POL draw instead of one small free hunt (0.02 to 0.10), plus the weekly prizes, the Mystery Hunt Box and 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. There is also a free allowance: an account with no pass receives at most 2 POL of game rewards in total, across every game, ever; after that the games keep paying only while a pass is active, and one-time progress rewards earned in the meantime are held and paid once it is. When your allowance is used up, the game you are playing and your Overview tell you, with the amount being held for you. 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.' },
{ id: 'presentation', title: 'The InstantAdPay presentation video', q: ['Where is the presentation video?', 'How do I share the presentation with my link?', 'What is the Build Wide video?'], tags: ['presentation', 'video', 'share', 'captions', 'build wide'],
re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i,
a: 'The InstantAdPay presentation is a narrated video of about six minutes at https://instantadpay.com/presentation, with captions in English, Italian, French, Spanish, German and Portuguese (pick the language under the video). It covers what the platform is, how far your ads reach, how one $20 purchase pays $10, $4 and $2 up three levels in the same transaction, why two and then five qualifying buyers unlock levels 2 and 3, Qualified Start, the Pipeline, LinkSpin and your first week. Members share it from Members > Promo tools > Share the presentation: the link carries your username (instantadpay.com/presentation?ref=<username>), sets you as the sponsor exactly like your invite link, and the page shows you as the person who shared it with a Join button. There is also a short Build Wide video, the first card under Promo tools > Videos, with its own front door ?v=wide on your invite link (the page opens on that video). The examples are illustrations, not promises of income.' },
{ id: 'passivedrip', title: 'PassiveDrip earning site', q: ['What is PassiveDrip?', 'Is there a faucet or paid to click?', 'When do coins turn into POL?'], tags: ['passivedrip', 'faucet', 'ptc', 'coins', 'earn'],
re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i,
a: 'PassiveDrip (https://passivedrip.com) is our earning site, listed under More ways to earn on your Earn tab. Claim the faucet, view paid-to-click ads, complete offers and roll the daily bonus for coins. When your balance reaches 2,000 coins ($1) it is paid out automatically in POL to your wallet on Polygon. Open it from the Earn tab with one tap: it signs you in with your InstantAdPay account, no new password. Add your Polygon wallet there so payouts can reach you. What you earn depends on what you do there; nothing is guaranteed.' },
{ id: 'spellwheel', title: 'SpellWheel word game', q: ['What is SpellWheel?', 'Is there a daily word puzzle?'], tags: ['games', 'spellwheel', 'word game', 'daily puzzle'],
re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i,
a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a 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. Guests play the first place. Signing in with your InstantAdPay account opens the second and saves your progress. The Mountain Lodge and the three places after it, plus the POL for the daily puzzle and streaks, are for Game Pass holders. POL is paid for first clears only: a small taste in the first two places, and the full table from the third place on for pass holders, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' },
{ id: 'warpwares', title: 'Warp & Wares season game', q: ['What is Warp & Wares?', 'How does Warp & Wares pay?', 'What is a sponsor dock?'], tags: ['games', 'warp and wares', 'trade wars', 'season', 'sponsor dock', 'turns'],
re: /(warp ?(and|&) ?wares|warpwares|trade ?wars|sponsor docks?|bonus turns|trading season)/i,
a: 'Warp & Wares (also in Members > Games) is the network\u2019s 30-day season game in the Trade Wars style. One shared galaxy of 1,200 sectors; every captain gets the same 200 turns a day (reset at midnight Central, never banked) to warp between sectors, buy ore, grain and parts where they are cheap and sell where they are not, haggle, leave fighters and mines to hold sectors, found a base and run a team of up to five with a shared vault. One tap signs you in with your InstantAdPay account. Credits stay in the game; POL is paid for fixed outcomes from a published season budget: the holders of the six landmark sectors and the top traders at each weekly tick (Sundays 9 AM Central), one-time milestones (first base, first garrison, first 100,000 credits traded), and the season-close leaderboard and titles. POL collects in your Warp & Wares balance and is sent automatically to the wallet linked to your InstantAdPay account (one free signature on the Wallet tab). Sponsor markets: docking at one opens a short verified sponsor visit on InstantAdPay and pays bonus turns, the only turns past the daily 200; that is gameplay only, never POL. When the season ends the galaxy resets and the next one starts. 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.' },
{ id: 'polywarriors', title: 'PolyWarriors fighting game and NFT warriors', q: ['What is PolyWarriors?', 'How do I get a mint pass?', 'How does fusing warriors work?'], tags: ['games', 'polywarriors', 'nft', 'mint pass', 'duel'],
re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i,
a: 'PolyWarriors (https://www.polywarriors.com, also in Members > Games) is a free cyberpunk turn-based fighting game, open since Oct 12. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit), and challenge other members to duels that play out while you are away. Your first win over each rival pays POL to the wallet on your InstantAdPay account. Your first warrior mints to your wallet as an NFT on Polygon, free; after that each $5 ad package you buy on InstantAdPay earns a mint pass. Fuse three warriors of the same rarity into one rarer warrior, and trade warriors with other members on the marketplace, settled in POL. Sign in with your InstantAdPay account in one tap. Nothing here is a promise of income.' },
{ id: 'clutterhunt', title: 'ClutterHunt hidden-object game', q: ['What is ClutterHunt?', 'How do hints work in ClutterHunt?'], tags: ['games', 'clutterhunt', 'hidden object', 'hints'],
re: /(clutter ?hunt|hidden.object|haunted manor)/i,
a: 'ClutterHunt (https://clutterhunt.com, also in Members > Games) is a free hidden-object game: search cozy, cluttered rooms for 12 hidden objects plus one sponsored find. This season is the Harvest Farmhouse (Nov 1 to 30: the Farmhouse Kitchen, the Pantry, the Harvest Dining Room, the Barn Loft, the Front Porch and the Cozy Parlor); the Haunted Manor closed with Halloween, and new rooms move in every season, and objects move every time you play. You get 2 free hints a round; after that, a short visit to a member’s page earns another. Sign in with your InstantAdPay account right in the game to save your stars and earn POL: each room pays POL for your first clear and your first 3-star clear every season (Expert rooms pay more), collected in your ClutterHunt balance and sent to the wallet on your InstantAdPay account automatically.' },
{ id: 'spooky-doors', title: 'Spooky Doors Halloween game', q: ['What is Spooky Doors?', 'How does the candy ladder pay?', 'How do I buy a costume?'], tags: ['games', 'spooky doors', 'halloween', 'candy', 'costume'],
re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i,
a: 'Spooky Doors (https://spookydoors.com) was the network’s Halloween game. The season ran Oct 4 through Halloween night and closed at midnight Central at the end of Oct 31, so the game and its Games tab card are off for now and the doors no longer pay. The Candy Crunch contest ended with the season: the top 10 candy collectors share 27 POL (10, 6, 4, then 1 each), paid from the game’s wallet after admin sign-off, and a winner without a linked wallet is paid once one is linked on InstantAdPay. Candy ladder POL you earned but had not received (0.10 POL or more) also pays out once your InstantAdPay wallet is linked. Costumes and door packs are no longer sold. Keep an eye on Members > Games for the next seasonal game: Turkey Drop opens Nov 2.' },
{ 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,
a: 'Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon\u2019s Peak, the Sunken Reef and the Shadow Citadel, where the Shadow King waits), earn stars, and rebuild your Stronghold and forge weapons. Chapters 1 and 2 are open to everyone; Chapter 3 needs a free InstantAdPay account; Chapters 4 to 6 need the Royal Charter, a one-time $5 (500 purchased credits, paid credits only), which a Kingdom Pass or an active Game Pass also covers. It pays POL for first clears only: a small taste through chapters 1 to 3 (about 1.2 POL in all), and for Charter holders the real ladder in chapters 4 to 6 (the Ember Dragon 3 POL, the Kraken 5, the Shadow King 7.5), never more in total than the player has paid in. Replays pay nothing, and once the Shadow King is beaten the game pays nothing more until new chapters are added. Rewards go into your game balance and are sent to the wallet on your InstantAdPay account on Polygon once it reaches 0.25 POL. They come from a reward pool funded by a share of Crown purchases, so they pay while the pool has funds (a clear the pool cannot cover pays nothing). Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game\u2019s Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. After a defeat you can also take a free revive by making a short verified visit to a member’s page. In the shop, Specials has a one-time Hero Bundle ($5: a forge weapon, a building level and 60 Crowns), the Kingdom Pass ($10 for 30 days: 10 Crowns a day, a 25-Crown chest each week and the Royal hero looks, no auto-renew) and Hero looks (Halloween looks for 40 Crowns each through Oct 31, yours to keep). Looks are cosmetic only.' },
{ id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'],
re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i,
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
{ id: '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. A counted refuel of $50 or more (either site) also earns you one free Downline Banners spot (downlinebanners.com, the network banner board), paid by the company and placed for your main wallet, so link a wallet to receive it.' },
{ id: 'downline-banners', title: 'Downline Banners (network banner board)', q: ['What is Downline Banners?', 'How do I use my LinkSpin Banner Spin on Downline Banners?', 'How do I sign in to Downline Banners?'], tags: ['downline banners', 'banner board', 'spot', 'banner spin'],
re: /(downline ?banners|banner (board|spot)|banner line)/i,
a: 'Downline Banners (https://downlinebanners.com) is the Crypto Team Build Network banner board on Polygon. A $5 spot (paid in POL) buys 300 guaranteed views on the board and a place in one global line; when later spots sell, the contract pays the 10 spots above them and the buyer\u2019s sponsor in the same transaction. Nothing is promised: you are paid only when spots sell after yours. Signed in on InstantAdPay? Open its My Spots page and you arrive signed in as your linked wallet, and your share link uses your InstantAdPay username. In My Spots, the "Use a LinkSpin Banner Spin" button puts one of your 468x60 Banner Spins on a spot in two taps, with click tracking under a Downline Banners source on LinkSpin. A $50+ Monthly Refuel earns one free spot. To promote it: Promo tools > Network sites > Downline Banners (or downlinebanners.com/promote) has your links, creatives in every common size, lines, headlines, an email and posts, all carrying your username.' },
{ id: 'viral-banner-blitz', title: 'Viral Banner Blitz (network banner loop)', q: ['What is Viral Banner Blitz?', 'How do I post on Viral Banner Blitz?'], tags: ['viral banner blitz', 'vbb', 'banner loop', '125x125'],
re: /(viral ?banner ?blitz|vbb|banner loop)/i,
a: 'Viral Banner Blitz (https://viralbannerblitz.com) is the network’s shared loop of 125x125 banners. InstantAdPay and LinkSpin members get one free post credit each day they sign in there (Sign in with InstantAdPay works). Real, verified visitors move the loop; a banner that rides out the end has cycled and earns network ad views, which are advertising, not cash. Weekly leaderboards count the visitors you send and the traffic sources they come from, with a prize pot paid in POL to the top three on each board. Your link is viralbannerblitz.com/?ref=your-username. Promo tools > Network sites > Viral Banner Blitz (or viralbannerblitz.com/promote) has your links, creatives, lines, headlines, an email and posts.' },
{ id: 'network-sites-kits', title: 'Promo tools: Network sites', q: ['Where are the Downline Banners and Viral Banner Blitz banners?', 'How do I promote the other network sites?'], tags: ['network sites', 'promo kit', 'promote', 'creatives'],
re: /(network sites|promo kit|promote (downline|viral|the other|network))/i,
a: 'Members > Promo tools > Network sites shows the promo kits of Downline Banners and Viral Banner Blitz with your InstantAdPay username already in every link: your personal links, creatives in 125x125, 468x60, 728x90, 300x250, 160x600, 1200x630 and 1080x1080 (download, copy the URL or copy ready HTML that links to you), 5 short lines, 3 headlines, an email and 2 social posts. Your username works as your sponsor link on those sites even if you never visited them. Each site keeps its own kit, so the copy here is always the current one; the same kit is on each site’s Promote page. Each link also has a tracked version that goes through LinkSpin first (so the network can see which site sent the visit) and then opens the same page with your username; use either one.' },
{ 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 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
// 2026-11-07 conversion linkage (reporting only)
{ id: 'network-conversions', title: 'Sign-ups and purchases on your click', q: ['I sent someone and they joined, why do I not see a conversion?', 'Do sign-ups on InstantAdPay show in my LinkSpin reports?', 'Does the landing tag track InstantAdPay purchases?'], tags: ['conversion tracking', 'lsclk', 'landing tag', 'reports', 'join', 'purchase'],
re: /((sign.?ups?|joins?|purchases?|sales?|conversions?).{0,40}(show|count|track|see|report).{0,30}(linkspin|reports?|landing tag|bridge|on my click)|(bridge|landing) page.{0,40}(click id|lsclk|track|count)|landing tag.{0,40}(instantadpay|purchases?|sign.?ups?|joins?))/i,
a: 'People you send to InstantAdPay or LinkSpin count with no goal and no pixel, as long as the click reaches the join page. With the LinkSpin landing tag on your page, your links to either site carry the click id, also inside a redirect link of your own. A spin link or Banner Spin pointed straight at either site carries it too. We keep the click 30 days and store it on the account at sign-up, then their sign-up, wallet link and each package they buy within 30 days of the click count on your click: a sign-up and a wallet once per click, each package on its own with its USD price. See them on Campaigns > Conversion tracking and in LinkSpin under Reports, Conversions, next to your goals. Your own account is never counted, a button that only runs a script cannot carry the click, and people who joined before 2026-11-07 cannot be matched afterwards. This is reporting only: it never changes who a sponsor is or what anyone is paid.' },
{ id: 'conversion-tracking', title: 'Conversion tracking (goal pixel)', q: ['How do I track conversions?', 'Can I see which ad brought a sign-up or sale?', 'Where do I put the goal pixel?', 'What is the landing tag?', 'How do I set up conversion tracking on WordPress?'], tags: ['conversion tracking', 'goal pixel', 'landing tag', 'cost per goal', 'aweber', 'getresponse', 'wordpress', 'setup guide'],
re: /(conver(sion|t)s?.{0,20}(track|pixel|goal)|track(ing)?.{0,30}(conversions?|sign.?ups?|sales|subscribers|leads)|goal pixel|landing tag|tracking pixel|cost per (goal|lead|sale|sign.?up|conversion)|thank.?you page|lsclk)/i,
a: 'Conversion tracking shows which of your ads bring subscribers and sales, not just clicks. It lives in your dashboard under Campaigns > Conversion tracking (https://instantadpay.com/my#campaigns). Three steps: 1) add a goal, like subscriber or sale (a default value is optional); 2) put the landing tag on the page your ad points to; 3) put the goal pixel on your thank-you page. Every click on your ad carries a click id (lsclk=...), and LinkSpin, our sister site, matches each goal to the click: first by the click id still in the address, then the id the landing tag stored, then LinkSpin\'s cookie, and last a 24-hour match on the same connection and browser (the panel says how sure each kind is). Each goal counts once per click, only within 30 days of a real click on your ad, and each campaign shows its goals and its cost per goal (30 days) in credits: the credits that campaign spent in the same 30 days, divided by its goals. Using Aweber or GetResponse? Set the form\'s thank-you (success) page to a page on YOUR site that carries the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL). If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. The Send a test conversion button fires your real pixel in test mode (Last test updates); to check your real thank-you page, add &test=1 to its pixel and open it once. Tests and your own clicks (on your ads, and on your LinkSpin spin links and Banner Spins) never count in your numbers; the card says how many of your own clicks were kept as tests. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://instantadpay.com/conversion-tracking' },
// 2026-10-23 (Marty: "they need to pay for the slot now to get a place in line"): 6 member slots, then a prepaid line
{ id: 'login-ads', title: 'Login ads: slots and the paid line', q: ['How do login ads work?', 'All login ad slots are taken, what now?', 'Can I reserve a login ad slot?', 'Can I cancel my login ad reservation?'], tags: ['login ad', 'login slot', 'reserve', 'queue', 'line', 'refund'],
re: /(log ?in.?ads?|sign.?in ads?|log ?in (ad )?(slots?|sponsor)|(reserve|reservation|queue|place in line|waiting list).{0,40}log ?in|log ?in.{0,40}(slots?|reserve|reservation|queue|place in line|waiting list)|reserve (a |the )?(next )?slot)/i,
a: 'A login ad is your page shown full screen to members right after they sign in, on the dashboard and in the connected games. A slot is a flat buy: 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once up front and never charged per day. Earned credits cannot pay for it. Up to 6 member slots run at once, because they all share the same sign-ins. When all 6 are taken you can reserve the next slot in Members > Campaigns: you pay the same price now, and your place in line is first paid, first served. Your 30 days only start when your turn comes, and the form shows your place and an estimated start date in Central time. That date is an estimate, because a slot can end early if its owner archives it. When your ad starts you get a notice on site and an email. Until it starts you can edit the link, image or headline for free, or cancel it and get every credit back. Once it has started, normal slot rules apply. A freed slot always goes to the line first, so a paused slot can only be resumed when a slot is open with nobody waiting.' },
// 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being
// signed out, and the honest answer reads far better than letting it look like a fault.
{ id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i,
a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' },
{ id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'],
re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i,
a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' },
{ id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is this a ponzi or a scam?'], tags: ['pyramid', 'scam', 'legit', 'ponzi'],
re: /(pyramid|ponzi|scam|scheme)/i,
a: 'Fair question. A pyramid pays for recruiting with no product; here every payment is for real ad delivery, bought by real advertisers, and the whole money flow is public. Check the code and every payout yourself at https://instantadpay.com/contract and https://instantadpay.com/ledger.' },
{ re: /(withdraw|cash ?out|payout request|minimum payout)/i,
{ id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'What is the minimum payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'],
re: /(withdraw|cash ?out|payout request|minimum payout)/i,
a: 'There are no withdrawals here, ever. The contract pays your share straight to your own wallet in the same transaction as the purchase. Nothing to request, nothing to wait on.' },
{ re: /(how (much|do i) earn|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. Play with scenarios on the home page calculator. No income is promised; nobody earns unless real ad buying happens.' },
{ re: /(qualif|unlock level|level 2|level 3|pass.?up)/i,
a: 'Level 1 is open to every member. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' },
{ re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i,
// "how much do I earn" used to fall through to the PRICE answer below, because that one
// matches "how much do" and this one only caught "how much earn" (Marty, 2026-09-17).
{ id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'],
re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i,
a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' },
{ id: 'network-rate', title: 'Network views and partner visits cost less than views here', 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 less: for a banner, 4 network views cost what 1 view here does, and 4 partner visits use up 1 visit of your pack. Text ads go further still: since November 12, 10 network views of a text ad cost what 1 view here does. 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)" or, for text ads, "Network views (1/10 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.' },
{ id: 'payment-trace', title: 'Why someone was not paid: trace a payment', q: ['Why did my sponsor not get paid?', 'I missed a payment', 'How do I trace a payment?'], tags: ['payment trace', 'missed payment', 'earnings', 'pass-up'],
re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i,
a: 'Every purchase and every share is on the chain, and you can read it yourself: open Members > Earnings > Trace a payment, enter the member number or username (yourself, anyone up to 3 levels below you, or your own uplines), and each purchase they were part of is laid out level by level: who was paid, who was skipped and why. The three usual answers: the person had not unlocked that level when the purchase settled (level 2 needs 2 qualifying $20+ buyers, level 3 needs 5, and qualification never applies backwards); the buyer used Qualified Start, so the purchase came from a linked wallet whose sponsor is the buyer\'s own main position, which means level 1 went to the buyer themselves; or the person\'s payouts were not switched on. Skipped shares pass up to the next qualified person, never to nobody.' },
{ id: 'walk-up', title: 'Unactivated sponsor: the walk-up rule', q: ['What if my sponsor has not switched on payouts?', 'Why did my purchase go to the company position?'], tags: ['sponsor', 'walk up', 'payouts', 'activation'],
re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i,
a: 'Your purchase never waits on your sponsor. If the person who referred you has not linked a wallet and switched on payouts when you buy, the site walks up your sponsor line to the first person who is activated with payouts on and the purchase goes through under them; if nobody in the line is ready it goes under the company position. You see a one-line note on the Buy tab and carry on. For the sponsor it is permanent: the contract locks a buyer to whoever was paid at the first purchase, so that referral moves to the upline who was paid and they cannot earn from that wallet later. They get a message saying so, and the upline gets one too. Two minutes on the Wallet tab prevents it.' },
// PIF + the holding tank. Asked together often ("should I pif someone from the tank"),
// and the honest answer is that the order matters: you cannot PIF someone still in the
// tank. Canned so it never depends on the AI provider being up (Marty, 2026-09-17).
// The second alternation catches the same question asked without the word PIF
// ("should I fund their first package", "can I buy it for them"). It needs BOTH a
// paying verb AND an explicit for-someone-else phrase, so ordinary pricing questions
// like "which package should I buy" are not stolen (Marty, 2026-09-17).
{ id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'],
re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i,
a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' },
{ id: 'who-invited', title: 'Who invited you? (naming your sponsor)', q: ['How do I add the person who invited me?', 'I joined without a link, can I name my sponsor?', 'What is the Who invited you card?'], tags: ['who invited you', 'invited', 'holding tank', 'no sponsor', 'sponsor link'],
re: /(who invited|invited (me|by)|joined without a (link|sponsor)|forgot (the|my|to use).{0,12}(link|sponsor)|(add|name|set|enter|pick|choose) (my |a )?sponsor|nobody invited)/i,
a: 'If you joined without a sponsor link, your Overview shows a Who invited you? card. Type the username of the person who invited you, confirm it, and they become your sponsor, here and on LinkSpin, and they get a notice. Do it before you switch on payouts or buy, because your sponsor locks on the contract at that point. It has to be a real member: not you, not someone in your own line, and not someone who has not switched on payouts with nobody above them who has (ask them to switch on first). Once you have a sponsor or a member number the card goes away. Nobody invited you? Tap Nobody invited me and stay in the holding tank; a small link on the Overview brings the card back while you are still there. Nothing on the site waits for your answer. New sign-ups cannot be adopted by hand for their first 24 hours, so you have a day to tell us before a member can pick you up.' },
{ 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. If someone invited you, type their username on the Who invited you? card on your Overview and this ends right away. 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 once they have been here 24 hours. A new sign-up shows an Opens in badge until then, with no Adopt button, so they have a day to tell us who invited them (the 24-hour safety net for wallet-linked members still runs on its own clock). 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 up to 10 people from the tank at one time (counting the ones who have not switched on payouts yet) 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 10 people held from the tank who have not switched on payouts yet, 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.' },
{ id: 'free-member', title: 'What free members earn', q: ['What do free members get?', 'Do I have to buy anything?', 'Credits or POL?'], tags: ['free member', 'credits', 'pol', 'activation'],
re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i,
a: 'Free members earn ad credits: view ads, watch videos, make verified visits, read inbox ads, sign in daily. Credits buy your own ads and are never cashed out. POL, the real crypto, is paid to your wallet by the contract when your referrals buy packages, once you are activated: the $20 starter package (2,000 credits to advertise with) and payouts switched on from the Wallet tab. Your own $20 purchase also makes you count as a qualifying buyer for your sponsor, and two or five such buyers in your own line open levels 2 and 3 for you.' },
{ id: 'join', title: 'How to join; do I need a wallet?', q: ['How do I join?', 'Do I need a wallet?', 'Do I need crypto experience?'], tags: ['join', 'sign up', 'wallet', 'email'],
re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i,
a: 'Join free with just your email at https://instantadpay.com/my, no wallet and no password needed. Your wallet only comes out when you buy a package or switch on payouts, and the site walks you through it.' },
{ re: /(referral link|invite link|share link|refer)/i,
a: 'You get your share link the moment you sign in, free members included. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' },
{ re: /(promo tools?|social posts?|email swipes?|banners?|text a friend|objection|share buttons?)/i,
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, and an Objection handling bank with the truth plus a ready-to-send reply. Everything is personalized with your invite link.' },
{ re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
{ id: 'referral-link', title: 'My referral and invite links', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools', 'angles'],
re: /(referral link|invite link|share link|refer)/i,
a: 'You get your share link the moment you sign in, free members included. Open Members > Promo tools: the "Your links" block at the top lists your invite link plus five angle versions (Instant, Ad spend, Free, Ledger, Two), each with a note on who it is for and Copy and Share buttons. They are the same link with a code on the end, so every join and purchase credits you; only the first page the person sees changes. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' },
{ id: 'banner-image', title: 'Banner image link and sizes', q: ['Why was my banner image refused?', 'What banner sizes are there?', 'How do I upload a banner?'], tags: ['banner', 'image', 'sizes', 'campaign'],
re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i,
a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Game and BixPay banner links in Promo tools are short (for example https://instantadpay.link/b/turkeydrop/728x90.png) so they fit the image fields on exchanges and safelists that cut long links. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' },
{ id: 'themes', title: 'Light and dark themes', q: ['Is there a light mode?', 'How do I switch themes?'], tags: ['theme', 'dark mode', 'light mode', 'appearance', 'accessibility'],
re: /(dark ?mode|light ?mode|dark theme|light theme|night mode|themes?|appearance|too bright|too dark|high contrast)/i,
a: 'InstantAdPay has light and dark themes (added 2026-11-02). In the member area use the Light, Dark or Auto control in the header, or the Appearance card on your Profile. Dark is the original look, Light is a bright green-grey workspace with the same layout, and Auto follows your device setting and switches with it. Your choice is saved on your account, so it follows you to any device once you sign in, and it applies to the public pages and your wall too. Nothing changes until you pick one. Both themes pass the accessibility contrast standard for text.' },
{ id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the email swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners', 'objections'],
re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i,
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, an Objection handling bank with the truth plus a ready-to-send reply, and a Games tab with a kit for every network game plus the EnjoyBestGames arcade (enjoybestgames.com, hundreds of free games; only the featured Polygon games pay, and your ?r= link cookies visitors as your referral for 30 days). Everything is personalized with your invite link.' },
{ id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'],
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' },
{ re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i,
{ id: 'prohibited-content', title: 'What content is not allowed?', q: ['What content is not allowed?', 'Can I put a link in my bio?', 'Can I advertise a casino or CBD?'], tags: ['prohibited content', 'rules', 'bio links', 'gambling', 'adult', 'link farm'],
re: /(not allowed|prohibited|forbidden|banned (content|words|niches?)|content (rules|policy)|what (content|ads|niches?) (is|are) (not )?(allowed|ok|accepted)|can i (post|promote|advertise|run) .*(casino|gambling|betting|adult|porn|cbd|weed|pharma|guns?)|link ?farm|backlinks?|links? in (the |my |your )?bio|bio (link|url)|why was my (bio|profile|link) (refused|rejected|blocked))/i,
a: 'Not allowed anywhere on InstantAdPay (ads, campaigns, line banners, wall offers, bios and social links): gambling, casinos, betting, lotteries and sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing and counterfeit goods; misleading financial promises. The bio is text only: no links and no domain names, links go in the social fields in Profile. Your bio, avatar and social links show on your public wall once you have bought a package; free accounts show only their name and the line’s ads there. Accounts created just to place links in profile fields (link farming) are removed without notice, with their profile text. The full list is in the Terms, section 8: https://instantadpay.com/terms#prohibited' },
{ id: 'wall', title: 'Your banner wall and its three positions', q: ['How does my wall work?', 'How do I own wall positions 2 and 3?'], tags: ['wall', 'banner wall', 'positions'],
re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i,
a: 'Your wall (instantadpay.com/wall/yourname) shows three ads. Position 1 is always your line banner. Positions 2 and 3 show your upline (or InstantAdPay) until you earn them: 2 qualifying buyers ($20 or more) make position 2 yours, 5 make position 3 yours, so a fully qualified member owns the whole page with their own links and offers. Set them in Profile > Your wall; an unlocked slot you leave empty keeps showing your upline until you fill it.' },
{ re: /(solo ad|inbox ad|inbox)/i,
a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members — give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' },
{ re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i,
{ id: 'solo-ads', title: 'Solo ads and the inbox', q: ['What is a solo ad?', 'How do inbox reads pay?'], tags: ['solo ad', 'inbox', 'campaigns'],
re: /(solo ad|inbox ad|inbox)/i,
a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members: give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' },
{ id: 'sponsor', title: 'Who is my sponsor; wrong sponsor', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Can I change my sponsor?'], tags: ['sponsor', 'invite link', 'last touch'],
re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i,
a: 'The invite link you opened most recently sets your sponsor, and the join page shows it: "Personal invitation from @name". It locks the moment you create your account, so opening someone else\'s link afterwards changes nothing, and your first purchase binds you to that same sponsor on the contract. If you have not joined yet and the page shows the wrong name, open the right person\'s link and it updates. If you already joined under the wrong sponsor by mistake, message support before your first purchase and the admin can move you.' },
{ id: 'sponsor-chat', title: 'Sponsor Chat', q: ['How do I message my sponsor?', 'Can I chat with my team?'], tags: ['chat', 'sponsor', 'messages'],
re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i,
a: 'Yes, Members has a two-way Sponsor Chat. You can message your direct sponsor for help (from Overview or the chat button), and sponsors can message anyone in their line. If they are online you chat live; if not, your message waits in their on-site inbox and they get an email. Sponsors can set themselves unavailable in Profile (you can still leave a note, they just reply later) and mute a member if needed. It is separate from the once-a-day team broadcast.' },
{ re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i,
a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits, and spend them on your own banner or text campaigns. You never see your own ads, and viewer rewards are credits, never cash.' },
{ re: /(credit|impression|cpm|what do i get|what am i buying)/i,
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners, text ads, full-screen login ads, and solo ads across the network, managed from the campaign manager in Members. Only your campaigns can spend your credits.' },
{ re: /(price|cost|package|how much is)/i,
a: 'Packages run 5 to 250 dollars, priced in dollars and settled in POL at the live rate when you buy. The full ladder with live pricing is on the home page. Packages of $20 or more count toward qualification.' },
{ re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
{ id: 'earn-credits', title: 'Earning credits: the daily set, videos, visits', q: ['How do I earn credits?', 'How does the daily ad set work?', 'How much is the daily claim?'], tags: ['earn credits', 'daily set', 'claim streak', 'videos', 'visits'],
re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i,
a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits (5 on day one, 7 on day two, 10 from day three, 25 on every 7th day in a row), then keep going with videos (up to 8 a day), verified visits (up to 20 a day) and inbox reads (up to 5 rewarded a day). A separate sign-in bonus pays 5 credits on your first sign-in each day, rising by one per consecutive day up to 10. Earned credits fund every campaign format except login ads. You never see your own ads, and viewer rewards are credits, never cash.' },
{ id: 'featured', title: 'Featured links', q: ['How do featured links work?', 'How do I extend a featured run?'], tags: ['featured links', 'campaigns', 'extend run'],
re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i,
a: 'Featured links run in the strip at the top of every member\'s Overview. Book one under Campaigns for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead; at most 10 links share any day. It is a flat buy, paid in full when booked, and the row shows days left and "runs through" a date. To keep it going use Extend run on the row, which books more days at the same rate; adding credits does not add days. Views (one per viewer per hour) and clicks are counted on the row.' },
{ id: 'verified-visits', title: 'Verified-visit packs', q: ['How do verified visits work?', 'How do I buy visits?'], tags: ['verified visits', 'visit pack', 'campaigns'],
re: /(verified visit|visit pack|buy visits|visits campaign)/i,
a: 'A verified-visit pack sends real members to your site: each one opens it in a new tab, stays at least 8 seconds and passes a check, and no member counts twice. It costs 3 credits per visit, minimum 20 visits, paid in full when you create it, then it fills over time (each member can do at most 20 visits a day). The row shows "N of M visits delivered" and Buy more visits adds to the pack. Members earn 1 credit per verified visit.' },
{ id: 'overview-video', title: 'What is InstantAdPay? The four-minute overview', q: ['What is InstantAdPay?', 'How does this work?', 'Is there an overview video?'], tags: ['overview', 'video', 'what is'],
re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i,
a: 'The quickest answer is the four-minute overview video: it is the first card on Members > Training and on the home page at https://instantadpay.com/#overview-video. It covers what the platform is, what free members get, the campaign formats, how the contract splits every purchase, wallet and payouts, Qualified Start, the payment trace and the tools for building a line.' },
{ id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'Which package should I buy?', 'What do I get for my money?'], tags: ['packages', 'price', 'credits', 'qualification'],
re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i,
a: 'Seven packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Starter $10 for 1,000, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500, Elite $500 for 70,000. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' },
{ id: 'credits', title: 'What ad credits are', q: ['What is a credit worth?', 'What are ad credits?'], tags: ['credits', 'ad formats', 'impressions'],
re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i,
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' },
{ id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'],
re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' },
{ re: /(safe|trust|rug|run away|company disappear)/i,
{ id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'],
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
{ id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'],
re: /(safe|trust|rug|run away|company disappear)/i,
a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' }
];
// CANNED + the FAQ seeds, in the shape kb.js stores (order keeps the first-match-wins sequence)
function seeds() {
return CANNED.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re.source,
handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(kbSeed.FAQ);
}
// ---- facts for the AI fallback ----
function systemPrompt() {
// PASS TIERS (2026-10-22): the passes above the weekly Game Pass (Explorer, Champion, Sovereign, Legend; names from gamepass.js
// TIER_DEFS). While sovTiers is off the assistant only says they are coming soon; once on, it quotes the live prices and contents.
// BONUS HEROES (2026-11-05): sold one time; while heroSales is off the assistant says they are coming soon, once on it quotes the live prices
function heroesFact() {
let h = null; try { h = HERO_SALE ? HERO_SALE() : null; } catch (e) { h = null; }
const base = 'Shards of Valor bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid, Roland the Paladin. Kestrel is FREE for every player once a hero in the party reaches level 20 (since 2026-11-14) and is NOT sold; anyone who bought her before keeps her. Valda, Morag and Roland are sold ONE TIME, owned for good, never a subscription; paid by a NEW package purchase of at least the price (sponsor and team paid as usual, the member keeps the package credits); credits already held never buy one. Three heroes fight at a time, picked at an inn, rest spot or dungeon camp; the roster keeps gear and level and earns half experience. A bonus hero joins at the party level (at most 20) and is never stronger than the free heroes. The Champion and Sovereign passes no longer include a hero (the Necromancer was dropped); the Legend pass opens every bonus hero while it is active.';
if (!h || !h.sale) return '- BONUS HEROES (COMING SOON, not on sale yet): ' + base + ' Never quote their prices or a launch date while they are not on sale.\n';
const each = (h.rows || []).map(r => r.name + (r.freeAt ? ' free at level ' + r.freeAt + ' (not sold)' : r.free ? ' free for everyone' : ' $' + r.usd)).join(', ');
return '- BONUS HEROES (ON SALE, Members > Games > Game Pass card at https://instantadpay.com/my#games): ' + each + (h.bundle && h.bundle.names.length ? '; the bundle ' + h.bundle.names.join(', ') + ' $' + h.bundle.usd : '') + '. ' + base + ' The bundle is heroes only (no level cap change).\n';
}
function passTiersFact() {
let t = null; try { t = PASS_TIERS ? PASS_TIERS() : null; } catch (e) { t = null; }
const soon = '- MORE GAME PASSES: monthly and yearly passes for Shards of Valor are COMING SOON and are not on sale yet. If someone asks about them (or about an Explorer, Champion, Sovereign or Legend pass, or a monthly or yearly pass), say they are coming soon and that the $5 weekly Game Pass is the pass on sale today. Never quote their prices, contents or a launch date.\n';
if (!t || !t.on) return soon;
const rows = (t.rows || []).filter(r => r.sale);
if (!rows.length) return soon;
return '- GAME PASS TIERS (on sale, Members > Games > Game Pass at https://instantadpay.com/my#games): beside the $5 weekly Game Pass, ' + rows.map(r => r.name + ' $' + r.usd + ' for ' + r.days + ' days (' + 'paid by the $' + r.usd + ' package, and the member keeps that package’s ad credits): ' + r.perks.join('; ')).join(' | ')
+ '. Each higher pass includes everything below it. Every pass is a Game Pass in every network game with the SAME daily POL caps (1.50 / 5 POL): a higher pass never pays more POL. Passes run side by side, each with its own end date; no auto-renew; buying again adds the pass length from its end date (or from now if it ended). Every pass is paid by a NEW package purchase of at least its price, made after tapping Get on that pass (since 2026-10-25 every pass price IS a one-click package amount: $5, $20, $50, $100, $250, so the right package is exactly the price); the pass starts when it settles, the sponsor and team are paid from the package as usual, and the member keeps the package credits for ads. Credits already held never buy a pass. Nothing earned in a game is taken away when a pass ends.\n';
}
// SYNDICATED RATE (Marty, 2026-10-27, approved 4:1) follows ads rates().synRateDivisor; the canned answer quotes 1/4, so
// the fast path rewrites it when the admin picks another N, and the AI fact always states the live N.
const SYN_N = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisor()) || 1)); } catch (e) { return 4; } };
// text ads have their own N since 2026-11-12 (Marty: 1/10); the canned answer quotes 4 and 10
const SYN_T = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisorText()) || 1)); } catch (e) { return 10; } };
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 of a banner cost what 1 view here does, and ' + n + ' partner visits use up 1 visit of your pack.' + (SYN_T() !== n ? ' Text ads: ' + SYN_T() + ' network views cost what 1 view here does.' : '') + ' 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 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)"); TEXT ads have their own network rate since 2026-11-12 (Marty): 1/' + SYN_T() + ' of the on-site text rate (' + SYN_T() + ' network views = the price of 1 view here, so 1 credit = ' + (10 * SYN_T()) + ' network text views at the default 1 credit per 10 views; credit log line "Network views (1/' + SYN_T() + ' rate)"), going forward only; 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;
// BixPay (2026-10-29) follows site config bixpayLive: until it is on the assistant only says the card is coming soon
let BIX_LIVE = () => false;
const bixLive = () => { try { return !!BIX_LIVE(); } catch (e) { return false; } };
const isBixId = id => /^(c-)?bixpay(-[a-z]+)?$/.test(String(id || ''));
const BIX_SOON_ANSWER = 'A BixPay Visa card for spending POL is coming to InstantAdPay soon: a self-custody wallet with a Visa card, made by BIX, a separate company. It is not switched on here yet. When it is, it shows up on your Wallet tab, with a partner-link field in your Profile and a guide at instantadpay.com/bixpay, and the release notes will say so.';
function bixFact() { return bixLive()
? '- BIXPAY VISA CARD (LIVE, 2026-10-29): BixPay = a self-custody wallet + Visa card made by BIX, a SEPARATE company (not InstantAdPay). The member sends USDT or USDC to the BixPay wallet on Polygon, loads the card, spends wherever Visa is accepted incl. Apple Pay and Google Pay. Virtual card $9.99 (plastic, metal and gold cost more). The ONLY fee we state: 3% per purchase, no load fee; for anything else say "see BIX’s terms". US: open in 31 states so far; not in your state yet = you can still get the wallet and build; elsewhere availability varies by country; KYC required for the card. Funding POL -> card: (1) swap POL to USDT/USDC on any exchange or on-ramp, send on Polygon (app: Wallet > Receive > USDT or USDC > Polygon address); (2) US: Cash App can send crypto straight to the BixPay wallet; (3) an in-app swap is announced by BIX but NOT live: never say members can swap POL inside the app today. Sign-up steps: partner link -> register in the BIX portal (bix.ibportal.io) -> download the BIX app -> Settings > Scan QR to link app and portal -> Cards > Create Card ($9.99 virtual). Partner plan, plain words: BIX puts half of the 3% fee and of card sales into its partner plan, paid over ten levels (15% level 1, 10% level 2, 2.5% each on levels 3 to 10) plus a 5% pool; sign-ups and commissions are tracked and paid by BIX in the BIX portal, never by InstantAdPay; any worked example is hypothetical, not typical, and never a promise. Disputes: BIX accepts a dispute up to 120 days after a transaction posts; they can take 30 to 60 business days. WHERE: Members > Wallet (the card with Get your BixPay card + How it works), Members > Profile > BixPay card (the member pastes their PARTNER link from BIX portal > Profile > Partner, the second box; the referral link with appId=3 is refused), Promo tools > BixPay tab (3 posts, an email swipe, 4 text-only banners, all carrying the member’s link, plus the tab’s click count), the public guide https://instantadpay.com/bixpay (add ?ref=<username> and the page carries that member’s link), one sentence in payout emails. WHOSE LINK: the member’s own partner link, else the first sponsor up the chain (10 levels) with one, else the network link; every card says which ("Using: your link / @name’s link / the network link"). Compliance: InstantAdPay is not the card issuer and earns a referral commission when someone signs up through a partner link; crypto assets can lose value. NEVER repeat BIX marketing claims (user counts, cards issued, spend per day, valuations, "bigger than X") as facts; if asked, say those are BIX’s own claims and we have not verified them.\n'
: '- BIXPAY VISA CARD: COMING SOON, not switched on yet. If asked about BixPay, BIX, a crypto Visa card or spending POL with a card, say it is coming to the Wallet tab soon and nothing is live yet; never quote its fees, steps, links or the partner plan until it is on.\n'; }
// Warp & Wares (2026-10-29, the 30-day season game) follows gamesLive the same way; its season window is WW_SEASON_START / WW_SEASON_END (Central, end exclusive)
const WW_END = /^\d{4}-\d{2}-\d{2}$/.test(String(process.env.WW_SEASON_END || '')) ? process.env.WW_SEASON_END : '2026-12-30';
const wwDay = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const wwOver = () => wwDay() >= WW_END;
const wwLive = () => { try { return !!GAME_LIVE('warpwares') && !wwOver(); } catch (e) { return false; } };
const WARPWARES_SOON_ANSWER = 'Warp & Wares, a 30-day space trading season game in the Trade Wars style, 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 WARPWARES_OVER_ANSWER = 'The Warp & Wares season is over; the next one is announced on the Games tab and in the release notes. The other games are on your Games tab (Members > Games).';
const wwAnswer = () => wwOver() ? WARPWARES_OVER_ANSWER : WARPWARES_SOON_ANSWER;
function warpwaresFact() { return wwLive() ? '- WARP & WARES (30-day season game, Members > Games): a Trade Wars-style trading and territory game in one shared galaxy of 1,200 sectors. Every captain gets 200 turns a day (reset midnight Central, never banked): warp, trade ore/grain/parts between markets, haggle, hold sectors with fighters and mines, found a base (six levels on build clocks), teams of five with a shared vault and elected leader. One-tap sign-in with the InstantAdPay account. PAYS POL from a published season budget: landmark holders and top traders at each weekly tick (Sundays 9 AM Central), one-time milestones (first base, first garrison, first 100,000 credits traded), the season-close leaderboard and titles. POL collects in the game balance and is paid automatically to the wallet linked on InstantAdPay. SPONSOR DOCK: docking at a sponsor market opens a short verified sponsor visit (charged to the advertiser like any game refuel visit, visit kind dock) and pays BONUS TURNS, the only turns past 200; gameplay only, never POL. Credits never turn into POL. Season Pass through the Game Pass: a hull step up, a second base slot, a named ship, a team banner, gold badges; never turns, fighters or prizes. Never state amounts, caps, totals or a season budget.\n' : wwOver() ? '- WARP & WARES: the season has ENDED; say the season is over and point to the Games tab for the next one.\n' : '- WARP & WARES: COMING SOON, not open yet. Never send members to the game address; say it is coming soon to the Games tab, and do not bring it up unless asked.\n'; }
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
// Shards of Valor (2026-11-06, Marty): open for testing from the Games tab once 'shardsofvalor' is in gamesLive; no POL until a launch date
function sovTestFact() { return GAME_LIVE && GAME_LIVE('shardsofvalor') ? '- SHARDS OF VALOR (OPEN TESTING since Nov 6, https://shardsofvalor.com, Members > Games > Shards of Valor > Play): a pixel adventure RPG for many players at once; lead three heroes across the islands, help the townspeople, fight in the dungeons and recover the eight Shards of Valor. It is in open testing: anyone can play it now, but it is NOT live and pays NO POL until a launch date is set; there is no launch date yet. ALL TESTING PROGRESS IS WIPED AT LAUNCH (heroes, levels, gold and items start fresh), because this phase is only for finding bugs. Never promise a date or a payout. Ask testers to report bugs through Support.\n' : ''; }
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 "- DOWNLINE BANNERS (LIVE 2026-11-13, https://downlinebanners.com, contract verified on Polygonscan): network banner board; a $5 spot in POL = 300 guaranteed views + a place in one line; the contract pays the 10 spots above and the buyer's sponsor when later spots sell; nothing promised. InstantAdPay sign-in carries members in as their linked wallet; share links use the InstantAdPay username; My Spots has a 'Use a LinkSpin Banner Spin' button. A counted Monthly Refuel of $50+ (either site) earns one free spot for the member's main wallet, paid by the company (no wallet linked = no spot).\n" + (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:
- 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.
- NETWORK SIGN-IN (built 2026-11-12): one sign-in for InstantAdPay and LinkSpin, same email on both. A member signed in on one site who follows a link from inside their account to the other (Engine Room, Refuel, Back to InstantAdPay) arrives signed in with no email code; opening the other site's sign-in screen while signed in here also signs them in by itself (one quiet try per browser every 30 minutes). Exception: when the account on the receiving site does not exist yet or is still a waiting account (never signed in), they get the normal email code once, email prefilled. Sign-out is per site and switches the automatic sign-in off on that site for 12 hours (a deliberate link from the other site still works). Sessions are ordinary member sessions (4 hours), the admin portal is never shared, and the sign-in grants nothing extra: purchases, payouts and wallet actions still need the wallet. If it fails, the email code always works.
- EARNERS CORNER (LIVE 2026-11-10, https://earnerscorner.com): the network's own forum (Discourse) for people who earn online: business opportunities, PTC, traffic exchanges and mailers, crypto earning and wallets, affiliate marketing, tools, plus an Our Network section. Read is open to everyone; posting needs signing in with the InstantAdPay account (no separate forum password). New accounts' first posts are reviewed; links unlock with trust and are open from day one for members with an on-chain position; referral links only in Promote Your Program; AI spam detection; a forum assistant answers network questions from the same official knowledge and links threads.
- STACK POL (LIVE 2026-11-09, https://stackpol.com): one site that adds up every POL payout in the network (InstantAdPay and LinkSpin TierPaid referral payments plus every game's payouts), refreshed every 5 minutes, with per-program pages (/earn/<program>), a public ledger showing each payout's username and Polygonscan link, and a blog. Members get a public page at stackpol.com/<username> by switching on 'Show my Stack POL page' in Promo tools > Stack POL; it is ON by default for every paid member (since 2026-11-09) and off only when they switch it off. It never holds money. STACK POL PRO (2026-11-09): one-time unlock, NEW MONEY only: ANY package of $10 or more bought by the member's own position unlocks it automatically (since 2026-11-09 evening, no order step); credits never count; it never uses up a package that also fulfils a Game Pass or hero order. Pro pages show the member's own LinkSpin Banner Spins in the ad spots (network zones otherwise), their spin links, a purple QR code to the page, a 'Want a personalized page like this?' button, and articles opened from the page (?ref=<username>) use the member's referral on every call to action. Pro owners get the Stack POL Pro badge. Totals are past payouts, never a promise of earnings.
${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${warpwaresFact()}${bixFact()}${turkeydropFact()}${sovTestFact()}- 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 LINKAGE (LIVE 2026-11-07, reporting only: it never changes sponsors, payouts, credits or anything on chain): a LinkSpin click id (lsclk or lsid in the address) arriving on any InstantAdPay page is kept 30 days in a first-party cookie (last click wins) and travels with the code request, and is stored with the account at sign-up, in-game sign-in included when the game passes it on. InstantAdPay then reports sign-up, wallet link and each package purchase (value = the USD price on the chain event, linked positions included) to LinkSpin, which counts join and wallet once per click and each purchase on its own, for the click's owner. The landing tag adds the click id to links to instantadpay.com, linkspin.app and the share domains, also inside a member's own redirect link; a spin link or Banner Spin pointed straight at those sites carries it with no goal needed. 30 days from the click to the event, same as goals. The first account on a click owns it. The click owner's own account and own clicks are never counted. People who joined before 2026-11-07 cannot be matched afterwards. Shown on the Conversion tracking card (with goals, 30 days) and in LinkSpin under Reports, Conversions.
- 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.
- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab (hook videos in production). Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com.
- INVITE PAGES: a member's link instantadpay.com/join/<username> opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two for an angle-matched headline. New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings).
- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase.
- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two, ?v=wide width-unlocks-depth with the Build Wide video; ?v=play opens the games angle), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle.
- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com. The Games tab (2026-10-31) also carries the EnjoyBestGames arcade kit: enjoybestgames.com is an engagement site with hundreds of free HTML5 games; the featured row Games that pay Polygon is the network's own games and the only ones that pay; the member link enjoybestgames.com/?r=username sets a 30-day cookie so every featured game and the site strip credit that member on InstantAdPay; share image, 4 posts and the 11 banner sizes are in the kit. The Network sites tab (2026-11-14) shows the Downline Banners and Viral Banner Blitz promo kits, read live from each site: the member's links (their InstantAdPay username is their sponsor link there too, even if they never visited), creatives in 7 sizes per angle, 5 lines, 3 headlines, an email and 2 posts; the same kits are on downlinebanners.com/promote and viralbannerblitz.com/promote. Viral Banner Blitz: a shared loop of 125x125 banners, one free post credit a day for InstantAdPay/LinkSpin members, verified visitors move the loop, a banner that cycles earns network ad views (advertising, not cash), weekly leaderboards with a POL prize pot.
- INVITE PAGES: a member's link instantadpay.com/join/<username> opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two|wide|play for an angle-matched headline (?v=wide: 'Width unlocks depth.', opens on the Build Wide video, vertical on phones). New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings).
- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use MetaMask/Phantom/SafePal (no hard block). The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads.
- LINE BANNER (free, set in Profile): every member can set a destination URL (must allow framing) plus an optional banner image. It is shown to their next THREE levels of new members during welcome tours (position 1 for directs, 2, 3 below), and on their public BANNER WALL at /wall/<username> — a shareable page showing their line ladder with their join link. Free viral traffic that compounds as the team grows; no credits spent.
- Ad packages: Micro $5/500 credits, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery.
- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Coming: featured rotation with disclosed rotation size, verified-visit packs.
- Members EARN credits by attention: in the Earn credits section of Members, each ad in the daily set opens FULL SCREEN in its own tab, showing the advertiser's real website. A countdown runs while you watch (it pauses if you leave the tab), then a quick human check (click the named icon) must be passed before the view counts. Finish the daily set, claim a small daily credit batch. Earned credits spend on banner and text campaigns; attention earns advertising, referrals earn money, and viewer rewards are never cash. Advertisers get real, verified visits to their site.
- Ad packages: Micro $5/500 credits, Starter $10/1,000, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500, Elite $500/70,000. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery.
- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Video watching is capped at 8 a day per member and pays 1, 2 or 4 credits for a 10, 30 or 60 second watch. FEATURED LINKS (live): a headline + link in the Featured strip at the top of every member's Overview, booked for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead, at most 10 links sharing any day; flat buy paid when booked; the row shows days left and 'runs through <date>', counts views (one per viewer per hour) and clicks, and offers Extend run. VERIFIED-VISIT PACKS (live): 3 credits per visit, minimum 20 visits, paid up front; each visit is a distinct member who opens the site in a new tab, stays 8 seconds and passes a check, at most 20 visits per member per day; the row shows 'N of M visits delivered' and Buy more visits adds to the pack; the visitor earns 1 credit.
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
- PROHIBITED CONTENT (2026-10-30, Terms section 8, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text.
- 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.
- BTC4HITS (2026-11-11): members of the closed BTC4Hits rotator site with a deliverable email were imported as waiting accounts (no wallet, no password, nothing mailed), with their BTC4Hits sponsor when that sponsor was also imported or already a member; the rest join the holding tank when they first sign in. They sign in here with the same email (code sign-in), or on LinkSpin at linkspin.app/from/btc4hits, where their active rotators became spin links. Pro status and old BTC4Hits commissions do not carry over.
- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; new sign-ups cannot be adopted by hand for 24 hours from sign-up (they show an Opens in badge and no Adopt button); a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 10 held at one time, counting those not yet switched on payouts, 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.
- WHO INVITED YOU (2026-11-07, Marty approved): a member with no sponsor and no member number sees a Who invited you? card on their Overview. They type a username, confirm in an in-page box, and that member becomes their sponsor (it follows to LinkSpin, lifts the activation hold, and the sponsor gets a new-referral email and notice). Refused: themselves, a username that does not exist, someone in their own line, a member who cannot take new members, a member with no payouts on and nobody above them on the contract, and anyone who already has a sponsor or a member number. Nobody invited me hides the card (a small Overview link brings it back while they are in the tank) and changes nothing else. It never blocks the site. It is not an adoption: no 7-day window and it does not count toward the two.
- SIGN-UP GRACE (2026-11-07): for 24 hours from sign-up nobody can adopt a member by hand. The 24-hour auto-assign is unchanged and runs from the wallet link, so a member who links a wallet in their first hour is matched about 24 hours after linking, with at most a short hand-adoption window first. Members back in the tank later have no grace.
- 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 10 people held from the tank who have not switched on payouts yet, 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.
- ONE ACCOUNT PER PERSON (Terms section 3, 2026-09-16): a person may hold exactly one account; second or duplicate accounts under any email, name or wallet, and self-referral through another account, are prohibited. The only sanctioned way to hold more than one position is Qualified Start (extra wallets linked inside the one account). Duplicates may be merged, suspended or closed and credits, prizes and contest rankings earned through them are forfeited; the contract's on-chain payments cannot be reversed. Family members join under the member's link with their own email.
- BLOG (public, instantadpay.com/blog): Marty's coaching and teaching articles on building a line, advertising that pays, and daily habits; each article has its own page and can be shared; RSS at /blog/feed.xml. Members who want to write their own articles: not offered today.
- ACHIEVEMENT BADGES ON TELEGRAM (2026-09-13): when a member unlocks Spark/Surge/Circuit/Nexus, their personalised badge image (username on the ribbon) is posted automatically to the team's Telegram payments topic and the main group, once per badge; members cannot trigger posts themselves (the 'Post to Telegram' button is admin-only); 'Share' opens a picker (X, Facebook, Telegram, WhatsApp, LinkedIn, Massifly (copies the post and opens the feed composer), the phone's own share menu, copy link, save image) that shares the member's public badge page instantadpay.com/b/<username>/<badge>, which shows the badge and their join link.
- PROMO TOOLKIT BY BADGE + AI COPY ENGINE (2026-09-14): Promo tools > AI Copy Engine shows the ladder: Free (links, posts, swipes, banners, wall, objections, shorts, badge pages), Spark (payouts on: one-tap campaign templates aimed at the member's link, printable handout with their QR at /handout/<username>), Surge (first qualifying buyer; the AI Copy Engine is live: posts, DMs, follow-ups, objection replies, emails, story posts, team broadcasts in the member's name with their link, honesty rules built in; 20 free generations a month), Circuit (60 free; Video Maker renders every promo video and short with the member's own end card and QR, hosted for download; split tester compares join angles by views, joins, buyers), Nexus (150 free; Leader Ops: three-level team triage with stalled flags and one-click nudges, AI-drafted team broadcasts, credit grants from the leader's earned pool to anyone in their line, co-branded join page showing the sponsor's bio, and the member's own partner code: welcome credits funded from the leader's pool at each redemption, plus a partner kit page /partners?ref=<username>&promo=CODE). After the free allowance each generation costs 10 ad credits from the earned pool. Credits are advertising, never money.
- MEMBER UPDATE EMAILS (2026-09-14, admin only): Admin > Releases > Email an update to members: pick release notes, add an intro, choose an audience (newsletter opt-ins, opt-ins active in the last 30 days, or everyone including those who declined), preview, send a test to the admin, then send; plain text from no-reply@instantadpay.com with an opt-out link; the log shows sent/opted out/failed.
- LINKED POSITIONS AND BADGES (2026-09-14): qualifying buyers on a member's linked positions count toward their achievement badges (Spark/Surge/Circuit/Nexus) and light their chip on their sponsor's line, and a badge once earned never regresses. CONTRACT RULE: levels 2 and 3 are paid to the MAIN wallet only when that wallet's own count of qualifying buyers reaches 2 and 5; buyers registered under a linked position count for that position, not the main wallet. Qualified Start positions buy UNDER the main wallet, so those buys raise the main count; a member whose old wallet was swapped out (its buyers stay with the old position) needs new $20+ buyers under the current main wallet before level 2 pays it. The contract still pays levels 2 and 3 to each position based on that position's OWN qualifying buyers, so the Qualifying buyers tile shows the main position's count with the linked positions' count underneath.
- CREDITS VS POL (2026-09-15, Marty's stance): EVERY member earns CREDITS (viewing, videos, visits, inbox, sign-in bonus, badge bonuses); credits are ad delivery, not money. POL is paid by the contract to a member's wallet when referrals buy packages. ALWAYS describe activation as 'the $20 starter package plus payouts switched on' and lead every earning answer with it; do NOT volunteer that level 1 can pay without a purchase. If someone asks point-blank whether a purchase is required for level-1 payouts, answer truthfully in one sentence: the contract pays level 1 to any member whose payouts are switched on, and the $20 package is what makes them a qualifying buyer for their sponsor, funds their own ads, and unlocks badges, tools, the holding tank and wall positions. A $20+ purchase by a referral makes that referral a qualifying buyer for their sponsor; 2 and 5 open levels 2 and 3. Never claim the payout itself is gated by a purchase.
- PIPELINE (live since 2026-09-15): a follow-up board on the dashboard, tab 'Pipeline' between My line and Buy packages, with its own training video on the Training tab. Columns: Talking to, Joined, Wallet linked, Payouts on, Bought, Building, Later. Prospects (from the My line prospect list) and directs are placed automatically from what they have actually done (coaching rung, on-chain buys); nobody drags cards. The sponsor adds a note, a follow-up date and a tag (hot, later, no response, not interested); a 'Follow up today' strip lists due cards; stalled cards (quiet 3+ days) are flagged; each card carries the message for its exact stage with 'Open chat with this message' (member chat) or copy.
- LEADER TOOLS (since 2026-10-16): a 'Leader tools' section on the Training tab with the Leader's Guide (a downloadable PDF: building wide, how width unlocks levels 2 and 3, network reach, Qualified Start, LinkSpin, the wallet as your key, the first week), the narrated presentation to share, and the Build wide video. My line and Pipeline each have a Leader tools card with a direct 'Download the Leader's Guide (PDF)' button and 'Open Leader tools'.
- UNACTIVATED SPONSOR = WALK UP, NEVER HOLD (2026-09-16, Marty): if a buyer's sponsor has not linked a wallet or switched on payouts, the purchase is NOT held. The site walks the sponsor line upward to the first upline who is activated with payouts on and the buy goes through under them (on-chain sponsorship for that buyer is then theirs, permanently); if nobody in the line is activated it goes under the company catch position (#1). The buyer sees a one-line notice and proceeds; once the position exists on the chain the skipped sponsor gets a blunt email + on-site message (they lost this referral for good, how to switch on payouts) and the upline who was paid gets a message that the referral is theirs permanently with a nudge to coach the one who missed it; the referral MOVES to whoever got paid (the account's stored sponsor is re-pointed when the position is created on-chain), so the buyer leaves the skipped sponsor's My line for good; the skipped sponsor can never earn from that wallet. Only a transient chain error ('rpc') still pauses a buy ("try again in a minute").
- CHASING UNICORNS (2026-11-12): a promo tool at instantadpay.com/chasing-unicorns (Members > Promo tools > 'Chasing Unicorns: the scam-spotting game', copy your own link, which ends in ?ref=<your username> so a join counts for you). It is a clearly labeled training simulation: a fake 'UnicornYield Pro' dashboard (ticking balance, countdown, fake cash-out popups, VIP upgrade, connect-wallet airdrop) where every button reveals one of 8 scam red flags and scores the visitor's 'scam radar'; then it shows what chasing scams costs and how InstantAdPay works instead, with a free join button. Nothing on the fake dashboard is real or touches any account. Made for people still waiting on a payout from another site.
- YOUR DIRECTS' DETAILS (2026-11-12): in Members > My line > 'Your line', each person who joined through your link shows their email (with a copy button), where they came from (the referring site and the link's source tag, e.g. 'from mailer.gold/mailergold'; 'no referring site' when the browser hid it; accurate source tags start 2026-11-12, older sign-ups mostly read 'no referring site') and how they joined (your invite link, your bridge page, a link version, a game, came over from LinkSpin, moved over from BTC4Hits). The same email + origin show in the Activity drop-down and the three-level downline card for your directs. Levels 2 and 3 never show emails: they belong to their own sponsor's direct relationship. The search box also matches email and source.
- FIND A MEMBER (2026-11-12): every member list on My line (Your line, the three-level downline, the Holding tank) has a search box at the top of its sort/filter bar. Type part of a name, username (with or without @), email or member number and the list narrows as you type, starting on page 1; it works together with the sort and the filter chips. Emails only show (and match) for your own level 1.
- DRILL DOWN FROM THE OVERVIEW (2026-09-15): every name chip in 'Your line at a glance' on the Overview is clickable; it jumps to My line with that person's Activity panel already open and the row highlighted.
- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through <date>', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends.
- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin.
- PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members.
- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL the network games (linked positions share it). PAYMENT (changed 2026-10-22): every pass is paid by a NEW on-chain package purchase of at least the pass price ($5 for the weekly pass), bought from one of the member's own positions AFTER tapping Get the Pass. The pass starts the moment that purchase settles. The sponsor and team are paid from that package exactly like any package, and the member keeps every credit of the package for ads. Credits (earned or purchased, old balances included) NEVER buy a pass, and a package bought before tapping Get the Pass does not count; if someone asks why, say the pass is paid by a fresh package so the team that brought them in is paid too. Passes bought before this change keep running. Buying again while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. FREE ALLOWANCE (2026-11-02, Marty: the games are a loss leader but the giveaway has a ceiling): an account with no pass receives at most 2 POL of game rewards EVER across all games combined; after that, one-time progress rewards wait as deferred and are paid once a pass is active, and repeatable daily rewards are not paid. Since 2026-11-03 the games say so the moment it happens ("You have used your free 2 POL in the games. Get the Game Pass to keep earning." plus the POL being held) and the Overview shows a Get the Game Pass card. Say it plainly: play free as long as you like, the free POL is a taste, the Game Pass is how the games keep paying. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit. PER-GAME PERKS (live 2026-10-22, also listed on the Game Pass card): PolHunter 5 missions/day instead of 3 + 2 Ad Detective cases/day; Gem Kingdom 1 free continue/day; Spooky Doors +1 door/day; ClutterHunt 2 bonus hints/day; SpellWheel streak 0.30 POL instead of 0.15 + 1 free hint/day; PolyBreak gem limit 1.5 POL/day instead of 0.5 + extra paddle every round; PolyWarriors 4th daily mission + defense 25 Circuits instead of 15; Drip Runner free shield every run; Road Agent 2 patrols/day + 25% more scrap. Buying a pass unlocks the gold Game Pass achievement badge (Members > Overview badges, share or post to Telegram). New free caps started 2026-10-26 (moved up from the announced 10-29).
- PLATFORM FACTS (2026-10-06): instantadpay.com/facts (footer link 'Platform facts') and instantadpay.com/llms.txt are the verified reference for how InstantAdPay works: contract 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 on Polygon; split 50% L1 / 20% L2 (needs 2 referred $20+ buyers) / 10% L3 (needs 5) / 10% platform wallet A / 10% platform wallet B, unqualified shares pass up (25 steps) then go to wallet A; purchased credits are on-chain (engine burns them in batches), earned credits are in the site database; credits are not transferable or cashable; POL payments are final, platform may return credits when a campaign fails because of a platform problem. When someone asks how the platform, payouts, credits or refunds work, answer from these facts and link /facts.
- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed.
- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility.
- LAUNCH WEEK SWIPES (2026-09-15): the founding-week checklist page (/launch) ends with four promoter emails members send to their OWN lists, one a day toward Monday's opening, with the member's invite link and the FOUNDER code (500 credits for anyone who joins before Mon 2026-09-21 9 AM Central) filled in, each with a Copy button. These are swipes for members, not emails the site sends.
- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18 and 2026-10-23): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 6 member slots run at once (raised from 3 on 2026-10-23) because every slot shares the same sign-ins; when all 6 are taken the member can RESERVE THE NEXT SLOT (since 2026-10-23): they pay the full slot price right then (same purchased-credits-only rule, balance drops at once, credit log 'Login slot reserved (queue #N)'), the ad waits in a paid line, first paid first served, and its 30 days do not start until its turn. Members > Campaigns shows their place in line and an ESTIMATED start date in Central time, worked out from the live slots' end dates and the reservations ahead; it is only an estimate because a slot ends early if its owner archives it. The oldest reservation starts automatically the moment a slot frees (a slot expires, or its owner pauses it to end or archive it; also checked every minute), and the owner gets an on-site notice and an email. Before it starts the owner can edit the link, image or headline for free, or cancel for a FULL refund (credited back as purchased credits, credit log 'Login slot reservation cancelled: refund'); after it starts normal slot rules apply. A freed slot goes to the line first: a paused slot can only be resumed while live slots plus reservations leave a place open, otherwise the owner is told the line is ahead of them. The admin can see the line and cancel-and-refund a reservation. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
- AD VIEWER OPEN-IN-TAB (2026-09-19): the earn viewer shows the advertiser's page inside a frame; a link in its bar opens the same site in a new tab for sites that refuse to load framed or where signing up is easier in a full tab. The view still credits from the frame's countdown and check.
- (2026-09-14 hold rule REPLACED on 2026-09-16 by the walk-up rule above: a purchase is never held for an unactivated sponsor; only a transient chain read error pauses a buy.)
- NO-PAYOUT POSITIONS (2026-09-14): admin can list member ids (Settings > No-payout positions) whose wallets must never be paid again (e.g. a compromised key). Those positions stay linked for history and counting only: the buy-from picker disables them, a purchase from them is refused, and invite links that would place a new member under them (or under their upline chain) route to the fallback sponsor instead. The contract itself cannot change a member's wallet.
- LINE AT A GLANCE, ALL LEVELS (2026-09-14): a gold chip on any level means that person made their $20+ buy (a qualifying buyer for their own sponsor); a small number on the chip is how many qualifying buyers of their own they have. My line rows say the same in words. Leaders use it to see who is one buyer short and encourage them.
- MY LINE SPONSOR LINE (2026-09-14): every row on My line, all three levels, shows who sponsored that person ("sponsored by @name", or "you" for directs).
- MY LINE ACTIVITY DROP-DOWN (2026-09-14): every row on My line, all three levels, has an Activity button that opens that person's activity: last seen, joined, stage and next step, ads viewed today and claim streak, campaigns active, link views in 30 days and joins, directs and qualifying buyers, wallet/payouts, badges, and a Working or Quiet verdict. Read-only, phone friendly.
- GETTING STARTED CARD (2026-09-14): the top of every new member's Overview shows four steps (username, link wallet, switch on payouts, first package) with the current one explained and one button that opens the right tab and highlights the control (Wallet tab > Link wallet; then Activate payouts). Encouragement only: it can be hidden, and members who only want to view ads and earn credits are never blocked. It disappears once all four are done.
- LEADERBOARD + REFERRAL CONTEST (2026-09-14): instantadpay.com/leaderboard ranks members by ad packages sold to people they directly sponsor (dollar value, read from the chain; a member's own linked positions and second accounts never count). Periods: this week (Monday to Sunday, Central time), this month, all time. Weekly and monthly winners are recorded automatically at rollover, announced in Telegram, and the credit prizes set by the admin (a ladder: 1st 1,000 / 2nd 500 / 3rd 250 weekly, 5,000 / 2,500 / 1,000 monthly by default) are granted automatically to those positions; the prize text is shown on the page and on the Overview's Leaderboard card, which also shows the member's own rank. Prizes are credits or packages, never cash.
- WHAT'S NEW / ROADMAP (2026-09-14): instantadpay.com/whats-new lists release notes (what shipped, dated, tagged new/improved/fixed) and the roadmap (planned / building, with rough ETAs). The Overview has a "What's new" card with the latest three notes and what is being built; a dot marks notes since the member's last look. Written by the admin in Admin > Releases.
- HOLDING TANK ALERTS: 24 hours after a new member joins (when they can be adopted), a note at the top of every member's Overview names them (usernames) and a post goes to the team's Telegram payments topic; adopt from My line > Holding tank (your own $20 package required).
- LEGACY WELCOME (former Faucet Wave / Tier One Ads members): they join through instantadpay.com/from/faucetwave or instantadpay.com/from/tieroneads and, if their email is on the legacy list, welcome-back credits are added automatically at signup (former advertisers 500, former earners 150; once per person; credits, not POL). They land in the holding tank like any member who joins without a sponsor. SOCIALPIX GATE (2026-09-20): socialpix.club no longer takes ad posts; its visitors are sent to instantadpay.com/from/socialpix (advertiser copy by default, ?seg=earn for the earner copy). No welcome-back credits for SocialPix arrivals; they join free by email and land in the holding tank.
- PROMO CODES: partner site owners get a reusable code; a member redeems it on a join link (?promo=CODE) or in the Overview box "Have a promo code?" and receives free ad credits (amount set per code by the admin, one use per account; codes can cap uses or expire). Credits, not POL.
- DORMANT-LEAD RESCUE: a FREE referral (no wallet, no purchase) with no message from their sponsor for 10 days triggers a warning email + dashboard flag to the sponsor ("unreached, tank in N days"); at 14 days (warning at least 4 days old) the lead moves to the holding tank and the sponsor is told. Sponsor resets the clock with a chat, a Nudge, or the "Contacted them" button (for phone/text contact). Leads whose sponsor link resolves to nobody go to the tank after a day. Nothing on-chain moves; anyone bound by a purchase never moves.
- PIF (pay it forward) button: on a free direct or an adopted member who has linked a wallet, the sponsor taps PIF, enters an amount (suggested: the $20 package plus fees), and their OWN wallet app opens with the member's address prefilled; the POL goes wallet to wallet. The site never touches the funds; it only logs the transaction and tells the recipient with a Polygonscan link. The gift is theirs; nothing forces a purchase. Before every PIF the member confirms a plain warning: the funds go wallet to wallet in good faith, InstantAdPay never holds or moves them and cannot reverse or recover them, and the member should only send what they are willing to give. You cannot PIF someone still in the holding tank: adopt them first, they link a wallet, then the button appears.
- PIF RISK (Marty, 2026-09-17, say this EVERY time PIF comes up, never sell PIF as a tactic): tell the member to make contact and get an explicit commitment BEFORE sending anything. The transfer is wallet to wallet and irreversible, there is no refund or chargeback and support cannot claw it back. The recipient may go quiet, spend it on something else or never sign in again, and none of that breaks any rule. A tank member joined with nobody working with them and may never have engaged, so an unanswered PIF is the easiest money on the site to lose. Honest arithmetic: if they buy $20 the sponsor gets 50 percent back so a gift that works costs about half, and a gift to someone who never answers costs all of it. Never gift money they need, never borrow to do it. If a member asks "should I PIF someone from the tank", the answer starts with talk to them first, not with the mechanics.
- FOUNDING WEEK / PRE-LAUNCH (Training > Founding week checklist, /launch, members only): eight items read live from the account: username, wallet linked, payouts on, level 2 qualified (2 buyers of $20+, or Qualified Start with 2 linked positions), the leader play = level 3 (5 qualifying buyers, up to 5 linked positions; then buy from the main wallet), line banner, links + play chosen (self-marked), first two placed. Reason: unqualified levels pass up, so leaders qualify BEFORE their teams' teams buy. Countdown shows when admin sets launchAt. Never call the site 'pre-launch' publicly: it is live and paying.
- COUNTRY TARGETING (2026-09-11): New campaign form has "Show to" tier checkboxes (Tier 1 = US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE by default; Tier 2 = rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO, etc.; Tier 3 = everyone else; lists editable in Admin > Settings geoTier1/geoTier2). Country comes from the viewer's IP (DB-IP lite). Applies to on-site delivery of every format; a narrowed banner/text ad is NOT sent to the partner network (which is worldwide). Unknown country never matches a narrowed campaign. Campaign rows show 'tier 1+2' chips and top viewer countries.
- SCHEDULING (2026-09-11): any campaign except featured can take an optional start and end time (local time) in the New campaign form; solo ads label it "Send from" (inbox deliveries begin then). A scheduled campaign shows "scheduled" until it starts; at the end it shows "ended" and the unspent budget returns to Available. Banner/text scheduled campaigns join the partner network at their start time. There is NO dayparting (hours-of-day targeting) by design; the daily cap paces budgets. Each campaign row shows a small views-by-hour chart (on-site views, viewer's local time, last 7 days).
- BALANCE RULE (members ask this a lot): a balance is what is NOT committed to a live campaign. Starting a campaign sets aside its whole budget at once (earned pool first, then purchased), so Available drops once and stays still while ads serve; the budget spends down inside Members > Campaigns. Dashboard shows Purchased available, Earned available, In live campaigns. A paused campaign keeps its unspent budget set aside so it can resume. A low balance with a live campaign is not lost credits. Refunds/comps of purchased money are credited off-chain as purchased-grade credits: shown under Purchased as "credited to you", fund anything incl. login ads. Viewing-earned credits never fund login ads.
- Members EARN credits by attention: in the Earn credits section of Members, each ad in the daily set opens FULL SCREEN in its own tab, showing the advertiser's real website. A countdown runs while you watch (it pauses if you leave the tab), then a quick human check (click the named icon) must be passed before the view counts. Finish the daily set, claim a small daily credit batch. Earned credits fund every campaign format except login ads; attention earns advertising, referrals earn money, and viewer rewards are never cash. DAILY SIGN-IN BONUS: separate from the claim, the first sign-in of each day pays 5 credits, rising by one per consecutive day up to 10; a missed day resets it. REPORT AN AD: every served ad carries a 'report' link (broken, inappropriate, spam, scam, other, plus a note) that emails the admin; the Shorts page uses reason buttons. Advertisers get real, verified visits to their site.
- Onsite SOLO ADS are live: a solo ad is a full message (subject + up to 2000 characters of formatted text + your link) delivered into members' on-site Inbox (Members > Inbox). The composer in Campaigns > Solo ad has a rich-text editor (bold, headings, lists, links), lets you ATTACH one image (PNG/JPG/WebP/GIF, up to 3MB) or one video (MP4/WebM, up to 25MB), and adds a call-to-action button with a custom label that opens the target URL. Cost 5 credits per guaranteed delivery, minimum 10 deliveries (50 credits). Each member receives a given solo at most once, and never the sender's own. Readers earn 2 credits per real read (10-second dwell on the open message, up to 5 rewarded reads/day) — claimed right from the message. Compose one in Campaigns > Solo ad.
- Campaign target URLs are checked the moment they are submitted: the page must be reachable and must ALLOW framing (no X-Frame-Options deny/sameorigin, no blocking CSP frame-ancestors), because surf views show the real site full screen. Frame-blocking or dead URLs are rejected with the exact reason; the fix is a landing page that allows framing. Login-ad targets skip the frame check (they are click-through only).
- SPONSOR CHAT (Members): a two-way, one-to-one chat. A member can start a conversation with their DIRECT sponsor; a sponsor can message anyone in their downline. Presence-aware — when both are online it is live, otherwise a message waits in the recipient's on-site inbox and sends an email. Each member has an availability toggle in Profile (default on; turning it off stops live chats but people can still leave a note) and can mute a specific person. This is separate from the once-a-day sponsor BROADCAST to the whole downline.
- PASSIVEDRIP (LIVE on the Earn tab for every member since 2026-10-03): https://passivedrip.com, an EARNING SITE (never call it a game): faucet claims, paid-to-click ad views, offers (offer walls) and a daily bonus roll earn coins; at 2,000 coins ($1) the balance is paid out AUTOMATICALLY in POL on Polygon to the wallet saved on PassiveDrip. The Earn tab card (More ways to earn: PassiveDrip) opens it with ONE TAP using the InstantAdPay account (no new password; it offers the member's InstantAdPay wallet to save). No income is promised.
- POLYBREAK (opens 2026-10-13, https://polybreak.app, in Members > Games): a free Arkanoid-style brick breaker. Eight hand-built rounds that then repeat with tougher silver bricks; colored bricks break in one hit, silver takes more hits each round, gold never breaks. Capsules: S slow, C catch, L laser, E enlarge, D disrupt (three balls), B break (a gate in the right wall skips the round), P extra paddle. One-tap sign-in with the InstantAdPay account; guests can play and their first clears are paid once they sign in. PAYS POL: the first clear of each round (replays pay nothing) and catches of the purple Polygon gem (a small random amount each time, the gem appears every so often during play), into the PolyBreak game balance, sent automatically to the wallet on the member's InstantAdPay account at the payout line shown in the game; rewards are paid from the game's pool, funded by a share of the one-more-paddle visits. ONE MORE PADDLE: when the last paddle is lost, a verified visit to a member's page (or a member video) continues the round with one paddle; it uses the daily refuel allowance shared with the other games. REFERRALS: each player's share link polybreak.app/r/<username>; a sponsor earns a share of the pool income from the paddle visits of players they invited. Never state a maximum or total a player can earn and never promise income.
- POLYWARRIORS (LIVE 2026-10-12, https://www.polywarriors.com, in Members > Games): a free cyberpunk turn-based fighting game. Recruit warriors that are each born with their own traits and rarity (Common, Rare, Epic, Legendary); fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit); challenge other members to async duels that play out while they are away. The FIRST win over each rival pays POL to the wallet on the member's InstantAdPay account (replays pay nothing). The first warrior mints to the member's wallet as an NFT on Polygon for free; after that every $5 ad package bought on InstantAdPay earns a mint pass. Fusion: three warriors of the same rarity fuse into one rarer warrior (the three are consumed). Marketplace: warriors trade between members, settled in POL. One-tap sign-in with the InstantAdPay account; guests can try fights but earn nothing until they sign in. A 40-second trailer and a promo kit are in Promo tools > Games > PolyWarriors. Never state a maximum or total a player can earn and never promise income.
- SPELLWHEEL (LIVE 2026-10-10, https://spellwheel.com, in Members > Games): a letter-wheel word game: swipe letters on the wheel to fill the crossword grid, travel through six cozy places (chapters: the Lantern Library, the Harbor Market, the Mountain Lodge, the Desert Caravan, the Snowy Cabin, the Glass Conservatory), and solve a new daily puzzle shared by everyone. LADDER since 2026-11-02: guests play the first place only and earn nothing (their clears carry over as progress at sign-in, never as POL); a free InstantAdPay account plays the first two places; the Mountain Lodge and beyond need an active Game Pass (the game answers "for Game Pass holders" with a link to the pass). POL, first clears only: levels 0.01/0.01/0.03/0.03/0.05/0.05 and a completed place 0.1/0.1/0.5/0.5/1/1 by chapter; from the third place on, and for the daily puzzle (0.03) and the 7-day streak, only pass holders are paid; a player who has cleared every place earns nothing more until new places ship. Collected in the SpellWheel balance and sent automatically to the wallet on the member's InstantAdPay account. One-tap sign-in with the InstantAdPay account. Never state totals or promise income.
- CLUTTERHUNT (LIVE 2026-10-03, https://clutterhunt.com, in Members > Games): a free hidden-object game. Search cozy, cluttered rooms for 12 hidden objects plus one sponsored find (a sealed letter with a sponsor's name; tapping it shows their ad). Rooms change with the seasons: the Haunted Manor (Attic, Library, Witch's Kitchen, Wizard's Study, Moonlit Greenhouse, Wine Cellar) through Oct 31, then new seasonal rooms. Objects move every round. Stars: finish under 3 minutes, use at most 1 hint, at most 6 wrong taps. 2 free hints a round; after that a short verified visit to a member's page earns a hint (shares the daily refuel allowance). Sign in with the InstantAdPay account right inside the game to save stars. PAYS POL since 2026-10-04: fixed rewards per room each season for the first clear and the first 3-star clear (more for Expert rooms, which unlock after all six rooms), collected in the ClutterHunt balance and sent automatically to the wallet on the member's InstantAdPay account once it reaches the payout amount. Players who cleared rooms before 10-04 can replay each room once to collect. NEVER state a maximum or total a player can earn (Marty's rule) and never promise earnings. HARVEST FARMHOUSE season 2026-11-01 to 11-30 (six new rooms: Farmhouse Kitchen, Pantry, Harvest Dining Room, Barn Loft, Front Porch, Cozy Parlor); the Haunted Manor closed 2026-11-01. Rewards unchanged: first clear 0.05 POL per room per season, +0.05 for three stars, Expert 0.15 and +0.10 for three stars, from the season pool while it lasts.
- 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. CLOSED 2026-11-01: the season is over, the card is hidden, doors and shop are off; Candy Crunch top 10 share 27 POL (10/6/4/1x7) paid after admin approval, unlinked winners paid once they link a wallet; unpaid ladder POL (0.10+) pays once a wallet is linked; next seasonal game is Turkey Drop (opens 2026-11-02).
- 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. LADDER since 2026-11-02 (Marty: the game funds itself): Chapters 1-2 open to everyone (guests included); Chapter 3 needs a free InstantAdPay account; Chapters 4-6 need the ROYAL CHARTER, $5 one time = 500 PURCHASED credits (paid credits only, never earned viewing credits), bought in the game's Specials; a Kingdom Pass or an active Game Pass counts as a Charter; anyone who had already spent $5+ of purchased credits in the game has it. It pays POL for FIRST clears only: chapters 1-3 are a taste (stages 0.01/0.01/0.02, bosses 0.1/0.2/0.5, about 1.2 POL in all); chapters 4-6 pay Charter holders only (stages 0.08/0.12/0.15, bosses 3/5/7.5 for the Ember Dragon, Kraken and Shadow King, about 19 POL for the full ladder) and a player's chapter 4-6 total never exceeds what they paid in. Replays pay nothing; after the Shadow King nothing more is paid until a new chapter ships. 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.
- 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.
- GAME TIERS (2026-11-02, Marty: every game funds itself; rolling out game by game, no announcements): guests get a first slice and earn nothing; a free InstantAdPay account gets a small taste of POL; the full content and the full rewards need a purchase (the $5 Game Pass, or a one-time unlock where the content is finite). Done so far: GEM KINGDOM (Royal Charter, see its own line), POLHUNTER (a free account hunts ONE code a day drawn on 0.02 to 0.10 POL; Game Pass holders hunt five a day at the full 0.05 to 1 POL draw and alone qualify for the weekly prizes and the Mystery Hunt Box; advertiser-funded finds pay the advertiser's amount on every tier), SPELLWHEEL (guests the first place, a free account the first two, the Mountain Lodge and beyond plus daily-puzzle and streak POL for Game Pass holders; see its own line). ALL OTHER GAMES since the evening of 2026-11-02: guests play but earn no POL (guest progress carries over at sign-in, guest POL does not); a free account earns 25% of each one-time progress reward (chapters, rounds, sectors, rungs, bosses, depth marks) and keeps the existing free daily limits on repeatable rewards; Game Pass holders earn 100%. Specifics: CLUTTERHUNT guests room 1, a free account rooms 1 and 2 at a quarter, Game Pass rooms 3 to 6 and Expert; POL MINER guests dig the Dirt (to 10 m), a free account to 24 m, Game Pass from the Gravel down; POLYWARRIORS the full table needs a PAID warrior mint or the Game Pass (the free first mint does not count), free accounts earn a quarter and cannot place for weekly prizes; TURKEY DROP weekly top-3 prizes go to Game Pass holders from the week of Nov 9 (the week of Nov 2 settles as announced); Drip Runner, PolyBreak, Road Agent and Spooky Doors follow the general rule. Nothing already paid changed.
- GAMES TAB (2026-10-01): Members > Games (/my#games) shows one card per network game (as of 2026-10-15: PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Road Agent, Spooky Doors during Halloween; all pay POL to the member's InstantAdPay wallet), with their own progress and a Play button that signs them in with one tap; new games appear there as they launch (PolHunter is one card). DRIP RUNNER (https://driprunner.app, LIVE for every member since 2026-10-01): tap-to-hop runner; gold drips, magenta bots, orange firewalls from chapter 2; each chapter has a drip goal for one run; the FIRST clear of a chapter pays a small POL drip (amount set by the admin, shown in the game) into the game balance, replays pay nothing; the balance is sent on Polygon to the member's InstantAdPay wallet once it reaches the payout line shown in the game. REFUELS: a run that ends can be refuelled with a verified visit to a member's page (once every page has been visited: a member video, a page seen more than 7 days ago again, or one of the network's own programs, so a game visit is never empty; since 2026-10-28 for every game's refuel, paddle, continue, hint and supply crate), up to 20 a day, separate from the 20 Earn-tab visits; the advertiser is charged as for any visit, the player gets fuel not credits. The POL pool is funded ONLY by a share of refuel ad spend plus POL spent in the hangar, so drips depend on refuels and can be zero when the pool is empty; say so honestly. HANGAR: Drip Magnet and Courier Mk II cost drips (game currency); Shield Core and Slow Field cost POL from the game balance, which returns to the pool. GUESTS can try a run without signing in; their clears pay once they sign in. REFERRALS: each player's share link /r/<username>; when members whose InstantAdPay sponsor is that player refuel, a share (10 percent by default) of each refuel's pool income goes to the sponsor's game balance. Telegram posts achievement badges (chapters, unlocks, refuel milestones, payouts). Never promise amounts or income. The public list of every game, open now and opening next, is https://instantadpay.com/games (shareable; add ?ref=<username> to keep the referral).
- Every purchase is split by an immutable smart contract in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. No withdrawals exist; money lands in members' own wallets instantly.
- Qualification: level 1 open to all; 2 buyers of $20+ unlock level 2; 5 unlock level 3. Unqualified shares pass up the sponsor line, checking up to 25 positions, else the platform receives them. Qualification cannot be bought and never expires.
- Every member gets a share link immediately (site code, /join/<code>); the contract locks a buyer to their sponsor at the buyer's FIRST purchase, so members should switch on payouts before their referrals buy.
- Transparency: live ledger at /ledger streams every chain event, and EVERY transaction row carries a clickable "verify" link — to the public block explorer when the chain has one, or to the built-in transaction viewer at /tx/<hash> (block, time, from/to, value, gas, decoded events, read live from the node). Plain-language contract review at /contract; the verified source is public.
- The contract cannot be paused, upgraded, or drained. The operator can only manage the ad catalog ($1-$500 bounds, 24h price timelock) and rotate keys.
PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile, /my#help (Help: support tickets). Public: /support (contact form for anyone signed out or locked out; support@instantadpay.com also works), /join/<username> (invite page, ?v=angle), /wall/<username>, /b/<username>/<badge>, /handout/<username>, /ledger, /tx/<hash>, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix.
RULES:
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page.
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above.
- Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor.
- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes.
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen.
- No em dashes. If you do not know, say so and point to /contract or the ledger.`;
- No em dashes. If you do not know, say so and point to /contract or the ledger.
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : '');
}
function askAI(message, historyText) {
// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
function endpoint() {
try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); }
}
function askAI(message, historyText, kbBlock) {
return new Promise((resolve, reject) => {
const body = JSON.stringify({
model: MODEL,
reasoning: { enabled: false }, // 2026-10-16: deepseek-v4-flash now thinks by default and spent the whole max_tokens on it (empty answers)
max_tokens: 300,
messages: [
{ role: 'system', content: systemPrompt() },
{ role: 'system', content: systemPrompt(kbBlock) },
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []),
{ role: 'user', content: String(message).slice(0, 600) }
]
});
const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST',
const ep = endpoint();
const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST',
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body) }, timeout: 30000 },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => {
try { resolve(JSON.parse(d).choices[0].message.content.trim()); }
catch (e) { reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); }
// OpenRouter pads a slow upstream with keepalive lines before the JSON, and when the
// provider gives up it can close having sent ONLY that padding: HTTP 200, no body.
// JSON.parse then threw and every question died on "I hit a snag" (Marty, 2026-09-17).
// Find the actual JSON object, and treat an empty answer as a failure worth retrying.
const i = d.indexOf('{');
if (i < 0) return reject(new Error('openrouter ' + res.statusCode + ': empty body (' + d.length + ' bytes of keepalive)'));
let txt = '';
try { txt = String(JSON.parse(d.slice(i)).choices[0].message.content || '').trim(); }
catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(i, i + 150))); }
if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content'));
resolve(txt);
});
});
req.on('error', reject);
@@ -112,16 +504,46 @@ function askAI(message, historyText) {
});
}
async function answer(message, historyText) {
const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) not (see|check|look)|contact support|reach support|support (ticket|desk)|\/support\b|my#help)/i;
// every reply leaves without em dashes (Marty's voice rule; the model slips one in now and then, 2026-10-20)
async function answer(message, historyText) { const r = await answerRaw(message, historyText); if (r && typeof r.reply === 'string') r.reply = r.reply.replace(/\s*\u2014\s*/g, ', '); return r; }
async function answerRaw(message, historyText) {
const msg = String(message || '').trim();
if (!msg) return { error: 'Say something first.' };
for (const c of CANNED) if (c.re.test(msg)) return { reply: c.a, canned: true };
if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it.' };
try { return { reply: await askAI(msg, historyText) }; }
catch (e) {
console.error('chat AI failed', e.message);
return { reply: 'I hit a snag answering that one. The contract review at https://instantadpay.com/contract and the live ledger at https://instantadpay.com/ledger cover most deep questions.' };
// 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 (!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 } : {});
if (hit && (hit.id === 'warpwares' || hit.id === 'c-warpwares') && !wwLive()) return { reply: wwAnswer(), canned: true, kb: hit.id };
if (hit && isBixId(hit.id) && !bixLive()) return { reply: BIX_SOON_ANSWER, canned: true, kb: hit.id };
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && (SYN_N() !== 4 || SYN_T() !== 10)) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'warpwares' && !wwLive() ? { reply: wwAnswer(), canned: true } : isBixId(c.id) && !bixLive() ? { reply: BIX_SOON_ANSWER, canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
let kbBlock = '', kbIds = [];
try {
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
const hits = await kb.context(query, 5);
const hitsOk = hits.filter(h => (pmLive() || !/^(c-)?polminer$/.test(String(h.entry && h.entry.id))) && (wwLive() || !/^(c-)?warpwares$/.test(String(h.entry && h.entry.id))) && (bixLive() || !isBixId(h.entry && h.entry.id)) && (tdLive() || !/^(c-)?turkeydrop$/.test(String(h.entry && h.entry.id)))); // not live yet: keep its answer out of the prompt
kbBlock = kb.promptBlock(hitsOk); kbIds = hitsOk.map(h => h.entry.id);
} catch (e) { console.error('kb search', e.message); }
if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true };
// One retry: the usual failure is a single provider dropping the request, and asking
// again almost always lands. Only after both fail do we admit defeat.
for (let attempt = 0; attempt < 2; attempt++) {
// handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16)
try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
catch (e) {
console.error('chat AI failed (attempt ' + (attempt + 1) + ')', e.message);
if (attempt === 0) await new Promise(r => setTimeout(r, 700));
}
}
// Never a dead end: say plainly that it was us, and offer a person.
return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true };
}
module.exports = { init, answer, enabled };
module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt };
+171 -23
View File
@@ -5,6 +5,7 @@
const fs = require('fs');
const path = require('path');
const db = require('./db');
const walletnudge = require('./walletnudge'); // POL waiting in the games with no wallet linked
let DATA_DIR = null, chain = null, accounts = null, mailer = null;
const DAY = 86400000;
@@ -55,12 +56,16 @@ async function member(id) {
const STALL_DAYS = 3;
async function describe(acct, now = Date.now()) {
const mm = await member(acct.memberId);
// unknown = the member is on chain but the read failed just now (member() swallows RPC errors and caches null for a
// minute); rungFor would call them "payouts on, no purchase" and the coach would mail a buyer the first-package nudge
// (2026-10-31 on LinkSpin: Marty, 4 purchases and 7 buyers, got "See a payout land"). Callers that mail must skip unknown.
const unknown = !!(acct.memberId && !mm);
const rung = rungFor(acct, mm);
const last = Math.max(acct.created || 0, acct.lastSeen || 0);
const quietDays = Math.floor((now - last) / DAY);
const stalled = rung < 6 && quietDays >= STALL_DAYS;
const stalled = !unknown && rung < 6 && quietDays >= STALL_DAYS;
const R = RUNGS[rung];
return { rung, label: R.label, next: R.next, say: R.say, quietDays, stalled, buyerCount: mm ? mm.buyerCount : 0,
return { rung, label: R.label, next: R.next, say: R.say, quietDays, stalled, unknown, buyerCount: mm ? mm.buyerCount : 0,
counted: !!(mm && mm.countedAsBuyer), joined: acct.created, lastSeen: acct.lastSeen || 0, onchainSponsorId: mm ? mm.sponsorId : null };
}
// coaching view for a sponsor: every direct, ladder rung, stalled flag, what to say
@@ -76,6 +81,11 @@ async function coachView(email) {
// bound: the contract pays whoever the member registered under. A direct who activated with
// no sponsor (or a different one) is in this line on the site but pays this member nothing.
c.bound = c.onchainSponsorId == null ? null : (myId > 0 && c.onchainSponsorId === myId);
c.free = !d.memberId; // still free: can be released to the holding tank (pay it forward)
// PIF gift target: a direct with a linked wallet who has NOT bought a package yet (rung < 3). Switching payouts on
// no longer hides the button (Marty 2026-10-07: a prospect with payouts on still needed his first $20).
c.address = (d.address && c.rung < 3) ? d.address : null;
c.polWaiting = d.address ? 0 : walletnudge.waitingFor(d.email); // earned in the games, stuck behind a missing wallet
out.push(Object.assign({ email: d.email, name: d.username ? '@' + d.username : (d.memberId ? 'member #' + d.memberId : d.email.replace(/^(.).*(@.*)$/, '$1***$2')), memberId: d.memberId || 0 }, c));
}
// most actionable first: stalled lowest rung, then quiet days
@@ -99,8 +109,11 @@ const J = {
const row = Object.assign({}, p, { id: this.db.nextId++, owner: email, created: Date.now(), updated: Date.now() }); this.db.prospects.push(row); this.save(); return row;
},
async removeProspect(email, id) { const n = this.db.prospects.length; this.db.prospects = this.db.prospects.filter(x => !(x.id === Number(id) && x.owner === email)); this.save(); return n !== this.db.prospects.length; },
async addView(token, angle, ts) { this.db.views.push({ token, angle, ts }); if (this.db.views.length > 50000) this.db.views = this.db.views.slice(-40000); this.save(); },
async views(tokens, since) { return this.db.views.filter(v => tokens.includes(v.token) && v.ts >= since); }
async addView(token, angle, ts, ref) { this.db.views.push({ token, angle, ts, ref: ref || '' }); if (this.db.views.length > 50000) this.db.views = this.db.views.slice(-40000); this.save(); },
async addClick(campaignId, src, ts) { this.db.clicks = this.db.clicks || []; this.db.clicks.push({ campaignId, src, ts }); if (this.db.clicks.length > 50000) this.db.clicks = this.db.clicks.slice(-40000); this.save(); },
async clicksFor(ids) { return (this.db.clicks || []).filter(c => ids.includes(c.campaignId)); },
async views(tokens, since) { return this.db.views.filter(v => tokens.includes(v.token) && v.ts >= since); },
async viewsSince(since) { return this.db.views.filter(v => v.ts >= since); }
};
const D = {
async lastNudge(email) { const r = await db.q('SELECT rung, ts FROM nudges WHERE email=?', [email]); return r[0] ? { rung: r[0].rung, ts: Number(r[0].ts) } : null; },
@@ -120,11 +133,17 @@ const D = {
return (await this.prospects(email)).find(x => x.id === r.insertId) || null;
},
async removeProspect(email, id) { const r = await db.q('DELETE FROM prospects WHERE id=? AND owner_email=?', [Number(id), email]); return r.affectedRows > 0; },
async addView(token, angle, ts) { await db.q('INSERT INTO join_views (token,angle,ts) VALUES (?,?,?)', [token, angle, ts]); },
async addView(token, angle, ts, ref) { await db.q('INSERT INTO join_views (token,angle,ts,ref) VALUES (?,?,?,?)', [token, angle, ts, ref || null]); },
async addClick(campaignId, src, ts) { await db.q('INSERT INTO click_sources (campaign_id,src,ts) VALUES (?,?,?)', [Number(campaignId), src, ts]); },
async clicksFor(ids) { if (!ids.length) return []; const rows = await db.q('SELECT campaign_id, src, ts FROM click_sources WHERE campaign_id IN (' + ids.map(() => '?').join(',') + ')', ids); return rows.map(r => ({ campaignId: r.campaign_id, src: r.src, ts: Number(r.ts) })); },
async views(tokens, since) {
if (!tokens.length) return [];
const rows = await db.q('SELECT token, angle, ts FROM join_views WHERE ts>=? AND token IN (' + tokens.map(() => '?').join(',') + ')', [since, ...tokens]);
return rows.map(r => ({ token: r.token, angle: r.angle, ts: Number(r.ts) }));
const rows = await db.q('SELECT token, angle, ts, ref FROM join_views WHERE ts>=? AND token IN (' + tokens.map(() => '?').join(',') + ')', [since, ...tokens]);
return rows.map(r => ({ token: r.token, angle: r.angle, ts: Number(r.ts), ref: r.ref || '' }));
},
async viewsSince(since) {
const rows = await db.q('SELECT token, angle, ts, ref FROM join_views WHERE ts>=?', [since]);
return rows.map(r => ({ token: r.token, angle: r.angle, ts: Number(r.ts), ref: r.ref || '' }));
}
};
const impl = () => db.enabled() ? D : J;
@@ -148,7 +167,31 @@ async function saveProspect(email, body) {
async function removeProspect(email, id) { return (await impl().removeProspect(String(email).toLowerCase(), id)) ? { ok: true } : { error: 'No such prospect.' }; }
// ---- link stats: views per angle (join page loads), joins and buyers per angle ----
async function recordView(token, angle) { try { await impl().addView(String(token || '').toLowerCase().slice(0, 40), String(angle || '').toLowerCase().slice(0, 20), Date.now()); } catch (e) {} }
// referring domain from a Referer header: our own pages count as 'direct', empty is 'direct'
function refHost(referer) {
try { const h = new URL(String(referer || '')).hostname.replace(/^www\./, '').toLowerCase(); return (!h || /instantadpay\.com$/.test(h)) ? 'direct' : h.slice(0, 80); } catch (e) { return 'direct'; }
}
async function recordView(token, angle, referer) { try { await impl().addView(String(token || '').toLowerCase().slice(0, 40), String(angle || '').toLowerCase().slice(0, 20), Date.now(), refHost(referer)); } catch (e) {} }
// where an ad click happened: our own surface (by page path) or an outside host
function clickSource(referer) {
try {
const u = new URL(String(referer || '')); const h = u.hostname.replace(/^www\./, '').toLowerCase();
if (!/instantadpay\.com$/.test(h)) return h.slice(0, 80) || 'unknown';
const p = u.pathname;
if (p.startsWith('/view')) return 'ad viewer'; if (p.startsWith('/my')) return 'member area'; if (p.startsWith('/ledger')) return 'live ledger';
if (p.startsWith('/wall/')) return 'member walls'; if (p.startsWith('/shorts')) return 'shorts'; if (p.startsWith('/plays')) return 'plays page'; if (p === '/' || p === '') return 'home page';
return 'site';
} 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 = {};
for (const r of rows) { out[r.campaignId] = out[r.campaignId] || {}; out[r.campaignId][r.src] = (out[r.campaignId][r.src] || 0) + 1; }
return out;
}
async function linkStats(email) {
const a = await accounts.byEmail(email);
if (!a) return { angles: [] };
@@ -156,16 +199,117 @@ async function linkStats(email) {
const now = Date.now();
const views = await impl().views(tokens, 0);
const joined = await accounts.listByReferrer(tokens);
const ANG = ['', 'instant', 'adspend', 'free', 'ledger', 'two'];
const ANG = ['', 'instant', 'adspend', 'free', 'ledger', 'two', 'wide', 'page']; // page = a viral link (any page + ?ref=)
const rows = {};
for (const k of ANG) rows[k] = { angle: k || 'plain', views30: 0, views: 0, joins: 0, buyers: 0 };
for (const v of views) { const r = rows[v.angle] || rows['']; r.views += 1; if (now - v.ts < 30 * DAY) r.views30 += 1; }
const src = {};
const srcRow = k => (src[k] = src[k] || { source: k, views30: 0, views: 0, joins: 0, buyers: 0 });
for (const v of views) { const r = rows[v.angle] || rows['']; r.views += 1; if (now - v.ts < 30 * DAY) r.views30 += 1; const s = srcRow(v.ref || 'direct'); s.views += 1; if (now - v.ts < 30 * DAY) s.views30 += 1; }
for (const j of joined.slice(0, 300)) {
const r = rows[String(j.joinedVia || '').toLowerCase()] || rows[''];
r.joins += 1;
if (j.memberId) { const mm = await member(j.memberId); if (mm && mm.countedAsBuyer) r.buyers += 1; }
const s = srcRow(j.joinedRef || 'direct'); s.joins += 1;
if (j.memberId) { const mm = await member(j.memberId); if (mm && mm.countedAsBuyer) { r.buyers += 1; s.buyers += 1; } }
}
return { angles: Object.values(rows), totalViews: views.length, totalJoins: joined.length };
const sources = Object.values(src).sort((a, b) => (b.views + b.joins * 5) - (a.views + a.joins * 5));
return { angles: Object.values(rows), sources, totalViews: views.length, totalJoins: joined.length };
}
// ---- the weekly member email (Marty, 2026-09-14; reformatted 2026-10-01 because one long text block was hard to read):
// one section per topic, each with a heading, the number that matters up front and ONE button. Sent as HTML with a
// plain-text twin built from the same sections.
const SITE = 'https://instantadpay.com';
const escH = v => String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const n0 = v => Number(v || 0).toLocaleString('en-US');
async function weeklyDigest(acct, view, lbWeek, tankN, now) {
const name = acct.username ? '@' + acct.username : 'there';
const S = []; // { title, big, bigLabel, lines[], rows[[label, value]], quotes[{to, text}], button{label, url} }
// credits: they sit on positions and each campaign pays from one, so the pooled total alone misleads
// members with linked positions (Jim Watts, 2026-09-27: "561 unspent" but a top-up allowed 19)
try {
const ids = [acct.memberId, ...(await accounts.positions(acct.email)).map(p => p.memberId)].filter(Boolean);
const bal = await X.ads.balances(ids, acct.email);
if (bal.available > 0) {
const onPos = (bal.per || []).filter(p => p.avail > 0).sort((a, b) => b.avail - a.avail);
const loose = (bal.credited || 0) + (bal.earned || 0);
const sec = { title: 'Ad credits ready to use', big: n0(bal.available), bigLabel: 'credits not running yet', lines: [], button: { label: 'Start a campaign', url: SITE + '/my#campaigns' } };
if (onPos.length > 1) {
sec.rows = onPos.map(p => ['Position #' + p.memberId, n0(p.avail)]);
if (loose) sec.rows.push(['Any position can use', n0(loose)]);
sec.lines.push('Each campaign spends from one position. Start from #' + onPos[0].memberId + ' to use the most credits at once.');
}
sec.lines.push('Point the campaign at your invite link so the views bring people to you.');
S.push(sec);
} else if (bal.inCampaigns > 0) S.push({ title: 'Ad credits', big: n0(bal.inCampaigns), bigLabel: 'credits working in live campaigns', lines: ['Everything you have is running. Nice.'] });
} catch (e) {}
// streak
try {
const st = await X.ads.viewStatus(acct.email);
if (st.streakDay > 1) S.push({ title: 'Daily claim streak', big: 'Day ' + st.streakDay, bigLabel: 'of your streak. Today’s claim pays ' + n0(st.claimCredits) + ' credits.', lines: ['Miss a day and the streak starts over.'], button: { label: 'Claim today', url: SITE + '/my#earn' } });
else S.push({ title: 'Free daily credits', lines: ['View five ads and claim once a day. The claim grows 5, 7, 10 credits, then 25 on every seventh day in a row.'], button: { label: 'Start today', url: SITE + '/my#earn' } });
} catch (e) {}
// contest
let first = false;
if (lbWeek && lbWeek.top) {
const me = lbWeek.top.find(r => r.name === '@' + acct.username) || null;
let mine = me; if (!mine) { try { mine = (await X.lb().view('week', acct.email)).me; } catch (e) {} }
first = !!(lbWeek.top.length && lbWeek.top[0].name === '@' + acct.username);
const sec = { title: 'This week’s referral contest', lines: [], button: { label: 'See the leaderboard', url: SITE + '/leaderboard' } };
if (lbWeek.prize) sec.intro = 'Prizes: ' + lbWeek.prize + '.';
if (lbWeek.top.length) sec.rows = lbWeek.top.slice(0, 3).map(r => [r.rank + '. ' + r.name, r.sales + ' sold']);
else sec.lines.push('No sales yet. The first one takes the top spot.');
if (mine) { sec.big = '#' + mine.rank; sec.bigLabel = 'is your place, with ' + mine.sales + ' sold'; }
else sec.lines.push('You are not on the board yet. One $20 package bought by someone you sponsor puts you there.');
S.push(sec);
}
// tank
if (tankN > 0 && acct.memberId) S.push({ title: 'Holding tank', big: n0(tankN), bigLabel: 'member' + (tankN === 1 ? '' : 's') + ' waiting for a sponsor', lines: ['Adopt one from My line and they join your team.'], button: { label: 'Adopt a member', url: SITE + '/my#line' } });
// line (sponsors only)
if (view.directs.length) {
const week = view.directs.filter(d => now - d.joined < 7 * DAY).length;
const sec = { title: 'Your team', rows: [['Direct members', n0(view.directs.length)], ['Joined this week', n0(week)], ['Gone quiet', n0(view.stalled)]], lines: [], button: { label: 'Open My line', url: SITE + '/my#line' } };
const q = view.directs.filter(d => d.stalled).slice(0, 3).map(d => ({ to: d.name, text: d.say.replace('{{name}}', d.name.replace(/^@/, '')) }));
if (q.length) { sec.lines.push('A quick message gets most people moving again. Copy these:'); sec.quotes = q; }
S.push(sec);
}
const subject = first ? 'You are #1 this week on InstantAdPay' : 'Your week on InstantAdPay: credits, streak, contest';
const tip = { text: 'Short on time? The twenty-minute day: claim your set, message one person on your team, check the tank, start one new conversation.', link: SITE + '/blog/the-twenty-minute-day' };
const legal = 'No income is guaranteed. Credits are advertising, not money.';
// plain text twin
const T = ['Hi ' + name + ', here is your week on InstantAdPay.', ''];
for (const s of S) {
T.push(s.title.toUpperCase());
if (s.big) T.push(s.big + ' ' + s.bigLabel);
if (s.intro) T.push(s.intro);
for (const r of s.rows || []) T.push(' ' + r[0] + ': ' + r[1]);
for (const l of s.lines) T.push(l);
for (const q of s.quotes || []) T.push(' To ' + q.to + ': "' + q.text + '"');
if (s.button) T.push(s.button.label + ': ' + s.button.url);
T.push('');
}
T.push(tip.text + ' ' + tip.link, '', 'InstantAdPay · ' + SITE + '/my', legal);
// html
const btn = b => '<a href="' + escH(b.url) + '" style="display:inline-block;background:#1e3a8a;color:#ffffff;text-decoration:none;font-weight:600;font-size:15px;padding:11px 20px;border-radius:8px">' + escH(b.label) + '</a>';
const card = s => '<tr><td style="padding:0 0 14px"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#ffffff;border:1px solid #e3e6ee;border-radius:12px"><tr><td style="padding:18px 20px">'
+ '<div style="font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:#6b7280;font-weight:700;margin:0 0 6px">' + escH(s.title) + '</div>'
+ (s.big ? '<div style="margin:0 0 10px"><span style="font-size:30px;font-weight:800;color:#111827">' + escH(s.big) + '</span> <span style="font-size:15px;color:#4b5563">' + escH(s.bigLabel) + '</span></div>' : '')
+ (s.intro ? '<p style="margin:0 0 8px;font-size:15px;line-height:1.5;color:#374151">' + escH(s.intro) + '</p>' : '')
+ (s.rows ? '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 10px;font-size:15px">' + s.rows.map(r => '<tr><td style="padding:5px 0;border-bottom:1px solid #f0f1f5;color:#374151">' + escH(r[0]) + '</td><td align="right" style="padding:5px 0;border-bottom:1px solid #f0f1f5;color:#111827;font-weight:700">' + escH(r[1]) + '</td></tr>').join('') + '</table>' : '')
+ s.lines.map(l => '<p style="margin:0 0 10px;font-size:15px;line-height:1.5;color:#374151">' + escH(l) + '</p>').join('')
+ (s.quotes || []).map(q => '<div style="margin:0 0 10px;padding:10px 12px;background:#f5f6fa;border-radius:8px;font-size:14px;line-height:1.5;color:#374151"><b style="color:#111827">To ' + escH(q.to) + '</b><br>' + escH(q.text) + '</div>').join('')
+ (s.button ? '<div style="margin:6px 0 0">' + btn(s.button) + '</div>' : '')
+ '</td></tr></table></td></tr>';
const html = '<!doctype html><html><body style="margin:0;padding:0;background:#f3f4f8">'
+ '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f8"><tr><td align="center" style="padding:20px 12px">'
+ '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif">'
+ '<tr><td style="padding:4px 4px 16px"><div style="font-size:20px;font-weight:800;color:#111827">Your week on InstantAdPay</div><div style="font-size:15px;color:#4b5563;margin-top:4px">Hi ' + escH(name) + ', here is where things stand.</div></td></tr>'
+ S.map(card).join('')
+ '<tr><td style="padding:2px 4px 14px;font-size:14px;line-height:1.5;color:#4b5563">' + escH(tip.text) + ' <a href="' + escH(tip.link) + '" style="color:#1e3a8a">Read how</a></td></tr>'
+ '<tr><td style="padding:0 4px 8px;font-size:12px;color:#9ca3af">InstantAdPay · <a href="' + SITE + '/my" style="color:#9ca3af">' + 'instantadpay.com/my</a><br>' + escH(legal) + '</td></tr>'
+ '</table></td></tr></table></body></html>';
return { subject, text: T.join('\n'), html, sections: S };
}
// ---- automatic nudges to stalled members + weekly digest to sponsors ----
@@ -180,6 +324,7 @@ async function nudgeTick() {
const all = await accounts.listAll(5000);
for (const acct of all) {
if (!acct.email || !acct.created || now - acct.created < STALL_DAYS * DAY) continue;
if (X.adminEmail && String(acct.email).toLowerCase() === String(X.adminEmail).toLowerCase()) continue; // the site owner is never coached (2026-10-31)
const c = await describe(acct, now);
if (!c.stalled) continue;
const R = RUNGS[c.rung]; if (!R.mail) continue;
@@ -192,20 +337,21 @@ async function nudgeTick() {
catch (e) { console.error('nudge', acct.email, e.message); }
if (nudges >= 40) break; // spread the load across ticks
}
// weekly digest: every sponsor with at least one direct
// weekly member email (Marty, 2026-09-14, modelled on the mailer.gold weekly): credits sitting unspent,
// the streak, the contest standings with the member's own rank, the tank, and the line for sponsors
let lbWeek = null; try { lbWeek = X.lb ? await X.lb().view('week') : null; } catch (e) {}
let tankN = 0; try { tankN = X.tank ? (await X.tank.adoptable()).length : 0; } catch (e) {}
for (const acct of all) {
if (!acct.email) continue;
const lastD = await impl().lastDigest(acct.email);
if (now - lastD < 7 * DAY) continue;
if (now - (acct.lastSeen || acct.created || 0) > 45 * DAY) { await impl().setDigest(acct.email, now); continue; } // gone quiet for six weeks: leave them to the nudges
const view = await coachView(acct.email);
if (!view.directs.length) { await impl().setDigest(acct.email, now); continue; }
const week = view.directs.filter(d => now - d.joined < 7 * DAY).length;
const lines = view.directs.slice(0, 25).map(d => '- ' + d.name + ': ' + d.label + (d.stalled ? ' (quiet ' + d.quietDays + ' days)' : '') + '. Next: ' + d.next);
const actions = view.directs.filter(d => d.stalled).slice(0, 3).map(d => '- Message ' + d.name + ': "' + d.say.replace('{{name}}', d.name.replace(/^@/, '')) + '"');
const body = 'Your line this week:\n' + week + ' joined in the last 7 days. ' + view.stalled + ' of your ' + view.directs.length + ' directs have gone quiet.\n\n'
+ lines.join('\n') + '\n\n' + (actions.length ? 'Three things to do today:\n' + actions.join('\n') + '\n\n' : '')
+ 'Open My line to message anyone in one click: https://instantadpay.com/my#line\n\nInstantAdPay';
try { await mailer.send(acct.email, 'Your line this week: ' + view.stalled + ' to nudge', body); digests += 1; } catch (e) { console.error('digest', acct.email, e.message); }
// audience: sponsors with directs (as before) unless the admin switched the weekly on for every member
const everyone = X.siteConfig && String(X.siteConfig().memberWeeklyEmail || '0') === '1';
if (!everyone && !view.directs.length) { await impl().setDigest(acct.email, now); continue; }
const { subject, text, html } = await weeklyDigest(acct, view, lbWeek, tankN, now);
try { await mailer.send(acct.email, subject, text, html); digests += 1; } catch (e) { console.error('digest', acct.email, e.message); }
await impl().setDigest(acct.email, now);
if (digests >= 30) break;
}
@@ -213,8 +359,10 @@ async function nudgeTick() {
return { nudges, digests };
}
function init(opts) {
let X = {}; // extra refs for the weekly member email (ads, tank, lb getter), 2026-09-14
function init(opts) { X = arguments[0] || {};
DATA_DIR = opts.dataDir; chain = opts.chain; accounts = opts.accounts; mailer = opts.mailer;
J.load();
}
module.exports = { init, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick };
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, clicksSince, refHost, viewsSince };
+194 -2
View File
@@ -72,13 +72,16 @@ async function bootstrap() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
const alterSafe0 = async sql => { try { await q(sql); } catch (e) { if (!['ER_DUP_FIELDNAME', 'ER_DUP_KEYNAME'].includes(e.code)) throw e; } };
await alterSafe0('ALTER TABLE earned_credits ADD COLUMN milestones VARCHAR(255) NULL'); // comma-joined granted milestone keys
await alterSafe0('ALTER TABLE earned_credits ADD COLUMN purchase_grade INT NOT NULL DEFAULT 0'); // part of the pool that is refunded/credited PURCHASED money: shows as purchased, funds login ads
await alterSafe0('ALTER TABLE earned_credits ADD COLUMN login_day CHAR(10) NULL'); // last daily-login-bonus day
await alterSafe0('ALTER TABLE earned_credits ADD COLUMN login_streak INT NOT NULL DEFAULT 0'); // consecutive-day streak
await alterSafe0('ALTER TABLE earned_credits ADD COLUMN login_ts BIGINT NOT NULL DEFAULT 0'); // when the last sign-in bonus was paid: enforces a 20h floor, whatever the day string says
// additive columns (MySQL 8 has no IF NOT EXISTS for columns)
const alterSafe = async sql => {
try { await q(sql); }
catch (e) { if (!['ER_DUP_FIELDNAME', 'ER_DUP_KEYNAME'].includes(e.code)) throw e; }
};
await alterSafe('ALTER TABLE promo_codes ADD COLUMN funder VARCHAR(190) NULL'); // member-funded partner codes (Nexus), 2026-09-14
await alterSafe('ALTER TABLE accounts ADD COLUMN username VARCHAR(30) NULL');
await alterSafe('ALTER TABLE accounts ADD UNIQUE KEY uq_username (username)');
await alterSafe('ALTER TABLE accounts ADD COLUMN member_id INT NULL');
@@ -113,13 +116,40 @@ async function bootstrap() {
// solo message bodies are sanitized rich text; TEXT gives them room
await alterSafe('ALTER TABLE campaigns MODIFY body TEXT NULL');
await alterSafe('ALTER TABLE campaigns ADD COLUMN cta_label VARCHAR(40) NULL');
await alterSafe('ALTER TABLE campaigns ADD COLUMN last_shown_day VARCHAR(10) NULL'); // login ads: charge only days they were actually shown (2026-09-15)
await alterSafe('ALTER TABLE campaigns ADD COLUMN width INT NULL'); // banner size (IAB) → also NAS width
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)
await alterSafe('ALTER TABLE campaigns ADD COLUMN starts BIGINT NULL'); // featured run start (booked day); any type: scheduled start
await q(`CREATE TABLE IF NOT EXISTS camp_hours (
campaign_id INT NOT NULL, day CHAR(10) NOT NULL, hour TINYINT NOT NULL, n INT NOT NULL DEFAULT 0,
PRIMARY KEY (campaign_id, day, hour)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site views per UTC hour, for the by-hour chart
await alterSafe('ALTER TABLE campaigns ADD COLUMN house TINYINT NOT NULL DEFAULT 0'); // admin house ad: free, never charged
await alterSafe('ALTER TABLE campaigns ADD COLUMN daily_cap INT NULL'); // optional credits/day pacing (banner + text)
await alterSafe('ALTER TABLE campaigns ADD COLUMN geo VARCHAR(16) NULL'); // country tiers the campaign shows to ('1,2'); NULL = everyone
await alterSafe('ALTER TABLE campaigns ADD COLUMN placement VARCHAR(8) NULL'); // visits packs: NULL/'all' everywhere, 'doors' / 'golden' = Spooky Doors only until rates.sdSeasonEnd (2026-10-02)
await q(`CREATE TABLE IF NOT EXISTS camp_geo (
campaign_id INT NOT NULL, cc CHAR(2) NOT NULL, n INT NOT NULL DEFAULT 0,
PRIMARY KEY (campaign_id, cc)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site serves per viewer country
await alterSafe('ALTER TABLE campaigns ADD COLUMN day_spent INT NOT NULL DEFAULT 0');
await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL");
// prepaid login-ad line (2026-10-23): status 'queued' = paid and waiting for a slot (never serves), 'cancelled' = refunded
// before it started; queued_at orders the line (first paid, first served). status is VARCHAR(12), so no change there.
await alterSafe('ALTER TABLE campaigns ADD COLUMN queued_at BIGINT NULL');
// short lease locks shared by every app copy (two run for ~30 s on each deploy): one conditional UPDATE takes a lock
// (holder IS NULL OR lease_until < now), the holder clears it, and an expired lease can be taken over after a crash
await q(`CREATE TABLE IF NOT EXISTS app_locks (
name VARCHAR(40) PRIMARY KEY,
holder VARCHAR(60) NULL,
lease_until BIGINT NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q("INSERT IGNORE INTO app_locks (name, holder, lease_until) VALUES ('login_queue', NULL, 0)");
// linked positions: extra wallets owned by one email account (Qualified Start).
// Each is its own on-chain member sponsored by the account's main member.
await q(`CREATE TABLE IF NOT EXISTS positions (
@@ -131,6 +161,39 @@ async function bootstrap() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS nudges (email VARCHAR(190) PRIMARY KEY, rung INT NOT NULL, ts BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS digests (email VARCHAR(190) PRIMARY KEY, ts BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS promo_codes (
code VARCHAR(24) NOT NULL PRIMARY KEY, credits INT NOT NULL, partner VARCHAR(80) NULL, note VARCHAR(200) NULL,
max_uses INT NOT NULL DEFAULT 0, expires BIGINT NOT NULL DEFAULT 0, active TINYINT NOT NULL DEFAULT 1, created BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // partner promo codes -> free ad credits
await q(`CREATE TABLE IF NOT EXISTS promo_redemptions (
code VARCHAR(24) NOT NULL, email VARCHAR(190) NOT NULL, credits INT NOT NULL, via VARCHAR(12) NOT NULL, ts BIGINT NOT NULL,
PRIMARY KEY (code, email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN paid INT NOT NULL DEFAULT 0'); // credits paid so far (the drip)
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN last_day CHAR(10) NULL'); // Central day of the last installment
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN expires BIGINT NOT NULL DEFAULT 0'); // unclaimed installments stop here; 0 = pre-drip row
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN ref VARCHAR(80) NULL');
await alterSafe0("ALTER TABLE visit_seen ADD COLUMN kind VARCHAR(8) NOT NULL DEFAULT 'earn'"); // 'refuel' = a Drip Runner refuel (own daily cap, 2026-09-30) // site the ?promo= link was opened from
await q('UPDATE promo_redemptions SET paid=credits WHERE expires=0 AND paid<credits'); // pre-drip redemptions were paid in full at once
await q(`CREATE TABLE IF NOT EXISTS page_hits (
day CHAR(10) NOT NULL, host VARCHAR(80) NOT NULL, path VARCHAR(40) NOT NULL, n INT NOT NULL DEFAULT 0,
PRIMARY KEY (day, host, path)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // admin Traffic tab: public page views by referring domain
await q(`CREATE TABLE IF NOT EXISTS blog_posts (
slug VARCHAR(80) NOT NULL PRIMARY KEY, title VARCHAR(140) NOT NULL, excerpt VARCHAR(300) NULL, body MEDIUMTEXT NULL, cover VARCHAR(300) NULL,
tags VARCHAR(200) NULL, status VARCHAR(12) NOT NULL DEFAULT 'draft', author VARCHAR(80) NULL, created BIGINT NOT NULL, updated BIGINT NOT NULL,
published_at BIGINT NULL, views INT NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // public blog articles written in Admin > Blog
await q(`CREATE TABLE IF NOT EXISTS adoptions (
id INT AUTO_INCREMENT PRIMARY KEY,
adoptee VARCHAR(190) NOT NULL, adopter VARCHAR(190) NOT NULL,
ts BIGINT NOT NULL, expires BIGINT NOT NULL, status VARCHAR(12) NOT NULL DEFAULT 'open',
note VARCHAR(600) NULL, closed BIGINT NULL,
INDEX (adoptee), INDEX (adopter), INDEX (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // holding-tank adoptions
await q(`CREATE TABLE IF NOT EXISTS lead_marks (
\`lead\` VARCHAR(190) PRIMARY KEY, sponsor VARCHAR(190) NULL, contacted_ts BIGINT NULL, warned_ts BIGINT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // dormant-lead rescue: manual "contacted" marks + warning sent
await q(`CREATE TABLE IF NOT EXISTS prospects (
id INT AUTO_INCREMENT PRIMARY KEY,
owner_email VARCHAR(190) NOT NULL,
@@ -143,6 +206,15 @@ async function bootstrap() {
updated BIGINT NOT NULL,
INDEX (owner_email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS pipeline_notes (
owner_email VARCHAR(190) NOT NULL,
person VARCHAR(190) NOT NULL,
note VARCHAR(1000) NULL,
follow_up BIGINT NULL,
tag VARCHAR(20) NULL,
updated BIGINT NOT NULL,
PRIMARY KEY (owner_email, person)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS join_views (
id INT AUTO_INCREMENT PRIMARY KEY,
token VARCHAR(40) NOT NULL,
@@ -150,6 +222,25 @@ async function bootstrap() {
ts BIGINT NOT NULL,
INDEX (token, ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await alterSafe('ALTER TABLE join_views ADD COLUMN ref VARCHAR(80) NULL'); // referring domain
await q(`CREATE TABLE IF NOT EXISTS click_sources (
id INT AUTO_INCREMENT PRIMARY KEY,
campaign_id INT NOT NULL,
src VARCHAR(80) NOT NULL,
ts BIGINT NOT NULL,
INDEX (campaign_id, ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
// repeat door visits after the cooldown (Spooky Doors, 2026-10-02); visit_seen keeps its one-row-per-campaign rule
await q(`CREATE TABLE IF NOT EXISTS visit_repeat (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
campaign_id INT NOT NULL,
email VARCHAR(190) NOT NULL,
day CHAR(10) NOT NULL,
ts BIGINT NOT NULL,
kind VARCHAR(8) NOT NULL DEFAULT 'door',
INDEX (email, day, kind),
INDEX (email, campaign_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS visit_seen (
campaign_id INT NOT NULL,
email VARCHAR(190) NOT NULL,
@@ -172,6 +263,30 @@ async function bootstrap() {
// sponsor CHAT (two-way) rides the same table: kind='chat' vs the default 'broadcast'
await alterSafe(`ALTER TABLE sponsor_messages ADD COLUMN kind VARCHAR(12) NOT NULL DEFAULT 'broadcast'`);
await alterSafe('ALTER TABLE sponsor_messages ADD INDEX idx_pair (to_email, from_email)');
// 2026-09-18: system notices used to be stored as 'broadcast', which is the kind the
// sign-in modal pops for — so a member with a backlog of payout notices got a fresh
// popup after every ad view. Retag the machine-generated ones so they stay in the inbox.
// Matched on subject, NOT on sender: these come from member 1 at ADMIN_EMAIL, which is
// also Marty's own member address, so his genuine broadcasts sit under the same sender.
// Idempotent — after the first pass nothing matches.
for (const like of ['You just got paid %POL on InstantAdPay',
'You missed %POL on InstantAdPay',
'%is trying to buy. %',
'You lost %payouts were not switched on%',
'% is now in your line for good%']) {
try { await q("UPDATE sponsor_messages SET kind='notice' WHERE kind='broadcast' AND subject LIKE ?", [like]); }
catch (e) {}
}
// ...but two of those DO need the member to act, and they lose money by not acting: a sale
// blocked or already lost because payouts are off, and a payout that passed them by. Those
// keep interrupting. The dividing line is "does this need you to do something", not
// "who sent it".
for (const like of ['You missed %POL on InstantAdPay',
'%is trying to buy. %',
'You lost %payouts were not switched on%']) {
try { await q("UPDATE sponsor_messages SET kind='alert' WHERE kind='notice' AND subject LIKE ?", [like]); }
catch (e) {}
}
// per-account chat settings: availability toggle (default on) + muted-member list (JSON emails)
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_available TINYINT NOT NULL DEFAULT 1');
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_mutes VARCHAR(4000) NULL');
@@ -203,6 +318,18 @@ async function bootstrap() {
burned_at BIGINT NULL,
INDEX (burned_tx)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
// credit activity ledger: one row per real credit movement (metered delivery rolls up per campaign per day)
await q(`CREATE TABLE IF NOT EXISTS credit_log (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(190) NOT NULL,
ts BIGINT NOT NULL,
day CHAR(10) NOT NULL,
delta INT NOT NULL,
kind VARCHAR(20) NOT NULL,
note VARCHAR(160) NOT NULL,
ref VARCHAR(40) NULL,
INDEX (email, ts), INDEX (email, kind, ref, day)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
// follow-up email sequence queue (one row per free account)
await q(`CREATE TABLE IF NOT EXISTS drips (
email VARCHAR(190) PRIMARY KEY,
@@ -215,7 +342,52 @@ async function bootstrap() {
INDEX (stopped, next_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await alterSafe('ALTER TABLE accounts ADD COLUMN joined_via VARCHAR(20) NULL'); // ?v= angle the lead came in on
await alterSafe('ALTER TABLE accounts ADD COLUMN joined_ref VARCHAR(80) NULL'); // referring domain of the first join-page visit
await alterSafe('ALTER TABLE accounts ADD COLUMN wall_offers VARCHAR(2000) NULL'); // JSON [{title,bannerUrl,targetUrl}] for wall positions 2-3 (unlock at 2 / 5 qualifying buyers)
await alterSafe('ALTER TABLE accounts ADD COLUMN profile_quarantined TINYINT NOT NULL DEFAULT 0'); // 2026-10-30 link-farm rule: first profile save of a new free account carried a link (spamscan.js)
await alterSafe('ALTER TABLE accounts ADD COLUMN bix_partner_link VARCHAR(300) NULL'); // BixPay partner link (bixpay.js, 2026-10-29); column name checked against MySQL 8 reserved words
await alterSafe('ALTER TABLE accounts ADD COLUMN theme VARCHAR(8) NULL'); // 2026-11-01 appearance: auto | light | dark (same column as LinkSpin)
// help desk (2026-10-16, tickets.js): one shared desk for IAP and, later, LinkSpin; email_message_id threads inbound mail
await q(`CREATE TABLE IF NOT EXISTS tickets (
id INT AUTO_INCREMENT PRIMARY KEY,
ref VARCHAR(20) NOT NULL UNIQUE,
platform VARCHAR(12) NOT NULL DEFAULT 'iap',
source VARCHAR(12) NOT NULL DEFAULT 'form',
email VARCHAR(190) NOT NULL,
name VARCHAR(80) NULL,
username VARCHAR(30) NULL,
subject VARCHAR(160) NOT NULL,
category VARCHAR(40) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'open',
priority VARCHAR(8) NOT NULL DEFAULT 'normal',
created BIGINT NOT NULL,
updated BIGINT NOT NULL,
last_member_at BIGINT NULL,
last_admin_at BIGINT NULL,
admin_unread TINYINT NOT NULL DEFAULT 0,
member_unread TINYINT NOT NULL DEFAULT 0,
INDEX (email), INDEX (status, updated), INDEX (platform, updated)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q(`CREATE TABLE IF NOT EXISTS ticket_messages (
id INT AUTO_INCREMENT PRIMARY KEY,
ticket_id INT NOT NULL,
author VARCHAR(8) NOT NULL,
body TEXT NOT NULL,
internal TINYINT NOT NULL DEFAULT 0,
attachments VARCHAR(400) NULL,
created BIGINT NOT NULL,
email_message_id VARCHAR(250) NULL,
via VARCHAR(12) NOT NULL DEFAULT 'web',
INDEX (ticket_id), INDEX (email_message_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
// help desk translations (2026-10-16): the English of a member message written in another language
await q(`CREATE TABLE IF NOT EXISTS ticket_translations (
message_id INT PRIMARY KEY,
ticket_id INT NOT NULL,
lang VARCHAR(8) NOT NULL,
body_en TEXT NOT NULL,
INDEX (ticket_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
}
// one-time import: only when the tables are empty and JSON files exist
@@ -257,4 +429,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 };
+86
View File
@@ -0,0 +1,86 @@
// discord-relay.cjs — mirror a Telegram group post into the Crypto Team Build Discord (relaunch 2026-10-09).
// Drop-in for every app that posts with the shared CTB Rewards bot. Call mirror() right where the app calls
// Telegram; it is fire-and-forget, never throws, and does nothing unless the DISCORD_WEBHOOK_* env is set.
// mirror({ chatId, threadId, text, photo, buttons })
// chatId the Telegram chat the post goes to. Only the community group is mirrored; DMs / alert chats are skipped.
// threadId forum topic: achievements (661565) -> #achievements, payments (632242) -> #payment-proofs,
// no topic (General) -> #achievements. Override with DISCORD_TOPIC_ACH / DISCORD_TOPIC_PAY.
// text Telegram HTML (converted to Discord markdown; user text is escaped so names with _ don't italicise)
// photo Buffer (uploaded) or a public image URL (embedded), optional
// buttons Telegram inline_keyboard (url buttons become links under the text), optional
// Env: DISCORD_WEBHOOK_ACHIEVEMENTS, DISCORD_WEBHOOK_PAYMENT_PROOFS, DISCORD_WEBHOOK_PROMOS, DISCORD_WEBHOOK_ANNOUNCEMENTS,
// DISCORD_WEBHOOK_OPS; DISCORD_TG_GROUP (default -1001258691510); DISCORD_RELAY=off to disable.
// The same post twice within 15 minutes (e.g. a badge sent to a topic AND to General) is mirrored once.
'use strict';
const crypto = require('node:crypto');
const GROUP = () => String(process.env.DISCORD_TG_GROUP || '-1001258691510');
const TOPIC_ACH = () => String(process.env.DISCORD_TOPIC_ACH || '661565');
const TOPIC_PAY = () => String(process.env.DISCORD_TOPIC_PAY || '632242');
const HOOKS = { achievements: 'DISCORD_WEBHOOK_ACHIEVEMENTS', 'payment-proofs': 'DISCORD_WEBHOOK_PAYMENT_PROOFS', promos: 'DISCORD_WEBHOOK_PROMOS', announcements: 'DISCORD_WEBHOOK_ANNOUNCEMENTS', ops: 'DISCORD_WEBHOOK_OPS' };
function hookFor(feed) { const v = String(process.env[HOOKS[feed]] || ''); return v.startsWith('https://discord.com/api/webhooks/') ? v : ''; }
function feedFor(threadId) { const t = String(threadId == null ? '' : threadId); if (t === TOPIC_PAY()) return 'payment-proofs'; if (t === TOPIC_ACH()) return 'achievements'; return 'achievements'; }
// ---- Telegram HTML -> Discord markdown ----
const ENT = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&apos;': "'", '&nbsp;': ' ' };
const unesc = s => s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, m => ENT[m] || m);
const escMd = s => s.replace(/([\\*_~`|])/g, '\\$1').replace(/^(\s*)([>#-])/gm, '$1\\$2');
const WRAP = { b: '**', strong: '**', i: '*', em: '*', u: '__', ins: '__', s: '~~', strike: '~~', del: '~~', code: '`', 'tg-spoiler': '||', spoiler: '||' };
function htmlToMd(html) {
const re = /<\/?([a-zA-Z-]+)(?:\s+[^>]*)?\/?>/g; const stack = []; let out = '', last = 0, inCode = 0, m;
const emit = t => { if (!t) return; const u = unesc(t); out += inCode ? u : escMd(u); };
const close = mk => { const ws = (/\s+$/.exec(out) || [''])[0]; out = out.slice(0, out.length - ws.length) + mk + ws; };
while ((m = re.exec(html))) {
emit(html.slice(last, m.index)); last = re.lastIndex; const raw = m[0], tag = m[1].toLowerCase();
if (tag === 'br') { out += '\n'; continue; }
if (!raw.startsWith('</')) {
if (tag === 'a') { const h = /href=(?:"([^"]*)"|'([^']*)')/i.exec(raw); stack.push({ tag, href: h ? (h[1] || h[2]) : '', start: out.length }); }
else if (tag === 'pre') { out += '```\n'; inCode++; stack.push({ tag, start: out.length }); }
else if (WRAP[tag]) { if (tag === 'code') inCode++; out += WRAP[tag]; stack.push({ tag, start: out.length }); }
} else {
let i = stack.length - 1; while (i >= 0 && stack[i].tag !== tag) i--; if (i < 0) continue;
const o = stack[i]; stack.length = i;
if (tag === 'a') { const inner = out.slice(o.start); out = out.slice(0, o.start) + (o.href ? '[' + inner + '](' + o.href + ')' : inner); }
else if (tag === 'pre') { out += '\n```'; inCode--; }
else if (WRAP[tag]) { if (tag === 'code') inCode--; close(WRAP[tag]); }
}
}
emit(html.slice(last)); return out.replace(/\n{3,}/g, '\n\n').trim();
}
// ---- sending: one queue per webhook, 1.2 s apart, 429 honoured ----
const queues = new Map(); const seen = new Map();
const sleep = ms => new Promise(r => setTimeout(r, ms));
function content(text, buttons) {
let c = htmlToMd(String(text || ''));
const links = []; try { for (const row of (buttons && buttons.inline_keyboard) || []) for (const b of row) if (b && b.url) links.push('[' + String(b.text || 'Open').replace(/[\[\]]/g, '') + '](<' + b.url + '>)'); } catch (e) {}
if (links.length) c += '\n\n' + links.join(' · ');
return c.length > 1990 ? c.slice(0, 1989) + '…' : c;
}
async function post(url, msg, attempt) {
const payload = { content: content(msg.text, msg.buttons), allowed_mentions: { parse: [] } };
let body, headers = {};
if (msg.photo && typeof msg.photo !== 'string') {
payload.attachments = [{ id: 0, filename: 'card.jpg' }];
const fd = new FormData(); fd.append('payload_json', JSON.stringify(payload)); fd.append('files[0]', new Blob([msg.photo]), 'card.jpg'); body = fd;
} else {
if (typeof msg.photo === 'string' && msg.photo) payload.embeds = [{ image: { url: msg.photo } }]; else payload.flags = 1 << 2;
body = JSON.stringify(payload); headers['Content-Type'] = 'application/json';
}
const r = await fetch(url + '?wait=true', { method: 'POST', headers, body, signal: AbortSignal.timeout(20000) });
if (r.status === 429 && (attempt || 0) < 2) { const j = await r.json().catch(() => ({})); await sleep((Number(j.retry_after) || 2) * 1000 + 250); return post(url, msg, (attempt || 0) + 1); }
if (!r.ok) console.error('[discord-relay] post failed http=' + r.status + ' ' + (await r.text().catch(() => '')).slice(0, 160));
}
function mirror(msg) {
try {
if (String(process.env.DISCORD_RELAY || 'on').toLowerCase() === 'off') return;
if (!msg || String(msg.chatId || '') !== GROUP()) return;
const feed = msg.feed || feedFor(msg.threadId); const url = hookFor(feed); if (!url) return;
const key = crypto.createHash('sha1').update(feed + '\n' + String(msg.text || '') + '\n' + (Buffer.isBuffer(msg.photo) ? msg.photo.length : String(msg.photo || ''))).digest('hex');
const now = Date.now(); for (const [k, t] of seen) if (now - t > 15 * 60000) seen.delete(k);
if (seen.has(key)) return; seen.set(key, now);
const prev = queues.get(url) || Promise.resolve();
queues.set(url, prev.then(() => post(url, msg, 0)).catch(e => console.error('[discord-relay]', e && e.message)).then(() => sleep(1200)));
} catch (e) { console.error('[discord-relay]', e && e.message); }
}
module.exports = { mirror, htmlToMd, feedFor };
+99
View File
@@ -0,0 +1,99 @@
# BixPay card integration (DRAFT for Marty, 2026-10-29)
Scope: InstantAdPay first, LinkSpin second, CTB when it launches. Nothing here is built yet.
## What we know about BIX (verified 2026-10-29)
- BIX = self-custody wallet + Visa card spent from USDT/USDC. Funding networks include Polygon, so a member can swap POL
to USDT in the BIX app and load the card with no bridge. No load fee; up to 3% per purchase, 1% FX.
- Cards: virtual $9.99, plastic $100, metal $250, gold $25,000. US = Visa Signature (29 states); elsewhere Visa Platinum.
- Partner plan: 50% of net fees and card sales -> 45% over 10 levels (15 / 10 / 2.5 x 8) + 5% pool.
- Partner link format: `https://bix.ibportal.io/auth/register?e=<43-char token>&a=1` (opaque token, not derivable from the
IB ID). The referral link (`&appId=3`) makes a card customer only; the PARTNER link makes a partner. We use the partner link.
- Company fallback link: Marty's partner link (IB12143793).
## 1. The profile field (one identity, follows the member)
- InstantAdPay Profile tab, new section **"BixPay card"**: one input, `bixPartnerLink`.
- Accepts a full partner link. Validation: host `bix.ibportal.io`, path `/auth/register`, `e=` present, `a=1`; strip `appId`
if pasted (the customer link) and tell the member "That's the card-customer link. Paste the Partner link from your BIX
portal profile instead." Max 300 chars. Saved on the IAP account; LinkSpin and CTB read it through the existing partner
API (the same way wallet and sponsor already flow), and LinkSpin's own Profile shows it read-only with "Edit on InstantAdPay".
- Member sees under the field: "Where to find it: BIX portal > Profile > Partner (the second box). Copy the link."
- Admin: the field shows on the member card; a count of members with a link set on the admin Overview.
## 2. The link each visitor gets (sponsor follows)
`bixLinkFor(member)` =
1. the member's own `bixPartnerLink`, else
2. walk the sponsor chain up to 10 levels, first sponsor with a link, else
3. the company link (site config `bixCompanyLink`, default Marty's partner link).
The card promo always shows WHOSE link is in play: "Your link" / "Your sponsor @name's link" / "Network link". That nudges
members to add their own, and sponsors to get their teams signed up.
For public pages (games' landing pages, /join/<user>), the referrer whose `?ref` is on the page resolves the same way.
## 3. Where members see it
### Wallet tab (primary)
Card: **"Spend your POL anywhere with a BixPay Visa card"**
"BixPay is a self-custody wallet with a Visa card. Send USDT or USDC to it on Polygon, load the card, and spend it wherever
Visa is accepted, including Apple Pay and Google Pay. Virtual cards from $9.99."
(No in-app swap: Marty confirmed 2026-10-29 he swaps POL to USDT/USDC on an exchange, then sends it to BixPay. The guide
gets a "turn your POL into USDT" step: any exchange or on-ramp, then send on Polygon. Add the swap line only once BIX
ships it; the founder said "in the next three months" on 10-17.)
Buttons: **Get your BixPay card** (partner link) · **How it works** (opens the guide).
Small line: "Using: your link / @sponsor's link / the network link. Add yours in Profile."
### Overview
A one-line announcement card the first week ("New: a Visa card for your POL"), dismissable like the other cards.
### Payout emails + game "link your wallet" nudges
One sentence after the amount: "Want to spend it? A BixPay Visa card turns POL into everyday purchases: <link>."
(Payout emails already carry the member's identity, so the link resolves per member.)
### Promo tools > new tab "BixPay"
- The member's link with Copy/Share.
- 3 posts (short, friendly, the "spend your crypto" angle), an email swipe, and 4 banners we make (no BIX logo until
Marty confirms brand rules; text-only "crypto Visa card" creative is safe).
- Every asset carries the member's resolved link.
### Guide page /bixpay (public, SEO)
What it is, the fee table, the funding path (POL -> USDT on Polygon -> card), the sign-up steps with screenshots, the
partner plan in plain words, and the compliance box. CTA carries the viewer's resolved link.
### Chatbot
Canned answers: what BixPay is, how to get the card, how to load it from POL, where to put my partner link, who gets the
credit. Facts in the system prompt with KNOWLEDGE_DATE.
## 4. Copy (Marty's voice, no em dashes)
- Wallet card title: "Spend your POL anywhere with a BixPay Visa card"
- Body: see above.
- Profile field label: "Your BixPay partner link"
- Profile help: "Join BixPay as a partner, then paste your Partner link here. Members and visitors who get a card through
your pages are credited to you in your BIX portal, up to ten levels deep."
- Email line: "Want to spend it? A BixPay Visa card turns POL into everyday purchases."
- Post 1 (short): "I spend my crypto with a Visa card now. BixPay keeps the keys with you, loads from USDT or USDC with no
load fee, and works with Apple Pay. Virtual card from $9.99: {L}"
- Fees line everywhere: "3% per purchase, no load fee. See BIX's terms for other charges."
- US line on the Wallet card and guide: "Available in 31 US states so far. Not in your state yet? You can still get the
wallet and build."
- Guide: a "Funding your card" section with three paths: (1) swap POL to USDT or USDC on any exchange, send on Polygon;
(2) Cash App (US): send crypto straight to the BixPay wallet; (3) the BIX in-app swap, once it ships.
- Post 2 (friendly): "Earning crypto is one thing. Spending it without jumping through hoops is another. BixPay fixed that
for me: a self-custody wallet and a Visa card in one app. Here's where I got mine: {L}"
- Post 3 (partner angle): "BixPay pays partners on every card and on card spending, ten levels deep. If you're building a
team anyway, this fits right in: {L}"
## 5. Compliance box (shown on the Wallet card's "How it works" and the guide)
"BixPay is a separate company. BIX issues the wallet and the card through its banking partners and sets its own fees,
limits, eligibility and terms. InstantAdPay is not the card issuer and earns a referral commission when you sign up
through a partner link. Card availability varies by country. Crypto assets can lose value."
## 6. Tracking
- Click counts per surface (wallet card, email, promo tools, guide) in the admin Traffic tab; per-member click counts on
the Promo tools BixPay tab. No sign-up credit on our side: the BIX portal shows each partner their directs and levels.
- If BIX ever offers a postback, add a "BixPay sign-ups" stat next to the click counts.
## 7. Rollout
1. IAP: field + resolver + Wallet card + guide + chatbot + promo tab (gated by site config `bixpayLive`).
2. LinkSpin: read-only field + Wallet/Credits card + promo entry, same resolver through the partner API.
3. CTB: same card and field in ctb-next, same identity.
4. Announcement (release note + member email + Telegram) after Marty's copy approval.
## Open questions for Marty / BIX upline
- Does a partner sign-up also get the card, or does the member need the app invitation too? (If both: show "Join as a
partner" and "Just want the card?" buttons, each with the member's own link type.)
- BIX name/logo use in our promo material.
- The pool's "50/50 rule".
- Any updated BIX materials.
+38
View File
@@ -0,0 +1,38 @@
# BixPay opportunity call, 2026-10-17 (Zoom replay notes, made 2026-10-29)
"$iNVU - Live Opportunity Call", 47 min. Host "Bass"; main speaker David Emenite (22-year network marketer; his own company
is a trading opportunity, "tap to trade"); BIX founder "Nick" (28, Germany, says he owns "one of the largest Forex brokers
on the planet"; BIX started "a couple of months ago"); leaders Tracy Fischer, Lisa, Alan Jones, Gary. The $iNVU / trading
company parts are NOT BIX. Transcript: D:/tmp/bix-zoom/transcript.txt; slides D:/tmp/bix-zoom/frames.
## Plan mechanics (as presented; matches the BIX commission PDF)
- The only fee claimed: 3% per transaction. "No top-up fees, no hidden fees." (A third-party review lists 1% FX, $0.75
under $50, ATM $1 + 0.6%, so present 3% as THE fee and point to BIX's terms for the rest.)
- 50% of the 3% goes into the plan; paid over 10 levels: L1 15%, L2 10%, L3-L10 2.5% each; the other 5% = BIX pool,
1 share per 10,000 cards in your network. Worked example: $1,000 spent -> $30 fee -> $15 into the plan.
- Card sales pay too: slide "EARN A 50% REFERRAL BONUS ON EVERY CARD PURCHASE" (virtual $9.99, plastic $100, metal $250,
24K gold $25,000; shipping to 179 countries). The optional $9.99/month rewards membership is also commissionable.
- Upcoming banking (SEPA IBAN, ACH, SWIFT, fiat on/off-ramp): instant 0%, SEPA/ACH 1%, "up to 50% included in the
compensation plan". Nick: IBANs and the in-app SWAP "in the next three months", i.e. NOT live on 10-17.
- Shareholder: 500,000 cards in your network "on a 50/50 rule" = shareholder of BIX (Nick). Network contest: first to
10,000 cards gets a $100,000 bonus. The 50/50 rule is still not defined on the call.
- US: "open in 31 states" (review on 10-24: 29), rest "first part of 2027". Wallet works everywhere; you can build from a
closed state. KYC required for the card; problems go to BIX support.
- Funding tip (Tracy/Bass): Cash App can send crypto straight to the BixPay wallet (about 20 transactions a month, up to
$5,000 a week); they used Coinbase before. Card works in Apple Wallet.
- Usage data quoted: average customer spends $1,400-1,500 a month (industry figure); Bass's back office shows $20-80 a
week per user so far.
## Claims to treat as marketing, not facts
300,000 downloads / 300,000 cards active, $3M spent per day, live since August with global launch ~6 weeks before the
call, "5 million users in one year, 80 million in three, bigger than Revolut", "worth a couple hundred million, $100B in
three years", "$1 to $1 million per day" spend limit, $2.6T daily payments, founder "a billionaire".
## What it changes in our integration draft (BIXPAY-INTEGRATION.md)
1. Don't promise an in-app swap yet. Copy becomes "load it with USDT or USDC on Polygon" until Marty confirms Swap works
in his app; add a short "how to turn POL into USDT" step (any exchange or the BIX swap once live).
2. Fees line: "3% per purchase, no load fee; see BIX's terms for other charges."
3. Lead with the $9.99 virtual card: it pays the referrer on the sale and on every swipe after.
4. US members: add "available in 31 states; not in your state yet? You can still build and get the wallet."
5. Add the Cash App funding path to the guide for non-crypto members (US).
6. Events in the call (Houston 10-20, Tampa 10-21, Bangkok 11-28) are the leaders' own, not ours.
+72
View File
@@ -0,0 +1,72 @@
# Release note draft: the Game Pass (not sent)
Status: DRAFT for Marty's review. Nothing below has been posted, emailed or published. Dates are placeholders until the caps start
date is set in Admin > Settings (`capsStartDate`) and `gamePassEnabled` is switched on.
## Short version (Telegram / feed)
The games now have a Game Pass: $5 for 7 days, all nine games on one account. Free play keeps paying real POL every day. The Pass
plays more: higher daily caps across every game, a seat in the weekly Pass Tournament with POL prizes, extra plays or a perk in each
game, and the Pass badge. Members > Games > Game Pass. From [DATE] the daily POL caps are account-wide: free play 0.30 POL a day on
repeatable rewards and 2 POL a day in all; with the Pass 1.50 and 5. One-time rewards you earn over the cap are never lost; they pay
over the next days.
## Release note (Admin > Releases, member-facing)
**The Game Pass: more game across all nine games**
Every member earns real POL in our games, and that does not change. What is new:
- **The Game Pass.** $5 for 7 days, one pass for your whole account (linked positions share it), covering PolHunter, Gem Kingdom,
SpellWheel, PolyWarriors, Road Agent, ClutterHunt, PolyBreak, Drip Runner and Spooky Doors while its season runs.
- **What it does.** Higher daily POL caps in every game (1.50 POL a day on repeatable play instead of 0.30, and 5 POL a day in all
instead of 2), a place in the weekly **Pass Tournament**, extra plays or a perk in each game (more PolHunter missions, a free
continue in Gem Kingdom, a free hint in SpellWheel and ClutterHunt, an extra patrol in Road Agent, a starting shield in Drip
Runner, an extra paddle in PolyBreak, an extra mission in PolyWarriors, an extra door in Spooky Doors), and the Pass badge.
- **How to get it.** Members > Games > Game Pass. Tap Get the Pass, then buy a new package of $5 or more. The pass starts the
moment that purchase settles. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your
ads. Credits you already hold never buy a pass. Buying again while a pass is active adds 7 days.
- **Account-wide daily caps, from [DATE].** Until now each game had its own daily limit. From [DATE] the limit is one number for
your whole account across all the games, reset at midnight Central: free play 0.30 POL a day on repeatable rewards (finds, daily
puzzles, patrols, gems, drips) and 2 POL a day for everything; with the Pass 1.50 and 5. A one-time reward (a boss, a chapter, a
sector, a room) never changes and is never lost: whatever is over the day's total carries to the next day until it is paid in
full. A 10 POL boss still pays 10 POL, over a few days.
- **The weekly Pass Tournament.** Monday to Sunday, Central time, pass holders are ranked by their plays across all the games. The
prize pool is 5% of that week's pass sales, paid in POL to the top three (50 / 30 / 20) and posted in Game Achievements on
Monday morning.
The Pass does not change what any reward pays. Free play pays; the Pass plays more.
## Announcement timing
- One week before `capsStartDate`: post the short version, publish this note, switch `gamePassEnabled` on so members can buy
ahead of the caps.
- On `capsStartDate`: the caps enforce themselves at midnight Central; nothing to deploy.
- First Monday 9 AM Central after launch: the first tournament settles and posts by itself (only while `gamePassEnabled` is on).
## Wording rules (chatbot, posts, pages)
Never "earn more", "pays for itself", "income". Always "free play pays; the Pass plays more". Reward amounts never change with the
Pass. Caps are per account, per Central day. Deferred progress rewards are "paid over the next days", never "lost".
## Update draft, 2026-10-22: how the Game Pass is paid (not sent)
Status: DRAFT for Marty's review. Nothing has been posted, emailed or published.
**Short version (Telegram / feed)**
A change to how the Game Pass is paid: from today every pass is paid by a new package purchase. Tap Get the Pass in Members >
Games, buy a package of $5 or more, and the pass starts the moment it settles. Your sponsor and team are paid from that package,
and you keep all of its credits for your ads. Credits you already hold no longer buy a pass. Passes you already have keep running.
**Release note (Admin > Releases)**
**The Game Pass is now paid with a new package**
- Tap Get the Pass (or Get on any pass) in Members > Games. Then buy a package of at least the pass price: $5 for the weekly Game
Pass.
- The pass starts the moment that purchase settles on chain. A package bought before you tapped Get does not count.
- Your sponsor and team are paid from that package exactly like any other package, and every credit of the package stays yours for
your ads.
- Credits you already hold, earned or purchased, no longer buy a pass.
- Any pass you already have keeps running to its end date.
+379
View File
@@ -0,0 +1,379 @@
# Game Pass: draft spec (2026-10-16)
> **PAYMENT RULE CHANGED 2026-10-22 (Marty): every pass is paid by a FRESH on-chain package purchase; no pass is ever bought with
> credits again.** See "Payment: the package rail" at the end. Older sections below that mention credits describe the rule as it was.
Marty's direction (10-16): a $5 weekly Game Pass that covers all nine games and raises the daily POL cap; a tighter
free cap so nobody farms the games all day for free. Pass = "more game", never pitched as payback. Free play keeps
paying real POL (the "paid before they ever pay" funnel in the presentation, deck and guide).
## 1. What the games pay today (live settings, 7-day earnings to 2026-10-16)
Two kinds of POL rewards exist in every game:
- **Progress rewards**: one-time per account (first clear of a stage, boss, sector, rival, chapter, room). Finite.
- **Daily play rewards**: repeatable every day (finds, daily puzzle, patrol, gems, drips). This is the "all day" risk.
| Game | Progress rewards (one-time, POL) | Daily play rewards (repeatable) | Game cap/day | Players (7d) | Median / p90 / max per player-day | POL out / week |
|---|---|---|---|---|---|---|
| PolHunter | none | finds 0.05-1.00 (skewed small), 3 missions/day | 40 | 38 | 0.48 / 0.97 / 4.04 | **102.1** |
| Gem Kingdom | stages 0.02-0.15; bosses 0.25 / 0.5 / 2 / 5 / 7.5 / **10** | none | 40 | 25 | 0.46 / 11.35 / **25.49** | **101.4** |
| SpellWheel | levels 0.02-0.05; chapters 0.25-1 | daily puzzle 0.03, streak 0.15 | 20 | 102 | 0.04 / 0.16 / 1.50 | 17.6 |
| Spooky Doors (to Oct 31) | ladder 0.1 / 0.25 / 0.5 / 1 / 2 | none | 25 | 11 | 0.85 / 1.00 / 2.00 | 10.7 |
| PolyWarriors | rivals 0.02-0.10, ladder 0.5, elite 0.12-0.5, elite clear 2 | none (PvP pays Circuits) | 20 | 10 | 0.18 / 1.09 / 4.94 | 8.8 |
| ClutterHunt | per room: clear 0.05, 3-star 0.05, expert 0.15, expert stars 0.10 | none | 20 | 13 | 0.20 / 0.95 / 1.05 | 6.4 |
| PolyBreak | rounds 0.02 / 0.03 / 0.05 | gems 0.01-0.15, up to 0.5/day | 5 | 39 | 0.02 / 0.06 / 0.12 | 1.3 |
| Drip Runner | chapters | drips 0.05, items | 5 | 15 | 0.05 / 0.15 / 0.25 | 1.2 |
| Road Agent | sectors 0.05-1.00 (3.60 total) | patrol 0.03/day | 25 | 5 | 0.08 / 0.16 / 0.16 | 0.5 |
| **All games** | | | | | | **~250 POL/week (~$23 at 9c)** |
PolHunter and Gem Kingdom are 81% of the burn. PolHunter is repeatable play (and every find is a delivered sponsor
visit, so that burn delivers advertiser inventory). Gem Kingdom's burn is its boss amounts: one player took 25.5 POL in
a single day. No other game pays more than 2 POL for any single reward.
## 2. The pass
- **$5, 7 days, all nine games.** One pass per account; buying while active extends by 7 days.
- (Superseded 2026-10-22, see "Payment: the package rail".) Paid with **purchased-grade credits only** (500 credits = the $5 package), through the existing game-purchase path
(`ads.gamePurchase` with `purchasedOnly`, the same rule as PolyWarriors mint passes). A $5 package bought while a pass
order waits fulfils it (the `pwpasses` pattern). Earned credits never buy a pass, or no money enters and the pass is
just a free cap increase.
- Money flow is the normal on-chain split of the $5 package: $2.50 sponsor, $1.00 level 2, $0.50 level 3, $1.00 company.
The company's $1 is what funds the extra POL; the games' 30% pool-share rule is an allowance, not cash.
## 3. Caps (account-wide, across all nine games)
| | Free | Pass |
|---|---|---|
| Daily play rewards (repeatable) | **0.30 POL/day** | **1.50 POL/day** |
| Everything (progress + daily), paced | **2.0 POL/day** | **5.0 POL/day** |
| Progress rewards | unchanged amounts for everyone; excess over the daily total **carries to the next day** (never lost) | same |
Why these numbers:
- Free 0.30/day sits under PolHunter's median (0.48) and SpellWheel's p90 (0.16 stays free). The regular PolHunter
hunter is the natural pass buyer; the casual SpellWheel player never notices.
- Pass 1.50/day is above today's p90 for every game, so a pass holder keeps everything they earn today and more.
Max repeatable per pass week = 10.5 POL (~$0.98), so the pass can never pay for itself and multi-accounting can't win.
- The paced total cap stops the Gem Kingdom spike (25 POL in a day) without changing any reward amount: a 10 POL boss
still pays 10 POL, over a few days.
- Company per pass: $1.00 in, at most $0.98 out if a holder maxes the repeatable cap every day. Realistic use (about
half) nets about $0.50 a pass. Progress rewards were payable to free players already, so the pass adds no cost there.
**DECIDED (Marty, 2026-10-16): Gem Kingdom's bosses stay at 5 / 7.5 / 10 POL.** "We need one that pays out bigger like
that anyway." The paced total cap spreads a big boss payout over a few days; the amounts do not change.
## 3a. API contract (both sides build to this)
> **Built 2026-10-16 (IAP side). Clarifications and additions to this contract, none of them breaking:**
>
> 1. **Where the endpoints live.** `GET /api/partner/player` exists today on each GAME (IAP reads the player's card line from it).
> The pass and caps version below is served by **IAP** (`https://instantadpay.com/api/partner/player`), so a game CALLS it; nothing
> changes on the game's own endpoint. Same for `polgrant`, `polgrant/void` and `tournament/*`: all on IAP.
> 2. **Signature, spelled out.** Each game signs with the shared secret it already holds (its `*_SSO_SECRET`; PolHunter uses
> `HUNT_SSO_SECRET`). 10-minute window on `ts` (ms).
> - `GET /api/partner/player?game=<slug>&m=<memberId>&e=<email>&ts=<ms>&sig=<hex>` with
> `sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts)`, `who` = memberId when > 0, else the lowercased email (the same string
> the games already compute for IAP's calls to them, with `game` added so IAP knows which secret to check).
> - `POST` endpoints: JSON body that includes `game: <slug>`, headers `X-Game-Ts: <ms>` and
> `X-Game-Sig: HMAC-SHA256(secret, ts + '\n' + rawBody)` hex (sign the exact bytes you send).
> - `GET /api/partner/tournament/pending?game=<slug>&ts&sig` with `who = 'tournament'`.
> 3. **`email` is accepted beside `memberId`.** Players who have not linked a wallet have `memberId: 0` in every hand-off token; send
> `email` too (the token has it) and IAP resolves the account by email. A linked position's member id resolves to the owner's
> account: the pass and the caps are per ACCOUNT.
> 4. **Extra fields in answers** (additive): `polgrant` also returns `carried` (POL paid from an earlier day's deferral, already
> inside `allowed`), `capHit` (`'daily'|'total'|null`), `enforced` (false before `capsStartDate`), `repeat` (true when the ref was
> already answered), `voided`. `caps` also has `enforced`, `pass` and `pending` (POL deferred for this game, not yet paid).
> `player` also returns `memberId, username, wallet, suspended, gamePassEnabled`. A suspended account gets `allowed: 0,
> suspended: true` and nothing is recorded (a cleared account can replay the ref).
> 5. **Carry-forward counts against the later day's total cap** (that is what "paced" means): a 10 POL boss on a 2 POL/day free
> account pays 1.7-2.0 a day until done, paid before that day's new grants. Carry-forward only happens on a LATER Central day
> than the deferral and only to the same game; the reply that carries it says `carried`.
> 6. **`void` reverses only that ref's own share** (its `allowed` on its day and whatever of its deferral is still queued). POL it
> already caused to be carried on a later day belongs to that later day and stays. The ref remains answered as voided.
> 7. **Hand-off tokens carry the flag** as `gamePass: { active, until }` (not `pass`, which the in-game sign-in flow already uses for
> its session token). Apply perks from it at sign-in; refresh from `player`/`polgrant` answers.
> 8. **Tournament prize payout seam.** IAP records the winners and POL amounts; a game faucet (Road Agent pattern) pays them:
> `GET /api/partner/tournament/pending` answers `{ ok, rows: [{ week, place, email, memberId, wallet, pol, ... }] }` (the same
> list is also under `pending`, the admin pane's name) for the rows still unpaid, and the paying game calls
> `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. PolHunter's faucet pays them
> (`polhunter/lib/tournament.js`, see "Games: as built"); Admin > Game Pass shows the unpaid rows meanwhile.
> 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the
> Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skipped the credit charge (retired 2026-10-22: there is no charge any more; the dev purchase event takes `minedAt`, `now` and `tx`).
IAP is the single source of truth for the pass and for the account-wide caps. Every game already signs partner calls
with its shared secret (the `/api/partner/player` pattern); the new calls use the same auth.
- `GET /api/partner/player?...` (existing) additionally returns `pass: { active: bool, until: ms|null }` and
`caps: { daily: n, total: n, used: { daily: n, total: n }, day: 'YYYY-MM-DD' }` (Central day).
- `POST /api/partner/polgrant` body `{ memberId, game, kind: 'daily'|'progress', pol, ref }` (ref = the game's own
idempotency key, e.g. `sector:3`, `find:<id>`). Response `{ allowed: n, deferred: n, pass: bool, day }`.
- `kind: 'daily'`: `allowed = min(pol, dailyCapRemaining, totalCapRemaining)`, the rest is DROPPED (never deferred).
- `kind: 'progress'`: `allowed = min(pol, totalCapRemaining)`, the rest is DEFERRED: IAP stores it and the game's
next call (any kind) on a later day gets it added to `allowed` first (carry-forward). Nothing is ever lost.
- Same `ref` twice = same answer (idempotent). Fail closed: if the game cannot reach IAP it grants nothing and retries
the same ref later.
- `POST /api/partner/polgrant/void` `{ memberId, game, ref }` when a game decides not to pay after all (rare).
- Settings on IAP (Admin > Settings, no deploy): `gamePassEnabled`, `gamePassPriceCredits` (500), `gamePassDays` (7),
`capFreeDaily` 0.30, `capFreeTotal` 2.0, `capPassDaily` 1.50, `capPassTotal` 5.0, `capsStartDate` (the free caps apply
only from this Central date; before it, the games' own caps stand, so the change can be announced a week ahead),
`passTournamentPct` 5.
- Pass purchase (superseded 2026-10-22: Buy only opens an order, a fresh package fulfils it): `POST /api/my/gamepass/buy` spends 500 purchased-grade credits (`ads.gamePurchase` with
`purchasedOnly`); a $5 package bought while a pass order waits fulfils it (the `pwpasses` pattern). Buying while active
extends `until` by 7 days. The Games tab shows the card, the state, and the expiry.
- Games get the pass flag at the sign-in hand-off and on every `polgrant` response; apply perks locally.
## 4. Pass perks per game (more game, not more payback)
| Game | Pass perk (besides the higher caps) |
|---|---|
| PolHunter | 5 missions/day instead of 3; Ad Detective twice a day. Finds still require the sponsor visit. |
| Gem Kingdom | one free continue per day (small, so Crowns sales are not undercut) |
| SpellWheel | streak bonus 0.15 -> 0.30; one free hint a day |
| PolyWarriors | +1 daily mission; defense pay 15 -> 25 Circuits; Pass mark on the warrior card |
| Road Agent | 2 patrols/day; +25% scrap. Fuel stays a sponsor visit. |
| ClutterHunt | 2 free hints a day |
| PolyBreak | gem cap 0.5 -> 1.5/day; one extra paddle per round |
| Drip Runner | a shield at the start of every run |
| Spooky Doors | +1 door a day while the season runs |
| All games | **Weekly Pass Tournament**: cross-game leaderboard (finds, clears, wins), prizes from 5% of pass sales (25c per pass) in POL; Pass badge; gold profile frame |
Ad-visit mechanics (fuel, Crowns, hints, refuels) stay as they are. Those verified visits are what advertisers pay for.
## 5. Build outline
1. **IAP (central):** durable `gamepass` map {email: {until, history}}; `GET /api/partner/player` returns `pass:{active, until}`;
new `POST /api/partner/polgrant` {member, game, kind: progress|daily, pol} -> {allowed, deferred} enforcing the
account-wide caps (fail closed when IAP is unreachable; games retry); Games tab card "Game Pass: $5 for 7 days, all
games"; buy flow via purchased credits or the $5 package; admin: passes sold, POL out per pass, cap hits.
2. **Each game:** read the pass flag at the sign-in hand-off; call `polgrant` before every POL grant (replaces each game's
own `dailyCapPol` for the account-wide rule; keep the local cap as a backstop); pace deferred progress rewards (queue,
pays out next day); apply its perk; show "Pass" state and a "Get the Pass" nudge when the free cap is hit.
3. **Tournament:** weekly job on IAP ranks pass holders across games, pays prizes from the games' wallets, posts to the
Game Achievements topic.
4. **Chatbot, release note, presentation games slide, and the guide's games section**: say "free play pays; the Pass
plays more" (never "earn more").
5. **QA:** iap-qa plus a scripted run per game: free cap hit -> nudge; pass bought -> cap raised; progress reward over
the cap -> paid the next day; pass expiry -> back to free caps.
## 6. Rollout
- Announce one week ahead (the free cap change affects today's PolHunter regulars). First week: pass at $5 with a
launch tournament; watch passes sold, POL out per pass, free-tier burn, verified visits delivered.
- Review after 14 days against: company net per pass >= $0.40, free burn under 150 POL/week, no drop in visit deliveries.
## Built (IAP side, 2026-10-16)
Everything below is on IAP, behind `gamePassEnabled` (default off). The caps are recorded from day one and ENFORCED only from
`capsStartDate`, so the change can be announced a week ahead and Admin can read what the caps would have done meanwhile.
**Files**
- `gamepass.js` (new): pass store, waiting orders, cap ledger (`DATA_DIR/gamepass-ledger.json`, refs kept 90 days), tournament,
admin stats, prune. Durable persisted maps `gamepass`, `gporders`, `gpprizes` (added to the DURABLE set in server.js so a deploy
never wipes them).
- `server.js`: settings defaults, init + hourly tournament tick + 6-hourly prune, purchase-event fulfilment (inside the
`marks.claim` block, so two app copies never double-fulfil), partner helpers (`GP_SECRETS`, `gpPartnerCheck`, `gpResolve`,
`gpDevNow`), `polUsdLive()` (catalog rate, 10-minute cache), `gpClaim` (the `gamePass` claim on every sign-in hand-off token,
including PolHunter's), and the endpoints below.
- `public/my.html` + `public/assets/my.js`: the Game Pass card at the top of Members > Games (state, caps line, Buy/Extend with
`IAP.confirmBox`, waiting state with a Buy-a-package button), deep link `/my#games?pass=1` (setPane now strips a `?query` from
the hash and highlights the card), the Overview nudge card `gpNudge` (shown once a day per browser after a game reports a free-cap
hit, never to pass holders). Asset tag bumped to `my.js?v=20261016a`.
- `public/admin.html` + `public/assets/admin.js`: Admin > Game Pass pane (passes sold week/total, active, POL out per pass week,
free/pass cap hits, deferred queue, tournament last run + unpaid prizes, "Settle last week now", comp a pass). Tag
`admin.js?v=20261016gp`.
- `chatbot.js`: canned answer + FACTS line, `KNOWLEDGE_DATE` 2026-10-16.
- `qa/gamepass.mjs` (new, `bash qa/run.sh gamepass`), `qa/walk.mjs` (Games tab card on/off + admin pane), `qa/run.sh`.
- `docs/GAME-PASS-RELEASE.md`: the member-facing release note draft (not sent).
**Settings** (Admin > Settings > Site settings; all read live, no deploy): `gamePassEnabled` ('0'), `gamePassPriceCredits` (500),
`gamePassDays` (7), `capFreeDaily` (0.30), `capFreeTotal` (2.0), `capPassDaily` (1.50), `capPassTotal` (5.0), `capsStartDate` ('',
Central YYYY-MM-DD), `passTournamentPct` (5), `telegramGamesTopicId` ('661565'), `telegramGamesChatId` ('' = the shared echo chat).
**Endpoints**
- Members: `GET /api/my/gamepass` -> `{ enabled, active, until, price, days, usd, waiting, bought, caps, capsStart, lastCapHit,
tournament }`; `POST /api/my/gamepass/buy` -> `{ ok, active, until }` or `{ needPay: true, payUrl: '/my?from=gamepass#buy',
order, price, need }`. Spends `gamePassPriceCredits` purchased-grade credits through `ads.gamePurchase(purchasedOnly)` with the
credit-log label "Game Pass (7 days)"; short = waiting order, fulfilled by the next $5+ package purchase event.
- Games (signed, see 3a): `GET /api/partner/player`, `POST /api/partner/polgrant`, `POST /api/partner/polgrant/void`,
`GET /api/partner/tournament/pending`, `POST /api/partner/tournament/paid`.
- Admin: `GET /api/admin/gamepass/stats`, `POST /api/admin/gamepass/comp { email, why }`,
`POST /api/admin/gamepass/tournament/run { week?, force? }`.
**Tournament job**: hourly tick; once Monday 9 AM Central has passed and the closed week (Mon 00:00 to Mon 00:00 Central) has no
row, exactly one app copy (`marks.claim('gamepass-tournament:<week>')`) ranks the week's pass holders by grants reported through
`polgrant` (progress and daily weigh the same, one point per ref with pol > 0), pool = `passTournamentPct` of the week's pass sales
in USD at the live catalog POL rate, split 50/30/20, rows recorded in `gpprizes` as pending, top 3 posted to the Game Achievements
topic (`telegramGamesTopicId`, only when enabled), winners get an inbox notice (kind `notice`). Comps (`/comp`) are passes, not
sales. If the POL rate is unavailable the tick retries next hour.
**Known limits / follow-ups**
- The cap ledger is a JSON file on the volume (like the other IAP side stores), not a MySQL table: during the ~30 s deploy overlap
two app copies each hold their own copy and the last save wins. A grant answered by the copy that is about to stop could be
re-answered fresh by the other on retry. Move `refs`/`days` into MySQL if the games report drift.
- `qa/gamepass.mjs` stubs the credit charge (`devPaid`) for the "buy -> active" step: `ads.gamePurchase(purchasedOnly)` needs a
position with on-chain package credits, which a local copy without RPC cannot have. The "short -> waiting order -> package fulfils
it" step runs the real path. The purchasedOnly charge itself is the live PolyWarriors mint path.
- Prize POL is not sent by IAP (see 3a item 8): PolHunter's faucet pays the pending rows every 10 minutes behind `GAMEPASS=on`;
the Games pane lists whatever is still unpaid.
- Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the
Game Pass keys show in the Site settings form).
## Pass tiers: Explorer, Champion, Sovereign, Legend (IAP side, 2026-10-18; restructured 2026-10-22)
Spec: `ultima-rpg/docs/IAP-PASSES-SPEC.md`. Marty approved the safe form on 2026-10-18 (never more POL) and Dallas's new structure
on 2026-10-22 (plus Sovereign and the yearly Legend). On 2026-10-25 Marty set every tier price to an InstantAdPay one-click
package amount ($5, $10, $20, $50, $100, $250, $500), so the cheapest qualifying package is exactly the pass price and the pass
comes with that package's ad credits (was $19.99 / $39.99 / $99.99 / $249.99). The weekly pass is unchanged. Everything above weekly stays
switched off for members (`sovTiers` 0) until Marty flips it.
| Tier | Name | Price | Length | In Shards of Valor (each includes everything below) |
|---|---|---|---|---|
| `weekly` | Game Pass | 500 credits ($5) | 7 days | the Game Pass in all nine games, the Sunless Vault, weapons unlocked |
| `explorer` | Explorer | 2000 ($20, the Activation package) | 30 days | weapons, gear, 2 DLC islands |
| `champion` | Champion | 5000 ($50, the Builder package) | 30 days | weapons, gear, 4 DLC islands of your choice, level cap 30 |
| `sovereign` | Sovereign | 10000 ($100, the Growth package) | 30 days | weapons, gear, all DLC islands, level cap 40 |
| `legend` | Legend | 25000 ($250, the Leader package) | 365 days | weapons, gear, all DLC islands, every bonus hero while active, level cap 40 |
**Bonus heroes (2026-11-05, Marty approved).** Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin are
SOLD ONE TIME (no subscription, no expiry), not by a tier: $20 each (2000 cents, the Activation package) and a $50 bundle (5000, the
Builder package) of Valda, Morag and Roland by default. Paid like a pass: POST /api/my/heroes/buy { hero } opens a waiting order (kind
hero); a fresh package of at least the price from one of the member's own positions fulfils it in `onEvent` (one package, one order, the
highest-priced it covers). Owned heroes live on the passes record (`heroes`, `heroBundle`) and never in `bought`, so they never feed the
Pass Tournament pool. Settings: `heroSales` (sale switch, OFF), `heroPrice<Name>Cents` (0 = free for every account), `heroBundlePriceCents`,
`heroBundleHeroes`, `heroBundleCap` (empty: no cap change; not approved). Shards of Valor reads `heroes`, `heroBundle`, `heroSale` (and
`heroBundleCap` only when set) on the sign-in hand-off. Admin > Game Pass has a hero test on the admin's own account. QA: qa/sov-heroes-store.cjs.
- **One table**: `gamepass.js` `TIER_DEFS` holds the rank, wire key, display name, settings stem, default price/length and the
member-card list for every tier. Rename a tier there (the card, admin pane, charge label and chatbot all read it).
- **Rank**: weekly < explorer < champion < sovereign < legend. Every tier is a Game Pass holder everywhere with exactly the pass
caps; `polgrant` keeps answering `pass: true` (a boolean).
- **Store**: `record.tiers = { weekly: { until }, explorer: { until }, champion: { until }, sovereign: { until }, legend: { until } }`,
the legacy `until` mirrors the weekly tier, bought rows carry `tier` (missing = weekly), waiting orders carry `tier` (missing =
weekly). Lazy migration: a record without `tiers` reads its `until` as the weekly tier.
- **Wire**: `flag()` = `{ active, until, tier, tiers }` (`tier` = highest active, `until` = that tier's end; `tiers` has all five
keys). The hand-off token carries `gamePass: { active, until, tier }`; `GET /api/partner/player` carries
`pass: { active, until, tier, tiers }`, so Shards of Valor sees `sovereign` / `legend`.
- **Buy**: `POST /api/my/gamepass/buy { tier }` (missing = weekly). Every tier above weekly needs `sovTiers` on (and the weekly pass
on); while off, nobody sees or buys them on /my, the admin included (2026-10-25: the member card shows every account the
member view). The admin tests them in Admin > Game Pass > Tier test and preview (`GET /api/admin/gamepass/preview`, `POST
/api/admin/gamepass/test-buy | test-cancel | test-comp { tier }`, always the signed-in admin's own account). Short of purchased credits: a
waiting order per tier; a package of at least the tier price fulfils the highest-priced order it covers (one pass per purchase,
each tx once). Copy names the package that pays for the pass, which since 2026-10-25 is exactly the price: $20 (Explorer), $50
(Champion), $100 (Sovereign), $250 (Legend); the card says the pass comes with that package's ad credits.
- **Renew / expiry**: no auto-renew, no proration. Buying again extends that tier from `max(now, until)` by its length (Legend: 365
days). Tiers run side by side; when a higher one ends the next one shows through. Admin comp takes a tier;
`POST /api/admin/gamepass/revoke { email, tier, why }` ends one tier now (support refunds only, credits are not returned by it).
- **Tournament**: any tier holds a seat; only weekly sales feed the pool unless `passTournamentTierSales` is `1` (then every tier's
sales do).
- **Settings** (defaults): `sovTiers` 0; kill switches `gamePassExplorerEnabled` / `gamePassChampionEnabled` /
`gamePassSovereignEnabled` / `gamePassLegendEnabled` 1 (a `0` stops one tier); `gamePassExplorerPriceCredits` 2000,
`gamePassChampionPriceCredits` 5000, `gamePassSovereignPriceCredits` 10000, `gamePassLegendPriceCredits` 25000;
`gamePassExplorerDays` / `gamePassChampionDays` / `gamePassSovereignDays` 30, `gamePassLegendDays` 365;
`passTournamentTierSales` 0. A value saved in the site settings file wins over these defaults.
- **Chatbot**: while `sovTiers` is off the assistant only says more passes are coming soon (no prices, no contents, no date); once
on, its fact lists each tier on sale with the live price, length and contents.
- **Member UI**: the Games tab card shows the tiers side by side (end dates in Central time); `/my#passes` opens it (the
Shards of Valor Buy button). **Admin**: Game Pass pane "By pass tier" table, comp per tier, end-a-tier button.
- **Tests**: `bash qa/run.sh sov-passes` (store unit checks + a local copy where the admin buys Explorer and Sovereign through the
real `ads.gamePurchase(purchasedOnly)` path with credits seeded by `qa/sov-passes-stub.cjs`, and a Legend order is fulfilled by
a $250 package).
## Games: as built (2026-10-16, local commits only, nothing deployed)
Everything is behind `GAMEPASS=on` (env, default off = today's behaviour, so the games can be deployed before launch). `IAP_URL` is
read where it already existed (default `https://instantadpay.com`). No reward amount changed anywhere; every game's local
`dailyCapPol` / pool / hidden ceiling still stands in FRONT of the IAP call as a backstop and none was raised.
**The shared client `polgrant.js`** (byte-identical copy in every repo, md5 `f3c00b90…116a`; change one, copy to the rest):
`spooky-doors/server/`, `road-agent/server/`, `match3-game/server/`, `seek-game/`, `spellwheel/`, `polybreak/`, `cyber-battle/game/`,
`polhunter/lib/`, `drip-runner/lib/`.
- `grant({ memberId, email, kind, pol, ref })` -> `POST /api/partner/polgrant` `{ game, memberId, email, kind, pol, ref }`, headers
`X-Game-Ts` + `X-Game-Sig` (plus an informational `X-Game`), 6 s timeout. Returns `{ allowed, deferred, carried, pass, day, capHit,
enforced, repeat, suspended, retry: false }` or `{ allowed: 0, retry: true, error }` on ANY non-200 / non-JSON / network error
(fail closed; a 404 "no such member" is also a retry, so the games only call it for signed-in IAP members).
- `email` always rides along (wallet-less members have `memberId: 0`; Drip Runner maps its negative `emailId` to 0). `whoOf()` = the
member id when > 0, else the lowercased email; the pass cache and the retry queue key on it.
- `voidGrant`, `fetchPass` (`GET /api/partner/player`, cached 10 min, fail-soft), `passOf` / `rememberPass` (hand-off claim
`gamePass: { active, until }` + every answer), `view()` for the lobby, `note(resp, kind, nominal)` = the player-facing line.
- Retry queue `polgrantq` in each game's store: `enqueue` dedupes per (who, ref); `retry(pay)` every 5 min, 48 h then `stuck` +
`notify('gpstuck')` once (each game routes it to its faucet alert path); `queued()` keeps a waiting ref from being re-asked.
- Carry-forward collection (SD-pattern games): `carrySweep()` on the existing tick, once a Central day per account with `gpOwed > 0`,
a zero-POL `progress` call with ref `carry:<YYYY-MM-DD>`; IAP folds the carry into `allowed` (`carried`). `gpOwed` is bookkeeping
(`+= deferred`, `-= carried`); the money truth is IAP's. **IAP accepts `pol: 0`** (verified by the integration test below).
- `tournamentPending()` reads `rows` from `GET /api/partner/tournament/pending`; `tournamentPaid(row, tx)` posts
`{ game, id?, week, place, memberId, email, tx }` (PolHunter only).
**Per game**
| Game | Files | Refs (kind) | Pass perk | Tests |
|---|---|---|---|---|
| Spooky Doors (`spooky-doors`) | server/pol.js (quote/settleGrant/grantGated/payQueued/carrySweep), server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `rung:<n>` (progress) | +1 door/day while the season runs | sim 63/63, gamepass 37/37, e2e 200 pass / 3 pre-existing timing fails |
| Road Agent (`road-agent`) | server/pol.js, server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `sector:<n>` (progress); `patrol:<day>`, `patrol:<day>:2` (daily) | 2 patrols/day, +25% scrap | sim pass, gamepass 22/22, e2e pass |
| Gem Kingdom (`match3-game`) | server/pol.js, server/server.js (`/api/continue/free`), src/world.js, src/battle.js, src/game.js, test/gamepass.cjs | `stage:<n>` (progress, bosses included) | one free continue/day, no sponsor visit | kingdom.test pass, gamepass 26/26, vite build ok |
| ClutterHunt (`seek-game`) | pol.js, server.js, public/game.js, public/index.html (`game.js?v=20261016gp`), test/gamepass.js | `<season>:<room>:<clear or stars or xclear or xstars>` (progress) | 2 bonus hints banked once per Central day | gamepass 23/23 |
| SpellWheel (`spellwheel`) | pol.js (`streakPassPol: 0.30`), server.js, public/play.js, public/play.html (`play.js?v=7`), test/gamepass.js | `level:<ch>:<n>`, `chapter:<ch>` (progress); `daily:<day>`, `streak:<day>` (daily) | streak 0.15 -> 0.30, 1 free hint/day | gamepass 25/25 |
| PolyBreak (`polybreak`) | pol.js (`gemDailyPassPol: 1.5`), server.js, public/play.js, public/play.html (`play.js?v=6`), test/gamepass.js | `round:<n>` (progress); `gem:<run>:<id>` (daily) | gem ceiling 0.5 -> 1.5/day; +1 paddle per round | gamepass 27/27, run.js 70/70 |
| PolyWarriors (`cyber-battle/game`) | pol.js, server.js (DEF_PAY_PASS 25), missions.js (3 + pass), public/game.js, public/game.html (`game.js?v=30`), test/gamepass.js | `rival:<id>`, `ladder`, `elite` (progress) | +1 daily mission (4), held defense 15 -> 25 Circuits, Pass row on the profile (card.js untouched) | gamepass 26/26 |
| Drip Runner (`drip-runner`) | lib/ledger.js (chapterDripGated), lib/game.js, server.js, public/play.js, public/play.html (`play.js?v=20261016gp`), test/gamepass.js | `chapter:<n>` (progress; the only POL it pays) | a shield at every run start | gamepass 28/28, run.js pass |
| PolHunter (`polhunter`) | lib/rewards.js (status `capped` / `gp-wait`), lib/detective.js, lib/faucet.js (`HUNT_DRY_RUN`), lib/tournament.js (new), server.js, public/app.js, public/app.html (`app.js?v=22`), test/gamepass.js | `find:<missionId>:<day>`, `detective:<boxId>` (daily) | 5 missions/day (+2), 2 Ad Detective cases/day | gamepass 42/42, run.js pass |
Game commits (local, not pushed): spooky-doors f54ef0c, road-agent d345bbf, match3-game 972dd71, seek-game 9751329, spellwheel b582b72,
polybreak e9c3a54, cyber-battle/game fa76d30, drip-runner a7b1fd9, polhunter 7391fd7 + 08486e1. Spooky Doors, Road Agent and Gem
Kingdom are Vite builds (hashed assets, no `?v=` bump).
**Decisions taken on the games side (flip if wanted)**
1. Advertiser-funded PolHunter missions (`mission.paid`) are NOT gated: the advertiser paid for that completion. Gate them in
polhunter/server.js (`gp.on() && !m.paid`) if the cap should cover them too.
2. A 0-allowed daily reward is still "done": a capped find counts as today's find (status `capped`, never reaches the faucet); a capped
gem/patrol/daily puzzle is recorded as handled with `pol: 0`. The player sees the cap line with the Pass link.
3. Fail closed, visibly: IAP unreachable = the reward is recorded (SD pattern: nothing written until IAP answers, ref queued; PolHunter:
a `gp-wait` row settled by the queue), the player sees "Your reward is recorded and pays as soon as InstantAdPay confirms it."
4. Perks read the cached flag (hand-off claim -> every grant answer -> `fetchPass` every 10 min); a pass bought mid-session shows
within 10 minutes or on the next grant.
5. Deferred progress rewards: the ledger row is written with `pol: allowed` (0 included) so the achievement is marked done; carry comes
back through `carry:<day>` or any later grant.
6. Not built: a per-game admin view of the queue (PolHunter's admin state shows queue + stuck counts and the tournament payer).
**Pass Tournament payer (PolHunter `lib/tournament.js`)**: every 10 min behind `GAMEPASS=on`, only with the faucet wallet configured.
Per pending row: a durable claim in `tourney-claims` BEFORE sending (`id:<id>` or `wk:<week>:<place>`), the tx hash written the
moment the chain has it, then `POST /api/partner/tournament/paid`. A claimed row with a hash is only re-reported, never re-sent; a
claim without a hash is retried after 10 min; a send failure releases the claim, leaves the row pending on IAP and alerts
(`tourneyfail`); low balance alerts once a day. `HUNT_DRY_RUN=on` records `wouldPay` and sends nothing. **Trap:** a claim written
during a dry run is permanent (`c.dry` rows are skipped forever), so a prize row seen while `HUNT_DRY_RUN=on` is never paid after the
flag is turned off unless `tourney-claims.json` on the PolHunter volume is cleared. Prizes bypass the per-find daily cap and the
payout threshold. Admin: `/api/admin/state` -> `tournament` and `gamepass` blocks.
**Integration test (both sides, local)**: `bash qa/run.sh gamepass-games` (qa/gamepass-games.cjs) boots IAP like qa/gamepass.mjs and
drives the REAL `spooky-doors/server/polgrant.js` and `polhunter/lib/tournament.js` against it (needs the sibling game repos under
`../..`): fetchPass free/pass, daily within/over cap, progress deferral, the `carry:<day>` zero-POL call on the next Central day
(`carried` > 0, idempotent repeat), void, bad secret and IAP-down -> `{ allowed: 0, retry: true }`, the retry queue, and the
tournament payer in dry run and live (mocked faucet.send) until IAP's pending list is empty. 2026-10-16: 44/44 after the `rows`
fix on the pending endpoint (the games read `rows`; IAP answered only `pending`).
## Payment: the package rail (2026-10-22, Marty)
**Why.** A pass paid from a credit balance brings in no new money and pays nobody upline: credits come from packages whose POL was
already split on chain ($2.50 sponsor, $1 level 2, $0.50 level 3, $1 company on a $5 package). Today's pass buyer paid from an old
balance. From now on every pass is a fresh package purchase, so the sponsor and team are paid exactly like any package.
**Rule.**
- `POST /api/my/gamepass/buy { tier }` never charges anything. It opens a waiting order for that tier (or returns the one already
open) and answers `{ needPay: true, order, orderTs, package, payUrl, message }`. The card sends the member to Buy credits.
- The order is fulfilled only by an on-chain `Purchase` event (`gamepass.onEvent`, inside the `marks.claim` block, so one app copy
acts) that meets ALL of:
- the buyer id is one of this account's own positions: the main member id (`accounts.byMemberId`) or a linked position
(`accounts.positionByMember`);
- `priceCents` is at least the tier price (setting `gamePass*PriceCredits`, now read as cents; the copy names the package that
covers it: $5, $20, $50, $100, $250);
- the purchase was mined AFTER the order was opened: block time from `eth_getBlockByNumber` (server.js `blockTime` dep), with a
30 s clock grace; if the block cannot be read after 3 tries the indexed-at time is used (never earlier than the block);
- the tx has never paid a pass or an order before (checked across every order and every bought row, every account).
- One pass per purchase: the highest-priced waiting order the package covers. The member keeps every credit of the package.
- Bought row: `{ via: 'package', tier, tx, cents, order, buyerId, usd: <pass price>, packageUsd }`. `buyerId` marks the new rail.
- Existing passes are untouched (never revoked). On 2026-10-22 production held two sales: one `via: 'credits'` (500 credits,
campaign 513) and one `via: 'package'` fulfilled under the old rule (tx 0xdbfb77c7...). No order was left waiting.
- Admin > Game Pass > **Pass sales**: every sale with how it was paid ("package", "credit-paid (old rule)", "package (old rule)"),
pass value, package value and the package tx; the header splits the counts. Stats field `passes.pay` and `sales`.
- Tests: `qa/gamepass.mjs` (order, package mined before the order refused, too small refused, another member refused, fresh package
fulfils, replayed tx refused, extend while active); `qa/sov-passes-store.cjs` and `qa/sov-passes-local.mjs` updated the same way.
- Not changed: the caps, the tiers, the tournament (pool = pass price of each sale), the hand-off claims.
+61
View File
@@ -0,0 +1,61 @@
# InstantAdPay reviewer kit: Jamie (@cryptojaime)
*Plain-text copy of the shareable page. Code minted 2026-09-29: CRYPTOJAIME, 500 credits, no cap, no expiry, one redemption per account. Jamie is member #166, sponsor martbost, wallet linked, payouts on.*
## Your code and link
- Code: **CRYPTOJAIME**
- Join link with the code built in: https://instantadpay.com/join/cryptojaime?promo=CRYPTOJAIME
- Existing members type CRYPTOJAIME into "Have a promo code?" on their Overview.
- Hook variants: add `&v=instant`, `&v=free`, `&v=ledger`, `&v=adspend` or `&v=two`.
## What the code does
500 credits per redemption (a credit is one cent of ad delivery, so $5 of advertising). Paid as a drip: 100 the day they redeem, then 100 on each day they finish the five-view daily ad set, five installments in all, 30 days to collect. One redemption per account, no cap on uses, never expires. Earned-grade credits: they run ads, never cash, cannot be withdrawn.
## What Jamie earns
Every redeemer is his direct referral. 50% of every package a direct buys (first and every one after), 20% at level 2 once two directs have bought a $20+ package, 10% at level 3 at five. Platform keeps 20%. Unqualified levels pass up.
| Package | Price | Credits | Direct sponsor gets |
|---|---|---|---|
| Micro | $5 | 500 | $2.50 |
| Activation (qualifying buy) | $20 | 2,000 | $10 |
| Builder | $50 | 5,500 | $25 |
| Growth | $100 | 12,000 | $50 |
| Leader | $250 | 32,500 | $125 |
## Paste-ready copy
**Video description / pinned comment**
InstantAdPay is the ad platform I have been reviewing: join free by email, earn credits by viewing ads, run your own campaign for nothing, and every ad package that sells is split by a smart contract on Polygon the moment it sells. No balances held, no payday, every payout public.
Use my code CRYPTOJAIME for 500 free ad credits, or just join through my link (the code is built in):
https://instantadpay.com/join/cryptojaime?promo=CRYPTOJAIME
Honest note: this is advertising, not investing. Members earn from the ad packages people in their line buy, nothing else. No income is promised, results depend on effort, and crypto involves risk.
**Short post / comment reply**
Free to join, ad credits for viewing ads, and packages that pay your sponsor instantly on-chain. Code CRYPTOJAIME gets you 500 free credits: https://instantadpay.com/join/cryptojaime?promo=CRYPTOJAIME
**DM to someone who already joined**
Glad you are in. Quick tip: open your Overview, find "Have a promo code?" and enter CRYPTOJAIME. That adds 500 free ad credits, 100 today and 100 more each day you finish your five ad views. Then link a wallet and switch on payouts so anything your own people buy pays you instantly.
## Creatives
Full banner kit, posts, swipes and objection answers: dashboard > Promo tools. Direct files:
https://instantadpay.com/banners/iap-hero-1200x630.png
https://instantadpay.com/banners/iap-advertise-earn-1200x630.jpg
https://instantadpay.com/banners/iap-wired-wednesday-1200x630.jpg
https://instantadpay.com/banners/iap-five-dollar-friday-1200x630.jpg
Pages to link: /ledger, /earning, /blog, /partners, /wednesday, /friday.
## The honest part
InstantAdPay sells advertising. Members earn from the ad packages people in their line buy, and nothing else. No earn-without-referring option, on purpose. No income guaranteed, results depend on effort, crypto involves risk of loss. Credits are ad delivery, never cash.
Contact: Marty Bostick, marty@marketingwithmarty.com, t.me/cryptoteambuild
+68
View File
@@ -0,0 +1,68 @@
# InstantAdPay Partner Kit (site owners)
*Plain-text version of the shareable page. Written for site owners who already know Marty and already run a downline builder.*
Video overview (4 min 46 s): https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/partner-overview.mp4
## Why I built it
You know I've been running ad sites for years, the kind your members already know: buy a package, run banners and text ads, click for credits. Two of mine, Faucet Wave and Tier One Ads, ran on a licensed script. The vendor went out of business, their license server went dark, and it crippled licenses that were fully paid. The sites died overnight and nothing I could do would bring them back.
So I built InstantAdPay from scratch as part of the Crypto Team Build Network. No vendor, no license server, and the part that always went wrong on ad sites, the money, is handled by a verified smart contract on Polygon instead of by me. When a package sells, the contract splits the payment and sends it in the same transaction. I never hold member funds, so there is no back office, no payday, and nothing anyone can switch off.
## What InstantAdPay is
An advertising platform where the ad spend in your line pays you. Members join free with an email address, no password and no wallet on day one. They earn credits by viewing ads and can run their first campaign for zero dollars. When they want more reach they buy an ad package, and every package that sells is split by the contract the moment it sells.
- Seven ad formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits. Views are timed on the server.
- Banner and text ads also push out to Network Ad Space, a partner rotation across other member sites.
- Daily caps, country tiers, start and end scheduling, and a balance rule that reserves a campaign's budget when it starts.
- Full WalletConnect integration: members link MetaMask, Trust, Phantom, SafePal or any WalletConnect wallet with one tap and one free signature, mobile or desktop, and buy or get paid straight from that wallet. No custody on my side.
- Every payout is a public transaction on Polygon. Splits and qualification rules are constants in a verified contract the operator cannot change.
## How the money moves
Every package splits the same way, in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. On a $20 package: $10, $4, $2, $4. A level with no qualified member passes its share up to the next qualified person above.
Qualification is earned, never bought. Every direct buyer pays their sponsor 50% from their first package. Two qualifying buyers ($20 or larger) open level 2, five open level 3.
| Package | Price | Credits |
|---|---|---|
| Micro | $5 | 500 |
| Activation (the qualifying buy) | $20 | 2,000 |
| Builder | $50 | 5,500 |
| Growth | $100 | 12,000 |
| Leader | $250 | 32,500 |
## What your members get
- A free start: join by email, view ads, earn credits, run a real campaign for nothing.
- Your promo credits on top, added the moment they join with your code.
- Instant, public payouts in POL to their own wallet, checkable on Polygonscan.
- Tools: invite message, social posts, email swipes, a banner kit in every size, objection answers, a public profile wall.
- Training videos and written team-building plays.
- A holding tank so members who arrive without a sponsor get adopted by qualified builders.
- Coaching built in: next-move card, nudges, and a live payments topic on Telegram.
## What you get for listing it in your builder
- Your spot at the top: you join directly under the company at the top, no sponsor in between, via the company link Marty sends you. Claim it by activating your account with at least the $20 package.
- Your own promo code: reusable, adds free ad credits per redemption, optional cap and expiry, one use per account, every redemption logged and visible.
- Your own line: your join link in your builder puts every member under you; each buyer pays you 50% of their first package and every one after, and their buyers open your level 2 and 3 shares.
- Ready-made creatives: banners in 468x60, 728x90, 300x250, 160x600, 120x600, 1200x630, text ad copy, email swipes, a program description.
- A bridge page for your brand on request, in InstantAdPay's design, carrying your code.
- Attribution you can check: signups and buyers are tagged with their source.
## Setting it up
1. Join with the company link Marty sends you (top placement, no sponsor in between) and pick your username. Your link: instantadpay.com/join/yourname
2. Send Marty your username and the site. He mints your code (for example YOURSITE) with the agreed credits.
3. Add InstantAdPay to your builder with https://instantadpay.com/join/yourname?promo=YOURSITE
4. Use the banners and text ads from the kit. Existing members type the code into "Have a promo code?" on their Overview.
5. Link a wallet, switch on payouts, and activate with at least the $20 package to claim your spot at the top.
## The honest part
InstantAdPay sells advertising. Members earn from the ad packages people in their line buy, and nothing else. There is no earn-without-referring option, on purpose. No income is guaranteed, results depend on effort, and cryptocurrency involves risk of loss. The contract, the ledger and every payout are public.
Contact: Marty Bostick, marty@marketingwithmarty.com, instantadpay.com, t.me/cryptoteambuild
+191
View File
@@ -0,0 +1,191 @@
// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early
// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives
// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep
// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every
// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands).
//
// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken
// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss).
// First boot: a document missing from MySQL is imported from its file, and the file is renamed <name>.imported-<date> (kept, not
// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by
// listing a folder). The SAME file ships in InstantAdPay and LinkSpin.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain
const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing
const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync,
unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync };
let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true;
const cache = new Map(); // name -> { body: string, at: ms }
const pending = new Map(); // name -> body string | null (delete)
let flushing = false, timer = null;
const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null };
function nameOf(p) {
if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null;
const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null;
const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/');
if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null;
return rel;
}
const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; };
const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null;
function put(name, body) { cache.set(name, { body, at: Date.now() }); pending.set(name, body); kick(); }
function drop(name) { cache.delete(name); pending.set(name, null); kick(); }
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); }
async function flush() {
if (!pool || flushing || !pending.size) return;
flushing = true;
try {
for (const [name, body] of [...pending]) {
if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round
if (!writer) { pending.delete(name); stats.refused++; continue; }
const c = await pool.getConnection();
try {
await c.beginTransaction();
const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE');
if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; }
if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; }
else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; }
await c.commit();
if (pending.get(name) === body) pending.delete(name);
} catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); }
finally { c.release(); }
}
} finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); }
}
// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk.
function install(dataDir) {
if (ROOT) return; ROOT = path.resolve(dataDir);
fs.readFileSync = function (p, o) {
if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]);
const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments);
const d = cache.get(n); if (!d) throw enoent(p);
return enc(o) ? d.body : Buffer.from(d.body, 'utf8');
};
fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); };
fs.writeFileSync = function (p, data, o) {
const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments);
const flag = o && typeof o === 'object' ? o.flag : null;
const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s);
};
fs.appendFileSync = function (p, data) {
const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments);
put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data)));
};
fs.renameSync = function (a, b) {
const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null;
if (!nb && !na) return O.renameSync.apply(fs, arguments);
let body;
if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); }
else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} }
if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body);
};
fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); };
fs.statSync = function (p, o) {
const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments);
const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); }
const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at);
return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false };
};
}
// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app
// must not run on an empty copy.
async function init(opts) {
const url = String(process.env.DOCSTORE_URL || '').trim();
if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; }
const mysql = require('mysql2/promise');
pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' });
await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB');
await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]);
const [rows] = await pool.query('SELECT name, body, updated_at FROM docs');
for (const r of rows) cache.set(r.name, { body: r.body, at: Number(r.updated_at) });
for (const sp of (opts && opts.splits) || []) await openSplit(sp);
// first boot for any document: import its file, then set the file aside
const stamp = new Date().toISOString().slice(0, 10);
const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; };
for (const p of walk(ROOT)) {
const n = nameOf(p); if (!n || cache.has(n)) continue;
const body = O.readFileSync.call(fs, p, 'utf8');
if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } }
await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]);
const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]);
cache.set(n, { body: got.body, at: Date.now() }); stats.imported++;
O.renameSync.call(fs, p, p + '.imported-' + stamp);
}
for (const sp of (opts && opts.splits) || []) await migrateSplit(sp);
ready = true;
console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot');
const shut = () => { flush().catch(() => {}).finally(() => {}); };
process.once('beforeExit', shut);
return true;
}
// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ----
// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest
// first); the module inserts / deletes rows itself and saves its document WITHOUT the field.
const ROWS = new Map(); const rowQ = []; let rowBusy = false;
async function openSplit(sp) {
await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id');
ROWS.set(sp.table, r.map(x => JSON.parse(x.body)));
}
async function insertMany(table, items, key, ts) {
for (let i = 0; i < items.length; i += 500) {
const part = items.slice(i, i + 500);
await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]);
}
}
// first boot: the array still inside the document moves to its table, then the document is saved without it
async function migrateSplit(sp) {
const d = cache.get(sp.doc); if (!d) return;
let obj; try { obj = JSON.parse(d.body); } catch (e) { return; }
const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return;
await insertMany(sp.table, arr, sp.key, sp.ts);
const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`');
if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed');
const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key]))));
merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged);
obj[sp.field] = []; const body = JSON.stringify(obj);
await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() });
console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table);
}
function rows(table) { return ROWS.get(table) || null; }
function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); }
async function runRows() {
rowBusy = true;
try {
while (rowQ.length && writer) {
const op = rowQ[0];
try {
if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]);
else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]);
rowQ.shift();
} catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); }
}
} finally { rowBusy = false; }
}
const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) });
const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); };
function isOn() { return ready && !!pool; }
// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true.
async function claim(key) {
if (!pool) return true;
await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB');
const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]);
return r.affectedRows === 1;
}
// SIGTERM during a deploy: write what is pending, then exit
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
+313
View File
@@ -0,0 +1,313 @@
'use strict';
// 5xYourTeam "The Draft" partner side (Marty approved the rules 2026-11-15). The network holding tank lives HERE (tank.js);
// 5xYourTeam coaches draft from it through four signed calls, and every pick is a real tank adoption through tank.adopt():
//
// POST /api/partner/draft/pool {} -> { ok, rules, pool: [card], excluded: {why: n} }
// POST /api/partner/draft/adopt { rid, coach, person, kind, week?, slot?, note? } -> { ok, ref, person, adoptionId, at, expires, holdUntil }
// POST /api/partner/draft/release { rid, coach, ref | person, why: 'coach' | 'return' } -> { ok, outcome: 'returned' | 'kept' | 'done' | <closed status>, already? }
// POST /api/partner/draft/status { ids: [person id] } -> { ok, people: { id: milestones | null } }
// coach = { wallet, hubId?, username?, positions } (the 5xYourTeam claim: positions = 5x positions this wallet holds)
// card = { id, username, door, joinedAt, lastSeen, wallet (bool), ready, holdUntil, opensAt, adoptions (outside 5x), adoptionsTotal, games, surfWei, surfCredits }
//
// Signature: X-Draft-Ts (ms) + X-Draft-Sig = hex HMAC-SHA256(DRAFT_PARTNER_SECRET, 'draft.v1.' + ts + '\n' + raw body), 5-minute
// window. A dedicated secret (not NETWORK_SSO_SECRET): this one can move sponsors. adopt and release carry a request id (rid): a
// retried or replayed call answers what the first one did and changes nothing.
//
// The rules (project-5xyourteam-draft, 11-15):
// - only 5xYourTeam position holders draft and coach: the signed claim (positions >= 1) REPLACES InstantAdPay's own-$20-buy rule
// for these calls only (the member's own tank button keeps its $20 rule); a coach needs an account here with a wallet linked,
// and someone on this contract in their line (tank.partnerEligibility); free members cannot adopt
// - the pool = tank.waiting() (rule 3 already applied: nobody the hub reports locked on any contract or sponsored, nobody adopted
// on LinkSpin) minus spam / suspended / flagged, throwaway or mistyped email domains, and anyone adopted twice already
// - max 10 open picks a coach (and the tank's people-held-at-once cap); max 2 adoptions per person (every pick counts, both sites)
// - a pick that has not STARTED (payouts on or a first purchase) in 3 days goes back to the pool; a coach cannot release one in its
// first 48 hours; a person who has had their 2 adoptions stays with the coach (the tank sweep rule); started picks stay
// - never anyone locked on a network contract: asked fresh at adopt and at every return; a hub that does not answer refuses / waits
// - 24-hour sign-up grace (tank.adopt refuses it; the card carries opensAt); coaches never see contact data: no email, phone or
// address leaves this module, person ids are hub ids (or an opaque i_ id the hub does not know)
// - the only mail: tank.adopt's normal "X is now your sponsor" adoption email. No switch-on-payouts reminders for picks, no
// payments-topic post (5xYourTeam posts its own Draft Day card)
//
// Auto-assign vs the 3-day window (the conflict the 5x build flagged), the rule implemented:
// - a drafted person is an open adoption with a sponsor, so they are out of the tank: no 24-hour activation hold, no auto-assign,
// no sign-up announcement, no dormant-lead rescue while the pick window runs
// - the pick's adoption row expires at +3 days (not IAP's 7), and tank.sweep leaves it alone (hooks.isDraftPick): this module
// closes it at 3 days with the pick's rule (started = payouts on or a purchase, a wallet alone is not started)
// - a returned pick goes back with their ORIGINAL join time (account `created` is never touched, so no new sign-up grace) and,
// with a wallet linked, a fresh 24-hour activation hold like anyone back in the tank (never the company)
// - sponsor moves go through tank.js setSponsor (sponsorfollow + the hub's /v1/sponsor-change with by 'adopt' / 'release')
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const db = require('./db');
const H = 3600000, D = 86400000;
const RULES = { returnMs: 3 * D, holdMs: 48 * H, maxOpen: 10, maxAdoptions: 2 };
const ADDR = /^0x[0-9a-f]{40}$/;
const lc = v => String(v || '').trim().toLowerCase();
// throwaway / disposable inboxes: the adoption email would go nowhere. Plus a mistyped big-provider domain (emailcheck.js).
const THROWAWAY = new Set(['mailinator.com', 'guerrillamail.com', 'guerrillamail.net', 'sharklasers.com', 'grr.la', '10minutemail.com', 'tempmail.com', 'temp-mail.org',
'yopmail.com', 'trashmail.com', 'getnada.com', 'maildrop.cc', 'dispostable.com', 'throwawaymail.com', 'fakeinbox.com', 'mintemail.com', 'mohmal.com', 'emailondeck.com',
'tempail.com', 'tempr.email', 'discard.email', 'spamgourmet.com', 'mailnesia.com', 'mytemp.email', 'tempmailo.com', 'burnermail.io', 'example.com', 'test.com']);
const DOORS = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners', vbb: 'Viral Banner Blitz',
ctb: 'CryptoTeamBuild', fivex: '5xYourTeam', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', dh: 'DownlineHydra', btc4hits: 'BTC4Hits', stackpol: 'Stack POL' };
let R = null; // { dataDir, accounts, chain, tank, ads, hooks: { hubInfo, resolvePerson, excluded, spamEmails, networkOn, suggestDomain }, requireHub, clock }
const clock = () => (R && R.clock ? R.clock() : Date.now());
const SECRET = () => String((R && R.secret) || process.env.DRAFT_PARTNER_SECRET || '').trim();
const enabled = () => SECRET().length >= 32;
// ---- storage: MySQL (draft_picks, draft_log) when DATABASE_URL is set, else a JSON document (local QA) ----
const J = {
st: null, FILE: () => path.join(R.dataDir, 'draft-partner.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.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.log = this.st.log || []; return this.st; },
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
async add(p) { const s = this.load(); const row = Object.assign({ id: s.nextId++ }, p); s.picks.push(row); this.save(); return Object.assign({}, row); },
async put(p) { const s = this.load(); const i = s.picks.findIndex(x => x.id === p.id); if (i >= 0) s.picks[i] = Object.assign({}, p); this.save(); },
async byId(id) { const x = this.load().picks.find(r => r.id === Number(id)); return x ? Object.assign({}, x) : null; },
async byRid(rid) { const x = this.load().picks.find(r => r.rid === rid); return x ? Object.assign({}, x) : null; },
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
async ofPerson(pid) { return this.load().picks.filter(r => r.personId === pid).map(x => Object.assign({}, x)); },
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
async openOfCoach(w) { return this.load().picks.filter(r => r.status === 'open' && r.coachWallet === w).map(x => Object.assign({}, x)); },
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
async countsByAdoptee() { const m = new Map(); for (const r of this.load().picks) m.set(r.adoptee, (m.get(r.adoptee) || 0) + 1); return m; },
async log(row) { const s = this.load(); s.log.push(row); if (s.log.length > 2000) s.log = s.log.slice(-2000); this.save(); },
async logs(n) { return this.load().log.slice(-(n || 100)).reverse(); }
};
const COLS = ['rid', 'adoptionId', 'adoptee', 'personId', 'coachEmail', 'coachWallet', 'coachHubId', 'kind', 'week', 'slot', 'ts', 'expires', 'holdUntil', 'status', 'closed', 'outcomeWhy', 'walletAt', 'payoutsAt', 'purchaseAt'];
const SQLC = { rid: 'rid', adoptionId: 'adoption_id', adoptee: 'adoptee', personId: 'person_id', coachEmail: 'coach_email', coachWallet: 'coach_wallet', coachHubId: 'coach_hub_id', kind: 'kind', week: 'week', slot: 'slot', ts: 'ts', expires: 'expires', holdUntil: 'hold_until', status: 'status', closed: 'closed', outcomeWhy: 'outcome_why', walletAt: 'wallet_at', payoutsAt: 'payouts_at', purchaseAt: 'purchase_at' };
const NUM = new Set(['adoptionId', 'ts', 'expires', 'holdUntil', 'closed', 'walletAt', 'payoutsAt', 'purchaseAt']);
const rowP = r => { if (!r) return null; const o = { id: Number(r.id) }; for (const k of COLS) { const v = r[SQLC[k]]; o[k] = NUM.has(k) ? Number(v || 0) : (v == null ? null : String(v)); } return o; };
const Q = {
async add(p) { const r = await db.q('INSERT INTO draft_picks (' + COLS.map(k => SQLC[k]).join(',') + ') VALUES (' + COLS.map(() => '?').join(',') + ')', COLS.map(k => p[k] == null ? null : p[k])); return Object.assign({ id: r.insertId }, p); },
async put(p) { await db.q('UPDATE draft_picks SET ' + COLS.map(k => SQLC[k] + '=?').join(',') + ' WHERE id=?', COLS.map(k => p[k] == null ? null : p[k]).concat([p.id])); },
async byId(id) { return rowP((await db.q('SELECT * FROM draft_picks WHERE id=?', [Number(id)]))[0]); },
async byRid(rid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE rid=?', [rid]))[0]); },
async byAdoption(aid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE adoption_id=?', [Number(aid)]))[0]); },
async ofPerson(pid) { return (await db.q('SELECT * FROM draft_picks WHERE person_id=? ORDER BY id', [pid])).map(rowP); },
async open() { return (await db.q("SELECT * FROM draft_picks WHERE status='open' ORDER BY id")).map(rowP); },
async openOfCoach(w) { return (await db.q("SELECT * FROM draft_picks WHERE status='open' AND coach_wallet=?", [w])).map(rowP); },
async recent(n) { return (await db.q('SELECT * FROM draft_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
async countsByAdoptee() { return new Map((await db.q('SELECT adoptee, COUNT(*) n FROM draft_picks GROUP BY adoptee')).map(r => [r.adoptee, Number(r.n)])); },
async log(x) { await db.q('INSERT INTO draft_log (ts,op,ok,code,reason,coach,person,ref,rid) VALUES (?,?,?,?,?,?,?,?,?)', [x.ts, x.op, x.ok ? 1 : 0, x.code || null, String(x.reason || '').slice(0, 400), x.coach || null, x.person || null, x.ref || null, x.rid || null]); },
async logs(n) { return (await db.q('SELECT * FROM draft_log ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(r => ({ ts: Number(r.ts), op: r.op, ok: !!r.ok, code: r.code, reason: r.reason, coach: r.coach, person: r.person, ref: r.ref, rid: r.rid })); }
};
const S = () => (db.enabled() ? Q : J);
async function ensureTables() {
if (!db.enabled()) return;
await db.q(`CREATE TABLE IF NOT EXISTS draft_picks (
id INT AUTO_INCREMENT PRIMARY KEY, rid VARCHAR(80) NOT NULL, adoption_id INT NOT NULL, adoptee VARCHAR(190) NOT NULL, person_id VARCHAR(40) NOT NULL,
coach_email VARCHAR(190) NOT NULL, coach_wallet VARCHAR(42) NOT NULL, coach_hub_id VARCHAR(40) NULL, kind VARCHAR(16) NULL, week VARCHAR(16) NULL, slot VARCHAR(16) NULL,
ts BIGINT NOT NULL, expires BIGINT NOT NULL, hold_until BIGINT NOT NULL, status VARCHAR(16) NOT NULL, closed BIGINT NULL, outcome_why VARCHAR(200) NULL,
wallet_at BIGINT NULL, payouts_at BIGINT NULL, purchase_at BIGINT NULL,
UNIQUE KEY rid (rid), KEY adoption (adoption_id), KEY person (person_id), KEY coach (coach_wallet, status), KEY st (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // 5xYourTeam draft picks (each one a tank adoption)
await db.q(`CREATE TABLE IF NOT EXISTS draft_log (
id INT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, op VARCHAR(16) NOT NULL, ok TINYINT NOT NULL, code VARCHAR(40) NULL, reason VARCHAR(400) NULL,
coach VARCHAR(42) NULL, person VARCHAR(40) NULL, ref VARCHAR(40) NULL, rid VARCHAR(80) NULL, KEY t (ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // every partner call, with its reason
}
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; await ensureTables(); }
// ---- signature ----
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
function verify(headers, raw) {
if (!enabled()) return { status: 503, error: 'draft partner not configured' };
const ts = String(headers['x-draft-ts'] || ''), sig = String(headers['x-draft-sig'] || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return { status: 401, error: 'stale' };
const want = sign(ts, raw);
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
try { const b = JSON.parse(raw || '{}'); return b && typeof b === 'object' ? { body: b } : { status: 400, error: 'bad json' }; } catch (e) { return { status: 400, error: 'bad json' }; }
}
// ---- helpers ----
const idOf = email => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; return hi && /^h_[0-9a-f]{16}$/.test(hi.id) ? hi.id : 'i_' + crypto.createHmac('sha256', SECRET() || 'local').update('pid:' + lc(email)).digest('hex').slice(0, 16); };
const doorOf = (email, via) => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; const k = lc((hi && hi.door) || via); return DOORS[k] || (k === 'hub' ? 'Network' : 'InstantAdPay'); };
function throwaway(email) {
const d = lc(email).split('@')[1] || ''; if (!d) return true;
if (THROWAWAY.has(d)) return true;
const fix = R.hooks && R.hooks.suggestDomain ? R.hooks.suggestDomain(d) : null; return !!(fix && fix !== d); // a mistyped provider: the mail bounces
}
function spamSet() { try { return new Set((R.hooks && R.hooks.spamEmails ? R.hooks.spamEmails() : []).map(lc)); } catch (e) { return new Set(); } }
const hubOff = () => R.requireHub !== false && !(R.hooks && R.hooks.networkOn && R.hooks.networkOn());
async function logCall(op, x) { const row = Object.assign({ ts: clock(), op }, x); try { await S().log(row); } catch (e) { console.error('draft log', e.message); } if (!x.ok) console.log('draft', op, 'refused', x.code || '', String(x.reason || '').slice(0, 120)); return row; }
const fail = async (op, code, reason, x) => { await logCall(op, Object.assign({ ok: false, code, reason }, x || {})); return { error: reason, code }; };
function purchasers() { const s = new Set(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) s.add(Number(ev.buyerId)); return s; }
// a coach: the wallet that holds the 5x position, then a position wallet here, then the hub's person for the hub id
async function coachAccount(c) {
const w = lc(c && c.wallet); if (!ADDR.test(w)) return { code: 'bad_coach', reason: 'Which coach? (wallet missing)' };
let a = await R.accounts.byAddress(w).catch(() => null);
if (!a && R.accounts.positionOwner) { const po = await R.accounts.positionOwner(w).catch(() => null); if (po && po.email) a = await R.accounts.byEmail(po.email); }
if (!a && c.hubId && R.hooks && R.hooks.resolvePerson) { try { const p = await R.hooks.resolvePerson({ id: String(c.hubId) }); if (p && p.email && !p.blocked) a = await R.accounts.byEmail(lc(p.email)); } catch (e) {} }
if (!a) return { code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link a wallet.' };
return { account: a, wallet: w };
}
// ---- the pool ----
let poolCache = null;
async function poolRows(fresh) {
if (!fresh && poolCache && clock() - poolCache.at < 30000) return poolCache;
const list = await R.tank.waiting(); const spam = spamSet(); const ex = { spam: 0, throwaway: 0, adoptedTwice: 0 };
const local = await R.tank.summaryMap(); const mine = await S().countsByAdoptee(); const rows = [];
for (const w of list) {
if ((R.hooks.excluded && R.hooks.excluded(w.email)) || spam.has(lc(w.email))) { ex.spam++; continue; }
if (throwaway(w.email)) { ex.throwaway++; continue; }
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
if (n >= RULES.maxAdoptions) { ex.adoptedTwice++; continue; }
rows.push({ email: w.email, card: { id: idOf(w.email), username: w.username || null, door: doorOf(w.email, w.via), joinedAt: Number(w.joined) || 0, lastSeen: Number(w.lastSeen) || 0,
// adoptions = OUTSIDE 5xYourTeam (5xYourTeam adds its own picks; counting them here too would double them); adoptionsTotal = all
wallet: !!w.wallet, ready: !!w.ready, holdUntil: w.holdUntil || 0, opensAt: w.opensAt || 0, adoptions: Math.max(0, n - (mine.get(w.email) || 0)), adoptionsTotal: n,
games: null, surfWei: null, surfCredits: Number(w.earned) || 0 } }); // games: InstantAdPay keeps no per-member game record (never invented)
}
poolCache = { at: clock(), rows, excluded: ex }; return poolCache;
}
async function pool() {
if (hubOff()) { await logCall('pool', { ok: false, code: 'hub_off', reason: 'the network hub is off, so locked people cannot be ruled out' }); return { ok: true, rules: rulesView(), pool: [], excluded: {}, hubOff: true }; }
const p = await poolRows(false);
return { ok: true, rules: rulesView(), pool: p.rows.map(r => r.card), excluded: p.excluded };
}
const rulesView = () => ({ returnHours: RULES.returnMs / H, holdHours: RULES.holdMs / H, maxOpen: RULES.maxOpen, maxAdoptions: RULES.maxAdoptions, graceHours: (RULES.graceMs || D) / H });
// ---- adopt ----
async function adopt(b) {
const rid = String(b.rid || '').slice(0, 80); const c = b.coach || {}; const pid = String(b.person || '').slice(0, 40); const kind = /^(draft|instant)$/.test(b.kind) ? b.kind : 'draft';
const x = { coach: lc(c.wallet) || null, person: pid || null, rid };
if (!/^[A-Za-z0-9_.:-]{8,80}$/.test(rid)) return fail('adopt', 'bad_rid', 'A request id (rid) is required.', x);
const prev = await S().byRid(rid);
if (prev) return { ok: true, repeat: true, ref: 'iap:' + prev.id, person: prev.personId, adoptionId: prev.adoptionId, at: prev.ts, expires: prev.expires, holdUntil: prev.holdUntil };
if (!(Number(c.positions) >= 1)) return fail('adopt', 'not_vested', 'Only 5xYourTeam position holders can draft and coach.', x);
if (hubOff()) return fail('adopt', 'hub_off', 'The network hub is off, so nobody can be drafted right now.', x);
const co = await coachAccount(c); if (!co.account) return fail('adopt', co.code, co.reason, x);
if ((await S().openOfCoach(co.wallet)).length >= RULES.maxOpen) return fail('adopt', 'full', 'Your team is full (' + RULES.maxOpen + ' open picks). Help one get started first.', x);
const hit = (await poolRows(true)).rows.find(r => r.card.id === pid);
if (!hit) return fail('adopt', 'gone', 'That player is no longer in the holding tank.', x);
const r = await R.tank.adopt(co.account.email, hit.email, String(b.note || ''), { partner: { positions: Number(c.positions), ttlMs: RULES.returnMs, maxOpen: RULES.maxOpen }, recordNote: '5xYourTeam draft pick (' + kind + (b.week ? ', week ' + String(b.week).slice(0, 10) : '') + (b.slot ? ', slot ' + String(b.slot).slice(0, 10) : '') + ')' });
if (!r || !r.ok) return fail('adopt', (r && r.code) || 'refused', (r && r.error) || 'The tank refused.', x);
poolCache = null;
const now = clock(); const acct = await R.accounts.byEmail(hit.email);
const pick = await S().add({ rid, adoptionId: Number(r.adoption.id), adoptee: hit.email, personId: pid, coachEmail: co.account.email, coachWallet: co.wallet, coachHubId: c.hubId ? String(c.hubId).slice(0, 40) : null,
kind, week: b.week ? String(b.week).slice(0, 16) : null, slot: b.slot ? String(b.slot).slice(0, 16) : null, ts: now, expires: now + RULES.returnMs, holdUntil: now + RULES.holdMs, status: 'open', closed: 0, outcomeWhy: null,
walletAt: acct && acct.address ? now : 0, payoutsAt: 0, purchaseAt: 0 });
await logCall('adopt', Object.assign(x, { ok: true, ref: 'iap:' + pick.id, reason: kind + ' pick by ' + (c.username ? '@' + String(c.username).slice(0, 40) : x.coach) }));
return { ok: true, ref: 'iap:' + pick.id, person: pid, adoptionId: pick.adoptionId, at: pick.ts, expires: pick.expires, holdUntil: pick.holdUntil };
}
// is the pick's adoption still the open one? (released on InstantAdPay itself, moved by a LinkSpin follow, ...) -> closed here too
async function reconcile(p) {
if (p.status !== 'open') return p;
const open = await R.tank.openOf(p.adoptee);
if (open.some(ad => Number(ad.id) === p.adoptionId)) return p;
p.status = 'moved'; p.closed = clock(); p.outcomeWhy = 'the adoption was closed on InstantAdPay (released, moved or followed from LinkSpin)'; await S().put(p);
await logCall('reconcile', { ok: true, code: 'moved', reason: p.outcomeWhy, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
return p;
}
// milestones seen so far (first-seen times; the chain events carry no timestamps here)
async function observe(p, a, buyers) {
if (!a) return p; const now = clock(); let ch = false;
if (a.address && !p.walletAt) { p.walletAt = now; ch = true; }
if (Number(a.memberId) > 0 && !p.payoutsAt) { p.payoutsAt = now; ch = true; }
if (Number(a.memberId) > 0 && !p.purchaseAt && buyers && buyers.has(Number(a.memberId))) { p.purchaseAt = now; ch = true; }
if (ch) await S().put(p); return p;
}
const started = (p, a) => !!(a && Number(a.memberId) > 0) || !!(p.payoutsAt || p.purchaseAt);
// close one open pick: 'coach' (released after the 48 h hold) or 'return' (3 days, not started). Shared by release() and sweep().
async function closePick(p, why, now) {
const a = await R.accounts.byEmail(p.adoptee);
await observe(p, a, purchasers());
if (started(p, a)) { p.status = 'done'; p.closed = now; p.outcomeWhy = 'started (payouts on or a purchase)'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'done'); return { outcome: 'done', why: p.outcomeWhy }; }
if (why === 'coach' && now < p.holdUntil) return { code: 'hold', reason: 'You picked them less than ' + (RULES.holdMs / H) + ' hours ago. Give them a little time first (' + Math.ceil((p.holdUntil - now) / H) + ' h left).' };
if (why === 'return' && now < p.expires) return { code: 'too_early', reason: 'The pick window runs until ' + new Date(p.expires).toISOString() + '.' };
const count = await R.tank.countAll(p.adoptee);
if (count >= RULES.maxAdoptions) { // their second adoption: they stay with this coach (the tank sweep rule, never back to nobody)
p.status = 'kept'; p.closed = now; p.outcomeWhy = 'adopted twice: stays with this coach'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired');
return { outcome: 'kept', why: p.outcomeWhy };
}
const lk = await R.tank.lockedWhy(p.adoptee);
if (lk === 'unknown') return { code: 'hub_unknown', reason: 'The network record cannot be checked right now. Try again later.' };
if (lk === 'locked') { p.status = 'kept'; p.closed = now; p.outcomeWhy = 'locked on a network contract: never moved'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired'); return { outcome: 'kept', why: p.outcomeWhy }; }
const note = why === 'return' ? '5xYourTeam pick returned: not started in ' + (RULES.returnMs / D) + ' days' : '5xYourTeam pick released by the coach';
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'release', note);
if (r && r.error) return { code: 'refused', reason: r.error };
await R.tank.closeAdoption(p.adoptionId, why === 'return' ? 'expired' : 'dropped'); // both still count toward their two adoptions
p.status = 'returned'; p.closed = now; p.outcomeWhy = note; await S().put(p); poolCache = null;
return { outcome: 'returned', why: note };
}
async function findPick(b) {
const ref = String(b.ref || ''); const m = /^iap:(\d+)$/.exec(ref);
if (m) return S().byId(Number(m[1]));
const pid = String(b.person || ''); const w = lc(b.coach && b.coach.wallet);
const rows = (await S().ofPerson(pid)).filter(p => p.coachWallet === w); return rows.find(p => p.status === 'open') || rows[rows.length - 1] || null;
}
async function release(b) {
const why = b.why === 'return' ? 'return' : 'coach'; const w = lc(b.coach && b.coach.wallet); const rid = String(b.rid || '').slice(0, 80);
const x = { coach: w || null, person: b.person ? String(b.person).slice(0, 40) : null, rid, ref: b.ref ? String(b.ref).slice(0, 40) : null };
let p = await findPick(b);
if (!p) return fail('release', 'no_pick', 'No such pick.', x);
if (p.coachWallet !== w) return fail('release', 'not_yours', 'Not your pick.', x);
x.person = p.personId; x.ref = 'iap:' + p.id;
p = await reconcile(p);
if (p.status !== 'open') { await logCall('release', Object.assign(x, { ok: true, code: 'already', reason: why + ': already ' + p.status })); return { ok: true, already: true, outcome: p.status }; }
const r = await closePick(p, why, clock());
if (!r.outcome) return fail('release', r.code, r.reason, x);
await logCall('release', Object.assign(x, { ok: true, code: r.outcome, reason: why + ': ' + r.why }));
return { ok: true, outcome: r.outcome };
}
// ---- status: milestones for the people 5xYourTeam holds picks for (anyone else answers null) ----
async function status(b) {
const ids = [...new Set((Array.isArray(b.ids) ? b.ids : []).map(v => String(v || '').slice(0, 40)).filter(Boolean))].slice(0, 500);
const buyers = purchasers(); const out = {};
const emails = []; const picksBy = {};
for (const id of ids) { const rows = await S().ofPerson(id); if (!rows.length) { out[id] = null; continue; } picksBy[id] = rows; emails.push(rows[0].adoptee); }
const tot = R.ads && R.ads.earnedTotals ? await R.ads.earnedTotals(emails).catch(() => ({})) : {};
for (const id of Object.keys(picksBy)) {
const rows = picksBy[id]; let last = rows[rows.length - 1]; const email = last.adoptee;
const a = await R.accounts.byEmail(email); if (!a) { out[id] = null; continue; }
last = await reconcile(last); last = await observe(last, a, buyers);
const count = await R.tank.countAll(email);
out[id] = { username: a.username || null, door: doorOf(email, a.joinedVia), lastSeen: Number(a.lastSeen) || 0,
wallet: a.address ? (rows.map(r => r.walletAt).filter(Boolean).sort((x, y) => x - y)[0] || clock()) : 0,
payouts: Number(a.memberId) > 0 ? (last.payoutsAt || clock()) : 0, purchase: Number(a.memberId) > 0 && buyers.has(Number(a.memberId)) ? (last.purchaseAt || clock()) : 0,
adoptions: Math.max(0, count - rows.length), // adoptions outside 5xYourTeam (5x counts its own picks itself)
games: null, surfWei: null, surfCredits: (tot[email] || {}).earned || 0,
pick: { ref: 'iap:' + last.id, status: last.status, coachWallet: last.coachWallet, expires: last.expires, holdUntil: last.holdUntil } };
}
return { ok: true, people: out };
}
// ---- the hourly sweep (server.js, beside tank.sweep): started picks close as done, unstarted ones past 3 days go back ----
let sweeping = null;
function sweep() { if (!sweeping) sweeping = sweepRun().finally(() => { sweeping = null; }); return sweeping; }
async function sweepRun() {
const now = clock(); const out = { done: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const buyers = purchasers();
for (let p of await S().open()) {
p = await reconcile(p); if (p.status !== 'open') { out.moved++; continue; }
const a = await R.accounts.byEmail(p.adoptee); await observe(p, a, buyers);
if (!started(p, a) && now < p.expires) continue;
const r = await closePick(p, 'return', now);
if (!r.outcome) { out.waiting++; continue; }
out[r.outcome] = (out[r.outcome] || 0) + 1;
await logCall('sweep', { ok: true, code: r.outcome, reason: r.why, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
}
return out;
}
// tank.sweep asks this before closing an expired adoption (the pick's own rule decides)
async function isDraftPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
async function adminView() { return { enabled: enabled(), rules: rulesView(), hubOff: hubOff(), picks: (await S().recent(200)).map(p => Object.assign({}, p, { adoptee: undefined, coachEmail: undefined })), log: await S().logs(200) }; }
// one entry for the HTTP routes (server.js) and the cross-repo test: op = pool | adopt | release | status
async function handle(op, body) {
if (op === 'pool') return pool();
if (op === 'adopt') return adopt(body);
if (op === 'release') return release(body);
if (op === 'status') return status(body);
return { error: 'unknown op', code: 'unknown_op' };
}
module.exports = { init, enabled, verify, sign, handle, pool, adopt, release, status, sweep, isDraftPick, adminView, RULES, _poolReset: () => { poolCache = null; } };
+1 -1
View File
@@ -22,7 +22,7 @@
{
"hours": 192,
"subject": "The one thing nobody tells you about ad platforms..",
"body": "This might be the most important email I send you about InstantAdPay.\n\nBecause there is a detail in how this works that most people do not notice until it is too late.\n\nIt is not about the ad credits, the formats, or even the commission structure.\n\nIt is about timing.\n\nHere is how it works. Your invite link is already live. If someone clicks it, signs up, and buys their first ad package, any package from $5 to $250, you receive 50 percent of that payment. The smart contract pays you in the same transaction. No holding tank, no withdrawal minimum, no waiting.\n\nThat is the upside everyone talks about.\n\nHere is what nobody mentions.\n\nThe moment a person buys their first package through any link, they are locked to that sponsor permanently. Every future package they buy pays that sponsor's line.\n\nSo if someone you know (a friend, a subscriber, a group contact) joins InstantAdPay through someone else's link and buys their first package there, they are locked to that other person for good.\n\n{{paid:You already bought, so your own placement is settled. Your link is live and paying.|If you have not bought yet, your link is still live. It still pays you 50 percent from anyone who clicks it today and buys.}}\n\nBut it will not capture the people you know unless you send it to them.\n\nOne person this week. Just put {{link}} where they will see it. That is all it takes.\n\n{{sponsor}} got their link from somewhere too. Same deal. Now it is your turn to pass it forward.\n\nMarty\n\n{{footer}}"
"body": "This might be the most important email I send you about InstantAdPay.\n\nBecause there is a detail in how this works that most people do not notice until it is too late.\n\nIt is not about the ad credits, the formats, or even the commission structure.\n\nIt is about timing.\n\nHere is how it works. Your invite link is already live. If someone clicks it, signs up, and buys their first ad package, any package from $5 to $500, you receive 50 percent of that payment. The smart contract pays you in the same transaction. No holding tank, no withdrawal minimum, no waiting.\n\nThat is the upside everyone talks about.\n\nHere is what nobody mentions.\n\nThe moment a person buys their first package through any link, they are locked to that sponsor permanently. Every future package they buy pays that sponsor's line.\n\nSo if someone you know (a friend, a subscriber, a group contact) joins InstantAdPay through someone else's link and buys their first package there, they are locked to that other person for good.\n\n{{paid:You already bought, so your own placement is settled. Your link is live and paying.|If you have not bought yet, your link is still live. It still pays you 50 percent from anyone who clicks it today and buys.}}\n\nBut it will not capture the people you know unless you send it to them.\n\nOne person this week. Just put {{link}} where they will see it. That is all it takes.\n\n{{sponsor}} got their link from somewhere too. Same deal. Now it is your turn to pass it forward.\n\nMarty\n\n{{footer}}"
},
{
"hours": 264,
+3 -2
View File
@@ -97,10 +97,11 @@ async function unsubscribe(email, t) {
const e = String(email || '').trim().toLowerCase();
if (!e || !t || t !== token(e)) return { error: 'That link is not valid.' };
const cur = await impl().get(e);
if (!cur) return { ok: true, already: true };
if (!cur) { try { await enqueue(e, '', ''); await impl().update(e, { stopped: 2 }); } catch (err) {} return { ok: true }; } // member without a drip row: record the opt-out anyway (update emails honour it)
await impl().update(e, { stopped: 2 });
return { ok: true };
}
async function isUnsubscribed(email) { const cur = await impl().get(String(email || '').toLowerCase()); return !!(cur && cur.stopped === 2); }
// ---- rendering ----
async function vars(email) {
@@ -178,4 +179,4 @@ async function tick() {
}
async function stats() { return impl().stats(); }
module.exports = { init, enqueue, tick, stats, sequence, setSequence, resetSequence, sendStep, unsubscribe, unsubUrl, DEFAULT_SEQUENCE };
module.exports = { init, enqueue, tick, stats, sequence, setSequence, resetSequence, sendStep, unsubscribe, unsubUrl, isUnsubscribed, DEFAULT_SEQUENCE };
+187
View File
@@ -0,0 +1,187 @@
// Syndicate member campaigns to DripOffers as paid-per-click offers.
//
// Third syndication rail, and the one that behaves least like the other two. Network Ad Space
// and AdRevLinks both serve impressions into a rotation. DripOffers serves *clicks*: a real
// person picks the offer off an offerwall, visits the target URL, and has to stay the pack's
// dwell time before anybody gets paid. So a DripOffers click is worth far more than an
// impression, and there are far fewer of them.
//
// The DripOffers database is not reachable from this server, so we talk to a narrow
// authenticated endpoint that runs there (public_html/iap-bridge.php) and does the insert
// locally. Six actions, no general query surface.
//
// FEATURE-FLAGGED: inert unless DRIPOFFERS_BRIDGE_URL and DRIPOFFERS_BRIDGE_KEY are set.
//
// Three things carried over deliberately from the NAS and AdRevLinks work:
//
// 1. DELIVERY IS READ, NEVER DERIVED. `status` counts rows in that platform's permanent
// per-click ledger. We never compute delivery from "ordered minus remaining", because
// remaining is mutable and deriving from it is what charged members for impressions that
// never ran on NAS.
//
// 2. EVERY WRITE IS IDEMPOTENT. Each campaign carries ref "iap:<id>" behind a UNIQUE index
// on the far side, so a retry after a timeout cannot book a second campaign.
//
// 3. A SYNDICATION HICCUP NEVER BLOCKS THE MEMBER. Callers swallow errors; the IAP campaign
// goes live either way.
//
// Capacity note (2026-09-18, corrected same day): the offerwall is a menu, not a rotator -
// every eligible campaign is listed at once, ordered by reward, and the earner chooses. So
// adding campaigns does not starve the others the way the AdRevLinks rotator does; it
// lengthens the menu.
//
// What is finite is total clicks, and the real figure is SMALL: the permanent click ledger
// shows roughly 40-50 clicks A DAY across the whole platform. (An earlier read of 2,700/day
// was wrong - it came from campaigns.received_today, which is only a daily figure while the
// nightly cron resets it, and that reset has stopped running.) Pack 2 puts our offers above
// the house campaigns, and they are indeed taking the large majority of that trickle.
//
// Hence a deliberately small MAX_CLICKS: at this volume a 10,000-click booking would sit at
// the top of the list for most of a year and crowd everything else out. Cost is not the reason
// for the caps - Marty owns the platform and treats these placements as free.
'use strict';
const https = require('https');
const { URL } = require('url');
const MIN_CREDITS = Number(process.env.DRIPOFFERS_MIN_CREDITS || 1000); // below this, not worth a listing
const MAX_CLICKS = Number(process.env.DRIPOFFERS_MAX_CLICKS || 2500);
const MIN_CLICKS = 500; // the platform's own floor
const PACK_ID = Number(process.env.DRIPOFFERS_PACK_ID || 2); // 2 = a 10-second dwell
const USER_ID = Number(process.env.DRIPOFFERS_USER_ID || 1); // the funding account
// Which IAP formats make sense as a click offer: the ones whose whole point is sending a
// person to the target URL. Video and solo are a different product, and featured is a slot
// buy on our own site rather than a destination.
const KINDS = ['banner', 'text', 'visits'];
function enabled() {
return !!(process.env.DRIPOFFERS_BRIDGE_URL && process.env.DRIPOFFERS_BRIDGE_KEY);
}
function call(action, payload, timeoutMs) {
return new Promise((resolve, reject) => {
if (!enabled()) return reject(new Error('dripoffers-disabled'));
const u = new URL(process.env.DRIPOFFERS_BRIDGE_URL);
const body = JSON.stringify(Object.assign({ action }, payload || {}));
const req = https.request({
hostname: u.hostname, path: u.pathname + u.search, method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body),
'X-Bridge-Key': process.env.DRIPOFFERS_BRIDGE_KEY },
timeout: timeoutMs || 25000
}, res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => {
let j = null;
try { j = JSON.parse(d); } catch (e) {}
if (!j) return reject(new Error('dripoffers ' + res.statusCode + ': ' + d.slice(0, 120)));
if (j.error) return reject(new Error(j.error));
resolve(j);
});
});
req.on('error', reject);
req.on('timeout', () => req.destroy(new Error('dripoffers timeout')));
req.end(body);
});
}
const refFor = campaignId => 'iap:' + Number(campaignId);
const kindOk = type => KINDS.includes(String(type || ''));
// How many clicks a campaign's remaining credits are worth, capped so one campaign cannot
// park itself at the top of the offerwall for a month.
function clicksFor(credits) {
const v = Math.max(0, Math.floor(Number(credits) || 0));
return Math.min(v, MAX_CLICKS);
}
// Country targeting. Unlike the AdRevLinks popup rail - which only has prices for five
// countries and so cannot carry a targeted campaign at all - this platform filters on an
// explicit country list, so geo-restricted campaigns CAN syndicate here. That is the point of
// including geo support: those campaigns currently reach no external rail at all.
//
// Tier 3 is the exception. It is defined as "everywhere the other two tiers are not", which an
// inclusion list cannot express, so a tier-3-only campaign is skipped rather than sent
// worldwide - sending it worldwide would quietly deliver the Tier 1 traffic its owner chose
// not to target.
function countriesFor(geo, tiers) {
const g = String(geo || '').trim();
if (!g) return '*';
const want = g.split(',').map(s => s.trim()).filter(Boolean);
if (want.length === 3) return '*';
const out = [];
if (want.includes('1')) out.push(...(tiers && tiers.t1 ? tiers.t1 : []));
if (want.includes('2')) out.push(...(tiers && tiers.t2 ? tiers.t2 : []));
if (!out.length) return null; // tier 3 only: not expressible, skip
return [...new Set(out.map(c => String(c).toUpperCase()))].join(',');
}
// What a click-earner sees in the offerwall list. A campaign's `name` is the member's own
// internal label and is often too short to mean anything to a stranger ("MG"), so the ad's
// headline comes first, then the label, and a very short label is qualified with the
// destination host rather than dropped or dressed up in copy we invented for them. The
// platform's own floor is five characters.
function titleFor(campaign, url) {
const clean = v => String(v || '').replace(/\s+/g, ' ').trim();
const head = clean(campaign.title), label = clean(campaign.name);
let host = '';
try { host = new URL(url).hostname.replace(/^www\./, ''); } catch (e) {}
const pick = head.length >= 5 ? head
: label.length >= 5 ? label
: label && host ? label + ' (' + host + ')'
: host;
return pick.length >= 5 ? pick.slice(0, 250) : null;
}
// Push a campaign. Returns null when it is not worth syndicating (or cannot be targeted
// faithfully) rather than throwing, so the caller treats "too small", "wrong format" and
// "disabled" the same quiet way.
async function push(campaign, opts) {
if (!enabled()) return null;
if (!kindOk(campaign.type)) return null;
const credits = Number((campaign.budget || 0) - (campaign.spent || 0) - (campaign.accrued || 0));
if (credits < MIN_CREDITS) return null;
const clicks = clicksFor(credits);
if (clicks < MIN_CLICKS) return null;
const url = String(campaign.targetUrl || campaign.target_url || '').trim();
if (!/^https?:\/\//i.test(url)) return null;
const countries = countriesFor(campaign.geo, (opts && opts.tiers) || null);
if (countries === null) return null;
const title = titleFor(campaign, url);
if (!title) return null;
// The offerwall shows this line under the title, so it has to read like an offer rather
// than like an internal campaign record.
const description = String(campaign.title || campaign.body || campaign.name || title).slice(0, 250);
return await call('create_ptc', {
title, description, url, clicks, countries,
device: 0,
pack_id: (opts && opts.packId) || PACK_ID,
user_id: USER_ID,
ref: refFor(campaign.id),
activate: !(opts && opts.paused)
});
}
// Real delivery, counted from the platform's own click ledger. Never derived.
async function readServed(campaignId) {
if (!enabled()) return null;
try { return await call('status', { ref: refFor(campaignId) }); }
catch (e) { if (/not found/i.test(e.message)) return null; throw e; }
}
async function pause(campaignId) { return enabled() ? call('pause', { ref: refFor(campaignId) }) : null; }
async function resume(campaignId) { return enabled() ? call('resume', { ref: refFor(campaignId) }) : null; }
async function remove(campaignId) {
if (!enabled()) return null;
try { return await call('delete', { ref: refFor(campaignId) }); }
catch (e) { if (/not found/i.test(e.message)) return null; throw e; }
}
async function packs() { return enabled() ? call('packs', {}) : null; }
module.exports = { enabled, push, readServed, pause, resume, remove, packs, titleFor,
clicksFor, countriesFor, kindOk, refFor,
MIN_CREDITS, MAX_CLICKS, MIN_CLICKS, PACK_ID, KINDS };
+104
View File
@@ -0,0 +1,104 @@
// Email typo check for NEW addresses (2026-10-22, after SendGrid bounces to gmai.com / outlook.comz).
// Same file lives in InstantAdPay and LinkSpin. Catches:
// 1. near-misses of the big mailbox providers (gmai.com, gmial.com, hotmial.com, yaho.com) -> "Did you mean ...?"
// 2. mistyped endings (.con, .cmo, .comz, .nett) -> "Did you mean ...?"
// 3. domains that cannot receive mail at all (no MX and no A/AAAA record)
// A DNS timeout or server error never blocks anyone (fails open). Only call it where an address enters for the
// first time - existing accounts must always be able to sign in with the address they already have.
const dns = require('dns').promises;
const POPULAR = ['gmail.com', 'googlemail.com', 'yahoo.com', 'ymail.com', 'hotmail.com', 'outlook.com', 'live.com',
'msn.com', 'icloud.com', 'me.com', 'mac.com', 'aol.com', 'protonmail.com', 'proton.me', 'mail.com', 'gmx.com',
'gmx.de', 'yandex.com', 'yandex.ru', 'zoho.com', 'comcast.net', 'att.net', 'verizon.net', 'sbcglobal.net',
'bellsouth.net', 'cox.net', 'charter.net', 'yahoo.co.uk', 'hotmail.co.uk', 'btinternet.com', 'yahoo.fr',
'hotmail.fr', 'orange.fr', 'web.de', 't-online.de', 'libero.it', 'yahoo.com.br', 'outlook.com.br', 'rediffmail.com',
'qq.com', '163.com', 'naver.com', 'seznam.cz', 'wp.pl', 'mail.ru'];
const POP = new Set(POPULAR);
// endings that are typos of .com/.net/.org (real TLDs like .co, .cm, .om are deliberately NOT here)
const BAD_TLD = { con: 'com', cmo: 'com', comm: 'com', comz: 'com', coom: 'com', cpm: 'com', vom: 'com', xom: 'com',
ocm: 'com', cmon: 'com', 'com.com': 'com', nett: 'net', nte: 'net', ent: 'net', ogr: 'org', orgg: 'org', rog: 'org' };
// optimal string alignment distance (Damerau-Levenshtein with adjacent swaps), capped
function dist(a, b) {
if (Math.abs(a.length - b.length) > 2) return 9;
const d = [];
for (let i = 0; i <= a.length; i++) { d[i] = [i]; }
for (let j = 0; j <= b.length; j++) d[0][j] = j;
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const c = a[i - 1] === b[j - 1] ? 0 : 1;
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c);
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
}
}
return d[a.length][b.length];
}
// providers that only ever use ONE domain, so gmail.co / gmail.cm / icloud.net are always typos.
// (outlook, hotmail, yahoo, live have real national domains like hotmail.it, so they are not listed.)
const SINGLE = { gmail: 'gmail.com', googlemail: 'googlemail.com', icloud: 'icloud.com', aol: 'aol.com',
protonmail: 'protonmail.com', ymail: 'ymail.com' };
const split = d => { const i = d.indexOf('.'); return i < 0 ? [d, ''] : [d.slice(0, i), d.slice(i + 1)]; };
function suggestDomain(domain) {
if (POP.has(domain)) return null;
const labels = domain.split('.');
const two = labels.slice(-2).join('.'), last = labels[labels.length - 1];
let d = domain;
if (BAD_TLD[two]) d = labels.slice(0, -2).concat(BAD_TLD[two]).join('.');
else if (BAD_TLD[last]) d = labels.slice(0, -1).concat(BAD_TLD[last]).join('.');
if (POP.has(d)) return d;
const near = nearestPopular(d);
if (near) return near;
return d !== domain ? d : null; // ending fixed but not a known provider: still suggest the fixed ending
}
function nearestPopular(domain) {
const [name, suffix] = split(domain);
if (SINGLE[name] && domain !== SINGLE[name]) return SINGLE[name];
let best = null, bestD = 9;
for (const p of POPULAR) {
const [pn, ps] = split(p);
if (ps !== suffix) continue; // only compare names that share the same ending
const dd = dist(name, pn);
if (dd < bestD) { best = p; bestD = dd; }
}
// 1 edit always counts; 2 edits only for longer names, so short real domains are left alone
return (bestD === 1 || (bestD === 2 && name.length >= 6)) ? best : null;
}
function withTimeout(promise, ms) {
return Promise.race([promise, new Promise((_, rej) => setTimeout(() => rej(Object.assign(new Error('timeout'), { code: 'ETIMEOUT' })), ms))]);
}
// true = has somewhere to deliver, false = definitely cannot receive mail, null = could not tell (fail open)
async function domainReceives(domain) {
const gone = c => c === 'ENOTFOUND' || c === 'ENODATA' || c === 'ESERVFAIL_NXDOMAIN';
try {
const mx = await withTimeout(dns.resolveMx(domain), 3000);
if (mx && mx.length && !(mx.length === 1 && mx[0].exchange === '')) return true; // RFC 7505 null MX = no mail
if (mx && mx.length) return false;
} catch (e) { if (!gone(e.code)) return null; }
try { await withTimeout(dns.resolve4(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
try { await withTimeout(dns.resolve6(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
return false;
}
// -> null when the address is fine, or { error, suggestion } to show the person
async function emailIssue(email) {
const e = String(email || '').trim().toLowerCase();
const at = e.lastIndexOf('@');
if (at < 1) return null; // the caller's own format check handles this
const local = e.slice(0, at), domain = e.slice(at + 1);
const fix = suggestDomain(domain);
if (fix && fix !== domain) {
const suggestion = local + '@' + fix;
return { error: 'Did you mean ' + suggestion + '? Please check the email address.', suggestion };
}
if (POP.has(domain)) return null;
const ok = await domainReceives(domain);
if (ok === false) return { error: 'The email domain "' + domain + '" cannot receive mail. Please check the address.', suggestion: null };
return null;
}
module.exports = { emailIssue, suggestDomain, domainReceives };
+158
View File
@@ -0,0 +1,158 @@
// The Engine Room (Fuel Your Offers stage 4, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
// LinkSpin. Each site gathers its OWN facts (facts shape below) and answers the other's signed /api/partner/engine call
// with them; build() turns both sites' facts + the refuel streak (InstantAdPay is its source of truth) + the member's goal
// into one plain dashboard: three dials, the streak panel, warning lights, six part lights and one "next move".
//
// facts (per site): { site: 'iap'|'linkspin', ok, credits: { available, inCampaigns }, campaigns: [{ id, name, type, status,
// budget, delivered, clicks, created }], clicksWeek, loginFree, buyUrl, adsUrl,
// LinkSpin only: goalsMonth, goalsCount, conv30, parts: { bannerSpin, spinLink, page, testing } each { state, note } }
// Everything is credits and counts. Nothing here is money or a promise.
'use strict';
const DAY = 86400000;
const n0 = v => (typeof v === 'number' && isFinite(v) ? v : Number(v) || 0);
const LINKS = {
iapBuy: 'https://instantadpay.com/my#buy', iapCampaigns: 'https://instantadpay.com/my#campaigns', iapTracking: 'https://instantadpay.com/my#conversions',
lsBuy: 'https://linkspin.app/credits#buy', lsAds: 'https://linkspin.app/ads', lsLinks: 'https://linkspin.app/links', lsBanner: 'https://linkspin.app/links#b', lsPages: 'https://linkspin.app/pages', lsConv: 'https://linkspin.app/conversions',
};
// 2026-10-25 (Marty: "the flow from InstantAdPay to LinkSpin is confusing"): every link points at the screen on the site the
// member is ON when that site can do the job (buy, campaigns, conversion goals: InstantAdPay's Campaigns > Conversion
// tracking card writes the same LinkSpin goals). Only LinkSpin-only tools (Banner Spin, spin links, pages) cross over, and
// engine-room.js tags those links with ?from=<site>&task=<key> so LinkSpin shows an arrival strip with the first step.
const linksFor = site => site === 'linkspin'
? { buy: LINKS.lsBuy, campaigns: LINKS.lsAds, tracking: LINKS.lsConv }
: { buy: LINKS.iapBuy, campaigns: LINKS.iapCampaigns, tracking: LINKS.iapTracking };
const ACTIVE = new Set(['active', 'paused']);
// credits a day across recent campaigns: what each delivered over the days it has run (30 at most), summed
function burnPerDay(camps, now) {
let b = 0;
for (const c of camps) {
const age = Math.max(1, Math.min(30, (now - n0(c.created)) / DAY));
if (c.status !== 'active' && now - n0(c.created) > 30 * DAY) continue;
b += n0(c.delivered) / age;
}
return b;
}
function part(state, label, note, link, key) { return { state, label, note, link, key }; }
function build(o) {
const now = o.now || Date.now();
const rf = o.refuel || { on: false };
if (!rf.on) return { on: false };
const sites = [o.iap, o.ls].filter(f => f && f.ok);
const camps = sites.flatMap(f => (f.campaigns || []).map(c => Object.assign({ site: f.site }, c)));
const recent = camps.filter(c => ACTIVE.has(c.status) || now - n0(c.created) <= 30 * DAY || c.status === 'out');
const locked = !rf.started;
const here = o.site === 'linkspin' ? 'linkspin' : 'iap', L = linksFor(here);
// ---- dial 1: fuel left vs this cycle's refuel ----
const left = sites.reduce((s, f) => s + n0(f.credits && f.credits.available) + n0(f.credits && f.credits.inCampaigns), 0);
const cy = rf.cycle || null;
const refuelCredits = cy ? ['iap', 'linkspin'].reduce((s, k) => s + (cy[k] && cy[k].refueled ? n0(cy[k].credits) + n0(cy[k].bonus) : 0), 0) : 0;
const burn = burnPerDay(recent, now);
const daysLeft = burn > 0 ? Math.floor(left / burn) : null;
const fuel = { left: Math.round(left), refuelCredits: Math.round(refuelCredits), pct: refuelCredits > 0 ? Math.max(0, Math.min(100, Math.round(left / refuelCredits * 100))) : null,
burnPerDay: Math.round(burn), daysLeft, label: 'Fuel left' };
// ---- dial 2: clicks this week, and per 1,000 credits on recent campaigns ----
const clicksWeek = sites.reduce((s, f) => s + n0(f.clicksWeek), 0), clicksPrev = sites.reduce((s, f) => s + n0(f.clicksPrevWeek), 0);
const del = recent.reduce((s, c) => s + n0(c.delivered), 0), clk = recent.reduce((s, c) => s + n0(c.clicks), 0);
// the dial reads this week against last week: half way = the same as last week
const clicks = { week: clicksWeek, prevWeek: clicksPrev, pct: clicksPrev > 0 ? Math.min(100, Math.round(clicksWeek / (2 * clicksPrev) * 100)) : null, per1000: del >= 100 ? Math.round(clk / del * 1000 * 10) / 10 : null, label: 'Clicks this week' };
// ---- dial 3: goals this month (conversion pixel, LinkSpin keeps it for both sites) vs the member's own goal ----
const lsF = o.ls && o.ls.ok ? o.ls : null;
const goalTarget = Math.max(0, Math.round(n0(o.goal))) || null;
const goals = { month: lsF ? n0(lsF.goalsMonth) : null, target: goalTarget, pct: goalTarget && lsF ? Math.min(100, Math.round(n0(lsF.goalsMonth) / goalTarget * 100)) : null, tracking: lsF ? n0(lsF.goalsCount) > 0 : null, label: 'Goals this month' };
// ---- warning lights ----
const low = camps.filter(c => c.status === 'active' && n0(c.budget) > 0 && n0(c.delivered) >= n0(c.budget) * 0.8);
const out = camps.filter(c => c.status === 'out' && now - n0(c.created) <= 60 * DAY);
const running = camps.filter(c => c.status === 'active');
const refuelSoon = rf.active && rf.daysToRefuel != null && rf.daysToRefuel <= 5;
const loginFree = sites.filter(f => n0(f.loginFree) > 0).map(f => f.site);
const warnings = [
{ key: 'low', on: low.length > 0, label: 'Ads at 80%', note: low.length ? low.length + ' ad' + (low.length === 1 ? ' is' : 's are') + ' past 80% of budget' : 'none running low' },
{ key: 'out', on: out.length > 0, label: 'Ads out', note: out.length ? out.length + ' ad' + (out.length === 1 ? '' : 's') + ' finished delivering' + (running.length ? '' : ', nothing running now') : 'none out' },
{ key: 'refuel', on: !!refuelSoon, label: 'Refuel day coming', note: rf.active ? (rf.windowOpen ? 'window open: refuel day ' + rf.refuelDayLabel : 'refuel day ' + rf.refuelDayLabel) : 'no refuel day yet' },
{ key: 'login', on: loginFree.length > 0, label: 'Login slot open', note: loginFree.length ? 'a login-ad slot is free on ' + loginFree.map(s => s === 'iap' ? 'InstantAdPay' : 'LinkSpin').join(' and ') : 'all login slots taken' },
];
// ---- the six parts ----
const P = (lsF && lsF.parts) || {};
const pFuel = !camps.length ? part('grey', 'Fuel', 'no ads yet', L.campaigns, 'ads')
: out.length && !running.length ? part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads')
: low.length || (daysLeft != null && daysLeft < 5) ? part('amber', 'Fuel', daysLeft != null && daysLeft < 5 ? 'about ' + daysLeft + ' days left at your burn' : 'an ad is running low', L.buy, 'refuel')
: running.length ? part('green', 'Fuel', running.length + ' ad' + (running.length === 1 ? '' : 's') + ' running', L.campaigns, 'ads') : part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads');
const pick = (k, label, link, key) => { const x = P[k]; return x ? part(x.state, label, x.note, link, key) : part('grey', label, lsF ? 'not set up' : 'LinkSpin did not answer', link, key); };
const parts = [pFuel, pick('bannerSpin', 'Banner spin', LINKS.lsBanner, 'bannerspin'), pick('spinLink', 'Spin link', LINKS.lsLinks, 'spinlink'), pick('page', 'Page', LINKS.lsPages, 'page'), pick('testing', 'Testing', LINKS.lsLinks, 'testing'),
lsF ? (n0(lsF.goalsCount) === 0 ? part('grey', 'Conversion tracking', 'no goal set', L.tracking, 'conversions') : n0(lsF.conv30) === 0 ? part('amber', 'Conversion tracking', 'no conversions tracked yet', L.tracking, 'conversions') : part('green', 'Conversion tracking', n0(lsF.conv30) + ' in 30 days', L.tracking, 'conversions'))
: part('grey', 'Conversion tracking', 'LinkSpin did not answer', L.tracking, 'conversions')];
// ---- one next move ----
const per1000 = c => n0(c.delivered) >= 200 ? n0(c.clicks) / n0(c.delivered) * 1000 : null;
const ranked = running.filter(c => per1000(c) != null).sort((a, b) => per1000(b) - per1000(a));
const linkFor = c => c.site === 'linkspin' ? LINKS.lsAds : LINKS.iapCampaigns;
const availAll = sites.reduce((s, f) => s + n0(f.credits && f.credits.available), 0);
let next;
const mIap = rf.minUsd ? rf.minUsd.iap : 20, mLs = rf.minUsd ? rf.minUsd.linkspin : 25;
const firstWhy = here === 'linkspin' ? 'A package of $' + mLs + ' or more here (or $' + mIap + '+ on InstantAdPay) starts the streak and lights this room.' : 'A package of $' + mIap + ' or more here (or $' + mLs + '+ on LinkSpin) starts the streak and lights this room.';
if (locked) next = { key: 'start', label: 'Refuel to start your engine', why: firstWhy, link: L.buy, guide: '/refuel' };
else if (rf.windowOpen) next = { key: 'refuel', label: 'Refuel now', why: 'Your refuel window is open: +' + rf.next.single + '% on one site, +' + rf.next.both + '% on each with both. A $' + (here === 'linkspin' ? mLs : mIap) + '+ package here counts.', link: L.buy, guide: '/refuel' };
else if (out.length && !running.length && availAll >= 100) next = { key: 'relaunch', label: 'Relaunch an ad', why: 'Nothing is running and you have ' + Math.round(availAll).toLocaleString('en-US') + ' credits free.', link: linkFor(out[0]) };
else if (daysLeft != null && daysLeft < 5) next = { key: 'pitstop', label: 'Top up' + (rf.pitStop && (rf.pitStop.iap || rf.pitStop.linkspin) ? ' (Pit Stop +' + rf.pitStop.pct + '%)' : ''), why: 'About ' + daysLeft + ' days of fuel left at your current burn.', link: L.buy };
else if (low.length) { const best = low.slice().sort((a, b) => (per1000(b) || 0) - (per1000(a) || 0))[0]; next = { key: 'topup', label: 'Top up the winner', why: '"' + (best.name || 'your ad') + '" is past 80% of its budget.', link: linkFor(best) }; }
else if (parts[5].state === 'grey') next = { key: 'tracking', label: 'Set up conversion tracking', why: here === 'linkspin' ? 'Count signups and sales back to the ad that sent them. Step 1: add a goal, then paste its two snippets on your pages.' : 'Count signups and sales back to the ad that sent them. Step 1: add a goal under Campaigns > Conversion tracking, then paste its two snippets on your pages.', link: parts[5].link, guide: '/conversion-tracking' };
else if (parts[1].state === 'grey') next = { key: 'bannerspin', label: 'Make a Banner Spin', why: 'Test up to 5 banners in one ad slot and let the winner show.' + (here === 'linkspin' ? '' : ' Banner Spin is a LinkSpin tool: the same email signs you in there.'), link: LINKS.lsBanner };
else if (parts[4].state !== 'green') next = { key: 'testing', label: 'Test A against B', why: 'Add a second page to your spin link so the rotation can pick a winner.' + (here === 'linkspin' ? '' : ' Spin links live on LinkSpin: the same email signs you in there.'), link: LINKS.lsLinks };
else if (ranked.length >= 2 && per1000(ranked[0]) > per1000(ranked[ranked.length - 1]) * 1.5) { const worst = ranked[ranked.length - 1]; next = { key: 'cut', label: 'Cut the loser', why: '"' + (worst.name || 'an ad') + '" brings the fewest clicks per 1,000 credits. Pause it and move the credits to "' + (ranked[0].name || 'your best ad') + '".', link: linkFor(worst) }; }
else next = { key: 'cruise', label: 'Keep it running', why: 'Every part is lit. Check again on your refuel day.', link: L.campaigns };
return {
on: true, locked, fuel, clicks, goals,
streak: { active: !!rf.active, months: rf.streak || 0, best: rf.best || 0, refuelDay: rf.refuelDayLabel || null, graceEnd: rf.graceLabel || null, windowOpen: !!rf.windowOpen, next: rf.next || null, pitStop: rf.pitStop || null, freeMiss: rf.freeMiss || null, both: !!(cy && cy.both), note: streakNote(rf, cy) },
warnings, parts, next, site: here, sites: { iap: !!(o.iap && o.iap.ok), linkspin: !!(o.ls && o.ls.ok) }, at: now,
};
}
// this site's own facts for one member. d: { site, adminMember, ads, coach, now?, bannerspin?, rotator?, pages?, convtrack? }
const monthStartCT = now => { const day = new Date(now).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); const [y, m] = day.split('-').map(Number);
for (const off of [5, 6]) { const ts = Date.UTC(y, m - 1, 1, off); const t = new Date(ts); if (t.toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) === day.slice(0, 8) + '01' && Number(t.toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', hour12: false })) % 24 === 0) return ts; } return Date.UTC(y, m - 1, 1, 6); };
async function facts(d, email) {
const now = d.now || Date.now(); const e = String(email || '').toLowerCase();
const out = { site: d.site, ok: true, credits: { available: 0, inCampaigns: 0 }, campaigns: [], clicksWeek: 0, loginFree: 0 };
try { const v = await d.adminMember.view(e); if (v && v.credits) out.credits = { available: n0(v.credits.available), inCampaigns: n0(v.credits.inCampaigns) }; } catch (er) {}
let list = []; try { list = (await d.ads.listCampaigns(e)).filter(c => !c.house && c.type !== 'game'); } catch (er) {}
out.campaigns = list.map(c => ({ id: c.id, name: c.name || null, type: c.type, status: c.status, budget: n0(c.budget), delivered: n0(c.spent), clicks: n0(c.clicks), created: n0(c.created) }));
try { out.clicksWeek = await d.coach.clicksSince(list.map(c => c.id), now - 7 * DAY); out.clicksPrevWeek = Math.max(0, (await d.coach.clicksSince(list.map(c => c.id), now - 14 * DAY)) - out.clicksWeek); } catch (er) {}
try { out.loginFree = n0((await d.ads.loginSlots()).free); } catch (er) {}
if (d.site === 'linkspin') {
const since30 = now - 30 * DAY;
try { out.goalsCount = d.convtrack.goalsOf(e).length; out.goalsMonth = d.convtrack.countSince(e, monthStartCT(now)); out.conv30 = d.convtrack.countSince(e, since30); } catch (er) { out.goalsCount = 0; out.goalsMonth = 0; out.conv30 = 0; }
const parts = {};
let spins = [], rots = [], pgs = [];
try { spins = await d.bannerspin.list(e); } catch (er) {}
try { rots = await d.rotator.list(e); } catch (er) {}
try { pgs = await d.pages.list(e); } catch (er) {}
const liveB = s => s.banners.filter(b => b.active && !b.adminOff);
if (!spins.length) parts.bannerSpin = { state: 'grey', note: 'not set up' };
else { const seen = spins.filter(s => !s.paused && s.imps30 > 0); parts.bannerSpin = seen.length ? { state: 'green', note: seen.reduce((n, s) => n + s.imps30, 0).toLocaleString('en-US') + ' views in 30 days' } : { state: 'amber', note: 'no views yet' }; }
if (!rots.length) parts.spinLink = { state: 'grey', note: 'not set up' };
else { const w = rots.reduce((n, r) => n + n0(r.hits7), 0); parts.spinLink = w > 0 ? { state: 'green', note: w.toLocaleString('en-US') + ' clicks this week' } : { state: 'amber', note: 'no clicks this week' }; }
const pub = pgs.filter(p => p.status === 'published');
parts.page = !pgs.length ? { state: 'grey', note: 'not set up' } : !pub.length ? { state: 'amber', note: 'draft only, not published' } : pub.some(p => n0(p.views) > 0) ? { state: 'green', note: pub.length + ' published' } : { state: 'amber', note: 'published, no views yet' };
const rotTest = rots.some(r => !r.paused && r.destinations.filter(x => x.active).length >= 2);
const rotTraffic = rots.some(r => !r.paused && r.destinations.filter(x => x.active && x.hits7 > 0).length >= 2);
const bsTest = spins.some(s => !s.paused && liveB(s).length >= 2);
const bsTraffic = spins.some(s => !s.paused && liveB(s).filter(b => b.imps30 > 0).length >= 2);
parts.testing = rotTraffic || bsTraffic ? { state: 'green', note: 'two or more versions getting traffic' } : rotTest || bsTest ? { state: 'amber', note: 'two versions set up, waiting for traffic' } : (rots.length || spins.length) ? { state: 'amber', note: 'only one version: add a second to test' } : { state: 'grey', note: 'not set up' };
out.parts = parts;
}
return out;
}
// the streak panel's one line about the next refuel (2026-10-24): once BOTH sites are refueled this cycle it says so,
// and only a cycle with one site done asks for the other one, by name
function streakNote(rf, cy) {
const nx = rf && rf.next; if (!rf || !rf.active || !nx) return '';
if (rf.windowOpen) return 'Window open: next refuel +' + nx.single + '% (+' + nx.both + '% on each with both).';
const iapDone = !!(cy && cy.iap && cy.iap.refueled), lsDone = !!(cy && cy.linkspin && cy.linkspin.refueled);
if ((cy && cy.both) || (iapDone && lsDone)) return 'Both engines fueled this cycle: +' + (nx.secondEngine || (cy.iap && cy.iap.pct) || 0) + '% on each.';
if (nx.secondEngine) return 'Refuel ' + (iapDone ? 'LinkSpin' : 'InstantAdPay') + ' this cycle for +' + nx.secondEngine + '% on both.';
return '';
}
module.exports = { streakNote, build, facts, burnPerDay, monthStartCT, LINKS };
+39
View File
@@ -0,0 +1,39 @@
// One proof-feed message per purchase (Marty, 2026-09-25).
//
// The feed used to post each tier payout on its own line and, in payouts mode, never said who
// bought what. Marty: "I see the level 1 payout, I see a level 2 payout, but I don't see who
// purchased something and what they bought." So: the buyer and the package first, then the
// level payouts under it, then any pass-ups, as ONE message. It composes from every event of
// the transaction, which is why the caller triggers it on AdminPaid, the last event the contract
// emits for a purchase: by then Purchase, TierPaid and PassedUp of that tx are all indexed.
//
// Pure: events in, HTML string out. Tested against real index rows before it shipped.
'use strict';
const PCT = { 1: 50, 2: 20, 3: 10 };
function usd(cents) { return ('$' + (cents / 100).toFixed(2)).replace(/\.00$/, ''); }
// txEvents: every indexed event with this tx. who(id) -> "#12 @name". weiToPol(wei) -> "1.23".
// Returns null when there is no Purchase in the tx (not a package purchase) or when
// `requirePayout` is set and no member was paid (a root or unsponsored buyer: nothing to prove).
function compose(txEvents, who, weiToPol, opts) {
opts = opts || {};
const pur = txEvents.find(e => e.type === 'Purchase');
if (!pur) return null;
const tiers = txEvents.filter(e => e.type === 'TierPaid').sort((a, b) => (a.tier || 0) - (b.tier || 0) || (a.li || 0) - (b.li || 0));
if (opts.requirePayout && !tiers.length) return null;
const lines = ['\u{1F9FE} <b>' + who(pur.buyerId) + '</b> bought a <b>' + usd(pur.priceCents) + ' package</b>'];
for (const t of tiers) {
const pct = PCT[t.tier];
const about = pct ? ' (' + usd(Math.round(pur.priceCents * pct / 100)) + ')' : '';
lines.push('\u{1F4B8} Level ' + t.tier + ': <b>' + weiToPol(t.amountWei) + ' POL</b>' + about + ' → ' + who(t.recipientId)
+ (t.hops > 0 ? ' <i>(passed up ' + t.hops + ')</i>' : ''));
}
if (!tiers.length) lines.push('<i>No member payout on this one: the buyer has nobody above them to pay.</i>');
const passed = txEvents.filter(e => e.type === 'PassedUp');
for (const p of passed) if (p.skippedId) lines.push('⏭ Level ' + (p.tier || '?') + ' skipped ' + who(p.skippedId) + ' (not yet qualified)');
return lines.join('\n');
}
module.exports = { compose };
+55
View File
@@ -0,0 +1,55 @@
// Earners Corner forum sign-in (Marty 2026-11-10): earnerscorner.com runs Discourse with DiscourseConnect, and InstantAdPay is the
// identity provider, so every forum name is a real InstantAdPay account (no separate forum sign-ups to farm). Discourse sends
// /forum/sso?sso=<base64 payload>&sig=<hex HMAC-SHA256>; we check the signature, make sure the visitor is signed in here, and send
// back a signed payload with the member's email, username and groups. Secret: env FORUM_SSO_SECRET (the same value is set in
// Discourse as discourse_connect_secret). Groups: network_members (paying member: an on-chain position) and wallet_linked; in
// Discourse those groups grant the trust level that may post links, so link spam needs a real member behind it.
'use strict';
const crypto = require('crypto');
const SECRET = () => String(process.env.FORUM_SSO_SECRET || '').trim();
const FORUM_URL = () => String(process.env.FORUM_URL || 'https://earnerscorner.com').replace(/\/+$/, '');
const sign = s => crypto.createHmac('sha256', SECRET()).update(s).digest('hex');
// -> { nonce, returnUrl } or { error }
function verify(sso, sig) {
if (SECRET().length < 32) return { error: 'The forum sign-in is not connected yet.' };
sso = String(sso || ''); sig = String(sig || '').toLowerCase();
if (!sso || !/^[0-9a-f]{64}$/.test(sig)) return { error: 'That forum sign-in link is incomplete.' };
const want = Buffer.from(sign(sso), 'hex'), got = Buffer.from(sig, 'hex');
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'That forum sign-in link is not valid.' };
const q = new URLSearchParams(Buffer.from(sso, 'base64').toString('utf8'));
const nonce = q.get('nonce'), returnUrl = q.get('return_sso_url') || '';
if (!nonce) return { error: 'That forum sign-in link is incomplete.' };
if (!returnUrl.startsWith(FORUM_URL() + '/')) return { error: 'That forum sign-in link points somewhere else.' };
return { nonce, returnUrl };
}
// the signed redirect back to the forum for this account
function redirectFor(v, acct, site) {
const email = String(acct.email || '').toLowerCase();
const groups = [];
if (Number(acct.memberId) > 0) groups.push('network_members');
if (acct.address) groups.push('wallet_linked');
const p = new URLSearchParams({ nonce: v.nonce, email, external_id: email, require_activation: 'false', suppress_welcome_message: 'false' });
if (acct.username) { p.set('username', acct.username); p.set('name', acct.username); }
if (acct.avatarUrl) p.set('avatar_url', /^https?:/.test(acct.avatarUrl) ? acct.avatarUrl : site + acct.avatarUrl);
// no website on sign-in (Marty 2026-11-14): Discourse holds a new user who "entered profile information without reading" for
// approval, and the stackpol.com link we filled in put every new member in the review queue. Members add their own.
if (groups.length) p.set('add_groups', groups.join(','));
const remove = ['network_members', 'wallet_linked'].filter(g => !groups.includes(g)); if (remove.length) p.set('remove_groups', remove.join(','));
const out = Buffer.from(p.toString()).toString('base64');
return v.returnUrl + (v.returnUrl.includes('?') ? '&' : '?') + 'sso=' + encodeURIComponent(out) + '&sig=' + sign(out);
}
// server-to-server: the forum's reward service asks "is this email an activated member, and where are payouts sent?" The request is
// signed with the same shared secret: header x-forum-sig = hex HMAC-SHA256 of "<email>.<unix seconds>", x-forum-ts = those seconds,
// valid for 5 minutes.
function verifyServer(email, ts, sig) {
if (SECRET().length < 32) return false;
const t = Number(ts); if (!(t > 0) || Math.abs(Date.now() / 1000 - t) > 300) return false;
const want = Buffer.from(sign(String(email || '').toLowerCase() + '.' + t), 'hex'), got = Buffer.from(String(sig || ''), 'hex');
return want.length === got.length && crypto.timingSafeEqual(want, got);
}
module.exports = { verify, verifyServer, redirectFor, sign, SECRET, FORUM_URL };
+219
View File
@@ -0,0 +1,219 @@
// InstantAdPay anti-fraud signals (Marty, 2026-09-16, after @megamol created megamol2/megamol3 under
// his own link and bought $20 on each to fake his two qualifying buyers).
//
// Per account: sign-up IP + user agent + browser device id (first-party cookie iap.dev), and the
// last-seen IP/UA/device on every sign-in. At sign-up:
// HARD BLOCK dup-device another account already used this browser
// HARD BLOCK ip-burst more than fraudMaxSignupsPerIpDay accounts from this IP in 24h
// HARD BLOCK sponsor-device the sponsor's account used this same browser
// FLAG sponsor-ip the sponsor signed up from / was last seen on this IP (households are legal, so flag only)
// FLAG shared-ip another account used this IP in the last 30 days
// Flagged accounts stay usable but never count on the leaderboard, cannot adopt from the holding tank,
// and show in Admin > Members. Suspended accounts (admin switch) cannot sign in at all.
// The contract's on-chain payments are outside all of this and are never reversed.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const db = require('./db');
let DATA_DIR = null;
const FILE = () => path.join(DATA_DIR, 'account-signals.json');
const J = { db: null, load() { try { this.db = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { this.db = {}; } }, save() { try { fs.writeFileSync(FILE(), JSON.stringify(this.db)); } catch (e) {} } };
let suspendedSet = new Set(); // refreshed on init and on every suspend/unsuspend
let flaggedSet = new Set(); // accounts carrying a hard flag (excluded from leaderboard / adoption)
const QS = ' To hold more than one position, sign in to your account and use Qualified Start on the Buy packages tab: link another wallet of your own as a position under your account. Each linked wallet that buys a $20 or larger package counts as one of YOUR qualifying buyers, its credits pool with yours, and half of that purchase comes straight back to your main wallet. That is the built-in way to self-qualify.';
const HARD = new Set(['dup-device', 'ip-burst', 'sponsor-device', 'sponsor-ip', 'multi-account']);
let seenAt = new Map(); // email -> ts of last recordSeen (throttle writes)
function norm(e) { return String(e || '').trim().toLowerCase(); }
function ipOf(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim().replace(/^::ffff:/, '').slice(0, 45); }
function uaOf(req) { return String(req.headers['user-agent'] || '').slice(0, 200); }
function cookies(req) { const out = {}; String(req.headers.cookie || '').split(';').forEach(p => { const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); }); return out; }
// in-game sign-in (2026-10-03): a cross-site request carries no iap.dev cookie, so the game sends its own browser id
function deviceOf(req) { const d = cookies(req)['iap.dev'] || (req && req.gameDev) || ''; return /^[a-f0-9]{32}$/.test(d) ? d : ''; }
function newDeviceId() { return crypto.randomBytes(16).toString('hex'); }
function deviceCookie(id, isProd) { return 'iap.dev=' + id + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (400 * 86400) + (isProd ? '; Secure' : ''); }
// ---- exception list ----
// Marty approves specific people to hold more than one account (partners, staff, a spouse
// on a shared machine). Their sign-ups must not be blocked, must not carry a hard flag,
// and must not be quietly dropped from the leaderboard or barred from adopting. Kept in
// its own small file so it works the same in DB mode and JSON mode, and so an allow entry
// can be added BEFORE the second account exists.
const ALLOW_FILE = () => path.join(DATA_DIR, 'fraud-allow.json');
let allowDb = null; // { "<email>": { note, at, by } }
function allowLoad() { if (allowDb) return allowDb; try { allowDb = JSON.parse(fs.readFileSync(ALLOW_FILE(), 'utf8')); } catch (e) { allowDb = {}; } if (!allowDb || typeof allowDb !== 'object') allowDb = {}; return allowDb; }
function allowSave() { try { fs.writeFileSync(ALLOW_FILE(), JSON.stringify(allowLoad())); } catch (e) { console.error('fraud allow save', e.message); } }
function isAllowed(email) { const e = norm(email); return !!(e && allowLoad()[e]); }
function allowList() { const d = allowLoad(); return Object.keys(d).sort().map(e => ({ email: e, note: d[e].note || '', at: d[e].at || 0, by: d[e].by || '' })); }
function allowAdd(email, note, by) {
const e = norm(email);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return { error: 'That email address does not look right.' };
allowLoad()[e] = { note: String(note || '').slice(0, 200), at: Date.now(), by: String(by || '').slice(0, 120) };
allowSave();
return { ok: true, list: allowList() };
}
function allowRemove(email) { const e = norm(email); const d = allowLoad(); if (d[e]) { delete d[e]; allowSave(); } return { ok: true, list: allowList() }; }
// The opposite list. An address here can never open an account, through any door. Same
// shape and file pattern as the allow list so it behaves identically in DB and JSON mode.
const BLOCK_FILE = () => path.join(DATA_DIR, 'fraud-block.json');
let blockDb = null; // { "<email>": { note, at, by } }
function blockLoad() { if (blockDb) return blockDb; try { blockDb = JSON.parse(fs.readFileSync(BLOCK_FILE(), 'utf8')); } catch (e) { blockDb = {}; } if (!blockDb || typeof blockDb !== 'object') blockDb = {}; return blockDb; }
function blockSave() { try { fs.writeFileSync(BLOCK_FILE(), JSON.stringify(blockLoad())); } catch (e) { console.error('fraud block save', e.message); } }
function isBlocked(email) { const e = norm(email); return !!(e && blockLoad()[e]); }
function blockList() { const d = blockLoad(); return Object.keys(d).sort().map(e => ({ email: e, note: d[e].note || '', at: d[e].at || 0, by: d[e].by || '' })); }
function blockAdd(email, note, by) {
const e = norm(email); if (!e || !e.includes('@')) return { error: 'Enter an email address.' };
blockLoad()[e] = { note: String(note || '').slice(0, 200), at: Date.now(), by: String(by || '').slice(0, 120) };
blockSave();
return { ok: true, list: blockList() };
}
function blockRemove(email) { const e = norm(email); const d = blockLoad(); if (d[e]) { delete d[e]; blockSave(); } return { ok: true, list: blockList() }; }
async function init(opts) {
DATA_DIR = opts.dataDir;
if (db.enabled()) {
await db.q(`CREATE TABLE IF NOT EXISTS account_signals (
email VARCHAR(190) PRIMARY KEY,
signup_ip VARCHAR(45) NULL, signup_ua VARCHAR(200) NULL, device_id CHAR(32) NULL, signup_at BIGINT NULL,
last_ip VARCHAR(45) NULL, last_ua VARCHAR(200) NULL, last_device CHAR(32) NULL, last_at BIGINT NULL,
flags VARCHAR(400) NULL, suspended TINYINT NOT NULL DEFAULT 0, suspended_reason VARCHAR(200) NULL, suspended_at BIGINT NULL,
INDEX (signup_ip), INDEX (device_id), INDEX (last_ip), INDEX (last_device), INDEX (suspended)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
} else J.load();
await refreshSets();
}
async function refreshSets() {
const rows = await all();
suspendedSet = new Set(rows.filter(r => r.suspended).map(r => r.email));
flaggedSet = new Set(rows.filter(r => (r.flags || []).some(f => HARD.has(f))).map(r => r.email));
}
async function all() {
if (db.enabled()) return (await db.q('SELECT * FROM account_signals')).map(rowPub);
if (!J.db) J.load();
return Object.values(J.db).map(pubJ);
}
const rowPub = r => ({ email: r.email, signupIp: r.signup_ip || '', signupUa: r.signup_ua || '', deviceId: r.device_id || '', signupAt: Number(r.signup_at || 0),
lastIp: r.last_ip || '', lastUa: r.last_ua || '', lastDevice: r.last_device || '', lastAt: Number(r.last_at || 0),
flags: parseFlags(r.flags), suspended: !!r.suspended, suspendedReason: r.suspended_reason || '', suspendedAt: Number(r.suspended_at || 0) });
const pubJ = a => ({ email: a.email, signupIp: a.signupIp || '', signupUa: a.signupUa || '', deviceId: a.deviceId || '', signupAt: a.signupAt || 0,
lastIp: a.lastIp || '', lastUa: a.lastUa || '', lastDevice: a.lastDevice || '', lastAt: a.lastAt || 0,
flags: a.flags || [], suspended: !!a.suspended, suspendedReason: a.suspendedReason || '', suspendedAt: a.suspendedAt || 0 });
function parseFlags(s) { try { const v = JSON.parse(s || '[]'); return Array.isArray(v) ? v : []; } catch (e) { return []; } }
async function get(email) {
const e = norm(email); if (!e) return null;
if (db.enabled()) { const r = await db.q('SELECT * FROM account_signals WHERE email=?', [e]); return r.length ? rowPub(r[0]) : null; }
if (!J.db) J.load(); return J.db[e] ? pubJ(J.db[e]) : null;
}
async function upsert(email, fields) {
const e = norm(email); if (!e) return;
if (db.enabled()) {
const cur = await get(e);
const v = Object.assign({ signupIp: null, signupUa: null, deviceId: null, signupAt: null, lastIp: null, lastUa: null, lastDevice: null, lastAt: null, flags: [], suspended: false, suspendedReason: null, suspendedAt: null }, cur || {}, fields);
await db.q(`INSERT INTO account_signals (email,signup_ip,signup_ua,device_id,signup_at,last_ip,last_ua,last_device,last_at,flags,suspended,suspended_reason,suspended_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE signup_ip=VALUES(signup_ip), signup_ua=VALUES(signup_ua), device_id=VALUES(device_id), signup_at=VALUES(signup_at),
last_ip=VALUES(last_ip), last_ua=VALUES(last_ua), last_device=VALUES(last_device), last_at=VALUES(last_at), flags=VALUES(flags), suspended=VALUES(suspended), suspended_reason=VALUES(suspended_reason), suspended_at=VALUES(suspended_at)`,
[e, v.signupIp || null, v.signupUa || null, v.deviceId || null, v.signupAt || null, v.lastIp || null, v.lastUa || null, v.lastDevice || null, v.lastAt || null, JSON.stringify(v.flags || []), v.suspended ? 1 : 0, v.suspendedReason || null, v.suspendedAt || null]);
return;
}
if (!J.db) J.load();
J.db[e] = Object.assign({ email: e }, J.db[e] || {}, fields); J.save();
}
// Has this BROWSER ever had an account? Used to stop the sign-in page telling an existing
// member "You're joining the line of @someone" just because they once clicked an invite
// link and the 30-day last-touch cookie is still around (Marty, 2026-09-17).
async function hasAccountOnDevice(req) {
const dev = deviceOf(req);
if (!dev) return false;
try { const rows = await all(); return rows.some(r => r.deviceId === dev || r.lastDevice === dev); }
catch (e) { return false; }
}
// ---- sign-up time ----
async function checkSignup(req, sponsorAccount, cfg, email) {
const ip = ipOf(req), dev = deviceOf(req); const flags = []; let block = null;
const rows = await all(); const now = Date.now();
const maxPerDay = Math.max(1, Number(cfg && cfg.fraudMaxSignupsPerIpDay) || 2);
const blockDevice = !(cfg && String(cfg.fraudBlockSharedDevice) === 'off');
// Everyone this sign-up collides with, so an approved exception can clear it below.
const collided = [];
if (dev) {
const same = rows.filter(r => r.deviceId === dev || r.lastDevice === dev);
if (same.length) { collided.push(...same.map(r => r.email)); flags.push('dup-device'); if (blockDevice) block = 'This browser already has an InstantAdPay account (' + mask(same[0].email) + '), and it is one account per person.' + QS + ' Shared computer at work or a library? Contact support.'; }
}
if (ip) {
const burst = rows.filter(r => r.signupIp === ip && now - (r.signupAt || 0) < 86400000);
if (burst.length >= maxPerDay) { flags.push('ip-burst'); block = block || 'Too many new accounts from this connection today, and it is one account per person.' + QS + ' If these are different people on one connection, try again tomorrow or contact support.'; }
const shared = rows.filter(r => (r.signupIp === ip || r.lastIp === ip) && now - Math.max(r.signupAt || 0, r.lastAt || 0) < 30 * 86400000);
if (shared.length) flags.push('shared-ip');
}
if (sponsorAccount && sponsorAccount.email) {
const sp = await get(sponsorAccount.email);
if (sp) {
if (dev && (sp.deviceId === dev || sp.lastDevice === dev)) { collided.push(sp.email); flags.push('sponsor-device'); if (blockDevice) block = block || 'The invite link you used belongs to an account on this same browser, so this would be a second account for the same person, which the Terms do not allow.' + QS; }
if (ip && (sp.signupIp === ip || sp.lastIp === ip)) flags.push('sponsor-ip');
}
}
// APPROVED EXCEPTION (Marty, 2026-09-17). Allow either the address signing up, or any
// account it collided with: whitelisting somebody's existing account is the usual case,
// because their second address is not known yet. Clearing the HARD flags matters as much
// as clearing the block, since those are what drop an account off the leaderboard and
// out of the holding tank. 'allowlisted' is recorded so the admin sees why it went through.
const okEmail = isAllowed(email);
const okOther = collided.some(e => isAllowed(e));
if (okEmail || okOther) {
block = null;
const kept = flags.filter(f => !HARD.has(f));
kept.push('allowlisted');
return { block: null, flags: [...new Set(kept)], ip, device: dev, allowlisted: true,
allowedBy: okEmail ? norm(email) : collided.find(e => isAllowed(e)) };
}
return { block, flags: [...new Set(flags)], ip, device: dev };
}
async function recordSignup(email, req, flags) {
const now = Date.now();
await upsert(email, { signupIp: ipOf(req), signupUa: uaOf(req), deviceId: deviceOf(req) || null, signupAt: now, lastIp: ipOf(req), lastUa: uaOf(req), lastDevice: deviceOf(req) || null, lastAt: now, flags: flags || [] });
if ((flags || []).some(f => HARD.has(f))) flaggedSet.add(norm(email));
}
async function recordSeen(email, req) {
const e = norm(email); if (!e) return;
const last = seenAt.get(e) || 0; if (Date.now() - last < 10 * 60 * 1000) return; seenAt.set(e, Date.now());
if (seenAt.size > 20000) seenAt.clear();
const cur = await get(e);
const fields = { lastIp: ipOf(req), lastUa: uaOf(req), lastDevice: deviceOf(req) || (cur ? cur.lastDevice : null), lastAt: Date.now() };
if (!cur) Object.assign(fields, { signupIp: null, signupUa: null, deviceId: deviceOf(req) || null, signupAt: null, flags: [] });
await upsert(e, fields);
}
// ---- admin ----
async function addFlags(email, flags) {
const cur = (await get(email)) || { flags: [] };
const merged = [...new Set([...(cur.flags || []), ...(flags || [])])];
await upsert(email, { flags: merged });
if (merged.some(f => HARD.has(f))) flaggedSet.add(norm(email)); else flaggedSet.delete(norm(email));
return merged;
}
async function clearFlags(email) { await upsert(email, { flags: [] }); flaggedSet.delete(norm(email)); }
async function suspend(email, reason) { await upsert(email, { suspended: true, suspendedReason: String(reason || '').slice(0, 200), suspendedAt: Date.now() }); suspendedSet.add(norm(email)); }
async function unsuspend(email) { await upsert(email, { suspended: false, suspendedReason: null, suspendedAt: null }); suspendedSet.delete(norm(email)); }
function isSuspended(email) { return suspendedSet.has(norm(email)); }
// Suspension still wins: an allow entry is permission to hold several accounts, not
// immunity from being suspended for something else.
function excluded(email) { const e = norm(email); if (suspendedSet.has(e)) return true; if (isAllowed(e)) return false; return flaggedSet.has(e); } // leaderboard / adoption
async function report() {
const rows = await all();
const groups = (key) => { const m = new Map(); for (const r of rows) { const k = r[key]; if (!k) continue; if (!m.has(k)) m.set(k, []); m.get(k).push(r.email); } return [...m.entries()].filter(([, v]) => new Set(v).size > 1).map(([k, v]) => ({ key: k, emails: [...new Set(v)] })); };
const byDevice = groups('deviceId').concat(groups('lastDevice'));
const byIp = groups('signupIp').concat(groups('lastIp'));
const dedupe = (list) => { const seen = new Set(); return list.filter(g => { const k = g.emails.slice().sort().join('|'); if (seen.has(k)) return false; seen.add(k); return true; }); };
return { flagged: rows.filter(r => (r.flags || []).length).map(r => ({ email: r.email, flags: r.flags, signupIp: r.signupIp, lastIp: r.lastIp, suspended: r.suspended })),
suspended: rows.filter(r => r.suspended).map(r => ({ email: r.email, reason: r.suspendedReason, at: r.suspendedAt })),
sharedDevice: dedupe(byDevice), sharedIp: dedupe(byIp), total: rows.length };
}
function mask(e) { return String(e || '').replace(/^(.{2}).*(@.*)$/, '$1***$2'); }
module.exports = { init, checkSignup, recordSignup, recordSeen, addFlags, clearFlags, suspend, unsuspend, isSuspended, excluded, report, get, deviceOf, hasAccountOnDevice, newDeviceId, deviceCookie, ipOf, HARD,
isAllowed, allowList, allowAdd, allowRemove, isBlocked, blockList, blockAdd, blockRemove };
+153
View File
@@ -0,0 +1,153 @@
// Five Dollar Friday (Marty, 2026-09-20). Every Friday, Central time, any ad package of $5 or more
// earns +20% bonus credits (purchased-grade, so they run login ads too), credited the moment the
// purchase indexes and labelled in the credit log. The day's wave is shown live (landing strip,
// Overview card, /api/friday), posted to Telegram at every ten packs and wrapped up at midnight,
// and five Fridays in a row earn the Five Fridays badge. Thursday 6 PM CT: an on-site notice and
// an email to active members (drip unsubscribes honoured). Friday 5 AM CT: the Telegram kickoff.
//
// Settings (siteConfig): fridayPromo '1'|'0', fridayBonusPct (20), fridayStart 'YYYY-MM-DD' (first
// Friday, 2026-09-25). Everything reads the chain index, never a marketing counter.
'use strict';
const fs = require('fs');
const path = require('path');
let X = {}, FILE = null, S = null;
const TZ = 'America/Chicago';
const dayOf = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
const weekdayOf = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, weekday: 'short' });
const hourOf = ts => Number(new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour: 'numeric', hour12: false }));
const isFriday = ts => weekdayOf(ts) === 'Fri';
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'friday.json'); S = load(); }
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { granted: {}, posts: {}, badges: {}, sent: {} }; } }
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
// shared across instances when the app is wired with marks (server.js); true when nobody else has it
async function claimOnce(key) { try { return X.marks ? await X.marks.claim(key) : true; } catch (e) { return true; } }
function cfg() {
const c = (X.siteConfig && X.siteConfig()) || {};
return {
on: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
pct: Math.max(0, Number(c.fridayBonusPct) || 20),
kickHour: Math.min(23, Math.max(0, Number(c.fridayKickHour == null ? 5 : c.fridayKickHour) || 0)), // Central hour of the Telegram kickoff (Marty 2026-10-07: 5 AM, was 9)
start: String(c.fridayStart || '2026-09-25'),
};
}
// the next Friday on or after today (Central), as a day key and a label
function nextFriday(now) {
const t0 = now || Date.now();
for (let d = 0; d < 8; d++) { const ts = t0 + d * 86400000; if (isFriday(ts) && dayOf(ts) >= cfg().start) return dayOf(ts); }
return null;
}
function labelOf(dayKey) { const [y, m, d] = dayKey.split('-').map(Number); return new Date(Date.UTC(y, m - 1, d, 12)).toLocaleDateString('en-US', { month: 'long', day: 'numeric', timeZone: 'UTC' }); }
// is the promo live right now (a Friday on or after the start, switched on)
function liveNow(now) { const c = cfg(); const t = now || Date.now(); return c.on && isFriday(t) && dayOf(t) >= c.start; }
function counts(dayKey) { return purchasesOn(dayKey).length; }
// every $5+ purchase on a given Central day, from the chain index
function purchasesOn(dayKey) {
const out = [];
try { for (const ev of X.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.priceCents >= 500 && dayOf(ev.ts) === dayKey) out.push(ev); } catch (e) {}
return out;
}
function paidOn(dayKey) {
let wei = 0n, n = 0;
try { for (const ev of X.chain.recentEvents(1e9)) if ((ev.type === 'TierPaid' || ev.type === 'AwardPaid') && dayOf(ev.ts) === dayKey) { wei += BigInt(ev.amountWei); n++; } } catch (e) {}
return { pol: Number(wei / 10n ** 14n) / 10000, n };
}
function stats(dayKey) {
const day = dayKey || dayOf(Date.now());
const p = purchasesOn(day); const paid = paidOn(day);
const usd = p.reduce((s, e) => s + e.priceCents, 0) / 100;
const buyers = new Set(p.map(e => e.buyerId)).size;
const bonus = Object.values(S.granted || {}).filter(g => g.day === day).reduce((s, g) => s + g.bonus, 0);
return { day, packs: p.length, usd, buyers, polPaid: paid.pol, payouts: paid.n, bonusCredits: bonus };
}
// public view
function view() {
const c = cfg(); const now = Date.now(); const live = liveNow(now); const next = nextFriday(now);
return { on: c.on, pct: c.pct, live, today: live ? stats(dayOf(now)) : null, nextFriday: next, nextLabel: next ? labelOf(next) : null, start: c.start };
}
// the bonus: once per purchase tx, on a Friday on or after the start
async function onEvent(ev) {
if (!ev || ev.type !== 'Purchase' || !liveNow(ev.ts) || ev.priceCents < 500) return null;
if (S.granted[ev.tx]) return null;
const c = cfg(); const bonus = Math.round((Number(ev.creditAmount) || 0) * c.pct / 100);
if (bonus <= 0) return null;
const a = await X.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, '');
await X.ads.addEarned(a.email, bonus, { purchased: true, log: { kind: 'bonus', note: 'Five Dollar Friday: +' + c.pct + '% on your ' + usd + ' package', ref: 'fdf:' + String(ev.tx).slice(0, 30) } });
S.granted[ev.tx] = { day: dayOf(ev.ts), memberId: ev.buyerId, bonus, at: Date.now() }; save();
try { await X.notify(ev.buyerId, 'Five Dollar Friday: +' + bonus + ' bonus credits', 'Your ' + usd + ' package landed on a Five Dollar Friday, so ' + bonus + ' bonus credits (+' + c.pct + '%) were added to your balance. Every pack bought on a Friday gets this. See your balance: https://instantadpay.com/my#campaigns', 'notice'); } catch (e) {}
// the wave, every ten packs
const st = stats(dayOf(ev.ts));
if (st.packs > 0 && st.packs % 10 === 0 && !S.posts[st.day + ':' + st.packs]) {
S.posts[st.day + ':' + st.packs] = Date.now(); save();
X.telegram('\u{1F4B5} <b>Five Dollar Friday</b> · <b>' + st.packs + ' packs</b> so far today from ' + st.buyers + ' buyers, <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members in the same transactions.\nEvery $5+ pack today earns +' + c.pct + '% credits: https://instantadpay.com/my#buy').catch(() => {});
}
return bonus;
}
// five Fridays in a row (the most recent five promo Fridays that have happened), any $5+ pack each
function fridayStreak(memberId) {
const c = cfg(); const now = Date.now(); const days = [];
for (let d = 0; d < 7 * 8 && days.length < 5; d++) { const ts = now - d * 86400000; const k = dayOf(ts); if (isFriday(ts) && k >= c.start && (k < dayOf(now) || liveNow(now))) days.push(k); }
let streak = 0;
for (const k of days) { if (purchasesOn(k).some(e => e.buyerId === Number(memberId))) streak++; else break; }
return streak;
}
function earnedBadge(memberId) {
if (S.badges[memberId]) return true;
if (fridayStreak(memberId) >= 5) { S.badges[memberId] = Date.now(); save(); return true; }
return false;
}
// scheduled moments, checked every few minutes: Thursday 18:00 CT notice + email, Friday kickoff at kickHour (5 AM CT),
// Saturday 00:xx CT wrap-up of the Friday that just ended
async function tick() {
const c = cfg(); if (!c.on) return;
const now = Date.now(); const day = dayOf(now); const wd = weekdayOf(now); const h = hourOf(now);
const next = nextFriday(now);
if (wd === 'Thu' && h >= 18 && next && !S.sent['thu:' + next] && await claimOnce('fri:thu:' + next)) {
S.sent['thu:' + next] = now; save();
const subject = 'Tomorrow is Five Dollar Friday';
const text = 'Tomorrow is Five Dollar Friday on InstantAdPay.\n\nAny ad package of $5 or more bought on Friday (Central time) earns +' + c.pct + '% bonus credits, added the moment the purchase settles. Your $5 pays your sponsor line the second it clears, and your line’s $5s pay you. Friday is when we all push at once.\n\nGame Pass too: the same Friday purchase gives you a free 7-day Game Pass for every game in the network (once per Friday, added automatically), and the $5 pack lands as 600 credits that you keep for your ads.\n\nLine up your pack: https://instantadpay.com/my#buy\nWatch the wave on the live ledger: https://instantadpay.com/ledger';
await broadcast(subject, text);
}
if (wd === 'Fri' && h >= c.kickHour && day >= c.start && !S.sent['kick:' + day] && await claimOnce('fri:kick:' + day)) {
S.sent['kick:' + day] = now; save();
X.telegram('\u{1F4B5} <b>It’s Five Dollar Friday.</b> Any ad package from $5 up earns <b>+' + c.pct + '% credits</b> today, and every pack pays its sponsor line in the same transaction. Game Pass day too: the same purchase gives you a free 7-day Game Pass for every game (once per Friday, automatic), and the $5 pack lands as 600 credits you keep for ads. Buy yours, then watch the ledger fill up: https://instantadpay.com/my#buy').catch(() => {});
}
if (wd === 'Sat' && h < 3) {
const fri = dayOf(now - 86400000);
if (isFriday(now - 86400000) && fri >= c.start && !S.sent['wrap:' + fri] && await claimOnce('fri:wrap:' + fri)) {
S.sent['wrap:' + fri] = now; save();
const st = stats(fri); const top = await topLines(fri);
X.telegram('\u{1F3C1} <b>Five Dollar Friday wrap-up</b> (' + labelOf(fri) + ')\n<b>' + st.packs + ' packs</b> from ' + st.buyers + ' buyers · $' + st.usd.toFixed(0) + ' in ad packages · <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members · ' + st.bonusCredits.toLocaleString() + ' bonus credits handed out'
+ (top.length ? '\nBiggest lines today: ' + top.map(t => t.who + ' (' + t.packs + ')').join(', ') : '') + '\nNext one is a week away. Line it up: https://instantadpay.com/my#buy').catch(() => {});
}
}
}
// most packs bought by a sponsor's directs on a day (the line that pushed hardest)
async function topLines(dayKey) {
const by = new Map();
for (const ev of purchasesOn(dayKey)) { let sp = 0; try { const m = await X.chain.member(ev.buyerId); sp = m && m.sponsorId ? Number(m.sponsorId) : 0; } catch (e) {} if (!sp) continue; by.set(sp, (by.get(sp) || 0) + 1); }
const rows = [...by.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3);
const out = []; for (const [id, packs] of rows) { let who = '#' + id; try { const a = await X.accounts.byMemberId(id); if (a && a.username) who = '@' + a.username; } catch (e) {} out.push({ memberId: id, who, packs }); }
return out;
}
// on-site notice + email to every active member (quiet 45+ days skipped, drip unsubscribes honoured)
async function broadcast(subject, text) {
let all = []; try { all = await X.accounts.listAll(5000); } catch (e) { return; }
const now = Date.now(); let n = 0;
for (const a of all) {
if (!a.email) continue;
if (now - (a.lastSeen || a.created || 0) > 45 * 86400000) continue;
try { await X.notify(a.memberId, subject, text, 'notice'); } catch (e) {}
try { if (X.mailer && X.mailer.hasKey() && !(X.drip && await X.drip.isUnsubscribed(a.email))) { await X.mailer.send(a.email, subject, text + '\n\nInstantAdPay'); n++; } } catch (e) {}
}
return n;
}
module.exports = { init, cfg, view, stats, onEvent, tick, fridayStreak, earnedBadge, liveNow, nextFriday, isFriday, labelOf, topLines };
+76
View File
@@ -0,0 +1,76 @@
// Friday Bonus Hunts (Marty, 2026-09-26).
//
// PolHunter hunters bank one extra FRIDAY hunt for each day, Saturday through Thursday (Central),
// that they do both of the things InstantAdPay's two slowest ad types need:
// - watch at least one video ad (video_seen has a row for that day), and
// - open at least one inbox (solo) ad that day (solo_inbox.read_ts falls on that day).
// Fairness rule: a member whose inbox had NO unread solo ad at the end of a day can't open one,
// so for them the video alone counts that day. Nobody is blocked by an empty inbox.
//
// Why these two: they were the worst-delivering ad types on 2026-09-26 (about 6-7 views per
// campaign per day against 40-50 for banners and text), because they only get a view when a
// member chooses to open them. The game gives members a reason to.
//
// This module only COUNTS. PolHunter decides how many of the banked hunts can be used (capped
// by how many missions exist) and only on the Friday itself.
'use strict';
let db = null;
function init(deps) { db = deps && deps.db; }
const TZ = 'America/Chicago';
const dayOf = ms => new Date(ms).toLocaleDateString('en-CA', { timeZone: TZ });
// Midnight Central at the START of a 'YYYY-MM-DD' day, as epoch ms. Found by testing the two
// possible offsets (CDT -5, CST -6) instead of assuming one, so it stays right across DST.
function ctStart(dayKey) {
for (const off of [5, 6]) {
const t = Date.parse(dayKey + 'T00:00:00Z') + off * 3600000;
if (dayOf(t) === dayKey && dayOf(t - 1) !== dayKey) return t;
}
return Date.parse(dayKey + 'T05:00:00Z');
}
function addDays(dayKey, n) {
const d = new Date(dayKey + 'T12:00:00Z'); d.setUTCDate(d.getUTCDate() + n); return d.toISOString().slice(0, 10);
}
function weekdayOf(dayKey) { return new Date(dayKey + 'T12:00:00Z').getUTCDay(); } // 0 Sun .. 5 Fri
// The Friday this week's banking counts toward: today if today is Friday, otherwise the next one.
function fridayFor(now) {
const today = dayOf(now || Date.now());
const wd = weekdayOf(today);
return addDays(today, (5 - wd + 7) % 7);
}
// { friday, today, isFriday, window:[Sat..Thu], days:[{day, video, solo, soloNeeded, banked, future}], banked }
async function bankFor(email, now) {
now = now || Date.now();
const e = String(email || '').trim().toLowerCase();
const friday = fridayFor(now), today = dayOf(now);
const days = []; for (let i = 6; i >= 1; i--) days.push(addDays(friday, -i)); // Sat .. Thu
const out = { friday, today, isFriday: today === friday, days: [], banked: 0 };
if (!e || !db || !db.enabled()) { out.days = days.map(d => ({ day: d, video: false, solo: false, soloNeeded: true, banked: false, future: d > today })); return out; }
const winStart = ctStart(days[0]), winEnd = ctStart(friday);
const vids = await db.q('SELECT DISTINCT day FROM video_seen WHERE email=? AND day>=? AND day<=?', [e, days[0], days[5]]);
const vset = new Set(vids.map(r => String(r.day instanceof Date ? r.day.toISOString().slice(0, 10) : r.day).slice(0, 10)));
// every solo row that could matter: delivered before the window closed
const solos = await db.q('SELECT delivered, read_ts FROM solo_inbox WHERE email=? AND delivered < ?', [e, winEnd]);
for (const d of days) {
const s = ctStart(d), eod = ctStart(addDays(d, 1));
const future = d > today;
const video = vset.has(d);
const solo = solos.some(r => r.read_ts && Number(r.read_ts) >= s && Number(r.read_ts) < eod);
// unread at the end of that day = delivered before end of day and not read by then
const unreadAtEnd = solos.some(r => Number(r.delivered) < eod && (!r.read_ts || Number(r.read_ts) >= eod));
// for today, "end of day" hasn't happened; they still need to open one if one is waiting now
const soloNeeded = d === today ? solos.some(r => Number(r.delivered) <= now && !r.read_ts) || solo : unreadAtEnd || solo;
const banked = !future && video && (solo || !soloNeeded);
out.days.push({ day: d, video, solo, soloNeeded, banked, future });
if (banked) out.banked++;
}
return out;
}
module.exports = { init, bankFor, fridayFor, ctStart };
+712
View File
@@ -0,0 +1,712 @@
// Game Pass (2026-10-16): the $5 weekly pass across all the network games (POL Miner 2026-10-28, Turkey Drop for its Nov season), and the account-wide POL cap service the games call
// before every POL grant. IAP is the single source of truth for both; the games keep their own caps only as a backstop.
// Spec: docs/GAME-PASS.md (section 3a is the contract the games build against).
//
// What lives here:
// - the pass store email -> { until, bought: [{ ts, via, tx | credits, usd }], lastCapHit } (durable persisted map 'gamepass')
// - pass orders order -> { status, email, ts, tx } (every pass is paid by a FRESH package purchase: see buy() / onEvent())
// - the cap ledger per member per Central day: used daily/total, deferred queue per game, every answered (game, ref) kept 90 days
// - the weekly Pass Tournament: ranks pass holders by grants reported through polgrant, records POL prizes for the games to pay
// - admin stats
//
// Not to be confused with the in-game SIGN-IN pass (server.js gamePassMint/gamePassOpen): that is a session token the games keep
// in localStorage. This module is the paid Game Pass product. Fields on the wire are `pass: { active, until }` (3a).
//
// Pass tiers (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md; Marty approved the "safe" form): beside the $5 weekly pass, the
// monthly Explorer ($20) and Champion ($40) passes. They sell islands and looks in Shards of Valor, NEVER power and NEVER more
// POL: every tier gets exactly the weekly pass caps (flag().active is true for any tier, so polgrant answers pass: true and
// nothing else changes). Tiers run side by side, each with its own expiry: record.tiers = { weekly: { until }, explorer: { until },
// champion: { until } }; the legacy `until` keeps mirroring the weekly tier (lazy migration: a record with no `tiers` reads its
// `until` as the weekly tier). flag().tier = the highest active tier. Explorer/Champion sales sit behind the site switch
// `sovTiers` (default off; while it is off the admin tests them from Admin > Game Pass, never on the member card). No proration, no auto-renew: buying again
// extends that tier from max(now, until).
// 2026-10-22 (Marty): every pass rides the package rail so sponsors get paid. Buying a pass never spends a credit balance any more
// (today's buyer paid from an old balance, so no new money came in and nobody upline was paid). A pass click opens an order; the
// order is fulfilled ONLY by an on-chain package Purchase of at least the tier price, mined after the order was opened, bought by
// one of that member's own positions (main or linked), each purchase tx used once. The member keeps that package's credits for ads.
// Bought rows: via 'package' (with tx and cents). The two rows from before this change are via 'credits' and 'package' and stay.
// 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 and Champion $39.99 (30 days), plus Sovereign $99.99 (30 days)
// and Legend $249.99 (365 days, the yearly pass), all in TIER_DEFS below and all behind the same sovTiers switch. The weekly
// pass is unchanged ($5 / 7 days / the same caps). Rank weekly < explorer < champion < sovereign < legend.
// 2026-10-25 (Marty): every tier price equals an InstantAdPay one-click package, so the cheapest qualifying package is exactly
// the pass price (no silent overpay): Explorer $20 (was 19.99), Champion $50 (was 39.99), Sovereign $100 (was 99.99), Legend
// $250 (was 249.99); weekly $5 unchanged. The pass comes with that package's ad credits.
'use strict';
const fs = require('fs');
const path = require('path');
const TZ = 'America/Chicago';
const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarriors', 'clutterhunt', 'polybreak', 'driprunner', 'roadagent', 'shardsofvalor', 'polminer', 'warpwares', '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', warpwares: 'Warp & Wares', turkeydrop: 'Turkey Drop' };
const SHARES = [0.5, 0.3, 0.2]; // tournament prize split, places 1-3
const KEEP_DAYS = 90; // answered refs and day rows are kept this long (idempotency window)
// THE pass table (2026-10-22, Dallas's structure, Marty approved): lowest to highest, a higher tier includes everything below.
// Rename a tier here (name) and nowhere else: the member card, the admin pane, the charge label and the chatbot read it from here.
// key = the wire value the games read (flag().tier / tiers); set = the Admin > Settings stem (gamePass<set>Enabled /
// PriceCredits / Days; weekly keeps its original gamePassPriceCredits / gamePassDays); price = the pass price in cents (100 = $1;
// the setting keeps its old 'PriceCredits' name): the package that pays for a pass must cost at least this much;
// perks = what the member card lists. Every tier is a Game Pass holder everywhere with the SAME caps (no extra POL).
const TIER_DEFS = [
{ key: 'weekly', name: 'Game Pass', set: '', price: 500, days: 7,
perks: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and weapons unlocked'] },
{ key: 'explorer', name: 'Explorer', set: 'Explorer', price: 2000, days: 30,
perks: ['Everything in the Game Pass, in every game', 'Shards of Valor: weapons and gear unlocked', 'Shards of Valor: 2 bonus islands'] },
{ key: 'champion', name: 'Champion', set: 'Champion', price: 5000, days: 30,
perks: ['Everything in Explorer', 'Shards of Valor: 4 bonus islands of your choice', 'Shards of Valor: level cap 30'] }, // 2026-11-05: the Druid moved to the one-time bonus heroes
{ key: 'sovereign', name: 'Sovereign', set: 'Sovereign', price: 10000, days: 30,
perks: ['Everything in Champion', 'Shards of Valor: every bonus island', 'Shards of Valor: level cap 40'] }, // 2026-11-05: the Necromancer was dropped
{ 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 bonus hero while Legend is active (Kestrel, Valda, Morag, Roland), and every new hero as it ships', 'Shards of Valor: level cap 40'] }, // new heroes as a Legend perk: Marty 2026-10-30 (Dallas's $100/year idea folded in here)
];
const TIERS = TIER_DEFS.map(d => d.key); // lowest to highest
const TIER_NAMES = Object.fromEntries(TIER_DEFS.map(d => [d.key, d.name]));
const TIER_DEF = Object.fromEntries(TIER_DEFS.map(d => [d.key, d]));
const tierOk = t => TIERS.includes(t);
const rowTier = b => (b && tierOk(b.tier)) ? b.tier : 'weekly'; // bought rows before 2026-10-18 have no tier: weekly
const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
// Bonus heroes for Shards of Valor (Marty approved 2026-11-05, Dallas's request): SOLD ONE TIME, no subscription, owned for good. Paid
// exactly like a pass: no credits, no direct POL; buying opens a waiting order, fulfilled by a FRESH package of at least the price
// bought by one of the member's own positions, so the sponsor line is paid as usual (onEvent). $20 each = the Activation package; the
// $50 bundle (the Builder package) is a settings list, default Valda + Morag + Roland (Dallas 13:26; Marty approved a $50 bundle of
// three). Settings (Admin > Settings, no deploy): heroSales (sale switch, default OFF), heroPrice<Set>Cents per hero (0 = free for
// every account, granted like a base hero), heroBundlePriceCents, heroBundleHeroes, heroBundleCap (a level the bundle would raise the
// cap to; UNSET = no cap change, Marty has not approved one). key = the wire value Shards of Valor reads (classes.json paid buy).
// 2026-11-14 (Marty approved, "Yes make it free"; Dallas: "The Archer should be free to everyone at level 20"): Kestrel is FREE for every
// player once a hero in their party reaches level 20 (the game decides, Shards of Valor classes.json freeAt) and is NOT SOLD here any more
// (freeAt): no buy, not in any bundle, waiting Kestrel orders are cancelled unpaid. A member who bought her keeps her (record.heroes.kestrel);
// nothing refunded. Valda, Morag and Roland, the $50 bundle and every price are unchanged.
const HERO_DEFS = [
{ key: 'kestrel', set: 'Kestrel', name: 'Kestrel the Archer', price: 2000, freeAt: 20, blurb: 'Quick and sharp-eyed: arrows on every foe.' },
{ key: 'valda', set: 'Valda', name: 'Valda the Barbarian', price: 2000, blurb: 'A berserker: hits harder the more she is hurt, light on armour.' },
{ key: 'morag', set: 'Morag', name: 'Morag the Druid', price: 2000, blurb: 'A healer of the wild: heals the whole party.' },
{ key: 'roland', set: 'Roland', name: 'Roland the Paladin', price: 2000, blurb: 'A holy knight: sword and shield, heals one hero at a time.' },
];
const HERO_KEYS = HERO_DEFS.map(d => d.key);
const HERO_DEF = Object.fromEntries(HERO_DEFS.map(d => [d.key, d]));
const HERO_SOLD = HERO_DEFS.filter(d => !d.freeAt).map(d => d.key); // free at a level in the game (Kestrel at 20): never sold, never in a bundle
const HERO_BUNDLE_DEFAULT = 'valda,morag,roland';
let R = null; // deps from server.js
let passes, orders, prizes, stackpro; // stackpro: Stack POL Pro owners, email -> { ts, tx, cents, order } (2026-11-09). durable persisted maps (server.js open-tokens store, DURABLE set)
let L = null; // the cap ledger: { members: { email: { days: {}, deferred: {}, weeks: {} } }, refs: { 'game:ref': {...} } }
let saveTimer = null;
// ---- Central time (no tz lib; same arithmetic as leaderboard.js) ----
function ctParts(ts) {
const s = new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' });
const m = /(\w{3}), (\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/.exec(s);
return { wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(m[1]), y: +m[4], mo: +m[2], d: +m[3], h: +m[5] % 24, mi: +m[6] };
}
function ctMidnight(ts) { const p = ctParts(ts); const guess = Date.UTC(p.y, p.mo - 1, p.d, 5, 0, 0); const q = ctParts(guess); return (q.h === 0 && q.d === p.d) ? guess : guess + 3600000; }
function weekStart(ts) { const p = ctParts(ts); const mid = ctMidnight(ts); return mid - ((p.wd + 6) % 7) * 86400000; }
const dayKey = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
const weekKey = ts => dayKey(weekStart(ts));
const dayLabel = key => new Date(key + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
// ---- settings (Admin > Settings, no deploy) ----
function cfg() {
const sc = R.siteConfig();
const n = (k, d) => { const raw = sc[k]; if (raw === undefined || raw === null || String(raw).trim() === '') return d; const v = Number(raw); return Number.isFinite(v) ? v : d; };
const start = String(sc.capsStartDate || '').trim();
const on = k => ['1', 'true', 'on', 'yes'].includes(String(sc[k]).trim().toLowerCase());
const offExplicit = k => ['0', 'false', 'off', 'no'].includes(String(sc[k]).trim().toLowerCase());
const price = Math.max(1, Math.round(n('gamePassPriceCredits', 500))), days = Math.max(1, Math.round(n('gamePassDays', 7)));
return {
enabled: on('gamePassEnabled'),
price, days,
// per tier: price in purchased-grade credits (100 = $1), length, and whether it is on sale. Every tier above weekly needs the
// master switch sovTiers AND the weekly pass switched on; its own gamePass<Set>Enabled is a kill switch (missing = on).
tierSales: on('sovTiers'),
tiers: Object.fromEntries(TIER_DEFS.map(d => [d.key, d.key === 'weekly' ? { price, days, sale: on('gamePassEnabled') }
: { price: Math.max(1, Math.round(n('gamePass' + d.set + 'PriceCredits', d.price))), days: Math.max(1, Math.round(n('gamePass' + d.set + 'Days', d.days))),
sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePass' + d.set + 'Enabled') }])),
tournamentTierSales: on('passTournamentTierSales'), // off: only weekly pass sales feed the Pass Tournament pool (exactly as before tiers)
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
// the free allowance (Marty 2026-11-02, "cap these so that if the user wants to keep playing they spend a tiny amount"):
// the most game POL an account EVER receives while it holds no pass, across every game. After that, progress rewards
// wait as deferred until a pass is active and repeatable rewards are dropped. 2 POL default; admin key capFreeLifetime.
freeLifetime: Math.max(0, n('capFreeLifetime', 2.0)),
pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) },
start: /^\d{4}-\d{2}-\d{2}$/.test(start) ? start : '',
pct: Math.max(0, n('passTournamentPct', 5)),
gamesChat: String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(),
gamesTopic: String(sc.telegramGamesTopicId || '').trim(),
heroes: (() => {
const price = Object.fromEntries(HERO_DEFS.map(d => [d.key, Math.max(0, Math.round(n('heroPrice' + d.set + 'Cents', d.price)))]));
const raw = sc.heroBundleHeroes == null || String(sc.heroBundleHeroes).trim() === '' ? HERO_BUNDLE_DEFAULT : String(sc.heroBundleHeroes);
const list = [...new Set(raw.split(',').map(x => x.trim().toLowerCase()).filter(k => HERO_SOLD.includes(k) && price[k] > 0))];
const capRaw = String(sc.heroBundleCap == null ? '' : sc.heroBundleCap).trim(), cap = capRaw === '' ? NaN : Number(capRaw);
return { sale: on('heroSales'), price, free: HERO_KEYS.filter(k => price[k] === 0), bundle: { heroes: list.length >= 2 ? list : [], price: Math.max(1, Math.round(n('heroBundlePriceCents', 5000))) },
cap: Number.isInteger(cap) && cap > 0 ? cap : null };
})(),
};
}
const enforcedOn = (c, day) => !!(c.start && day >= c.start);
// ---- ledger file ----
const FILE = () => path.join(R.dataDir, 'gamepass-ledger.json');
function load() { try { L = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { L = null; } if (!L || typeof L !== 'object') L = { members: {}, refs: {} }; L.members = L.members || {}; L.refs = L.refs || {}; }
function save() { saveTimer = null; try { fs.writeFileSync(FILE(), JSON.stringify(L)); } catch (e) { console.error('gamepass ledger save', e.message); } }
function touch() { if (!saveTimer) saveTimer = setTimeout(save, 500); }
function member(e) { return (L.members[e] = L.members[e] || { days: {}, deferred: {}, weeks: {} }); }
function dayRow(M, day) {
return (M.days[day] = M.days[day] || { daily: 0, total: 0, carried: 0, dropped: 0, deferredOut: 0, grants: 0, hits: { daily: 0, total: 0 },
tier: { free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 } },
would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 } }); // would = what the caps would have done before capsStartDate
}
function init(deps) {
R = deps;
passes = R.persistedMap('gamepass');
orders = R.persistedMap('gporders');
prizes = R.persistedMap('gpprizes');
stackpro = R.persistedMap('stackpro');
load();
}
// ---- the pass ----
function rec(e) { return passes.get(e) || null; }
// per-tier expiry (ms, 0 = never held). A record from before tiers has no `tiers`: its legacy `until` is the weekly tier
// (lazy migration, idempotent: every write stores `tiers` and mirrors tiers.weekly into `until`).
function tiersOf(p) {
const out = {}; const T = (p && p.tiers) || {};
for (const k of TIERS) out[k] = Number(T[k] && T[k].until) || 0;
if (p && !p.tiers) out.weekly = Number(p.until) || 0;
return out;
}
function topTier(T, t) { for (let i = TIERS.length - 1; i >= 0; i--) if (T[TIERS[i]] > t) return TIERS[i]; return null; }
// { active, until, tier, tiers }: active = any tier on (every tier is a Game Pass holder everywhere, same caps); tier = the
// highest active tier; until = that tier's end. With nothing active, until is the last end the account ever had (as before
// tiers) or null. tiers = each tier's end while it is active, else null.
function flag(email, now) {
const p = rec(String(email || '').toLowerCase()); const t = now || Date.now(); const T = tiersOf(p); const tier = topTier(T, t);
const tiers = {}; for (const k of TIERS) tiers[k] = T[k] > t ? T[k] : null;
const last = Math.max(...TIERS.map(k => T[k]));
return { active: !!tier, until: tier ? T[tier] : (last || null), tier, tiers };
}
function writeTiers(cur, T, extra) {
const tiers = {}; for (const k of TIERS) if (T[k]) tiers[k] = { until: T[k] };
return Object.assign({}, cur, { until: T.weekly || 0, tiers }, extra || {});
}
function extend(e, via, extra, now, tier) {
tier = tierOk(tier) ? tier : 'weekly';
const c = cfg(); const tc = c.tiers[tier]; const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] };
const T = tiersOf(cur);
const until = Math.max(t, T[tier]) + tc.days * 86400000; T[tier] = until; // renewing early loses nothing: from max(now, until)
const bought = [Object.assign({ ts: t, via, tier, usd: tc.price / 100, days: tc.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
passes.set(e, writeTiers(cur, T, { bought, ts: t }));
return { until, days: tc.days, tier };
}
function waitingOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind !== 'hero' && o.kind !== 'stackpro') out.push(Object.assign({ order: k }, o, { tier: tierOk(o.tier) ? o.tier : 'weekly' })); return out; }
function waitingOrder(e, tier) { return waitingOrders(e).find(o => o.tier === (tier || 'weekly')) || null; }
// the admin's tier test: drop a waiting order that was opened for testing, so a later real package never fulfils it by surprise
function cancelOrder(email, tier) {
const e = String(email || '').toLowerCase(); const w = waitingOrder(e, tier || 'weekly'); if (!w) return { ok: true, none: true };
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order, tier: w.tier };
}
function comp(email, why, tier, now) { // support comp: counts as no sale
const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }, now, tier);
return { active: true, until: x.until, days: x.days, tier: x.tier };
}
// support refund (never automatic): that tier ends now; the record keeps what it was
function revoke(email, tier, why, now) {
const e = String(email || '').toLowerCase(); if (!tierOk(tier)) return { error: 'unknown tier' };
const t = now || Date.now(); const p = passes.get(e); const T = tiersOf(p);
if (!p || !(T[tier] > t)) return { error: 'No active ' + TIER_NAMES[tier] + ' pass on this account.' };
const was = T[tier]; T[tier] = t;
passes.set(e, writeTiers(p, T, { revokes: [{ ts: t, tier, why: String(why || 'support').slice(0, 80), was }].concat(p.revokes || []).slice(0, 50) }));
return { ok: true, tier, was, until: t };
}
// on sale for this viewer: the tier's own switch, or the admin portal's tier test (Admin > Game Pass) while sovTiers is off
const tierOpen = (c, tier, preview) => !!(c.tiers[tier].sale || (preview && tier !== 'weekly'));
const PACKAGE_USD = [5, 10, 20, 50, 100, 250, 500]; // copy only: the package that covers a price
const packageFor = usd => PACKAGE_USD.find(x => x >= usd) || usd;
// GET /api/my/gamepass: exactly what a member sees, for EVERY account, the admin's included (2026-10-25, Marty: no admin-only
// tier UI on the member card). opts.preview = the admin portal's tier test (GET /api/admin/gamepass/preview): every tier, each
// one open to the admin's own account while sovTiers is off.
function view(email, now, opts) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const f = flag(e, t); const p = rec(e); const w = waitingOrder(e, 'weekly');
const admin = !!(opts && opts.preview); const T = tiersOf(p);
const caps = capsFor(e, t);
// the tier rows this member sees: weekly always; a higher tier while on sale, in the admin preview, or to a current holder (holders
// keep their pass when a sale is switched off, they just cannot buy more)
const passRows = TIERS.filter(k => k === 'weekly' || c.tiers[k].sale || admin || T[k] > t).map(k => {
const tc = c.tiers[k]; return { tier: k, name: TIER_NAMES[k], perks: TIER_DEF[k].perks, price: tc.price, usd: tc.price / 100, days: tc.days, package: packageFor(tc.price / 100),
active: T[k] > t, until: T[k] > t ? T[k] : null, waiting: !!waitingOrder(e, k), sale: !!tc.sale, open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
});
const tiered = passRows.some(r => r.tier !== 'weekly');
return { enabled: c.enabled, active: f.active, until: f.until, tier: f.tier, price: c.price, days: c.days, usd: c.price / 100,
waiting: !!w, waitingSince: w ? w.ts : null, bought: p ? (p.bought || []).length : 0,
caps, capsStart: c.start || null, lastCapHit: p && p.lastCapHit && (t - p.lastCapHit.ts) < 2 * 86400000 ? p.lastCapHit : null,
tournament: { pct: c.pct, shares: SHARES, next: nextTournamentAt(t) },
show: c.enabled || tiered, passes: passRows, tierPreview: tiered && admin && !c.tierSales,
heroes: heroView(e, t, opts) }; // bonus heroes (2026-11-05): sold one time, shown while heroSales is on, to an owner, or in the admin test
}
// POST /api/my/gamepass/buy { tier }. tier missing = weekly (exactly the pass as it was before tiers). opts.preview = the admin
// portal's tier test (POST /api/admin/gamepass/test-buy, the admin's own account only): a tier that is not on sale still opens an order.
// A pass is ALWAYS paid by a fresh package purchase (2026-10-22, Marty: the pass rides the package rail so sponsors get paid). This never
// spends credits: it opens (or reuses) a waiting order for that tier and sends the member to buy a package of at least the tier price.
// The order is fulfilled by onEvent() below; the member keeps every credit of that package for ads.
function buy(email, now, tier, opts) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
tier = (tier === undefined || tier === null || tier === '') ? 'weekly' : String(tier).toLowerCase();
if (!tierOk(tier)) return { error: 'There is no such pass.' };
const tc = c.tiers[tier]; const name = TIER_NAMES[tier];
if (tier === 'weekly') { if (!c.enabled) return { error: 'The Game Pass is not open yet.' }; }
else if (!tierOpen(c, tier, !!(opts && opts.preview))) return { error: 'The ' + name + ' pass is not open yet.' };
let w = waitingOrder(e, tier); const reused = !!w;
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, tier }); w = Object.assign({ order: k }, orders.get(k)); }
const pkg = packageFor(tc.price / 100);
if (!reused) console.log('gamepass order opened', tier, e, w.order, 'needs a package of', tc.price, 'cents');
return { ok: false, needPay: true, tier, payUrl: tier === 'weekly' ? '/my?from=gamepass#buy' : '/my?from=gamepass&tier=' + tier + '#buy', order: w.order, orderTs: w.ts, reused,
price: tc.price, usd: tc.price / 100, package: pkg,
message: (tier === 'weekly' ? 'Your Game Pass' : 'Your ' + name + ' pass') + ' starts the moment your next package of $' + pkg + ' or more settles on chain. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
}
// Stack POL Pro (Marty 2026-11-09): a one-time unlock for the member's stackpol.com page (their LinkSpin Banner Spins and spin links
// on the page, the shareable stack card). Like a pass or a hero it is NEW MONEY only: "Get Pro" opens a waiting order, and the next
// package purchase of $10 or more by one of the member's own positions fulfils it (onEvent). Never credits, never direct POL; the
// member keeps every credit of the package and the sponsor line is paid on chain as usual. Owned for good once paid.
const STACK_PRO_CENTS = 1000;
function stackOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'stackpro') out.push(Object.assign({ order: k }, o)); return out; }
function stackPro(email) { const e = String(email || '').toLowerCase(); return stackpro.get(e) || null; }
function stackProView(email) { const e = String(email || '').toLowerCase(); const own = stackpro.get(e) || null; const w = stackOrders(e)[0] || null; return { pro: !!own, since: own ? own.ts : null, waiting: !!w, order: w ? w.order : null, usd: STACK_PRO_CENTS / 100 }; }
function buyStackPro(email, now) {
const e = String(email || '').toLowerCase(); const t = now || Date.now();
if (stackpro.get(e)) return { ok: true, pro: true };
let w = stackOrders(e)[0]; const reused = !!w;
if (!w) { const k = 'sp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, kind: 'stackpro' }); w = Object.assign({ order: k }, orders.get(k)); console.log('stack pro order opened', e, k); }
return { ok: false, needPay: true, payUrl: '/my?from=stackpro#buy', order: w.order, orderTs: w.ts, reused, usd: STACK_PRO_CENTS / 100, package: packageFor(STACK_PRO_CENTS / 100),
message: 'Stack POL Pro switches on the moment your next package of $10 or more settles on chain. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
}
function cancelStackOrder(email) { const e = String(email || '').toLowerCase(); const w = stackOrders(e)[0]; if (!w) return { ok: true }; orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order }; }
function compStackPro(email, on, note) { const e = String(email || '').toLowerCase(); if (on) stackpro.set(e, { ts: Date.now(), via: 'comp', note: String(note || '').slice(0, 120) }); else stackpro.delete(e); return { ok: true, pro: !!on }; }
// a package bought WITHOUT a Pro order first, granted by the admin (Marty 2026-11-09, Orlando's $10 package): recorded as a
// package sale with its tx so it counts as new money, and the tx is marked used like any fulfilment
function grantStackProForPackage(email, tx, cents, buyerId, note) {
const e = String(email || '').toLowerCase(); if (!e) return { error: 'No account.' };
if (stackpro.get(e)) return { ok: true, already: true };
stackpro.set(e, { ts: Date.now(), via: 'package', tx, cents, buyerId, note: String(note || 'admin grant: package bought without a Pro order').slice(0, 120) });
console.log('stack pro granted for package', e, tx, cents, 'cents');
return { ok: true, pro: true };
}
// Marty 2026-11-09 (evening): "Any $10 package or higher unlocks it". No Get Pro step: the member's own package purchase of $10 or more,
// on chain, switches Pro on for good. Still new money only (credits never reach onEvent). Only packages from the Pro launch on count
// (a reindex of older history never hands it out). A Pro order left waiting from the first version is closed as paid by the same tx.
const PRO_START = Date.parse('2026-11-09T21:30:00Z');
function proFromPackage(e, ev, cents) {
if (cents < STACK_PRO_CENTS || stackpro.get(e)) return false;
const t = (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()); if (t < PRO_START) return false;
stackpro.set(e, { ts: t, via: 'package', tx: ev.tx, cents, buyerId: Number(ev.buyerId) || 0 });
for (const o of stackOrders(e)) orders.set(o.order, Object.assign({}, orders.get(o.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), buyerId: Number(ev.buyerId) || 0 }));
console.log('stack pro unlocked by package', e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents');
return true;
}
function stackProOwners() { return [...stackpro.keys()]; }
// A package purchase landing on chain fulfils one of this account's waiting orders: the highest-priced one the package covers.
// Rules (2026-10-22): the buyer must be one of this account's own positions (main member id or a linked position); the purchase must
// be mined AFTER the order was opened (block time, ORDER_SKEW_MS for clock drift); one pass per purchase of $5 or more; each tx used
// once across every account and order. Credit balances never fulfil an order.
const ORDER_SKEW_MS = 30000;
function txUsed(tx) {
if (!tx) return false;
for (const [, o] of orders) if (o && o.tx === tx) return true;
for (const [, p] of passes) if (p && (p.bought || []).some(b => b.tx && b.tx === tx)) return true;
return false;
}
async function ownerOf(ev) { // the account behind the buying position
if (ev.devEmail && !R.isProd) return String(ev.devEmail).toLowerCase();
const id = Number(ev.buyerId) || 0; if (!id) return null;
let a = await R.accounts.byMemberId(id);
if (!a && R.accounts.positionByMember) { const pos = await R.accounts.positionByMember(id); if (pos && pos.email) a = { email: pos.email }; }
return a && a.email ? String(a.email).toLowerCase() : null;
}
async function minedAt(ev) { // block time in ms; the indexed-at time only when the block cannot be read (it is never earlier than the block)
if (ev.devMinedAt && !R.isProd) return Number(ev.devMinedAt);
if (ev.block && R.blockTime) {
for (let i = 0; i < 3; i++) { try { const s = await R.blockTime(ev.block); if (s > 0) return s * 1000; } catch (e) {} await new Promise(r => setTimeout(r, 1500)); }
console.warn('gamepass: block time unavailable for', ev.block, '- using the indexed-at time');
}
return Number(ev.ts) || Date.now();
}
async function onEvent(ev) {
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
const c = cfg(); const cents = ev.priceCents || 0;
if (!TIERS.some(k => cents >= c.tiers[k].price) && !heroOrderPrices(c).some(x => cents >= x) && cents < STACK_PRO_CENTS) return null;
const e = await ownerOf(ev); if (!e) return null;
const pro = proFromPackage(e, ev, cents); // any $10+ package unlocks Stack POL Pro; it rides along, never takes the package from an order
const withPro = r => pro ? Object.assign(r || {}, { stackPro: true, email: e }) : r;
if (!waitingOrders(e).length && !heroOrders(e).length) return withPro(null);
if (txUsed(ev.tx)) return withPro(null); // each purchase counts once, everywhere
const at = await minedAt(ev);
// one package fulfils ONE order, pass or bonus hero (2026-11-05): the highest-priced one it covers, then the oldest
const all = waitingOrders(e).map(o => Object.assign({ price: c.tiers[o.tier].price }, o)).concat(heroOrders(e).filter(o => heroOrderOpen(e, o.hero)).map(o => Object.assign({ price: heroOrderPrice(c, o.hero) }, o))).concat(stackpro.get(e) ? [] : stackOrders(e).map(o => Object.assign({ price: STACK_PRO_CENTS }, o)));
const w = all.filter(o => cents >= o.price && at + ORDER_SKEW_MS >= o.ts).sort((x, y) => y.price - x.price || x.ts - y.ts)[0];
if (!w) { console.log('gamepass: package', String(ev.tx).slice(0, 12), 'by', e, 'fulfils no order (bought before the order or too small)'); return withPro(null); }
if (w.kind === 'stackpro') {
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
stackpro.set(e, { ts: (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()), via: 'package', tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0 });
console.log('stack pro fulfilled by package', e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents');
return { order: w.order, stackPro: true, email: e };
}
if (w.kind === 'hero') {
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
const g = grantHeroes(e, w.hero, 'package', { tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0, usd: heroOrderPrice(c, w.hero) / 100, packageUsd: cents / 100 }, (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()));
console.log('bonus heroes fulfilled by package', w.hero, e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents:', g.heroes.join(','));
return withPro({ order: w.order, hero: w.hero, heroes: g.heroes });
}
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
const x = extend(e, 'package', { tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0, usd: c.tiers[w.tier].price / 100, packageUsd: cents / 100 }, (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()), w.tier);
console.log('gamepass fulfilled by package', w.tier, e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents, until', new Date(x.until).toISOString());
return withPro({ order: w.order, until: x.until, tier: w.tier });
}
// ---- bonus heroes (2026-11-05) ----
// owned for good: record.heroes = { kestrel: { ts, via, tx, order, cents, usd, bundle? } }, record.heroBundle = { ts, via, heroes, tx, order }
// (in the passes map, the same durable record as the passes). A hero is never in `bought`, so hero sales never feed the Pass Tournament pool.
function heroOrders(e) {
const out = [];
for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'hero') {
if (HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt) { orders.set(k, Object.assign({}, o, { status: 'cancelled', cancelledAt: Date.now(), why: 'free at level ' + HERO_DEF[o.hero].freeAt + ' in the game' })); continue; } // never paid: she is free now
out.push(Object.assign({ order: k }, o));
}
return out;
}
function heroOrder(e, key) { return heroOrders(e).find(o => o.hero === key) || null; }
const heroOrderPrice = (c, key) => key === 'bundle' ? c.heroes.bundle.price : (c.heroes.price[key] || 0);
const heroOrderPrices = c => [c.heroes.bundle.price].concat(HERO_SOLD.map(k => c.heroes.price[k]).filter(x => x > 0));
// a waiting hero order still worth fulfilling: nothing in it is owned yet (a bundle also needs its list set)
function heroOrderOpen(e, key) { const c = cfg(), own = new Set(heroesOwned(e).owned); if (key === 'bundle') return c.heroes.bundle.heroes.length > 0 && !c.heroes.bundle.heroes.some(k => own.has(k)); return HERO_SOLD.includes(key) && !own.has(key); }
// -> { owned: bought, comped and free heroes; bought: on the record; bundle: bought as the bundle }
function heroesOwned(email) {
const p = rec(String(email || '').toLowerCase()), c = cfg(), H = (p && p.heroes) || {};
return { owned: HERO_KEYS.filter(k => H[k] || c.heroes.free.includes(k)), bought: HERO_KEYS.filter(k => H[k]), bundle: !!(p && p.heroBundle) };
}
// the hand-off claim for Shards of Valor (server.js sovMint): what this member owns, and the current sale (the game keeps it, so a free
// hero opens for guests too)
function heroClaim(email) {
const c = cfg(), h = heroesOwned(email), out = { heroes: h.owned, heroBundle: h.bundle, heroSale: { free: c.heroes.free, bundle: c.heroes.bundle.heroes, each: (c.heroes.price.valda || 2000) / 100, bundlePrice: c.heroes.bundle.price / 100 } };
if (h.bundle && c.heroes.cap) out.heroBundleCap = c.heroes.cap; // only once Marty sets heroBundleCap (unset today: heroes only)
return out;
}
function grantHeroes(e, key, via, extra, now) {
const t = now || Date.now(), c = cfg(), cur = passes.get(e) || { until: 0, bought: [] }, H = Object.assign({}, cur.heroes || {});
const list = key === 'bundle' ? c.heroes.bundle.heroes.slice() : [key], got = [];
for (const k of list) if (!H[k]) { H[k] = Object.assign({ ts: t, via }, extra || {}, key === 'bundle' ? { bundle: true } : {}); got.push(k); }
const upd = { heroes: H }; if (key === 'bundle') upd.heroBundle = Object.assign({ ts: t, via, heroes: list }, extra || {});
passes.set(e, Object.assign({}, cur, upd));
// never a second charge for a hero you have: drop waiting orders that are now owned (in full or in part)
for (const o of heroOrders(e)) if (!heroOrderOpen(e, o.hero)) orders.set(o.order, Object.assign({}, orders.get(o.order), { status: 'cancelled', cancelledAt: t, why: 'already owned' }));
return { heroes: got, owned: heroesOwned(e).owned };
}
// the member card part: every hero, its price and state, and the bundle. open = on sale (heroSales) or the admin portal's test (opts.preview)
function heroView(email, now, opts) {
const e = String(email || '').toLowerCase(), c = cfg(), h = heroesOwned(e), own = new Set(h.owned), preview = !!(opts && opts.preview), open = c.heroes.sale || preview;
const items = HERO_DEFS.map(d => { const price = c.heroes.price[d.key], fa = d.freeAt || null; return { key: d.key, name: d.name, blurb: d.blurb, price, usd: price / 100, package: packageFor(price / 100), free: price === 0, freeAt: fa, owned: own.has(d.key), waiting: !fa && !!heroOrder(e, d.key), open: !fa && open && price > 0 && !own.has(d.key) }; });
const B = c.heroes.bundle, bOwn = B.heroes.filter(k => own.has(k));
const bundle = B.heroes.length ? { key: 'bundle', names: B.heroes.map(k => HERO_DEF[k].name), heroes: B.heroes, price: B.price, usd: B.price / 100, package: packageFor(B.price / 100), owned: bOwn.length === B.heroes.length, some: bOwn.length > 0, waiting: !!heroOrder(e, 'bundle'), open: open && !bOwn.length } : null;
return { sale: c.heroes.sale, preview: preview && !c.heroes.sale, show: c.heroes.sale || preview || h.bought.length > 0, items, bundle, owned: h.owned, bundleOwned: h.bundle };
}
// POST /api/my/heroes/buy { hero: kestrel | valda | morag | roland | bundle }: opens (or reuses) a waiting order; a fresh package of at
// least the price fulfils it (onEvent). Never spends credits. Refuses a hero already owned, a free one, and a bundle when any of its
// heroes is already owned (the rest one at a time costs less).
function buyHero(email, now, key, opts) {
const e = String(email || '').toLowerCase(), c = cfg(), t = now || Date.now(); key = String(key || '').toLowerCase();
if (key !== 'bundle' && !HERO_KEYS.includes(key)) return { error: 'There is no such hero.' };
if (!(c.heroes.sale || (opts && opts.preview))) return { error: 'Bonus heroes are not on sale yet.' };
const own = new Set(heroesOwned(e).owned);
if (key === 'bundle') {
const B = c.heroes.bundle; if (!B.heroes.length) return { error: 'There is no hero bundle right now.' };
const have = B.heroes.filter(k => own.has(k)); if (have.length) return { error: 'You already have ' + have.map(k => HERO_DEF[k].name).join(' and ') + ', so the bundle is not for you: get the others one at a time.' };
} else {
if (HERO_DEF[key].freeAt) return { error: HERO_DEF[key].name + ' is free for every player at level ' + HERO_DEF[key].freeAt + ' in Shards of Valor, so she is not for sale.' };
if (c.heroes.price[key] === 0) return { error: HERO_DEF[key].name + ' is free for everyone.' };
if (own.has(key)) return { error: 'You already have ' + HERO_DEF[key].name + '. Heroes are yours for good.' };
}
let w = heroOrder(e, key); const reused = !!w;
if (!w) { const k = 'hero-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', kind: 'hero', hero: key, email: e, ts: t }); w = Object.assign({ order: k }, orders.get(k)); }
const price = heroOrderPrice(c, key), pkg = packageFor(price / 100);
const name = key === 'bundle' ? 'The hero bundle (' + c.heroes.bundle.heroes.map(k => HERO_DEF[k].name).join(', ') + ')' : HERO_DEF[key].name;
if (!reused) console.log('bonus hero order opened', key, e, w.order, 'needs a package of', price, 'cents');
return { ok: false, needPay: true, hero: key, payUrl: '/my?from=heroes&hero=' + key + '#buy', order: w.order, orderTs: w.ts, reused, price, usd: price / 100, package: pkg,
message: name + ' joins you in Shards of Valor the moment your next package of $' + pkg + ' or more settles on chain. One time, yours for good. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
}
function cancelHeroOrder(email, key) {
const e = String(email || '').toLowerCase(), w = heroOrder(e, String(key || '').toLowerCase()); 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, hero: w.hero };
}
function compHero(email, key, why) { // support or the admin test: counts as no sale
const e = String(email || '').toLowerCase(); key = String(key || '').toLowerCase(); if (key !== 'bundle' && !HERO_KEYS.includes(key)) return { error: 'There is no such hero.' };
return Object.assign({ ok: true }, grantHeroes(e, key, 'admin', { note: String(why || 'support').slice(0, 80), usd: 0 }));
}
function revokeHero(email, key, why) { // support only (an admin test, a mistaken comp); never automatic
const e = String(email || '').toLowerCase(); key = String(key || '').toLowerCase(); const p = passes.get(e); const H = Object.assign({}, (p && p.heroes) || {});
const keys = key === 'all' ? Object.keys(H) : [key]; if (!p || !keys.some(k => H[k])) return { error: 'This account does not own that hero.' };
const gone = []; for (const k of keys) if (H[k]) { gone.push(Object.assign({}, H[k], { hero: k, revokedAt: Date.now(), why: String(why || 'support').slice(0, 80) })); delete H[k]; }
const upd = { heroes: H, heroRevokes: gone.concat(p.heroRevokes || []).slice(0, 50) };
if (p.heroBundle && !(p.heroBundle.heroes || []).every(k => H[k])) upd.heroBundle = null;
passes.set(e, Object.assign({}, p, upd)); return { ok: true, revoked: gone.map(g => g.hero) };
}
function heroStats() {
const c = cfg(); const out = { sale: c.heroes.sale, sold: Object.fromEntries(HERO_KEYS.map(k => [k, 0])), bundles: 0, comped: 0, usd: 0, waiting: 0 };
for (const [, p] of passes) {
if (!p) continue;
for (const [k, h] of Object.entries(p.heroes || {})) { if (!(k in out.sold)) continue; if (h.via === 'admin') { out.comped += 1; continue; } out.sold[k] += 1; if (!h.bundle) out.usd += Number(h.usd) || 0; }
if (p.heroBundle && p.heroBundle.via !== 'admin') { out.bundles += 1; out.usd += Number(p.heroBundle.usd) || 0; }
}
for (const [, o] of orders) if (o.status === 'waiting' && o.kind === 'hero' && !(HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt)) out.waiting += 1;
out.usd = Math.round(out.usd * 100) / 100; return out;
}
// ---- the caps ----
function capsFor(email, now, game) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const day = dayKey(t); const pass = flag(e, t).active;
const lim = pass ? c.pass : c.free; const M = L.members[e]; const D = M && M.days[day];
const used = { daily: r6(D ? D.daily : 0), total: r6(D ? D.total : 0) };
const out = { daily: lim.daily, total: lim.total, used, day, enforced: enforcedOn(c, day), pass };
out.lifetime = { cap: c.freeLifetime, used: r6(M && M.freeTotal != null ? M.freeTotal : (M ? Object.values(M.days).reduce((n, d) => n + ((d.tier && d.tier.free && d.tier.free.allowed) || 0), 0) : 0)) }; // the free allowance, what has been used of it
if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0));
out.lifetime.done = !pass && out.lifetime.used + 1e-9 >= out.lifetime.cap; // the free allowance is used up (only a pass pays from here)
out.lifetime.waiting = M ? r6(Object.values(M.deferred).reduce((n, q) => n + (q || []).reduce((m, x) => m + (x.left || 0), 0), 0)) : 0;
return out;
}
// quest-site check (Zealy, 2026-11-05): has this account earned any game reward, and how much in total
function activity(email) {
const M = L.members[String(email || '').toLowerCase()]; if (!M) return { grants: 0, pol: 0 };
return Object.values(M.days).reduce((o, d) => ({ grants: o.grants + (d.grants || 0), pol: r6(o.pol + (d.total || 0)) }), { grants: 0, pol: 0 });
}
// POST /api/partner/polgrant. Returns { allowed, deferred, pass, day } (+ carried, capHit, enforced, repeat).
function grant(o) {
const e = String(o.email || '').toLowerCase(); const game = String(o.game || '').toLowerCase(); const kind = o.kind === 'progress' ? 'progress' : 'daily';
const pol = r6(o.pol); const ref = String(o.ref || '').slice(0, 120); const t = o.now || Date.now(); const day = dayKey(t);
if (!e || !GAMES.includes(game) || !ref || !(pol >= 0)) return { error: 'memberId/email, game, kind, pol and ref are required' };
const key = game + ':' + ref;
const prev = L.refs[key];
if (prev) return { allowed: prev.allowed, deferred: prev.deferred, pass: prev.pass, day: prev.day, carried: prev.carried || 0, capHit: prev.capHit || null, enforced: !!prev.enforced, repeat: true, voided: !!prev.voided };
const c = cfg(); const pass = flag(e, t).active; const lim = pass ? c.pass : c.free; const enforced = enforcedOn(c, day);
const M = member(e); const D = dayRow(M, day); const tier = D.tier[pass ? 'pass' : 'free'];
let totalRem = Math.max(0, r6(lim.total - D.total)), dailyRem = Math.max(0, r6(lim.daily - D.daily));
// the free allowance: a running total of what this account received while it held no pass (seeded once from the day rows
// still on file); once it reaches freeLifetime, a free account's room for today is zero, carry included
if (M.freeTotal == null) M.freeTotal = r6(Object.values(M.days).reduce((n, d) => n + ((d.tier && d.tier.free && d.tier.free.allowed) || 0), 0));
let lifetimeHit = false;
if (!pass && enforced) { const room = Math.max(0, r6(c.freeLifetime - M.freeTotal)); if (room < totalRem) totalRem = room; lifetimeHit = room < pol; } // hit = the allowance, not the day, is what trims this grant
// carry-forward: progress POL deferred on an EARLIER day for this game is paid first, inside today's total cap
let carried = 0; const q = M.deferred[game] || [];
for (const d of q) {
if (d.day >= day || d.left <= 0) continue;
const take = enforced ? Math.min(d.left, Math.max(0, r6(totalRem - carried))) : d.left;
if (take <= 0) break;
d.left = r6(d.left - take); carried = r6(carried + take); d.paid = (d.paid || []).concat([{ day, pol: take, ref }]).slice(-20);
}
M.deferred[game] = q.filter(d => d.left > 0);
if (carried) { D.total = r6(D.total + carried); D.carried = r6(D.carried + carried); tier.allowed = r6(tier.allowed + carried); totalRem = Math.max(0, r6(totalRem - carried)); }
// the new grant
let allowed = pol, deferred = 0, dropped = 0, capHit = null;
const wouldAllowed = kind === 'daily' ? Math.min(pol, dailyRem, totalRem) : Math.min(pol, totalRem);
const wouldHit = wouldAllowed < pol ? (kind === 'daily' && dailyRem <= totalRem ? 'daily' : 'total') : null;
if (enforced) {
allowed = r6(wouldAllowed); capHit = wouldHit;
if (kind === 'daily') { dropped = r6(pol - allowed); if (dropped) D.dropped = r6(D.dropped + dropped); }
else { deferred = r6(pol - allowed); if (deferred) { q.push({ ref, pol, left: deferred, ts: t, day }); M.deferred[game] = q; D.deferredOut = r6(D.deferredOut + deferred); } }
if (capHit) { D.hits[capHit] += 1; tier[capHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1; }
} else if (wouldHit) { // before capsStartDate: everything is allowed, but Admin sees what the caps would have done
D.would[kind === 'daily' ? 'dropped' : 'deferred'] = r6(D.would[kind === 'daily' ? 'dropped' : 'deferred'] + (pol - wouldAllowed));
D.would[wouldHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1;
}
if (kind === 'daily') D.daily = r6(D.daily + allowed);
D.total = r6(D.total + allowed); tier.allowed = r6(tier.allowed + allowed); D.grants += 1;
if (!pass) M.freeTotal = r6((M.freeTotal || 0) + allowed + carried); // counts toward the free allowance only while no pass is held
// tournament activity: one point per reported grant (progress and daily weigh the same)
if (pol > 0) { const wk = weekKey(t); M.weeks[wk] = M.weeks[wk] || {}; M.weeks[wk][game] = (M.weeks[wk][game] || 0) + 1; }
if (capHit) { const p = passes.get(e) || { until: 0, bought: [] }; passes.set(e, Object.assign({}, p, { lastCapHit: { ts: t, day, game, kind: capHit, pass, lifetime: !!lifetimeHit } })); }
const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed, lifetimeHit };
L.refs[key] = out; touch();
// waiting = every game's progress POL deferred for this account (it pays once a pass is active, inside the pass cap); the games
// show it in the allowance note (Marty 2026-11-03: tell members at the cap to get the Pass, and what is waiting for them)
const waiting = r6(Object.values(M.deferred).reduce((n, q) => n + (q || []).reduce((m, x) => m + (x.left || 0), 0), 0));
return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false, lifetimeHit, freeUsed: r6(M.freeTotal || 0), freeLifetime: c.freeLifetime, waiting };
}
// POST /api/partner/polgrant/void: the game decided not to pay after all. Reverses this ref's own share (the carry it triggered
// belongs to earlier refs and stays). The ref stays answered, as voided, so a replay is still idempotent.
function voidGrant(o) {
const game = String(o.game || '').toLowerCase(); const ref = String(o.ref || '').slice(0, 120); const key = game + ':' + ref;
const prev = L.refs[key]; if (!prev) return { ok: true, unknown: true };
if (prev.voided) return { ok: true, voided: true, repeat: true };
const M = member(prev.email); const D = dayRow(M, prev.day);
const own = r6(prev.own || 0);
D.total = Math.max(0, r6(D.total - own)); if (prev.kind === 'daily') D.daily = Math.max(0, r6(D.daily - own));
const tier = D.tier[prev.pass ? 'pass' : 'free']; tier.allowed = Math.max(0, r6(tier.allowed - own));
let removed = 0; const q = M.deferred[game] || []; for (const d of q) if (d.ref === ref) { removed = r6(removed + d.left); d.left = 0; } M.deferred[game] = q.filter(d => d.left > 0);
if (removed) D.deferredOut = Math.max(0, r6(D.deferredOut - removed));
const wk = weekKey(prev.ts || Date.now()); if (M.weeks[wk] && M.weeks[wk][game]) M.weeks[wk][game] -= 1;
Object.assign(prev, { voided: true, allowed: 0, deferred: 0, carried: 0, voidedAt: Date.now(), reversed: { allowed: own, deferred: removed } }); touch();
return { ok: true, voided: true, reversed: { allowed: own, deferred: removed } };
}
// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ----
function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; }
function holdersIn(start, end) { // any tier holds a Pass Tournament seat (every tier above weekly includes everything Weekly gives)
const out = [];
for (const [e, p] of passes) { if (!p || !(Math.max(...TIERS.map(k => tiersOf(p)[k])) > start)) continue; if ((p.bought || []).some(b => b.ts < end)) out.push(e); }
return out;
}
const isSale = b => b && b.via !== 'admin'; // comps are passes, not sales
// the pool counts weekly pass sales only, unless passTournamentTierSales adds the sales of every tier above weekly (default off: the pool exactly as before tiers)
function salesIn(start, end, withTiers) { let n = 0, usd = 0; for (const [, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b) && b.ts >= start && b.ts < end && (withTiers || rowTier(b) === 'weekly')) { n += 1; usd += Number(b.usd) || 0; } return { n, usd: Math.round(usd * 100) / 100 }; }
function scoresFor(wk, emails) {
return emails.map(e => { const M = L.members[e]; const g = (M && M.weeks[wk]) || {}; const score = Object.values(g).reduce((n, x) => n + x, 0); const first = ((passes.get(e) || {}).bought || []).reduce((m, b) => Math.min(m, b.ts), Infinity);
return { email: e, score, games: g, first }; }).filter(x => x.score > 0).sort((a, b) => b.score - a.score || a.first - b.first || (a.email < b.email ? -1 : 1));
}
async function runTournament(startTs, opts) {
const c = cfg(); const start = weekStart(startTs); const end = start + 7 * 86400000; const wk = dayKey(start);
if (prizes.get(wk) && !(opts && opts.force)) return prizes.get(wk);
const polUsd = await R.polUsd().catch(() => 0);
if (!(polUsd > 0)) return { error: 'POL rate unavailable; the tournament for the week of ' + wk + ' will be settled on the next hourly pass.' };
const sales = salesIn(start, end, c.tournamentTierSales); const poolUsd = Math.round(sales.usd * c.pct) / 100;
const poolPol = r6(poolUsd / polUsd);
const ranked = scoresFor(wk, holdersIn(start, end));
const winners = [];
for (let i = 0; i < Math.min(3, ranked.length); i++) {
const x = ranked[i]; let a = null; try { a = await R.accounts.byEmail(x.email); } catch (e) {}
winners.push({ place: i + 1, email: x.email, username: (a && a.username) || null, memberId: (a && a.memberId) || 0, wallet: (a && a.address) || null, score: x.score, games: x.games, pol: r6(poolPol * SHARES[i]), usd: Math.round(poolUsd * SHARES[i] * 100) / 100, status: 'pending', tx: null });
}
const row = { week: wk, label: 'week of ' + dayLabel(wk), start, end, sales: sales.n, salesUsd: sales.usd, pct: c.pct, poolUsd, polUsd, poolPol, holders: holdersIn(start, end).length, ranked: ranked.length, winners,
unallocatedPol: r6(poolPol - winners.reduce((n, w) => n + w.pol, 0)), ranAt: Date.now(), posted: false };
prizes.set(wk, row);
console.log('gamepass tournament', wk, 'sales', sales.n, 'pool', poolPol, 'POL', 'winners', winners.length);
if (winners.length && c.enabled) {
const medal = ['\u{1F947}', '\u{1F948}', '\u{1F949}'];
const lines = winners.map(w => medal[w.place - 1] + ' ' + (w.username ? '@' + w.username : 'member #' + (w.memberId || '?')) + ' · ' + w.score + ' plays · ' + w.pol.toFixed(2) + ' POL');
const html = '\u{1F3AE} <b>Game Pass Tournament</b> · ' + row.label + '\n' + lines.join('\n') + '\n' + sales.n + ' pass' + (sales.n === 1 ? '' : 'es') + ' sold · prize pool ' + poolPol.toFixed(2) + ' POL (' + c.pct + '% of pass sales)\n'
+ 'Prizes are paid in POL by the games to the winners’ InstantAdPay wallets. Get the Pass: https://instantadpay.com/my#games?pass=1';
try { await R.telegram(html); row.posted = true; prizes.set(wk, row); } catch (e) { console.error('gamepass tournament post', e.message); }
for (const w of winners) { try { await R.notify(w.email, 'Game Pass Tournament: you placed #' + w.place, '<p>You finished <b>#' + w.place + '</b> in the Game Pass Tournament for the ' + row.label + ' with ' + w.score + ' plays across the games. Your prize of <b>' + w.pol.toFixed(2) + ' POL</b> is paid to the wallet on your InstantAdPay account by the games this week.</p>'); } catch (e) {} }
}
return row;
}
// hourly: once Monday 9 AM Central has passed and the closed week has no row yet, exactly one app copy settles it (marks.claim)
async function tournamentTick(now) {
const t = now || Date.now(); const c = cfg(); if (!c.enabled) return null;
const ws = weekStart(t); if (t < ws + 9 * 3600000) return null; // not yet 9 AM Monday for the week that just closed
const prev = ws - 7 * 86400000; const wk = dayKey(prev);
if (prizes.get(wk)) return null;
if (!holdersIn(prev, ws).length && !salesIn(prev, ws, c.tournamentTierSales).n) { prizes.set(wk, { week: wk, label: 'week of ' + dayLabel(wk), start: prev, end: ws, sales: 0, salesUsd: 0, poolPol: 0, winners: [], ranAt: Date.now(), empty: true }); return null; }
if (!(await R.marks.claim('gamepass-tournament:' + wk))) return null;
return runTournament(prev);
}
// GET /api/partner/tournament/pending: prize rows the games still have to pay (the Road Agent faucet pattern)
function pending() { const out = []; for (const [, row] of prizes) for (const w of row.winners || []) if (w.status === 'pending') out.push({ week: row.week, label: row.label, place: w.place, email: w.email, username: w.username, memberId: w.memberId, wallet: w.wallet, pol: w.pol, usd: w.usd, score: w.score }); return out.sort((a, b) => a.week < b.week ? -1 : a.week > b.week ? 1 : a.place - b.place); }
function markPaid(week, place, tx, by) {
const row = prizes.get(String(week)); if (!row) return { error: 'no such week' };
const w = (row.winners || []).find(x => x.place === Number(place)); if (!w) return { error: 'no such place' };
if (w.status === 'paid') return { ok: true, repeat: true, tx: w.tx };
Object.assign(w, { status: 'paid', tx: String(tx || '').slice(0, 80), paidAt: Date.now(), paidBy: by || null }); prizes.set(String(week), row);
return { ok: true };
}
// ---- admin ----
function monthStart(ts) { const p = ctParts(ts); return ctMidnight(Date.UTC(p.y, p.mo - 1, 1, 17)); } // the 1st of the Central month, 00:00 Central
// per tier: active = accounts whose HIGHEST active tier is this one (each account counted once); sales by Central week / month /
// all time (comps are not sales); renewals30d = purchases in the last 30 days by accounts that held this tier before; expiring7d =
// this tier ends within the next 7 Central days (today included); waitingOrders = orders waiting for a package.
function tierStats(t) {
const ws = weekStart(t), ms = monthStart(t), d30 = t - 30 * 86400000;
const soon = ctMidnight(ctMidnight(t) + 7 * 86400000 + 3 * 3600000); // Central midnight that ends day 7 (DST-safe)
const out = {}; for (const k of TIERS) out[k] = { name: TIER_NAMES[k], active: 0, soldWeek: 0, usdWeek: 0, soldMonth: 0, usdMonth: 0, soldTotal: 0, usdTotal: 0, renewals30d: 0, expiring7d: 0, comped: 0, waitingOrders: 0 };
for (const [, p] of passes) {
if (!p) continue; const T = tiersOf(p); const top = topTier(T, t); if (top) out[top].active += 1;
for (const k of TIERS) if (T[k] > t && T[k] <= soon) out[k].expiring7d += 1;
const rows = p.bought || [];
for (const b of rows) {
const k = rowTier(b); const o = out[k]; if (!isSale(b)) { o.comped += 1; continue; }
const usd = Number(b.usd) || 0; o.soldTotal += 1; o.usdTotal += usd;
if (b.ts >= ws) { o.soldWeek += 1; o.usdWeek += usd; }
if (b.ts >= ms) { o.soldMonth += 1; o.usdMonth += usd; }
if (b.ts >= d30 && rows.some(x => x !== b && rowTier(x) === k && x.ts < b.ts)) o.renewals30d += 1;
}
}
for (const [, o] of orders) if (o.status === 'waiting' && o.kind !== 'hero' && o.kind !== 'stackpro') out[tierOk(o.tier) ? o.tier : 'weekly'].waitingOrders += 1;
for (const k of TIERS) for (const f of ['usdWeek', 'usdMonth', 'usdTotal']) out[k][f] = Math.round(out[k][f] * 100) / 100;
return out;
}
// every sale row, newest first, labelled by how it was paid. Rows from the new package rail carry buyerId (2026-10-22); the two
// rows from before (one paid with a credit balance, one fulfilled by a package under the old rule) are labelled as such.
function payLabel(b) {
if (b.via === 'credits') return 'credit-paid (old rule)';
if (b.via === 'package') return ('buyerId' in b) ? 'package' : 'package (old rule)';
return String(b.via || '?');
}
function salesList(limit) {
const out = [];
for (const [e, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b)) out.push({ ts: b.ts, email: e, tier: rowTier(b), name: TIER_NAMES[rowTier(b)], via: b.via, label: payLabel(b),
tx: b.tx || null, usd: Number(b.usd) || 0, packageUsd: b.packageUsd || (b.cents ? b.cents / 100 : null), credits: b.credits || null, buyerId: b.buyerId || null });
return out.sort((a, b) => b.ts - a.ts).slice(0, limit || 50);
}
function payMix() {
const m = { credit: { n: 0, usd: 0 }, packageOld: { n: 0, usd: 0 }, package: { n: 0, usd: 0, packageUsd: 0 } };
for (const [, p] of passes) for (const b of (p && p.bought) || []) {
if (!isSale(b)) continue; const usd = Number(b.usd) || 0;
const k = b.via === 'credits' ? 'credit' : (b.via === 'package' && !('buyerId' in b)) ? 'packageOld' : 'package';
m[k].n += 1; m[k].usd = Math.round((m[k].usd + usd) * 100) / 100;
if (k === 'package') m.package.packageUsd = Math.round((m.package.packageUsd + (Number(b.packageUsd) || (b.cents ? b.cents / 100 : 0))) * 100) / 100;
}
return m;
}
function adminStats(now) {
const t = now || Date.now(); const c = cfg(); const ws = weekStart(t); const day = dayKey(t); const wkFrom = dayKey(ws);
let active = 0, soldTotal = 0, usdTotal = 0, soldWeek = 0, usdWeek = 0, waiting = 0, comped = 0;
for (const [, p] of passes) { if (!p) continue; if (topTier(tiersOf(p), t)) active += 1; for (const b of p.bought || []) { if (!isSale(b)) { comped += 1; continue; } soldTotal += 1; usdTotal += Number(b.usd) || 0; if (b.ts >= ws) { soldWeek += 1; usdWeek += Number(b.usd) || 0; } } }
for (const [, o] of orders) if (o.status === 'waiting' && o.kind !== 'hero' && o.kind !== 'stackpro') waiting += 1;
const wk = { pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, carried: 0, dropped: 0, deferredOut: 0, grants: 0, would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 }, players: 0 };
const today = { allowed: 0, grants: 0, players: 0 };
let qEntries = 0, qPol = 0, qMembers = 0; const byGame = {};
for (const [e, M] of Object.entries(L.members)) {
let inWeek = false;
for (const [d, D] of Object.entries(M.days)) {
if (d < wkFrom) continue; inWeek = true;
for (const k of ['pass', 'free']) { wk[k].allowed = r6(wk[k].allowed + D.tier[k].allowed); wk[k].hitsDaily += D.tier[k].hitsDaily; wk[k].hitsTotal += D.tier[k].hitsTotal; }
wk.carried = r6(wk.carried + D.carried); wk.dropped = r6(wk.dropped + D.dropped); wk.deferredOut = r6(wk.deferredOut + D.deferredOut); wk.grants += D.grants;
for (const k of ['dropped', 'deferred']) wk.would[k] = r6(wk.would[k] + D.would[k]); wk.would.hitsDaily += D.would.hitsDaily; wk.would.hitsTotal += D.would.hitsTotal;
if (d === day) { today.allowed = r6(today.allowed + D.total); today.grants += D.grants; today.players += 1; }
}
if (inWeek) wk.players += 1;
let mine = 0; for (const [g, q] of Object.entries(M.deferred)) for (const x of q) { qEntries += 1; qPol = r6(qPol + x.left); mine += 1; byGame[g] = r6((byGame[g] || 0) + x.left); }
if (mine) qMembers += 1;
const W = M.weeks[wkFrom] || {}; for (const [g, n] of Object.entries(W)) { byGame['plays:' + g] = (byGame['plays:' + g] || 0) + n; }
void e;
}
const rows = [...prizes.values()].sort((a, b) => a.week < b.week ? 1 : -1);
return { enabled: c.enabled, tierSales: c.tierSales, settings: { price: c.price, days: c.days, tiers: c.tiers, tournamentTierSales: c.tournamentTierSales, free: c.free, pass: c.pass, capsStart: c.start || null, pct: c.pct, enforced: enforcedOn(c, day) },
week: { start: ws, label: 'week of ' + dayLabel(wkFrom), day },
tiers: tierStats(t), month: { start: monthStart(t), label: dayLabel(dayKey(monthStart(t))) + ' to date' },
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting, pay: payMix() },
sales: salesList(50),
pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today },
capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would },
deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame },
tournament: { lastRun: rows[0] ? rows[0].ranAt : null, last: rows[0] || null, next: nextTournamentAt(t), pending: pending().length, history: rows.slice(0, 8) } };
}
// ---- housekeeping: answered refs and day rows older than KEEP_DAYS, week tallies older than 10 weeks ----
function prune(now) {
const t = now || Date.now(); const cut = t - KEEP_DAYS * 86400000; const cutDay = dayKey(cut); const cutWeek = dayKey(weekStart(t - 70 * 86400000)); let n = 0;
for (const [k, r] of Object.entries(L.refs)) if ((r.ts || 0) < cut) { delete L.refs[k]; n++; }
for (const [e, M] of Object.entries(L.members)) {
for (const d of Object.keys(M.days)) if (d < cutDay) { delete M.days[d]; n++; }
for (const w of Object.keys(M.weeks)) if (w < cutWeek) { delete M.weeks[w]; n++; }
if (!Object.keys(M.days).length && !Object.keys(M.weeks).length && !Object.values(M.deferred).some(q => q.length)) delete L.members[e];
}
for (const [k, o] of orders) if (o.status === 'waiting' && t - o.ts > 30 * 86400000) orders.delete(k); // a pass order nobody paid for in a month is forgotten
if (n) touch();
return n;
}
module.exports = { STACK_PRO_CENTS, stackPro, stackProView, buyStackPro, cancelStackOrder, compStackPro, stackProOwners, grantStackProForPackage, init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, TIER_DEFS, HERO_DEFS, HERO_KEYS, heroesOwned, heroClaim, heroView, buyHero, cancelHeroOrder, compHero, revokeHero, heroStats, flag, activity, view, buy, cancelOrder, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
_ledger: () => L };
+101
View File
@@ -0,0 +1,101 @@
// Game figures for the daily snapshot (Marty 2026-10-08: one card for the whole ecosystem, games as their own block).
// Two live sources, no estimates:
// players sent in — counted here every time InstantAdPay hands a member into a game (/api/my/<game>), per UTC hour,
// so "last 24 h" is exact and survives restarts (DATA_DIR/game-handoffs.json)
// payouts + POL — read from Polygon: outgoing transfers from each game's payout wallet in the last 24 h (Etherscan v2,
// the same query the hourly wallet watcher on core uses). Our own wallets and the fee wallets are skipped.
// Env: GAME_WALLETS = "slug:0x…,slug:0x…" (set from the /root/.<game>-address files on core), ETHERSCAN_KEY.
'use strict';
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', polminer: 'POL Miner', warpwares: 'Warp & Wares', 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
const SKIP = () => new Set(['0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', '0xcbe203312e0ea3b542da7a2e7f0a8a09db948f75'].concat(Object.values(wallets())));
const FILE = () => path.join(R.dataDir, 'game-handoffs.json');
function load() { try { return JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { return {}; } }
function init(deps) { R = deps; }
const hourKey = t => new Date(t || Date.now()).toISOString().slice(0, 13);
// a member was handed into a game: one tick in this hour's bucket (buckets older than 3 days are dropped)
function handoff(slug) {
try {
const h = load(), k = hourKey(); h[k] = h[k] || {}; h[k][slug] = (h[k][slug] || 0) + 1;
const cut = hourKey(Date.now() - 3 * 86400000); for (const key of Object.keys(h)) if (key < cut) delete h[key];
fs.writeFileSync(FILE(), JSON.stringify(h));
} catch (e) { /* counting must never break a hand-off */ }
}
function sentIn(since) { const h = load(), out = {}; const k0 = hourKey(since); for (const [k, m] of Object.entries(h)) if (k >= k0) for (const [slug, c] of Object.entries(m)) out[slug] = (out[slug] || 0) + c; return out; }
// outgoing payouts from one game wallet since `since` (ms): { count, wei }
async function payoutsFor(addr, since) {
const out = { count: 0, wei: 0n }; if (!KEY()) return out;
const url = 'https://api.etherscan.io/v2/api?chainid=137&module=account&action=txlist&address=' + addr + '&startblock=0&endblock=99999999&sort=desc&page=1&offset=500&apikey=' + KEY();
const r = await fetch(url, { signal: AbortSignal.timeout(20000) }); const j = await r.json(); const rows = Array.isArray(j.result) ? j.result : [];
const skip = SKIP(), sinceS = Math.floor(since / 1000);
for (const x of rows) {
if (Number(x.timeStamp) < sinceS) break; // sorted newest first
if (x.isError !== '0' || String(x.from).toLowerCase() !== addr || !x.value || x.value === '0') continue;
if (skip.has(String(x.to).toLowerCase())) continue;
out.count++; out.wei += BigInt(x.value);
}
return out;
}
// everything the card needs: per game and totals, last 24 h
async function gather(since) {
const W = wallets(), sent = sentIn(since), games = [];
const slugs = new Set([...Object.keys(W), ...Object.keys(sent)]);
for (const slug of slugs) {
const g = { slug, name: NAMES[slug] || slug, sentIn: sent[slug] || 0, payouts: 0, wei: 0n, error: null };
if (W[slug]) { try { const p = await payoutsFor(W[slug], since); g.payouts = p.count; g.wei = p.wei; } catch (e) { g.error = e.message; } }
games.push(g);
}
games.sort((a, b) => (b.sentIn - a.sentIn) || (Number(b.wei - a.wei)));
const totals = games.reduce((t, g) => ({ sentIn: t.sentIn + g.sentIn, payouts: t.payouts + g.payouts, wei: t.wei + g.wei }), { sentIn: 0, payouts: 0, wei: 0n });
return { games, totals, chainChecked: !!KEY() && Object.keys(W).length > 0 };
}
// ---- all-time running total of game payouts, for the admin P&L (Marty 2026-10-18) ----
// Every outgoing POL send from each game wallet to a player, from the wallet's first transaction.
// Kept in DATA_DIR/game-payouts-alltime.json per wallet { block, count, wei, players[] } and topped up
// incrementally (only blocks after the last one seen), so after the first scan a refresh is one call per game.
const AT_FILE = () => path.join(R.dataDir, 'game-payouts-alltime.json');
let atState = null, atAt = 0, atBusy = null;
const sleep = ms => new Promise(r => setTimeout(r, ms));
function atLoad() { if (!atState) { try { atState = JSON.parse(fs.readFileSync(AT_FILE(), 'utf8')); } catch (e) { atState = {}; } } return atState; }
function atSave() { try { fs.writeFileSync(AT_FILE() + '.tmp', JSON.stringify(atState)); fs.renameSync(AT_FILE() + '.tmp', AT_FILE()); } catch (e) {} }
async function atScan(slug, addr) {
const st = atLoad(); let w = st[slug];
if (!w || w.addr !== addr) w = st[slug] = { addr, block: 0, count: 0, wei: '0', players: [] };
const skip = SKIP(), players = new Set(w.players); let wei = BigInt(w.wei), count = w.count, maxBlock = w.block; // committed only when the scan finishes, so a failed page never double-counts
for (let page = 1; page <= 10; page++) { // Etherscan caps page*offset at 10,000; the next refresh carries on from the last block
const url = 'https://api.etherscan.io/v2/api?chainid=137&module=account&action=txlist&address=' + addr + '&startblock=' + (w.block + 1) + '&endblock=99999999&sort=asc&page=' + page + '&offset=1000&apikey=' + KEY();
const r = await fetch(url, { signal: AbortSignal.timeout(20000) }); const j = await r.json();
if (!Array.isArray(j.result)) { if (/no transactions/i.test(String(j.message || ''))) break; throw new Error(String(j.result || j.message || 'etherscan')); }
for (const x of j.result) {
const b = Number(x.blockNumber); if (b > maxBlock) maxBlock = b;
if (x.isError !== '0' || String(x.from).toLowerCase() !== addr || !x.value || x.value === '0') continue;
const to = String(x.to).toLowerCase(); if (skip.has(to)) continue;
count++; wei += BigInt(x.value); players.add(to);
}
if (j.result.length < 1000) break;
await sleep(400);
}
w.block = maxBlock; w.count = count; w.wei = wei.toString(); w.players = [...players]; delete w.error;
}
async function atRefresh() {
const W = wallets();
for (const [slug, addr] of Object.entries(W)) { try { await atScan(slug, addr); } catch (e) { (atLoad()[slug] || {}).error = e.message; } await sleep(400); }
atSave(); atAt = Date.now();
}
// { games: [{ slug, name, count, wei, players }], totals, at }; refreshed at most every 10 minutes, never blocks the page past 25 s
async function allTime() {
if (!KEY()) return { error: 'ETHERSCAN_KEY not set' };
if (Date.now() - atAt > 600000 && !atBusy) atBusy = atRefresh().finally(() => { atBusy = null; });
if (atBusy && !atAt) await Promise.race([atBusy, sleep(25000)]);
const st = atLoad(), W = wallets(), games = [];
for (const slug of Object.keys(W)) { const w = st[slug]; if (!w) continue; games.push({ slug, name: NAMES[slug] || slug, count: w.count, wei: w.wei, players: w.players.length, error: w.error || null }); }
games.sort((a, b) => (BigInt(b.wei) > BigInt(a.wei) ? 1 : -1));
return { games, at: atAt || null, scanning: !!atBusy };
}
module.exports = { init, handoff, gather, allTime, NAMES };
+120
View File
@@ -0,0 +1,120 @@
'use strict';
// Country lookup for ad targeting, zero dependencies. Data: DB-IP "IP to Country
// Lite" (CC BY 4.0, attribution "IP Geolocation by DB-IP" is shown on the site).
// The server downloads the current month's CSV once, keeps it in DATA_DIR/geo/,
// loads it into sorted range tables (IPv4 as uint32, IPv6 as BigInt) and answers
// countryOf(ip) by binary search. Refreshes monthly.
const fs = require('fs');
const path = require('path');
const https = require('https');
const zlib = require('zlib');
let DATA_DIR = '.';
let v4 = { start: [], end: [], cc: [] }, v6 = { start: [], end: [], cc: [] };
let loaded = false, loadedFile = '';
// Tier lists (affiliate-marketing convention). Editable in Admin > Settings as
// comma-separated ISO codes; tier 3 = everything else.
const DEFAULT_TIER1 = 'US,CA,GB,AU,NZ,IE,DE,FR,NL,SE,NO,DK,FI,CH,AT,BE';
const DEFAULT_TIER2 = 'IT,ES,PT,PL,CZ,HU,GR,RO,SK,SI,HR,BG,EE,LV,LT,LU,IS,MT,CY,JP,KR,SG,HK,TW,IL,AE,SA,QA,KW,BH,OM,ZA,BR,MX,AR,CL,CO,UY,CR,PA,MY,TH,TR,RU,UA,KZ';
function ip4(s) { const p = s.split('.'); if (p.length !== 4) return null; let n = 0; for (const x of p) { const v = Number(x); if (!/^\d{1,3}$/.test(x) || v > 255) return null; n = n * 256 + v; } return n; }
function ip6(s) {
try {
let [head, tail] = s.split('::');
const h = head ? head.split(':') : [], t = tail ? tail.split(':') : [];
if (s.includes('::')) { while (h.length + t.length < 8) h.push('0'); }
const parts = h.concat(t); if (parts.length !== 8) return null;
let n = 0n; for (const p of parts) { if (!/^[0-9a-f]{0,4}$/i.test(p)) return null; n = (n << 16n) + BigInt(parseInt(p || '0', 16)); }
return n;
} catch (e) { return null; }
}
function find(tbl, x) {
let lo = 0, hi = tbl.start.length - 1;
while (lo <= hi) { const mid = (lo + hi) >> 1; if (tbl.start[mid] <= x) { if (x <= tbl.end[mid]) return tbl.cc[mid]; lo = mid + 1; } else hi = mid - 1; }
return null;
}
// ISO-2 country code or null (private ranges, unknown, no data yet)
function countryOf(ip) {
if (!loaded || !ip) return null;
let s = String(ip).trim().replace(/^::ffff:/i, '');
let cc = null;
if (s.includes('.')) { const n = ip4(s); cc = n == null ? null : find(v4, n); }
else { const n = ip6(s); cc = n == null ? null : find(v6, n); }
return cc && cc !== 'ZZ' ? cc : null; // ZZ = private/reserved: unknown
}
function tierLists(cfg) {
const parse = (v, def) => new Set(String(v || def).toUpperCase().split(/[\s,]+/).filter(Boolean));
return { t1: parse(cfg && cfg.geoTier1, DEFAULT_TIER1), t2: parse(cfg && cfg.geoTier2, DEFAULT_TIER2) };
}
// '1' | '2' | '3' | null (unknown country never matches a restricted campaign)
function tierOf(cc, cfg) {
if (!cc) return null;
const { t1, t2 } = tierLists(cfg);
return t1.has(cc) ? '1' : t2.has(cc) ? '2' : '3';
}
// ── data file: DATA_DIR/geo/dbip-country-lite-YYYY-MM.csv.gz ──
function monthKey(d) { d = d || new Date(); return d.getUTCFullYear() + '-' + String(d.getUTCMonth() + 1).padStart(2, '0'); }
function fileFor(mk) { return path.join(DATA_DIR, 'geo', 'dbip-country-lite-' + mk + '.csv.gz'); }
function download(mk) {
return new Promise((resolve, reject) => {
fs.mkdirSync(path.join(DATA_DIR, 'geo'), { recursive: true });
const tmp = fileFor(mk) + '.part';
const req = https.get('https://download.db-ip.com/free/dbip-country-lite-' + mk + '.csv.gz', { headers: { 'User-Agent': 'InstantAdPay/1.0 (+https://instantadpay.com)' }, timeout: 60000 }, res => {
if (res.statusCode !== 200) { res.resume(); return reject(new Error('HTTP ' + res.statusCode)); }
const out = fs.createWriteStream(tmp);
res.pipe(out); out.on('finish', () => { fs.renameSync(tmp, fileFor(mk)); resolve(fileFor(mk)); }); out.on('error', reject);
});
req.on('error', reject); req.on('timeout', () => { req.destroy(new Error('timeout')); });
});
}
function loadFile(file) {
const raw = zlib.gunzipSync(fs.readFileSync(file)).toString('utf8');
const a4 = { start: [], end: [], cc: [] }, a6 = { start: [], end: [], cc: [] };
for (const line of raw.split('\n')) {
if (!line) continue;
const c = line.indexOf(','), c2 = line.indexOf(',', c + 1);
if (c < 0 || c2 < 0) continue;
const s = line.slice(0, c), e = line.slice(c + 1, c2), cc = line.slice(c2 + 1).trim().toUpperCase();
if (cc.length !== 2) continue;
if (s.includes('.')) { const a = ip4(s), b = ip4(e); if (a != null && b != null) { a4.start.push(a); a4.end.push(b); a4.cc.push(cc); } }
else { const a = ip6(s), b = ip6(e); if (a != null && b != null) { a6.start.push(a); a6.end.push(b); a6.cc.push(cc); } }
}
// DB-IP ships sorted; guard anyway
const order = t => { const idx = t.start.map((_, i) => i).sort((i, j) => (t.start[i] < t.start[j] ? -1 : t.start[i] > t.start[j] ? 1 : 0)); return { start: idx.map(i => t.start[i]), end: idx.map(i => t.end[i]), cc: idx.map(i => t.cc[i]) }; };
v4 = order(a4); v6 = order(a6); loaded = true; loadedFile = file;
return { v4: v4.start.length, v6: v6.start.length };
}
// load the newest local file now; fetch this month's if missing (async, non-blocking)
async function init(opts) {
DATA_DIR = opts.dataDir;
try {
const dir = path.join(DATA_DIR, 'geo');
const files = fs.existsSync(dir) ? fs.readdirSync(dir).filter(f => /^dbip-country-lite-\d{4}-\d{2}\.csv\.gz$/.test(f)).sort() : [];
if (files.length) { const n = loadFile(path.join(dir, files[files.length - 1])); console.log('geo: loaded', files[files.length - 1], n.v4, 'v4 +', n.v6, 'v6 ranges'); }
} catch (e) { console.error('geo: load failed', e.message); }
refresh().catch(e => console.error('geo: refresh failed', e.message));
}
// this month's file: download if missing, then (re)load it; safe to call daily
async function refresh() {
const mk = monthKey();
const f = fileFor(mk);
if (!fs.existsSync(f)) {
try { await download(mk); } catch (e) {
// early in the month DB-IP may not have published yet: fall back to last month
const d = new Date(); d.setUTCMonth(d.getUTCMonth() - 1); const prev = monthKey(d);
if (!fs.existsSync(fileFor(prev))) await download(prev);
}
}
const dir = path.join(DATA_DIR, 'geo');
const files = fs.readdirSync(dir).filter(x => /^dbip-country-lite-\d{4}-\d{2}\.csv\.gz$/.test(x)).sort();
const newest = path.join(dir, files[files.length - 1]);
if (newest !== loadedFile) { const n = loadFile(newest); console.log('geo: loaded', files[files.length - 1], n.v4, 'v4 +', n.v6, 'v6 ranges'); }
for (const old of files.slice(0, -2)) { try { fs.unlinkSync(path.join(dir, old)); } catch (e) {} }
return { file: files[files.length - 1], ranges: v4.start.length + v6.start.length };
}
function status() { return { loaded, file: path.basename(loadedFile || ''), v4: v4.start.length, v6: v6.start.length }; }
module.exports = { init, refresh, countryOf, tierOf, tierLists, status, DEFAULT_TIER1, DEFAULT_TIER2 };
+362
View File
@@ -0,0 +1,362 @@
// Network hub sync (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity).
// Everything here sleeps unless HUB_ENABLED is on: server.js does not even init this module without it, so no file is
// written, no route answers and no hook is wired. The InstantAdPay <-> LinkSpin direct sync (lssync.js / lsinbound.js)
// keeps running exactly as before either way.
//
// Inbound (POST /api/hub/events, signed by the hub with HUB_SECRET: X-Hub-Ts + X-Hub-Sig = hex HMAC-SHA256(ts + newline +
// raw body), 5-minute window). The hub only moves its cursor after a 2xx and may send an event twice:
// member.joined someone joined at another door: /v1/resolve the person (and, climbing, any sponsor not here yet) and
// hand the rows to lsinbound.receive, the same waiting-account path LinkSpin-first members take, with
// joinedVia 'hub' and joinedRef 'hub:<door>'. First-platform rule as there: an account that already
// exists here keeps its sponsor and only gets empty fields filled. Joins from this site are skipped.
// wallet.connected filled only on a waiting account that still has no wallet (lsinbound fill rules). A claimed account
// links its own wallet here; the hub's wallet is not proof of ownership on InstantAdPay.
// sponsor.changed ignored on purpose (2026-11-14): lsinbound's follow rule needs sponsorSetAt / By / PrevEmail, which the
// hub view does not expose, and someone the InstantAdPay contract holds never moves anyway.
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
// anything else ignored.
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
// in the log so one bad row cannot hold every later event back.
//
// Outbound (/v1/join, /v1/wallet, signed as HUB_SITE): new accounts made here since the flag first went on and every main
// wallet linked here go into a persisted outbox (DATA_DIR/hubsync.json) and are sent in order, never in the way of a
// sign-up. Retried with backoff on 5xx / network / 404-before-join; a 400/409 refusal is final and logged.
// Gaps closed 2026-11-13 (Marty: "let's get the gaps report built"), all still one way:
// - any later change to a member's username or sponsor goes to /v1/join again (names them; a sponsor only lands where the
// hub has none), old members included, not only accounts made since the flag went on;
// - a DELIBERATE sponsor change (sponsorfollow: adopt, rescue, release, expire->expiry, admin) goes to /v1/sponsor-change;
// - every MemberActivated on the InstantAdPay contract goes to /v1/contract-bind (contract 'iap', the sponsor by wallet),
// by email when the wallet belongs to an account here, else by wallet alone.
// - every paid Purchase goes to /v1/contract-spend (2026-11-14, rule 2: the contract with money spent decides the network
// sponsor when two contracts hold different ones).
// Where the hub and InstantAdPay name different sponsors, nothing is forced on either side: the case goes to `disagree`
// (Admin > /api/admin/hub) for Marty, since an InstantAdPay member bound on our contract cannot move anyway.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
let R = null, st = null, chain_ = Promise.resolve(), timer = null, sending = false, interval = null;
const MAX_UP = 25, EVENT_TRIES = 5, OUT_TRIES = 20, KEEP_DONE = 5000;
const SHELL_ORIGINS = new Set(['linkspin', 'btc4hits', 'hub']);
const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expire', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts // came here from another site: that site tells the hub itself
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim());
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
const SITE = () => String(process.env.HUB_SITE || 'iap').trim().toLowerCase();
const on = () => enabled() && !!URL_() && SECRET().length >= 32;
const norm = v => String(v || '').trim().toLowerCase();
const FILE = () => path.join(R.dataDir, 'hubsync.json');
function load() {
if (st) return st;
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
if (!st || typeof st !== 'object') st = {};
st.since = Number(st.since) || Date.now(); // only accounts made after the flag first went on are reported as joins
st.done = st.done || {}; st.tries = st.tries || {}; st.outbox = st.outbox || []; st.reported = st.reported || {};
st.disagree = st.disagree || {}; st.log = st.log || [];
st.stats = Object.assign({ batches: 0, events: 0, applied: 0, skipped: 0, ignored: 0, gaveUp: 0, sent: 0, refused: 0, sendErrors: 0 }, st.stats || {});
return st;
}
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('hubsync save', e.message); } }
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
// deps: { dataDir, accounts, lsinbound }
function init(deps) { R = deps; load(); save(); }
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
function verify(headers, raw) {
if (SECRET().length < 32) return false;
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return false;
const want = sign(ts, raw);
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
}
async function hubPost(p, body, timeout) {
const raw = JSON.stringify(body); const ts = String(Date.now());
const r = await fetch(URL_() + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(timeout || 15000) });
let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, body: j };
}
async function resolve(q) {
const r = await hubPost('/v1/resolve', q);
if (r.status !== 200) throw new Error('hub resolve ' + r.status);
return (r.body && r.body.person) || null;
}
const doorOf = p => norm(p && p.firstDoor && p.firstDoor.site).replace(/[^a-z0-9_-]/g, '').slice(0, 30) || 'network';
// Rule 2 (Marty 2026-11-14): the sponsor written here is the one the InstantAdPay CONTRACT holds for them when it holds them
// (person.locks.iap), never the plain network sponsor, which may come from another contract where they spent money
const CONTRACT = 'iap';
const sponsorFor = p => { const l = p && p.locks && p.locks[CONTRACT]; if (l) return (l.sponsor && l.sponsor.email) || null; return (p && p.sponsor && p.sponsor.email) || null; };
const rowOf = p => ({ email: norm(p.email), username: p.username || null, wallet: p.wallet || null, sponsorEmail: sponsorFor(p), joinedAt: Number(p.firstDoor && p.firstDoor.at) || null, profile: null });
// what InstantAdPay and the hub each say the sponsor is; a difference is recorded, never forced
async function compare(email, hubSponsorEmail, how) {
const sp = await R.accounts.sponsorOf(email); const here = sp ? norm(sp.email) : null; const there = norm(hubSponsorEmail) || null;
const s = load();
if (here === there) { delete s.disagree[email]; return; }
s.disagree[email] = { at: Date.now(), iap: here, hub: there, how };
}
async function memberJoined(ev) {
if (norm(ev.data && ev.data.site) === SITE()) return 'own';
const first = await resolve({ id: ev.personId });
if (!first || !first.email) return first ? 'no-email' : 'unknown'; // the hub must give this site seeEmails
if (first.blocked) return 'blocked';
const email = norm(first.email); const A = R.accounts;
const existing = await A.byEmail(email);
const rows = [rowOf(first)]; const doors = { [email]: doorOf(first) }; const seen = new Set([email]);
if (existing && !A.isUnclaimedShell(existing)) rows[0].wallet = null; // a real account links its own wallet here
// sponsors not on InstantAdPay yet come along as waiting accounts too (lsinbound builds them from rows in the same batch)
let p = first;
for (let i = 0; i < MAX_UP && sponsorFor(p); i++) {
const se = norm(sponsorFor(p)); if (seen.has(se) || await A.byEmail(se)) break;
const up = await resolve({ email: se }); if (!up || !up.email || up.blocked) break;
seen.add(se); rows.push(rowOf(up)); doors[se] = doorOf(up); p = up;
}
const sum = await R.lsinbound.receive(rows, { via: 'hub', refOf: e => 'hub:' + (doors[e] || 'network') });
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
await compare(email, rows[0].sponsorEmail, 'hub-join');
note({ type: 'joined', email, door: doors[email], created: sum ? sum.created : 0, existed: !!existing });
return 'applied';
}
async function walletConnected(ev) {
const p = await resolve({ id: ev.personId });
if (!p || !p.email || !p.wallet || p.blocked) return 'skip';
const a = await R.accounts.byEmail(p.email);
if (!a) return 'not-here'; // member.joined makes the account; a wallet alone does not
if (!R.accounts.isUnclaimedShell(a) || a.address) return 'kept'; // claimed accounts link their own wallet here
const sum = await R.lsinbound.receive([rowOf(p)], { via: 'hub', refOf: () => 'hub:' + doorOf(p) });
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
return 'applied';
}
async function apply(ev) {
if (ev.type === 'member.joined') return memberJoined(ev);
if (ev.type === 'wallet.connected') return walletConnected(ev);
// sponsor.changed is IGNORED here on purpose (checked 2026-11-14 for the switch-on): it would need the deliberate-change
// record (at / by / previous sponsor) to go through sponsorfollow's rule, and a member locked on the InstantAdPay contract
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
return 'ignored';
}
function prune() {
const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b);
for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP_DONE))) delete s.done[q];
}
async function handle(events) {
const s = load(); s.stats.batches++; let failed = null;
for (const ev of Array.isArray(events) ? events : []) {
const seq = Number(ev && ev.seq); if (!seq) continue;
if (s.done[seq]) { s.stats.skipped++; continue; } // delivered twice: already applied
s.stats.events++;
try {
const r = await apply(ev);
s.done[seq] = Date.now(); delete s.tries[seq];
if (r === 'applied') s.stats.applied++; else s.stats.ignored++;
} catch (e) {
s.tries[seq] = (s.tries[seq] || 0) + 1;
console.error('hubsync event', seq, ev.type, e.message);
if (s.tries[seq] >= EVENT_TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; }
failed = e; break; // answer 503: the hub sends this one (and everything after it) again
}
}
prune(); save();
return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } };
}
// the POST /api/hub/events handler: { status, body }. Batches run one at a time.
function receive(headers, raw) {
if (!R || !enabled()) return Promise.resolve({ status: 404, body: { error: 'not found' } });
if (!verify(headers, raw)) return Promise.resolve({ status: 401, body: { error: 'unauthorized' } });
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); }
const run = chain_.then(() => handle(b.events)); chain_ = run.catch(() => {}); return run;
}
// ---------- outbound ----------
function enqueue(kind, email) {
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
s.outbox.push({ kind, email, at: Date.now(), tries: 0, next: 0 }); save(); kick();
}
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(e => console.error('hubsync flush', e.message)); }, 2000); }
// accounts.onChange: a new account made here, or a later username / sponsor change on any account, goes to /v1/join;
// a deliberate sponsor change also goes to /v1/sponsor-change
function touch(email) {
if (!R || !on() || !email) return;
(async () => {
const e = norm(email); const a = await R.accounts.byEmail(e); const s = load();
if (!a || SHELL_ORIGINS.has(a.joinedVia)) return;
const sp = await R.accounts.sponsorOf(e); const spE = sp ? norm(sp.email) : '';
const key = (a.username || '') + '|' + spE;
const rep = s.reported[e];
if (!rep) { s.reported[e] = { u: a.username || null, k: key }; enqueue('join', e); } // new here, or an older member's first change since the flag
else if (rep.k !== key) { rep.u = a.username || null; rep.k = key; enqueue('join', e); }
const rec = R.follow && R.follow.get ? R.follow.get(e) : null;
if (rec && DELIBERATE.has(rec.by) && norm(rec.sponsorEmail) === spE && Number(rec.at) > 0 && s.reported[e].sc !== Number(rec.at)) {
s.reported[e].sc = Number(rec.at); enqueue('sponsor', e);
}
save();
})().catch(err => console.error('hubsync touch', err.message));
}
// chain.onEvent (once across copies): a payout switch-on on the InstantAdPay contract goes to /v1/contract-bind
function onChain(ev) {
if (ev && ev.type === 'Purchase') return onPurchase(ev);
if (!R || !on() || !ev || ev.type !== 'MemberActivated' || !ev.account) return;
(async () => {
let spW = null; try { const m = ev.sponsorId ? await R.chain.member(ev.sponsorId) : null; spW = m && m.account ? norm(m.account) : null; } catch (e) {}
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
s.outbox.push({ kind: 'bind', email: norm(ev.account), wallet: norm(ev.account), sponsorWallet: spW, at: Date.now(), tries: 0, next: 0 }); save(); kick();
})().catch(err => console.error('hubsync onChain', err.message));
}
// chain.onEvent: money paid into the InstantAdPay contract (Purchase with POL in) goes to /v1/contract-spend (Marty 2026-11-14,
// rule 2: when two contracts hold different sponsors, the one with money spent decides the network sponsor). Keyed by the
// buyer's position wallet, the same key as its bind, so the bind is always sent first; the tx hash makes a resend count once.
// A 404 (bind not there yet, or a linked extra position the hub does not know) is retried like any other miss.
function onPurchase(ev) {
if (!R || !on() || !ev.buyerId || !(Number(ev.priceCents) > 0)) return;
try { if (BigInt(ev.paidWei || '0') <= 0n) return; } catch (e) { return; } // nothing paid in: not a spend
(async () => {
const m = await R.chain.member(ev.buyerId); const w = m && m.account ? norm(m.account) : null; if (!w) return;
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
s.outbox.push({ kind: 'spend', email: w, wallet: w, cents: Number(ev.priceCents), tx: ev.tx || null, paidAt: Number(ev.ts) || Date.now(), at: Date.now(), tries: 0, next: 0 }); save(); kick();
})().catch(err => console.error('hubsync onPurchase', err.message));
}
// accounts.onWalletLinked: a main wallet linked here goes to /v1/wallet
function wallet(email) {
if (!R || !on() || !email) return;
(async () => {
const a = await R.accounts.byEmail(email);
if (a && a.address && !R.accounts.isUnclaimedShell(a)) enqueue('wallet', norm(email)); // a waiting account's wallet came from a sync
})().catch(err => console.error('hubsync wallet', err.message));
}
// sponsorfollow / tank.js label a window expiry 'expire'; the hub (and its DELIBERATE list) calls it 'expiry' (fixed 2026-11-15:
// before, IAP window-expiry moves never reached the hub as a sponsor change)
const HUB_BY = { expire: 'expiry' };
const hubBy = by => HUB_BY[by] || by;
const ROUTE = { join: '/v1/join', wallet: '/v1/wallet', sponsor: '/v1/sponsor-change', bind: '/v1/contract-bind', spend: '/v1/contract-spend' };
async function bodyFor(item) {
if (item.kind === 'spend') {
let owner = null; try { owner = (await R.accounts.byAddress(item.wallet)) || (R.accounts.positionOwner ? await R.accounts.positionOwner(item.wallet) : null); } catch (e) {}
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, cents: item.cents, tx: item.tx || undefined, at: item.paidAt };
}
if (item.kind === 'bind') {
let owner = null; try { owner = await R.accounts.byAddress(item.wallet); } catch (e) {}
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, sponsorRef: item.sponsorWallet || '' };
}
const a = await R.accounts.byEmail(item.email); if (!a) return null;
if (item.kind === 'sponsor') {
const sp = await R.accounts.sponsorOf(a.email); const rec = R.follow && R.follow.get ? R.follow.get(a.email) : null;
if (!rec || !DELIBERATE.has(rec.by) || norm(rec.sponsorEmail) !== (sp ? norm(sp.email) : '')) return null; // superseded since
return { email: a.email, sponsorEmail: sp ? sp.email : null, by: hubBy(rec.by) };
}
if (item.kind === 'wallet') return a.address ? { email: a.email, wallet: a.address } : null;
const sp = await R.accounts.sponsorOf(a.email);
return { email: a.email, ref: sp ? sp.email : (a.sponsorRef || undefined), username: a.username || undefined };
}
async function flush(force) { // force (tests, admin): ignore the backoff wait
if (!R || !on() || sending) return { skipped: true };
sending = true; const s = load(); const now = Date.now(); const held = new Set(); let sent = 0;
try {
for (const item of s.outbox.slice()) {
if (held.has(item.email)) continue; // keep each member's calls in order (join before wallet)
if (item.next > now && !force) { held.add(item.email); continue; }
const drop = (why, code) => { s.outbox.splice(s.outbox.indexOf(item), 1); if (why) note({ type: 'out-' + why, kind: item.kind, email: item.email, code: code || null }); };
let r = null;
try {
const body = await bodyFor(item); if (!body) { drop('gone'); save(); continue; }
r = await hubPost(ROUTE[item.kind] || '/v1/wallet', body);
} catch (e) { r = { status: 0, body: { error: e.message } }; }
const code = (r.body && r.body.error) || null;
if (r.status >= 200 && r.status < 300) {
drop(null); s.stats.sent++; sent++;
if (item.kind === 'join' && r.body && r.body.person) await compare(item.email, r.body.person.sponsor && r.body.person.sponsor.email, 'iap-join');
} else if ((r.status === 400 || r.status === 409) || (r.status === 403 && code === 'blocked') || (item.kind === 'sponsor' && r.status === 404)) {
drop('refused', code); s.stats.refused++;
} else {
item.tries++; s.stats.sendErrors++;
if (item.tries >= OUT_TRIES) drop('gave-up', code || String(r.status));
else { item.next = now + Math.min(3600000, 30000 * Math.pow(2, item.tries)); held.add(item.email); }
}
save();
}
} finally { sending = false; }
return { sent, waiting: s.outbox.length };
}
// password sign-ups do not fire accounts.onChange until they pick a username: every 10 minutes, any account made here since
// the flag went on that the hub has not heard about yet is queued
async function reconcile() {
if (!R || !on()) return { skipped: true };
const s = load(); let queued = 0;
for (const a of await R.accounts.listAll(1e6)) {
const e = norm(a.email);
if (!e || s.reported[e] || SHELL_ORIGINS.has(a.joinedVia) || Number(a.created) < s.since) continue;
s.reported[e] = { u: a.username || null }; s.outbox.push({ kind: 'join', email: e, at: Date.now(), tries: 0, next: 0 }); queued++;
}
if (queued) { save(); kick(); }
return { queued };
}
function start() {
if (interval) return;
interval = setInterval(() => flush().catch(e => console.error('hubsync flush', e.message)), 30000);
const rec = setInterval(() => reconcile().catch(e => console.error('hubsync reconcile', e.message)), 10 * 60000);
for (const t of [interval, rec]) if (t.unref) t.unref();
}
// ---------- rule 3: the holding tank asks the hub (Marty 2026-11-14) ----------
// The tank never offers anyone locked on ANY network contract, or anyone the hub already knows a sponsor for. tank.js asks
// through its hooks (networkHeld, networkLocked, network); server.js wires them only with HUB_ENABLED, so with the flag off
// the tank works exactly as before. One /v1/locked {emails, detail} call per 2,000 emails, cached per email: fresh for 10
// minutes. CONSERVATIVE when the hub cannot be reached: the last answer stands for up to 1 hour, after that the person is
// held ('unknown', not offered, not moved to the tank, not auto-assigned) until the hub answers again. A held tank for a
// while is the safe side; offering someone a contract already holds is not. After a failed call the hub is left alone
// for 2 minutes (page views must not each wait for a timeout).
const HELD_FRESH_MS = 10 * 60000, HELD_STALE_MS = 60 * 60000, HELD_DOWN_MS = 2 * 60000, HELD_CHUNK = 2000;
const held = new Map(); let heldDownUntil = 0, heldBusy = Promise.resolve();
async function refreshHeld(emails, timeout) {
const run = heldBusy.then(async () => {
const now = Date.now(); const miss = emails.filter(e => { const c = held.get(e); return !c || now - c.at > HELD_FRESH_MS; });
if (!miss.length || now < heldDownUntil) return;
try {
for (let i = 0; i < miss.length; i += HELD_CHUNK) {
const part = miss.slice(i, i + HELD_CHUNK);
const r = await hubPost('/v1/locked', { emails: part, detail: true, ids: true }, timeout || 5000); // ids: hub id + door per row (a hub without it ignores the flag)
if (r.status !== 200 || !r.body || !r.body.found || typeof r.body.found !== 'object') throw new Error('hub locked ' + r.status);
if (held.size > 60000) held.clear();
const at = Date.now(); for (const e of part) held.set(e, { at, row: r.body.found[e] || null });
}
} catch (e) { heldDownUntil = Date.now() + HELD_DOWN_MS; load().stats.heldErrors = (load().stats.heldErrors || 0) + 1; console.log('hubsync: hub /v1/locked unreachable:', e.message); }
});
heldBusy = run.catch(() => {}); return run;
}
const whyHeld = (c, now) => (!c || now - c.at > HELD_STALE_MS ? 'unknown' : c.row && c.row.locked ? 'locked' : c.row && c.row.sponsored ? 'sponsored' : null);
// accounts -> Map email -> 'locked' | 'sponsored' | 'unknown' for the ones the tank must not offer
async function heldAmong(accts, opts) {
const out = new Map(); if (!R || !on()) return out;
const emails = [...new Set((accts || []).map(a => norm(a && a.email)).filter(Boolean))]; if (!emails.length) return out;
await refreshHeld(emails, opts && opts.timeout);
const now = Date.now(); for (const e of emails) { const w = whyHeld(held.get(e), now); if (w) out.set(e, w); }
return out;
}
// release, rescue and expiry moves: 'locked' (on any network contract) | 'unknown' (hub not answering) | null
async function lockedAnywhere(email) {
if (!R || !on()) return null; const e = norm(email); if (!e) return null;
await refreshHeld([e]); const w = whyHeld(held.get(e), Date.now());
return w === 'locked' || w === 'unknown' ? w : null;
}
// the sponsor the hub knows for a tank member, for tank.alignToNetwork: this contract's lock first, else the network sponsor
// OFF unless HUB_TANK_ALIGN=on: aligning moves sponsors (and on LinkSpin a linked wallet then has its payouts switched on, which
// locks that sponsor on the contract), so the first run over a full tank is Marty's deliberate step, not a side effect of the
// deploy. While it is off the people the hub knows a sponsor for are simply held out of the tank (rule 3).
const alignOn = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_TANK_ALIGN || '').trim());
async function hubSponsor(email) {
if (!R || !on() || !alignOn()) return null; const e = norm(email); if (!e) return null;
await refreshHeld([e]); const c = held.get(e); if (!c || !c.row || Date.now() - c.at > HELD_STALE_MS) return null;
const l = c.row.locks && Object.prototype.hasOwnProperty.call(c.row.locks, CONTRACT) ? c.row.locks[CONTRACT] : undefined;
const sp = norm(l !== undefined ? l : c.row.sponsorEmail);
return sp && sp !== e ? { sponsorEmail: sp, via: l !== undefined ? 'network hub, InstantAdPay contract' : 'network hub' } : null;
}
// the hub id and first door of a person the tank cache holds (5xYourTeam draft pool, 2026-11-15): { id, door } | null. Read-only, no call.
function hubInfo(email) { const c = held.get(norm(email)); return c && c.row && c.row.id ? { id: c.row.id, door: c.row.door || null } : null; }
function adminView() {
const s = load();
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
}
module.exports = { _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
+72
View File
@@ -0,0 +1,72 @@
// Email intake for the help desk (2026-10-16): SendGrid Inbound Parse posts every message sent to the support hosts
// (support@help.instantadpay.com, reply+<ref>@help.instantadpay.com, anything @linkspin.app) here as multipart/form-data.
// We turn it into a new ticket or a reply on an existing one (tickets.ingestEmail), after dropping robots: bounces,
// auto-replies, bulk mail and our own messages, so two autoresponders can never ping-pong. The URL carries a secret key
// (env SUPPORT_INBOUND_KEY); SendGrid retries anything that is not 2xx, so the route always answers 200 once the key passes.
'use strict';
let tickets = null, accounts = null;
function init(d) { tickets = d.tickets; accounts = d.accounts || null; }
const key = () => String(process.env.SUPPORT_INBOUND_KEY || '').trim();
// a small multipart reader: text fields only, files skipped (attachments are not kept yet)
function parseMultipart(buf, contentType) {
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || ''); if (!m) return {};
const boundary = Buffer.from('--' + (m[1] || m[2]).trim());
const out = {}; let pos = buf.indexOf(boundary);
while (pos >= 0) {
const next = buf.indexOf(boundary, pos + boundary.length); if (next < 0) break;
const part = buf.slice(pos + boundary.length + 2, next - 2); // skip CRLF after the boundary and before the next
const sep = part.indexOf('\r\n\r\n');
if (sep > 0) {
const head = part.slice(0, sep).toString('utf8');
const nm = /name="([^"]+)"/i.exec(head);
if (nm && !/filename=/i.test(head)) out[nm[1]] = part.slice(sep + 4).toString('utf8');
}
pos = next;
}
return out;
}
const header = (raw, name) => { const m = new RegExp('^' + name + ':\\s*([^\\r\\n]*(?:\\r?\\n[ \\t][^\\r\\n]*)*)', 'im').exec(raw || ''); return m ? m[1].replace(/\r?\n[ \t]+/g, ' ').trim() : ''; };
const addrOf = s => { const m = /<([^>]+)>/.exec(s || ''); return String(m ? m[1] : s || '').trim().toLowerCase(); };
const nameOf = s => { const m = /^\s*"?([^"<]*?)"?\s*</.exec(s || ''); return m ? m[1].trim() : ''; };
const ROBOT_FROM = /(mailer-daemon|postmaster|no-?reply|do-?not-?reply|bounce|notifications?@)/i;
// keep what the person wrote, not the quoted history under it
function stripQuoted(text) {
let t = String(text || '').replace(/\r\n/g, '\n');
const cuts = [/^On .{3,200}wrote:\s*$/m, /^-{2,}\s*Original Message\s*-{2,}/im, /^From:\s.+\n(?:Sent|Date):\s/m, /^_{10,}\s*$/m];
for (const re of cuts) { const m = re.exec(t); if (m) t = t.slice(0, m.index); }
return t.split('\n').filter(l => !/^\s*>/.test(l)).join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
const htmlToText = h => String(h || '').replace(/<(br|\/p|\/div)[^>]*>/gi, '\n').replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
const perSender = new Map(); // sender -> [timestamps], at most 20 messages an hour become tickets or replies
function flood(addr) { const now = Date.now(); const a = (perSender.get(addr) || []).filter(t => now - t < 3600000); a.push(now); perSender.set(addr, a); return a.length > 20; }
// returns a short outcome string for the log
async function handle(buf, contentType) {
const f = parseMultipart(buf, contentType);
const raw = f.headers || '';
const from = addrOf(f.from); if (!from || !/@/.test(from)) return 'no sender';
let rcpts = []; try { rcpts = (JSON.parse(f.envelope || '{}').to || []).map(addrOf); } catch (e) {}
if (!rcpts.length) rcpts = String(f.to || '').split(',').map(addrOf);
const auto = header(raw, 'Auto-Submitted'), prec = header(raw, 'Precedence');
if ((auto && !/^no$/i.test(auto)) || /bulk|junk|list/i.test(prec) || header(raw, 'X-Autoreply') || header(raw, 'X-Autorespond') || ROBOT_FROM.test(from)) return 'robot dropped: ' + from;
if (/@(instantadpay\.com|help\.instantadpay\.com|linkspin\.app)$/.test(from)) return 'own address dropped';
if (flood(from)) return 'flood dropped: ' + from;
// support@instantadpay.com is forwarded by NameSilo to iap-support@linkspin.app (its forwarder will not deliver to our own
// help. subdomain), so that one address means an InstantAdPay ticket even though it arrives on the LinkSpin host
const iapAlias = r => /^iap-support@linkspin\.app$/.test(r);
const platform = rcpts.some(r => /@linkspin\.app$/.test(r) && !iapAlias(r)) ? 'linkspin' : 'iap';
let subject = String(f.subject || '').replace(/\s+/g, ' ').trim();
const plus = rcpts.map(r => /^reply\+((?:iap|ls)-\d{4,9})@/.exec(r)).find(Boolean); // the reply-to we put on ticket mail
if (plus) { const ref = plus[1].toUpperCase(); if (!subject.toUpperCase().includes(ref)) subject = '[' + ref + '] ' + subject; }
const body = stripQuoted(f.text || htmlToText(f.html)) || '(empty message)';
const r = await tickets.ingestEmail({ from, name: nameOf(f.from), subject, text: body, platform, confirm: true,
// new tickets only from member emails (Marty 2026-10-24); LinkSpin-first members are InstantAdPay accounts too (lsinbound)
canOpen: accounts ? async addr => { try { return !!(await accounts.byEmail(addr)); } catch (e) { return true; } } : null,
messageId: header(raw, 'Message-ID'), inReplyTo: header(raw, 'In-Reply-To'), references: header(raw, 'References') });
if (r && r.error) return 'refused: ' + r.error;
return (r.created ? 'new ticket ' : 'reply on ') + (r.ticket && r.ticket.ref) + ' from ' + from;
}
module.exports = { init, key, handle, stripQuoted, parseMultipart };
+76
View File
@@ -0,0 +1,76 @@
// Knowledge-base seeds that are not CANNED fast-path answers (kb.js): the public FAQ on the home page,
// the Platform Facts page (/facts), the wallets guide's Common questions, and support replies worth
// keeping. An entry here that nobody has edited in Admin > Knowledge base is refreshed when its text
// changes in this file; edit it in the admin pane and it becomes the admin's own.
// House rules: plain words, no em dashes, never a promise of income.
const FAQ = [
{ id: 'f-coinbase', title: 'Can I use my regular Coinbase account?', source: 'ticket',
questions: ['Can I use my regular Coinbase account?', 'Can I use Coinbase?', 'Can I connect my Coinbase exchange account?', 'How do I connect Coinbase?', 'Can I pay from my exchange account?'],
tags: ['coinbase', 'exchange account', 'connect coinbase', 'wallet', 'safepal'],
answer: 'Your regular Coinbase account won\'t connect here. Coinbase is an exchange: they hold the crypto for you, which works for buying and selling. InstantAdPay runs on a smart contract on Polygon, and to buy a package or receive payouts you sign that contract yourself, which only a wallet you control can do. You don\'t need Coinbase Wallet; we recommend SafePal (free, phone app or desktop browser extension). Install it, write down your recovery phrase, add Polygon (POL) and copy your address, send POL from Coinbase choosing the Polygon network (send a small test first), then open instantadpay.com in SafePal\'s browser (or the browser with the extension), sign in with your email and tap Link wallet (one free signature). You only need a wallet to buy a package or receive payouts.' },
{ id: 'f-how-fast', title: 'How fast do I really get paid?', source: 'faq',
questions: ['How fast do I get paid?', 'When does my commission arrive?', 'Is there an approval step for payouts?'],
tags: ['payout', 'speed', 'same transaction', 'ledger'],
answer: 'Payouts happen inside the very transaction that pays for the package. There is no approval step and nobody holding funds. Your share lands in your own wallet the moment your referral\'s purchase confirms, and the public ledger at https://instantadpay.com/ledger lets you watch each one go through.' },
{ id: 'f-what-buying', title: 'What am I actually buying?', source: 'faq',
questions: ['What am I actually buying?', 'What is the product?', 'Do bigger packages give bonus credits?'],
tags: ['product', 'ad delivery', 'credits', 'packages'],
answer: 'You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy. The $5 package mints 500 credits, and the bigger packages mint bonus credits on top, up to 70,000 on the $500 package. Earnings only come from referring people who also buy real ad delivery, and the contract splits every purchase automatically. Nothing is a promise of income.' },
{ id: 'f-refunds', title: 'Refunds', source: 'faq',
questions: ['Can I get a refund?', 'Is my purchase refundable?', 'Can a POL payment be reversed or charged back?', 'What happens if my campaign fails to deliver?'],
tags: ['refund', 'chargeback', 'reverse payment', 'final'],
answer: 'Payments are on-chain and final: a POL payment cannot be reversed, charged back or refunded to a wallet. Unused credits stay in your balance until you spend them. If a campaign fails to deliver because of a platform problem, the platform may return the affected credits to your balance, labeled as returned purchased credits.' },
{ id: 'f-credits-transfer', title: 'Can credits be transferred or turned into POL?', source: 'faq',
questions: ['Can I transfer credits to another member?', 'Can I give my credits to a friend?', 'Can I sell my credits or exchange them for POL?', 'Are credits a token?'],
tags: ['credits', 'transfer', 'cash value', 'token'],
answer: 'No. Credits are advertising credit, not currency. They cannot be transferred between members and cannot be exchanged back into POL or cash. Purchased credits are recorded on-chain and burned as your campaigns spend them; earned credits (welcome, viewing, visits, promo codes) are kept by the site and labeled separately.' },
{ id: 'f-price-feed', title: 'How the POL price of a package is set', source: 'faq',
questions: ['How is the POL price calculated?', 'Why did the POL amount change?', 'What price feed do you use?'],
tags: ['price', 'chainlink', 'pol price', 'rate'],
answer: 'Prices are set in US dollars and paid in POL. The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon, so the POL amount moves with the market. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers. Any package price change waits 24 hours before it takes effect.' },
{ id: 'f-contract', title: 'The contract address and network', source: 'faq',
questions: ['What is the contract address?', 'Which network is the contract on?', 'Is the contract verified?', 'Can the split be changed?'],
tags: ['contract', 'address', 'polygonscan', 'verified', 'polygon'],
answer: 'InstantAdPay runs on Polygon mainnet (chain id 137). The contract is 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 and its source is verified and public. The percentages and qualification rules are constants in the code, there is no function that changes them, and the contract holds no member funds. The plain-language review is at https://instantadpay.com/contract and the reference facts at https://instantadpay.com/facts.' },
{ id: 'f-platform-share', title: 'Where the platform share goes', source: 'faq',
questions: ['Where does the 20 percent platform share go?', 'What are the platform wallets?', 'What happens to a share nobody qualifies for?'],
tags: ['platform', 'platform wallets', 'fees', 'pass-up'],
answer: 'The 20 percent platform share is two fixed 10 percent fees to platform wallet A (0x7627fc78876948ac9d95c1c9eb061e7d6d647b70) and B (0x8b7d33849a2c4d92c985be31e46dc564ba901ad2). Platform income pays for operations, development, marketing and the game rewards. If nobody within 25 steps qualifies for a level, that share goes to wallet A, and every pass-up is recorded on-chain with the reason. Overpayment is returned to the buyer in the same transaction.' },
{ id: 'f-active-viewing', title: 'Why the video or timer paused', source: 'faq',
questions: ['Why did my video ad pause?', 'Why did the countdown stop?', 'Why was my view not counted?'],
tags: ['video', 'timer', 'countdown', 'paused', 'anti-fraud'],
answer: 'Viewing is active only: video ads pause when you switch tabs or the window loses focus, and viewing and visit timers only count while the page is in front. The server also checks the elapsed time, so a view cannot be credited early. Keep the tab in front until the countdown finishes and pass the quick check.' },
{ id: 'f-game-rewards', title: 'Where game POL rewards come from', source: 'faq',
questions: ['Where do the game rewards come from?', 'Are game rewards guaranteed?', 'Why did a game reward not pay?'],
tags: ['games', 'rewards', 'pool', 'pol'],
answer: 'The network games pay small POL rewards for gameplay milestones from game wallets and reward pools the company tops up from platform income (some games also fund a pool from in-game sales). Rewards are per action, paid while the pool covers them, and never guaranteed. You sign in to every game with your InstantAdPay account, so your sponsor carries across them.' },
{ id: 'f-not-investment', title: 'What InstantAdPay is not', source: 'faq',
questions: ['Is this an investment?', 'Is there guaranteed income?', 'Does InstantAdPay hold my money?'],
tags: ['investment', 'income', 'guarantee', 'custody', 'disclaimer'],
answer: 'InstantAdPay is an advertising platform with a referral program, not an investment, token sale or security. Credits are not a token and have no cash value. It does not hold member money: payments are split by the contract in the same transaction. And it is not a guarantee of income: referral payouts happen only when real advertising is bought in your line.' },
{ id: 'f-how-much-pol', title: 'How much POL do I need?', source: 'faq',
questions: ['How much POL do I need?', 'How much POL for fees?', 'What does a package cost in POL?'],
tags: ['pol', 'fees', 'gas', 'buy packages'],
answer: 'The Buy packages tab shows the live POL cost of each package. Have that plus 2 or 3 POL for network fees; there is no other cost. Trust Wallet users should keep about double, because Trust blocks a purchase that spends most of the wallet.' },
{ id: 'f-moonpay-declined', title: 'MoonPay declined my card', source: 'faq',
questions: ['Why did MoonPay decline my card?', 'My card was refused buying POL', 'MoonPay will not take my payment'],
tags: ['moonpay', 'card', 'declined', 'buy pol'],
answer: 'Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy POL on an exchange and withdraw it to your own wallet on the Polygon network. MoonPay is an independent provider with its own fees, limits and a first-time ID check.' },
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
tags: ['wallet', 'position', 'qualified start', 'metamask'],
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
answer: 'Coinbase, Kraken, Binance and most exchanges sell POL. Withdraw it to your own wallet address and pick the Polygon network on the withdrawal screen, never MATIC on Ethereum or another chain. Sending on the wrong network can lose the funds, so send a small test first.' },
{ id: 'f-recovery-phrase', title: 'Recovery phrase and scam safety', source: 'faq',
questions: ['Someone asked for my recovery phrase', 'Will support ever ask for my private key?', 'Someone messaged me asking for money'],
tags: ['recovery phrase', 'private key', 'scam', 'security'],
answer: 'Never share your recovery phrase or private key with anyone. Nobody from InstantAdPay will ever ask for them, and nobody from InstantAdPay will message you first asking for money or wallet access. If someone does, do not reply, and tell support through Help at https://instantadpay.com/my#help.' },
{ id: 'f-conv-thankyou', title: 'Conversion tracking with Aweber or GetResponse', source: 'faq',
questions: ['How do I track sign-ups from my ads?', 'Where do I put the goal pixel?', 'How do I use conversion tracking with Aweber?', 'How do I use conversion tracking with GetResponse?', 'My autoresponder thank-you page is not mine, can I still track?'],
tags: ['conversion tracking', 'goal pixel', 'landing tag', 'aweber', 'getresponse', 'thank you page', 'autoresponder'],
answer: 'Open Campaigns > Conversion tracking, add a goal (like subscriber), then copy its two snippets: the landing tag goes on the page your ad points to, the goal pixel on your thank-you page. Set your autoresponder\'s thank-you (success) page to a page on YOUR site that carries the goal pixel. Aweber: in your sign-up form settings, choose \'Thank You Page: custom page\' and paste your page\'s address. GetResponse: in the form or landing page settings, pick \'Thank-you page: custom URL\' and paste your page\'s address. If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. Use Send a test conversion to check the pixel; tests never count in your numbers.' },
];
module.exports = { FAQ };
+280
View File
@@ -0,0 +1,280 @@
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
// The chatbot answers from maintained entries, and good support replies become entries.
//
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
// updated, created, edited, deleted, seedHash }
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
// path serves the new text.
// source canned | faq | ticket | admin
//
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
//
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
//
// Dual store like the other modules: MySQL table kb_entries when DATABASE_URL is set, else
// DATA_DIR/kb.json (local dev and the QA harness).
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const db = require('./db');
let DATA_DIR = null, SEEDS = [], ready = null;
let cache = null, cacheAt = 0, index = null;
const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
function stem(w) {
if (SYN[w]) return SYN[w];
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
return w;
}
function words(text) {
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
}
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
function terms(text) {
const w = words(text), out = w.slice();
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
return out;
}
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
const K1 = 1.2, B = 0.75;
function fieldText(e, f) {
if (f === 'questions') return (e.questions || []).join(' . ');
if (f === 'tags') return (e.tags || []).join(' . ');
return e[f] || '';
}
function buildIndex(entries) {
const docs = entries.map(e => {
const d = { e, f: {} };
for (const f of Object.keys(FIELDS)) {
const t = terms(fieldText(e, f)), tf = new Map();
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
d.f[f] = { tf, len: t.length };
}
return d;
});
const df = new Map(), avg = {};
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
for (const d of docs) {
const seen = new Set();
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
}
return { docs, df, avg, n: docs.length };
}
function rank(idx, query, k) {
if (!idx || !idx.n) return [];
const qt = [...new Set(terms(query))];
if (!qt.length) return [];
const out = [];
for (const d of idx.docs) {
let s = 0;
for (const t of qt) {
const n = idx.df.get(t); if (!n) continue;
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
for (const f of Object.keys(FIELDS)) {
const tf = d.f[f].tf.get(t); if (!tf) continue;
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
}
}
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
}
out.sort((a, b) => b.score - a.score);
return out.slice(0, k || 5);
}
// keep hits that are close to the best one, and only when the best is a real match
const MIN_SCORE = 3;
function relevant(hits) {
if (!hits.length || hits[0].score < MIN_SCORE) return [];
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
return hits.filter(h => h.score >= floor);
}
// ---------------------------------------------------------------- store
const row = r => ({ id: r.id, title: r.title, questions: parse(r.questions, []), answer: r.answer, tags: parse(r.tags, []), pattern: r.pattern || '',
handoff: !!r.handoff, order: r.ord == null ? null : Number(r.ord), source: r.source, ticketRef: r.ticket_ref || '', seedHash: r.seed_hash || '',
edited: !!r.edited, deleted: !!r.deleted, created: Number(r.created), updated: Number(r.updated) });
function parse(s, d) { try { const v = JSON.parse(s || ''); return Array.isArray(v) ? v : d; } catch (e) { return d; } }
const D = {
async ensure() {
await db.q(`CREATE TABLE IF NOT EXISTS kb_entries (
id VARCHAR(64) PRIMARY KEY,
title VARCHAR(200) NOT NULL,
questions TEXT NULL,
answer TEXT NOT NULL,
tags VARCHAR(800) NULL,
pattern TEXT NULL,
handoff TINYINT NOT NULL DEFAULT 0,
ord INT NULL,
source VARCHAR(16) NOT NULL DEFAULT 'admin',
ticket_ref VARCHAR(20) NULL,
seed_hash CHAR(40) NULL,
edited TINYINT NOT NULL DEFAULT 0,
deleted TINYINT NOT NULL DEFAULT 0,
created BIGINT NOT NULL,
updated BIGINT NOT NULL,
INDEX (deleted, updated)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
},
async all() { return (await db.q('SELECT * FROM kb_entries')).map(row); },
async put(e) {
await db.q(`INSERT INTO kb_entries (id,title,questions,answer,tags,pattern,handoff,ord,source,ticket_ref,seed_hash,edited,deleted,created,updated)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), questions=VALUES(questions), answer=VALUES(answer), tags=VALUES(tags),
pattern=VALUES(pattern), handoff=VALUES(handoff), ord=VALUES(ord), source=VALUES(source), ticket_ref=VALUES(ticket_ref), seed_hash=VALUES(seed_hash),
edited=VALUES(edited), deleted=VALUES(deleted), updated=VALUES(updated)`,
[e.id, e.title, JSON.stringify(e.questions || []), e.answer, JSON.stringify(e.tags || []), e.pattern || null, e.handoff ? 1 : 0, e.order == null ? null : e.order,
e.source, e.ticketRef || null, e.seedHash || null, e.edited ? 1 : 0, e.deleted ? 1 : 0, e.created, e.updated]);
}
};
const J = {
file: () => path.join(DATA_DIR, 'kb.json'),
async ensure() {},
async all() { try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
async put(e) {
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
if (i >= 0) all[i] = e; else all.push(e);
const tmp = J.file() + '.tmp';
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
fs.renameSync(tmp, J.file());
}
};
const store = () => db.enabled() ? D : J;
// ---------------------------------------------------------------- seeds
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
function seedEntry(s) {
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
order: s.order == null ? null : s.order, source: s.source || 'faq' };
}
async function syncSeeds() {
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
const seedIds = new Set(SEEDS.map(s => s.id));
let added = 0, refreshed = 0, retired = 0;
for (const s of SEEDS) {
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
}
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
}
function init(opts) {
DATA_DIR = opts.dataDir; SEEDS = opts.seeds || []; cache = null; index = null;
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
return ready;
}
async function load(force) {
if (ready) await ready;
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
const all = await store().all();
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear();
return cache;
}
const rx = new Map();
function compiled(src) {
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
return rx.get(src);
}
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
// ---------------------------------------------------------------- the chatbot side
async function fastPath(msg) {
const list = (await load()).filter(e => e.pattern).sort(byOrder);
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
return null;
}
async function search(query, k) { await load(); return rank(index, query, k || 5); }
async function context(query, k) { return relevant(await search(query, k || 5)); }
const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)';
function promptBlock(hits) {
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
}
// ---------------------------------------------------------------- the admin side
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
function validate(o, cur) {
o = o || {};
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
const answer = clean(o.answer).slice(0, 4000);
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
if (!title) return { error: 'Give the entry a title or at least one question.' };
if (!answer) return { error: 'The answer is empty.' };
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
}
async function list(q) {
const all = (await load(true)).slice();
if (!q) return all.sort((a, b) => b.updated - a.updated);
const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry));
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
return ranked.concat(plain);
}
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
async function create(o) {
const v = validate(o); if (v.error) return v;
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
await store().put(e); await load(true);
return { ok: true, entry: e };
}
async function update(id, o) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
const v = validate(o, cur); if (v.error) return v;
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
await store().put(e); await load(true);
return { ok: true, entry: e };
}
async function remove(id) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true);
return { ok: true };
}
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
// KNOWLEDGE_DATE already speaks for the code.
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
async function stamp() {
const all = await load();
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
return { updated: max ? ctDay(max) : '', count: all.length };
}
async function test(question) {
const fast = await fastPath(String(question || ''));
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
}
module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
+218
View File
@@ -0,0 +1,218 @@
// The Refuel Kit (Fuel Your Offers stage 3, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
// LinkSpin; each site keeps ITS OWN program's kits (InstantAdPay art promotes InstantAdPay, LinkSpin art promotes
// LinkSpin, never mixed).
//
// A kit is one month's members-only banner set: { month 'YYYY-MM', theme, released, sizes 728x90 300x250 468x60 160x600
// 1200x630 } with one base image per size, stored as data in DATA_DIR/kits/ (kits.json + <month>/<size>.<ext>).
// Admin uploads the base art and previews the personalization; nothing here generates art (real art is Marty's).
//
// Who gets which kit: a counted refuel (the streak in refuel.js, InstantAdPay is the source of truth) unlocks the kit
// of the Central-time month it landed in. The entitlement arrives as { months: { 'YYYY-MM': streakMonthAtUnlock } }
// from opts.entitled(email). Kits stay usable after their month; missing a refuel only stops NEW kits.
// streak month 3+ at unlock an animated GIF version of each banner size
// streak month 6+ at unlock a "custom banners" credit for BannerKitAI: the entitlement and a note only, no integration
//
// Personalized on the server per member: their @username and a QR code to their own link are drawn onto each banner
// with ffmpeg (the badge renderer's approach). Rendered files are cached in DATA_DIR/kits/out/<hash>.<ext> and served
// publicly at /kitimg/<hash>.<ext> (ad networks and IAP banner campaigns load them by URL); the hash is an HMAC of
// member + kit + size + variant + base-art version, so it cannot be guessed and changes when the art changes.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { spawn } = require('child_process');
const SIZES = { '728x90': [728, 90], '300x250': [300, 250], '468x60': [468, 60], '160x600': [160, 600], '1200x630': [1200, 630] };
const ORDER = ['728x90', '300x250', '468x60', '160x600', '1200x630'];
// where the QR and the name go on each size: q = QR box (x, y, side), t = name (x expr, y expr, font px)
const LAYOUT = {
'728x90': { q: ['W-84', 6, 78], t: ['W-96-tw', 'H-30', 18] },
'468x60': { q: ['W-58', 4, 52], t: ['W-68-tw', 'H-24', 14] },
'300x250': { q: ['W-82', 'H-82', 76], t: ['8', 'H-30', 16] },
'160x600': { q: ['(W-120)/2', 'H-128', 120], t: ['(W-tw)/2', 'H-160', 16] },
'1200x630': { q: ['W-212', 'H-212', 182], t: ['32', 'H-66', 34] },
};
let X = {}, DIR = null, OUT = null, FILE = null, SALT = null;
const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
const norm = e => String(e || '').trim().toLowerCase();
function init(opts) {
X = opts || {}; DIR = path.join(X.dataDir, 'kits'); OUT = path.join(DIR, 'out'); FILE = path.join(DIR, 'kits.json');
try { fs.mkdirSync(OUT, { recursive: true }); } catch (e) {}
const sf = path.join(DIR, 'salt'); try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (e) {}
if (!SALT) { SALT = crypto.randomBytes(16).toString('hex'); try { fs.writeFileSync(sf, SALT, { flag: 'wx' }); } catch (e) { try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (er) {} } }
}
const program = () => X.program === 'linkspin' ? 'linkspin' : 'iap';
const brand = () => program() === 'linkspin' ? 'LinkSpin' : 'InstantAdPay';
function load() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.kits = s.kits || {}; s.credits = s.credits || {}; return s; } catch (e) { return { kits: {}, credits: {} }; } }
function save(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s, null, 1)); fs.renameSync(tmp, FILE); }
const ctMonth = ts => new Date(ts || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }).slice(0, 7);
const monthLabel = m => new Date(Date.UTC(Number(m.slice(0, 4)), Number(m.slice(5, 7)) - 1, 15)).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
// ---- admin: the kits ---------------------------------------------------------------------------------
function baseFile(month, size) {
const d = path.join(DIR, month);
for (const ext of ['png', 'jpg', 'gif']) { const f = path.join(d, size + '.' + ext); if (fs.existsSync(f)) return f; }
return null;
}
function kitView(k) {
const sizes = ORDER.map(s => { const f = baseFile(k.month, s); return { size: s, ready: !!f, v: f ? Math.round(fs.statSync(f).mtimeMs) : 0 }; });
return { month: k.month, label: monthLabel(k.month), theme: k.theme || '', released: !!k.released, program: program(), sizes, complete: sizes.every(x => x.ready), updated: k.updated || 0 };
}
function listKits() { const s = load(); return Object.values(s.kits).sort((a, b) => b.month.localeCompare(a.month)).map(kitView); }
function saveKit(b) {
const month = String(b.month || ''); if (!MONTH_RE.test(month)) return { error: 'Month as YYYY-MM.' };
const s = load(); const k = s.kits[month] || { month, theme: '', released: false, created: Date.now() };
if (b.theme != null) k.theme = String(b.theme).trim().slice(0, 80);
if (b.released != null) {
if (b.released && !kitView(k).complete) return { error: 'Upload all five sizes before releasing the kit.' };
k.released = !!b.released;
}
if (b.remove) { delete s.kits[month]; save(s); return { ok: true, removed: true }; }
k.updated = Date.now(); s.kits[month] = k; save(s);
return { ok: true, kit: kitView(k) };
}
const MAGIC = { png: b => b[0] === 0x89 && b[1] === 0x50, jpg: b => b[0] === 0xff && b[1] === 0xd8, gif: b => b.slice(0, 3).toString() === 'GIF' };
function uploadBase(month, size, buf, mime) {
if (!MONTH_RE.test(String(month))) return { error: 'Month as YYYY-MM.' };
if (!SIZES[size]) return { error: 'Size must be one of ' + ORDER.join(', ') + '.' };
const ext = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' }[String(mime || '').split(';')[0].trim()];
if (!ext || !buf || buf.length < 32 || !MAGIC[ext](buf)) return { error: 'Use a PNG, JPG or GIF file.' };
const d = path.join(DIR, month); fs.mkdirSync(d, { recursive: true });
for (const e of ['png', 'jpg', 'gif']) { try { fs.unlinkSync(path.join(d, size + '.' + e)); } catch (er) {} }
fs.writeFileSync(path.join(d, size + '.' + ext), buf);
const s = load(); if (!s.kits[month]) s.kits[month] = { month, theme: '', released: false, created: Date.now() }; s.kits[month].updated = Date.now(); save(s);
return { ok: true, kit: kitView(s.kits[month]) };
}
// placeholder art for tests and previews: the program's existing banners from public/banners (no paid image APIs)
function usePlaceholder(month) {
const pre = program() === 'linkspin' ? 'linkspin-' : 'iap-';
const pick = { '728x90': [pre + '728x90.png'], '300x250': [pre + '300x250.png'], '468x60': [pre + '468x60.png'], '160x600': [pre + '160x600.png'],
'1200x630': program() === 'linkspin' ? ['linkspin-og-1200x630.png'] : ['iap-hero-1200x630.png', 'iap-advertise-earn-1200x630.jpg'] };
const done = [];
for (const size of ORDER) {
const f = pick[size].map(n => path.join(X.publicDir, 'banners', n)).find(p => fs.existsSync(p)); if (!f) continue;
const buf = fs.readFileSync(f); const r = uploadBase(month, size, buf, /\.jpg$/.test(f) ? 'image/jpeg' : 'image/png'); if (r.ok) done.push(size);
}
return { ok: true, sizes: done, kit: kitView(load().kits[month] || { month }) };
}
// ---- the renderer ---------------------------------------------------------------------------------------
let FONT;
function font() {
if (FONT !== undefined) return FONT;
FONT = process.env.BADGE_FONT || null; if (FONT) return FONT;
const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/bold\.ttf$/i.test(e.name) || /DejaVuSans-Bold\.ttf$/.test(e.name)) return f; } return null; };
for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } }
if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf';
return FONT;
}
const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%');
function run(args, cwd) {
return new Promise(resolve => {
const p = spawn(X.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'], cwd });
const out = []; let err = '';
p.stdout.on('data', c => out.push(c)); p.stderr.on('data', c => { err += c; });
p.on('error', e => resolve({ code: -1, err: e.message })); p.on('close', code => resolve({ code, out: Buffer.concat(out), err }));
});
}
// one personalized banner: base scaled to the exact size, QR (white quiet zone) and @name on a dark box
async function renderStill(base, size, name, link, stage, outFile) {
const [W, H] = SIZES[size]; const L = LAYOUT[size]; const F = font();
if (!F) return { error: 'No font for the renderer.' };
const qr = X.qrcode || require('qrcode'); // opts.qrcode: a test copy without node_modules
const qrFile = outFile + '.qr.png';
await qr.toFile(qrFile, link, { margin: 1, width: L.q[2], errorCorrectionLevel: 'M', color: { dark: '#000000', light: '#ffffff' } });
const winPath = /:/.test(F); const fontFile = winPath ? path.basename(F) : F;
const ex = v => String(v).replace(/W/g, String(W)).replace(/H/g, String(H));
const tx = String(L.t[0]).replace(/W/g, String(W)).replace(/tw/g, 'text_w'); const ty = ex(L.t[1]);
const showName = stage !== 0, showQr = stage === undefined || stage === 2;
const chain = ['[0:v]scale=' + W + ':' + H + ':flags=lanczos,setsar=1[b]'];
let last = 'b';
if (showQr) { chain.push('[1:v]scale=' + L.q[2] + ':' + L.q[2] + '[q]'); chain.push('[' + last + '][q]overlay=x=' + ex(L.q[0]) + ':y=' + ex(L.q[1]) + '[o]'); last = 'o'; }
if (showName && name) { chain.push('[' + last + ']drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=white:fontsize=" + L.t[2] + ':box=1:boxcolor=0x0b1418@0.72:boxborderw=6:x=' + tx + ':y=' + ty + '[n]'); last = 'n'; }
const args = ['-v', 'error', '-y', '-i', path.resolve(base), '-i', path.resolve(qrFile), '-filter_complex', chain.join(';'), '-map', '[' + last + ']', '-frames:v', '1'];
if (/\.jpg$/.test(outFile)) args.push('-q:v', '3');
args.push(path.resolve(outFile));
const r = await run(args, winPath ? path.dirname(F) : undefined);
try { fs.unlinkSync(qrFile); } catch (e) {}
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'Render failed: ' + String(r.err || '').slice(0, 200) };
return { ok: true };
}
// the animated version (streak month 3+): the banner, then the name, then the name and the QR, looping
async function renderGif(base, size, name, link, outFile) {
const frames = [0, 1, 2].map(i => outFile + '.f' + i + '.png');
for (let i = 0; i < 3; i++) { const r = await renderStill(base, size, name, link, i, frames[i]); if (r.error) return r; }
const list = outFile + '.txt';
fs.writeFileSync(list, frames.map((f, i) => "file '" + path.resolve(f).replace(/\\/g, '/') + "'\nduration " + (i === 2 ? 3 : 1)).join('\n') + "\nfile '" + path.resolve(frames[2]).replace(/\\/g, '/') + "'\n");
const r = await run(['-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', list, '-filter_complex', 'split[a][b];[a]palettegen=max_colors=96[p];[b][p]paletteuse=dither=bayer', '-loop', '0', path.resolve(outFile)]);
for (const f of frames.concat(list)) { try { fs.unlinkSync(f); } catch (e) {} }
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'GIF render failed: ' + String(r.err || '').slice(0, 200) };
return { ok: true };
}
const hashOf = (email, month, size, variant, v) => crypto.createHmac('sha256', SALT).update([norm(email), program(), month, size, variant, v].join('|')).digest('hex').slice(0, 28);
function indexFile() { return path.join(OUT, 'index.json'); }
function noteIndex(h, meta) { let ix = {}; try { ix = JSON.parse(fs.readFileSync(indexFile(), 'utf8')); } catch (e) {} ix[h] = meta; const tmp = indexFile() + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(ix)); fs.renameSync(tmp, indexFile()); }
// render (or reuse) one personalized file; returns { url, file, size, variant, w, h, bytes }
async function personal(who, month, size, variant) {
const base = baseFile(month, size); if (!base) return { error: 'That kit has no ' + size + ' art yet.' };
const v = Math.round(fs.statSync(base).mtimeMs);
const ext = variant === 'gif' ? 'gif' : size === '1200x630' ? 'jpg' : 'png';
const h = hashOf(who.email, month, size, variant, v + '|' + who.name + '|' + who.link);
const out = path.join(OUT, h + '.' + ext);
if (!fs.existsSync(out)) {
const tmp = path.join(OUT, h + '.' + process.pid + '.' + Date.now() + '.' + ext);
let r; try { r = variant === 'gif' ? await renderGif(base, size, who.name, who.link, tmp) : await renderStill(base, size, who.name, who.link, undefined, tmp); } catch (e) { r = { error: 'The banner renderer is not available: ' + e.message }; }
if (r.error) return r;
try { fs.renameSync(tmp, out); } catch (e) { try { fs.unlinkSync(tmp); } catch (er) {} }
noteIndex(h, { email: norm(who.email), month, size, variant, ts: Date.now() });
}
const [w, hh] = SIZES[size];
return { ok: true, url: '/kitimg/' + h + '.' + ext, abs: String(X.siteUrl || '').replace(/\/+$/, '') + '/kitimg/' + h + '.' + ext, file: out, size, variant, w, h: hh, bytes: fs.statSync(out).size, ext };
}
// public serving: only files already rendered for an entitled member
function servePath(name) { const m = /^([a-f0-9]{28})\.(png|jpg|gif)$/.exec(String(name || '')); if (!m) return null; const f = path.join(OUT, m[0]); return fs.existsSync(f) ? { file: f, mime: { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[m[2]] } : null; }
// ---- the member ------------------------------------------------------------------------------------------
async function whoOf(email) {
const w = await X.linkFor(norm(email)); if (!w || !w.link) return null;
return { email: norm(email), name: w.username ? '@' + w.username : '', link: w.link };
}
async function myKits(email) {
const ent = (await X.entitled(norm(email)).catch(() => null)) || null;
if (!ent || !ent.on) return { on: false };
const s = load(); const months = ent.months || {};
const nowMonth = String(ent.today || '').slice(0, 7) || ctMonth(); // a kit released early still waits for its month
const kits = Object.values(s.kits).filter(k => k.released && k.month <= nowMonth).sort((a, b) => b.month.localeCompare(a.month)).slice(0, 12).map(k => {
const streakAt = months[k.month] || 0; const unlocked = streakAt > 0;
return Object.assign(kitView(k), { unlocked, streakAt, gif: unlocked && streakAt >= 3, custom: unlocked && streakAt >= 6 });
});
// the BannerKitAI "custom banners" credit: an entitlement on record, nothing more yet
const customMonths = Object.entries(months).filter(([, k]) => k >= 6).map(([m]) => m);
if (customMonths.length) {
const e = norm(email); const have = s.credits[e] || {}; let changed = false;
for (const m of customMonths) if (!have[m]) { have[m] = { ts: Date.now(), used: false }; changed = true; }
if (changed) { s.credits[e] = have; save(s); }
}
const credits = Object.entries((s.credits[norm(email)] || {})).map(([m, c]) => ({ month: m, used: !!c.used }));
const cur = nowMonth; const who = await whoOf(email).catch(() => null);
return { on: true, program: program(), brand: brand(), link: who ? who.link : null, name: who ? who.name : null, current: cur, currentLabel: monthLabel(cur), unlockedCurrent: !!months[cur],
kits, customCredits: credits, customNote: credits.length ? 'Custom banners made for your own offer with BannerKitAI are coming. Your credit is saved on your account and will be honored when it opens.' : null,
nextRefuel: ent.nextRefuel || null };
}
async function renderFor(email, month, size, variant) {
const mk = await myKits(email); if (!mk.on) return { error: 'The Refuel Kit is not switched on.' };
const k = mk.kits.find(x => x.month === month); if (!k) return { error: 'No such kit.' };
if (!k.unlocked) return { error: 'Your next counted refuel unlocks this kit.' };
if (!SIZES[size]) return { error: 'No such size.' };
if (variant === 'gif' && !k.gif) return { error: 'The animated version comes with a 3-month streak.' };
const who = await whoOf(email); if (!who) return { error: 'Set a username first, so your banners carry your own link.' };
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
}
async function preview(month, size, username, variant) {
const link = String(X.siteUrl || '').replace(/\/+$/, '') + '/join/' + (username || 'yourname');
const who = { email: 'preview@' + program(), name: '@' + (username || 'yourname'), link };
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
}
module.exports = { init, SIZES, ORDER, LAYOUT, listKits, saveKit, uploadBase, usePlaceholder, myKits, renderFor, preview, servePath, ctMonth, monthLabel, font };
+148
View File
@@ -0,0 +1,148 @@
// Leaderboard + weekly/monthly referral contest (Marty, 2026-09-14).
// Sales credit = tier-1 payouts on-chain: the direct sponsor of every package sold. A member's own linked
// positions and second accounts do not count for them (only sales to other people's accounts). Periods run
// on Central time: week = Monday 00:00 to Sunday 23:59, month = calendar month. Winners are recorded at
// rollover (checked hourly), announced to Telegram, and credit prizes are granted automatically.
const fs = require('fs');
const path = require('path');
const themehead = require('./themehead'); // light/dark theme head script (2026-11-01)
let R = null; // { chain, accounts, ads, dataDir, siteConfig, notify(text), pushFeed(ev) }
const TZ = 'America/Chicago';
let cache = { at: 0, rows: null };
const FILE = () => path.join(R.dataDir, 'leaderboard-winners.json');
function init(refs) { R = refs; }
// Central-time helpers (no tz lib): shift by the zone offset at that instant
function ctParts(ts) {
const s = new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' });
const m = /(\w{3}), (\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/.exec(s);
return { wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(m[1]), y: +m[4], mo: +m[2], d: +m[3], h: +m[5] % 24, mi: +m[6] };
}
function ctMidnight(ts) { // the instant of 00:00 Central on the Central date of ts
const p = ctParts(ts); const guess = Date.UTC(p.y, p.mo - 1, p.d, 5, 0, 0); // CDT = UTC-5; CST = UTC-6
const q = ctParts(guess); return (q.h === 0 && q.d === p.d) ? guess : guess + 3600000;
}
function weekStart(ts) { const p = ctParts(ts); const mid = ctMidnight(ts); const back = (p.wd + 6) % 7; return mid - back * 86400000; }
function monthStart(ts) { const p = ctParts(ts); return ctMidnight(Date.UTC(p.y, p.mo - 1, 1, 12)); }
function periodBounds(period, ts) {
const now = ts || Date.now();
if (period === 'week') return { start: weekStart(now), end: now, label: 'This week' };
if (period === 'lastweek') { const s = weekStart(now); return { start: weekStart(s - 1), end: s, label: 'Last week' }; }
if (period === 'month') return { start: monthStart(now), end: now, label: 'This month' };
if (period === 'lastmonth') { const s = monthStart(now); return { start: monthStart(s - 1), end: s, label: 'Last month' }; }
return { start: 0, end: now, label: 'All time' };
}
// member id -> account email (main ids + linked positions), refreshed every minute
let idMap = { at: 0, map: {}, names: {} };
async function memberMap() {
if (Date.now() - idMap.at < 60000) return idMap;
const map = {}, names = {};
const list = await R.accounts.listAll(5000);
for (const a of list) {
if (a.memberId) { map[a.memberId] = a.email; names[a.email] = a.username ? '@' + a.username : 'member #' + a.memberId; }
else names[a.email] = a.username ? '@' + a.username : a.email.replace(/@.*/, '') + '@';
try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) map[p.memberId] = a.email; } catch (e) {}
}
idMap = { at: Date.now(), map, names }; return idMap;
}
const computeCache = {};
async function compute(period) {
const c = computeCache[period]; if (c && Date.now() - c.at < 30000) return c.val;
const val = await computeRaw(period); computeCache[period] = { at: Date.now(), val }; return val;
}
async function computeRaw(period) {
const { start, end, label } = periodBounds(period);
const { map, names } = await memberMap();
const price = {}; // tx -> cents
for (const e of R.chain.recentEvents(1e9)) if (e.type === 'Purchase') price[e.tx + ':' + e.buyerId] = Number(e.priceCents || 0);
const rows = {};
for (const e of R.chain.recentEvents(1e9)) {
if (e.type !== 'TierPaid' || e.tier !== 1 || e.ts < start || e.ts >= end) continue;
const sponsor = map[e.recipientId], buyer = map[e.buyerId];
if (!sponsor) continue;
if (buyer && buyer === sponsor) continue; // own positions never count
if (R.fraud && ((buyer && R.fraud.excluded(buyer)) || R.fraud.excluded(sponsor))) continue; // flagged / suspended accounts never count (2026-09-16)
const r = rows[sponsor] = rows[sponsor] || { email: sponsor, name: names[sponsor], sales: 0, cents: 0, pol: 0n, buyers: new Set() };
r.sales += 1; r.cents += price[e.tx + ':' + e.buyerId] || 0; r.pol += BigInt(e.amountWei || 0); if (buyer) r.buyers.add(buyer);
}
// sign-ups sponsored in the period (site-side), for the secondary column
const joins = {};
for (const a of await R.accounts.listAll(5000)) {
if (!a.sponsorRef || a.created < start || a.created >= end) continue;
let s = null; try { s = await R.accounts.sponsorOf(a.email); } catch (e) {}
if (s && s.email !== a.email) joins[s.email] = (joins[s.email] || 0) + 1;
}
for (const [em, n] of Object.entries(joins)) { const r = rows[em] = rows[em] || { email: em, name: names[em] || em, sales: 0, cents: 0, pol: 0n, buyers: new Set() }; r.joins = n; }
// the admin's own account (company placements, tank arrivals) is not a contestant
if (R.adminEmail && rows[R.adminEmail]) delete rows[R.adminEmail];
const out = Object.values(rows).map(r => ({ email: r.email, name: r.name, sales: r.sales, usd: r.cents / 100, pol: Number(r.pol / 10n ** 14n) / 10000, buyers: r.buyers.size, joins: r.joins || 0 }))
.sort((a, b) => b.usd - a.usd || b.sales - a.sales || b.joins - a.joins);
out.forEach((r, i) => { r.rank = i + 1; });
return { period, label, start, end, rows: out };
}
async function view(period, meEmail) {
const key = period || 'week';
const r = await compute(key);
const sc = R.siteConfig();
const prize = prizeText(key.includes('month') ? 'month' : 'week', sc);
const me = meEmail ? r.rows.find(x => x.email === meEmail) : null;
return { period: r.period, label: r.label, start: r.start, end: r.end, prize: prize || '', top: r.rows.slice(0, 10).map(pub), me: me ? pub(me) : null, count: r.rows.length,
winners: winners().slice(0, 6) };
}
const pub = r => ({ rank: r.rank, name: r.name, sales: r.sales, usd: r.usd, buyers: r.buyers, joins: r.joins });
// "1000,500,250" -> [1000, 500, 250]: credits for 1st, 2nd, 3rd... (Marty: award the top X positions, 2026-09-14)
const ladder = v => String(v || '').split(',').map(x => Math.round(Number(x)) || 0).filter(n => n > 0);
const ORD = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th'];
const ladderText = l => l.length ? l.map((n, i) => ORD[i] + ' ' + n.toLocaleString()).join(' · ') + ' credits' : '';
function prizeText(kind, sc) { const t = kind === 'week' ? sc.leaderboardWeeklyPrize : sc.leaderboardMonthlyPrize; if (t) return t; return ladderText(ladder(kind === 'week' ? sc.leaderboardWeeklyCredits : sc.leaderboardMonthlyCredits)); }
function winners() { try { return JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { return []; } }
// rollover: once a completed week/month has no winner recorded, record it, grant credits, announce
async function rolloverTick() {
const now = Date.now(); const sc = R.siteConfig(); const w = winners(); let changed = false;
for (const kind of ['week', 'month']) {
const cur = kind === 'week' ? weekStart(now) : monthStart(now);
const prevStart = kind === 'week' ? weekStart(cur - 1) : monthStart(cur - 1);
if (prevStart < Date.parse('2026-09-08T05:00:00Z')) continue; // contest starts with the week of Sep 8
if (w.find(x => x.kind === kind && x.start === prevStart)) continue;
const r = await compute(kind === 'week' ? 'lastweek' : 'lastmonth');
const lad = ladder(kind === 'week' ? sc.leaderboardWeeklyCredits : sc.leaderboardMonthlyCredits);
const top = r.rows.filter(x => x.sales > 0).slice(0, Math.max(3, lad.length));
const prize = prizeText(kind, sc);
const rec = { kind, start: prevStart, end: cur, prize: prize || '', ladder: lad, top: top.map(pub), granted: [], at: now };
w.unshift(rec); changed = true;
for (let i = 0; i < lad.length && i < top.length; i++) { try { await R.ads.addEarned(top[i].email, lad[i], { log: { kind: 'bonus', note: 'Leaderboard prize: rank ' + (i + 1) + ' (' + kind + ')' } }); rec.granted.push({ rank: i + 1, name: top[i].name, credits: lad[i] }); } catch (e) {} }
if (top[0]) {
const when = new Date(prevStart).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' });
const line = '\u{1F3C6} <b>InstantAdPay</b> · ' + (kind === 'week' ? 'Weekly' : 'Monthly') + ' referral contest (from ' + when + '): <b>' + top[0].name + '</b> wins with ' + top[0].sales + ' package' + (top[0].sales === 1 ? '' : 's') + ' sold ($' + top[0].usd + ')' + (top[1] ? ' · 2nd ' + top[1].name + ' ($' + top[1].usd + ')' : '') + (top[2] ? ' · 3rd ' + top[2].name + ' ($' + top[2].usd + ')' : '') + (rec.granted.length ? '\nCredits awarded: ' + rec.granted.map(g => g.name + ' +' + g.credits.toLocaleString()).join(', ') : (prize ? '\nPrize: ' + prize : '')) + '\ninstantadpay.com/leaderboard';
try { await R.notify(line); } catch (e) {}
try { R.pushFeed({ type: 'Contest', kind, winner: top[0].name, ts: now }); } catch (e) {}
}
}
if (changed) fs.writeFileSync(FILE(), JSON.stringify(w.slice(0, 60), null, 1));
}
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
async function renderPage() {
const week = await view('week'), month = await view('month'), all = await view('all');
const sc = R.siteConfig();
const table = v => '<table class="lb"><tr><th>#</th><th>Member</th><th>Packages</th><th>Sales</th><th>Buyers</th><th>New members</th></tr>'
+ (v.top.length ? v.top.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b></td><td>' + r.sales + '</td><td>$' + r.usd.toLocaleString() + '</td><td>' + r.buyers + '</td><td>' + r.joins + '</td></tr>').join('') : '<tr><td colspan="6" class="muted">No sales yet in this period.</td></tr>') + '</table>';
const fmtD = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' });
const desc = 'Who is selling the most ad packages on InstantAdPay this week and this month. Weekly and monthly referral contest standings, read from the chain.';
let h = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leaderboard | InstantAdPay</title><meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="https://instantadpay.com/leaderboard"><meta property="og:title" content="InstantAdPay leaderboard"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="https://instantadpay.com/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:var(--gold);font-weight:800}.prize{border-left:4px solid var(--mint);background:var(--mint-soft);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}</style></head><body><div class="wrap lbw">'
+ '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">Referral contest</p><h1>Leaderboard: <em>who is selling</em>.</h1><p class="lead">Ranked by ad packages sold to other people (your own positions never count, and the company account is not a contestant). Read from the chain, updated live. Weeks run Monday to Sunday, Central time.</p></section>';
h += '<h2 style="font-size:24px;margin:0 0 4px">' + week.label + ' <span class="muted small">' + fmtD(week.start) + ' to Sunday</span></h2>' + (week.prize ? '<div class="prize"><b>Weekly prizes:</b> ' + esc(week.prize) + '</div>' : '') + table(week);
h += '<h2 style="font-size:24px;margin:0 0 4px">' + month.label + '</h2>' + (month.prize ? '<div class="prize"><b>Monthly prizes:</b> ' + esc(month.prize) + '</div>' : '') + table(month);
h += '<h2 style="font-size:24px;margin:0 0 4px">All time</h2>' + table(all);
const w = winners();
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
return h;
}
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
+124
View File
@@ -0,0 +1,124 @@
// Money moving in and out of the receiver wallets, which the chain index cannot tell us about
// (Marty, 2026-09-23). The P&L derives revenue from AdminPaid events and holdings from
// eth_getBalance, so two real things were invisible:
//
// OUT a draw. Marty funded RM Circle #139's Culmen->Apex upgrade from Receiver A. That is a
// legitimate use of house profit, but nothing recorded it, so "earned" and "on hand" drift
// apart for ever. ("Why would I ever keep a receiver wallet that I never take anything out
// of? That's stupid, so I need to be able to account for it.")
// IN outside income paid into the same wallet, e.g. a ClickBaitPays withdrawal. Real profit,
// but it is not an AdminPaid event, so the revenue lines never see it.
//
// Both are hand-entered because only Marty knows what a transfer was for. Storage:
// DATA_DIR/ledger.json { entries: [{id, date, dir, asset, amount, usd, wallet, note, tx, ts}] }
const fs = require('fs');
const path = require('path');
let FILE = null;
const DIRS = ['in', 'out'];
// 'outside': a wallet that is not one of ours above, e.g. Marty funding a game wallet from his own Tangem
const WALLETS = ['feeA', 'feeB', 'engine', 'hunt', 'outside'];
// assets we can actually value; anything else is recorded but valued only by the usd field
const ASSETS = ['POL', 'USDC', 'USDT', 'DAI', 'other'];
// WHY a kind and not just a direction (Marty, 2026-09-23): three different things move through
// Receiver A and only one of them is profit.
// revenue outside income earned by the business, e.g. a ClickBaitPays withdrawal in POL.
// Counts toward profit AND toward the balance.
// draw house profit spent on something, e.g. funding RM Circle #139's upgrade. Leaves the
// wallet, but it is not a cost of running InstantAdPay.
// transfer Marty's own capital moved in or out for safekeeping, e.g. consolidating balances
// from other owned positions into the Tangem receiver. Touches the balance ONLY and
// must never show up as revenue, or the P&L reports his savings as earnings.
// cost a real cost of running the network (2026-10-04, Marty: top up game wallets as needed and record each top-up so
// the P&L balances; "show what I spent in advertising versus income" at tax time). Every cost has a category.
const KINDS = ['revenue', 'draw', 'transfer', 'cost'];
// tax-friendly cost categories: advertising + rewards are both "advertising and promotion" on the tax summary
// games (2026-10-05, Marty): game wallet top-ups are a marketing cost for InstantAdPay, booked apart from paid traffic
const CATS = { advertising: 'Advertising (paid traffic, ad networks)', games: 'Game marketing (game wallet top-ups)', rewards: 'Player rewards (game and earning-site payouts)', software: 'Software and hosting', other: 'Other costs' };
function init(opts) {
FILE = path.join(opts.dataDir, 'ledger.json');
// one-time move (2026-10-05): earlier game wallet top-ups, booked by the wallet watcher as Player rewards, become Game marketing
try { const d = load(); let n = 0; for (const e of d.entries) if (e.kind === 'cost' && e.category === 'rewards' && /^Player rewards funding: /.test(e.note || '')) { e.category = 'games'; e.note = e.note.replace(/^Player rewards funding: /, 'Game marketing: '); n++; } if (n) { save(d); console.log('ledger: moved', n, 'game wallet top-ups to Game marketing'); } } catch (e) { console.error('ledger migrate', e.message); }
}
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { entries: [] }; } }
function save(d) {
const tmp = FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(d, null, 1));
fs.renameSync(tmp, FILE); // never leave a half-written ledger behind
}
const newId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
const num = v => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6) / 1e6 : 0; };
function entries() {
return load().entries.slice().sort((a, b) =>
(b.date || '').localeCompare(a.date || '') || (b.ts || 0) - (a.ts || 0));
}
function put(input) {
const d = load();
const dir = DIRS.includes(input.dir) ? input.dir : null;
if (!dir) return { error: 'Say whether the money came in or went out.' };
const amount = num(input.amount);
const usd = num(input.usd);
if (!amount && !usd) return { error: 'Give an amount, in POL or in dollars.' };
const note = String(input.note || '').trim().slice(0, 200);
if (!note) return { error: 'Say what this was for. An unexplained line is the thing we are fixing.' };
const date = /^\d{4}-\d{2}-\d{2}$/.test(String(input.date || '')) ? input.date
: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Central, like every other day key here
const e = {
id: input.id && d.entries.find(x => x.id === input.id) ? input.id : newId(),
date, dir, amount, usd, note,
asset: ASSETS.includes(input.asset) ? input.asset : 'POL',
kind: KINDS.includes(input.kind) ? input.kind : (dir === 'in' ? 'revenue' : 'draw'),
wallet: WALLETS.includes(input.wallet) ? input.wallet : 'feeA',
tx: /^0x[0-9a-fA-F]{64}$/.test(String(input.tx || '')) ? String(input.tx).toLowerCase() : '',
ts: Date.now(),
};
if (e.kind === 'cost') e.category = CATS[input.category] ? input.category : 'other';
if (e.tx && d.entries.some(x => x.tx === e.tx && x.id !== e.id)) return { error: 'That transaction is already recorded.', duplicate: true };
const i = d.entries.findIndex(x => x.id === e.id);
if (i >= 0) d.entries[i] = e; else d.entries.push(e);
save(d);
return { ok: true, entry: e };
}
function remove(id) {
const d = load();
const i = d.entries.findIndex(x => x.id === id);
if (i < 0) return { error: 'No such entry.' };
const [gone] = d.entries.splice(i, 1);
save(d);
return { ok: true, entry: gone };
}
// Totals per wallet, split by direction. POL is summed separately from dollar-denominated assets
// because only POL can be reconciled against an on-chain balance.
function totals(wallet) {
const rows = load().entries.filter(e => !wallet || e.wallet === wallet);
const t = { inPol: 0, outPol: 0, inUsd: 0, outUsd: 0, count: rows.length,
// revenue and draws are the P&L numbers; transfers move the balance and nothing else
revenuePol: 0, revenueUsd: 0, drawPol: 0, drawUsd: 0, transferPol: 0, costPol: 0, costUsd: 0 };
for (const e of rows) {
const pol = e.asset === 'POL' ? e.amount : 0;
if (e.dir === 'in') { t.inPol += pol; t.inUsd += e.usd; } else { t.outPol += pol; t.outUsd += e.usd; }
if (e.kind === 'revenue') { t.revenuePol += pol; t.revenueUsd += e.usd; }
else if (e.kind === 'draw') { t.drawPol += pol; t.drawUsd += e.usd; }
else if (e.kind === 'cost') { t.costPol += (e.dir === 'out' ? pol : -pol); t.costUsd += (e.dir === 'out' ? e.usd : -e.usd); }
else t.transferPol += (e.dir === 'in' ? pol : -pol);
}
for (const k of Object.keys(t)) if (k !== 'count') t[k] = Math.round(t[k] * 1e6) / 1e6;
return t;
}
// earned (AdminPaid) + POL in - POL out = what should be sitting there. Any drift is a transfer
// nobody has written down yet, and naming the number is the whole point of this file.
function reconcile(earnedPol, actualPol, wallet) {
const t = totals(wallet || 'feeA');
const expected = Math.round((Number(earnedPol || 0) + t.inPol - t.outPol) * 1e6) / 1e6;
const actual = Math.round(Number(actualPol || 0) * 1e6) / 1e6;
return { earnedPol: Number(earnedPol || 0), expected, actual,
drift: Math.round((actual - expected) * 1e6) / 1e6, totals: t };
}
module.exports = { init, entries, put, remove, totals, reconcile, DIRS, ASSETS, KINDS, WALLETS, CATS, entriesFor: year => load().entries.filter(e => String(e.date || '').startsWith(String(year))) };
+33
View File
@@ -0,0 +1,33 @@
// Legacy bridge: former Faucet Wave / Tier One Ads members (EvolutionScript sites Marty closed)
// arrive via /from/<brand>; if their email is on the private legacy list (DATA_DIR/legacy.json,
// email -> { b: 'faucetwave'|'tier1ads'|'both', s: 'a' (advertiser) | 'e' (earner) }) they get a
// one-time welcome-back credit grant at account creation. Grants are recorded in
// DATA_DIR/legacy-grants.json so a person is only ever credited once.
const fs = require('fs');
const path = require('path');
let DATA_DIR = null, list = null, grants = null;
function init(opts) { DATA_DIR = opts.dataDir; list = null; grants = null; }
function load() {
if (list === null) { try { list = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'legacy.json'), 'utf8')); } catch (e) { list = {}; } }
if (grants === null) { try { grants = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'legacy-grants.json'), 'utf8')); } catch (e) { grants = {}; } }
}
function reload() { list = null; grants = null; load(); }
function lookup(email) { load(); return list[String(email || '').trim().toLowerCase()] || null; }
// credits for this email, or null when not listed / already granted. Records the grant.
function grant(email, cfg) {
load();
const e = String(email || '').trim().toLowerCase();
const rec = list[e];
if (!rec || grants[e]) return null;
const credits = rec.s === 'a' ? (Number(cfg.legacyCreditsAdvertiser) || 500) : (Number(cfg.legacyCreditsEarner) || 150);
grants[e] = { credits, seg: rec.s, brand: rec.b, at: Date.now() };
fs.writeFileSync(path.join(DATA_DIR, 'legacy-grants.json'), JSON.stringify(grants));
return { credits, seg: rec.s, brand: rec.b };
}
function stats() {
load();
const g = Object.values(grants);
return { listed: Object.keys(list).length, granted: g.length, credits: g.reduce((a, x) => a + (x.credits || 0), 0) };
}
module.exports = { init, reload, lookup, grant, stats };
+61
View File
@@ -0,0 +1,61 @@
// Login-ad showings per day per surface (Marty, 2026-10-18). The sign-in interstitial now runs on
// the dashboard AND inside the games' sign-in kit; before raising the 3-slot cap he wants a week of
// combined numbers. One row per Central day, surface ('dashboard' or a game slug) and kind:
// 'member' (a member's slot was shown), 'house' (the house login ad), 'none' (a sign-in with no
// login ad to show). MySQL table login_shows when the DB is on, else DATA_DIR/login-shows.json.
'use strict';
const fs = require('fs');
const path = require('path');
const db = require('./db');
let DATA_DIR = null, J = null, ready = null;
const ctDay = t => new Date(t === undefined ? Date.now() : t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const FILE = () => path.join(DATA_DIR, 'login-shows.json');
function init(opts) { DATA_DIR = opts.dataDir; }
function ensure() {
if (!ready) ready = db.q(`CREATE TABLE IF NOT EXISTS login_shows (
day VARCHAR(10) NOT NULL, surface VARCHAR(40) NOT NULL, kind VARCHAR(10) NOT NULL, n INT NOT NULL DEFAULT 0,
PRIMARY KEY (day, surface, kind)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`).catch(e => { ready = null; throw e; });
return ready;
}
function load() { if (J) return J; try { J = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { J = {}; } return J; }
// surface: 'dashboard' | game slug; ad: what ads.serve returned (null = nothing to show)
async function record(surface, ad) {
const s = String(surface || 'dashboard').toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 40) || 'dashboard';
const kind = !ad ? 'none' : ad.house ? 'house' : 'member';
const d = ctDay();
try {
if (db.enabled()) {
await ensure();
await db.q('INSERT INTO login_shows (day,surface,kind,n) VALUES (?,?,?,1) ON DUPLICATE KEY UPDATE n=n+1', [d, s, kind]);
} else {
const k = d + '|' + s + '|' + kind, st = load();
st[k] = (st[k] || 0) + 1;
fs.writeFileSync(FILE(), JSON.stringify(st));
}
} catch (e) { console.error('login shows', e.message); }
}
// last `days` Central days, newest first: { day, dashboard: {member,house,none}, games: {member,house,none}, byGame: {slug: shown} }
async function report(days) {
days = Math.max(1, Math.min(90, Number(days) || 14));
const since = ctDay(Date.now() - (days - 1) * 86400000);
let rows = [];
if (db.enabled()) {
await ensure();
rows = (await db.q('SELECT day, surface, kind, n FROM login_shows WHERE day>=?', [since])).map(r => ({ day: String(r.day), surface: r.surface, kind: r.kind, n: Number(r.n) }));
} else {
for (const [k, n] of Object.entries(load())) { const [day, surface, kind] = k.split('|'); if (day >= since) rows.push({ day, surface, kind, n }); }
}
const out = {};
const blank = () => ({ member: 0, house: 0, none: 0 });
for (let i = 0; i < days; i++) { const d = ctDay(Date.now() - i * 86400000); out[d] = { day: d, dashboard: blank(), games: blank(), byGame: {} }; }
for (const r of rows) {
const o = out[r.day]; if (!o || !['member', 'house', 'none'].includes(r.kind)) continue;
if (r.surface === 'dashboard') o.dashboard[r.kind] += r.n;
else { o.games[r.kind] += r.n; if (r.kind !== 'none') o.byGame[r.surface] = (o.byGame[r.surface] || 0) + r.n; }
}
return Object.values(out).sort((a, b) => (a.day < b.day ? 1 : -1));
}
module.exports = { init, record, report };
+176
View File
@@ -0,0 +1,176 @@
// Conversion tracking, InstantAdPay half (Marty approved 2026-10-23). LinkSpin owns goals and conversions;
// this module does three things:
// record(click) every click through /api/ads/click/:id gets an id ('i' + 11 hex) that rides on the target URL as
// ?lsclk=<id>, and the click row is stored here (MySQL ad_clicks, or a capped JSON file locally)
// flush loop unpushed rows go to LinkSpin POST /api/partner/clicks every ~3 s, 500 per request, signed exactly
// like lssync.js (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET). A row is marked pushed only
// after LinkSpin answers ok, so a failure keeps it for the next try (backoff up to 5 minutes).
// LinkSpin upserts by id, so two app copies pushing the same rows during a deploy is harmless.
// conv(email,..) the member's goals and summary through POST /api/partner/conv (op summary/create/update/remove/test),
// summary cached 60 s per email.
// owners (2026-10-26) the soft keys members sign in from ride on the click push, so LinkSpin keeps a member's own
// clicks (ads here, spin links and Banner Spins there) as tests, never counted
// No LS_SYNC_SECRET (or shorter than 32 chars): clicks still get ids and rows, nothing is sent.
// The raw IP is never stored: only the soft key 's:' + sha256(ip + '|' + ua) first 20 hex, same on both sites.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
const stats = { pushed: 0, lastAt: null, lastError: null, errors: 0 };
const cache = new Map(); // email -> { at, data }
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
const on = () => SECRET().length >= 32;
const useDb = () => !!(R && R.db && R.db.enabled());
const JCAP = 5000;
const JFILE = () => path.join(R.dataDir, 'adclicks.json');
function init(deps) {
R = deps;
if (useDb()) ensureTable().catch(e => console.error('lsconv table', e.message));
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 3000); if (timer.unref) timer.unref(); }
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
}
// column names checked against MySQL 8 reserved words (none of id, campaign_id, owner_email, cname, ctype, sk, country,
// device, placement, target, spent, is_self, ts, pushed is reserved)
async function ensureTable() {
await R.db.q(`CREATE TABLE IF NOT EXISTS ad_clicks (
id VARCHAR(16) PRIMARY KEY,
campaign_id INT NOT NULL,
owner_email VARCHAR(190) NOT NULL,
cname VARCHAR(80) NULL,
ctype VARCHAR(12) NULL,
sk VARCHAR(24) NULL,
country VARCHAR(4) NULL,
device VARCHAR(8) NULL,
placement VARCHAR(80) NULL,
target VARCHAR(500) NULL,
spent INT NOT NULL DEFAULT 0,
is_self TINYINT NOT NULL DEFAULT 0,
ts BIGINT NOT NULL,
pushed TINYINT NOT NULL DEFAULT 0,
INDEX (pushed, ts),
INDEX (campaign_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
}
// ---- helpers (pure) ----
const newId = () => 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(String(ip || '') + '|' + String(ua || '')).digest('hex').slice(0, 20);
const deviceOf = ua => /Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/i.test(String(ua || '')) ? 'mobile' : 'desktop';
function placementOf(referer) {
try { const u = new URL(String(referer || '')); if (!/^https?:$/.test(u.protocol)) return null; return (u.host.replace(/^www\./, '') + u.pathname.replace(/\/+$/, '')).replace(/[^\w.\-\/:]/g, '').slice(0, 80) || null; }
catch (e) { return null; }
}
// append lsclk=<id> without touching anything already in the URL (string insert keeps the original encoding of every
// existing param); an existing lsclk is never replaced; a URL that does not parse goes out unchanged
function withClickId(target, id) {
const t = String(target || '');
let u; try { u = new URL(t); } catch (e) { return t; }
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk')) return t;
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
}
// ---- own-click tests (Marty approved 2026-10-26) ----
// A member's own click is a test on LinkSpin, on every click type. LinkSpin knows the soft keys its members sign in from;
// InstantAdPay members may never sign in there, so the soft keys of their InstantAdPay sessions ride along with the click
// push as owners: [{ owner, sk, ts }] (no raw IP, same hash as the click rows). Queued at most once per 6 h per
// email + soft key; a failed push puts them back. Also checked here so an own click is flagged self=1 at the source.
const OWN_MS = 31 * 86400e3, ownSeen = new Map(); let ownQueue = new Map();
function noteSession(email, ip, ua) {
const e = String(email || '').trim().toLowerCase(); if (!e || e.length > 190) return false;
const sk = softKey(ip, ua); const k = e + '|' + sk; const now = Date.now();
if (now - (ownSeen.get(k) || 0) < 6 * 3600e3) return false;
ownSeen.set(k, now); if (ownSeen.size > 50000) ownSeen.delete(ownSeen.keys().next().value);
if (on()) { ownQueue.set(k, { owner: e, sk, ts: now }); if (ownQueue.size > 5000) ownQueue.delete(ownQueue.keys().next().value); }
return true;
}
function isOwnerSk(owner, sk) { const t = ownSeen.get(String(owner || '').toLowerCase() + '|' + sk); return !!(t && Date.now() - t <= OWN_MS); }
function takeOwners() { const out = [...ownQueue.values()].slice(0, 2000); for (const o of out) ownQueue.delete(o.owner + '|' + o.sk); return out; }
function requeueOwners(list) { for (const o of list || []) if (!ownQueue.has(o.owner + '|' + o.sk)) ownQueue.set(o.owner + '|' + o.sk, o); }
// ---- storage ----
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!Array.isArray(jstate.rows)) throw 0; } catch (e) { jstate = { rows: [] }; } return jstate; }
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 500); }
function jcap() { const st = jload(); if (st.rows.length <= JCAP) return; let drop = st.rows.length - JCAP; st.rows = st.rows.filter(r => !(drop > 0 && r.pushed && drop--)); if (st.rows.length > JCAP) st.rows = st.rows.slice(-JCAP); }
// c = the campaign (ads.campaignById shape); returns the stored row
async function record(c, req, opts) {
const o = opts || {};
const ip = o.ip || String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const ua = String(req.headers['user-agent'] || '');
const row = { id: newId(), camp: Number(c.id), cname: String(c.name || c.title || '').slice(0, 80) || null, type: String(c.type || '').slice(0, 12) || null,
owner: String(c.owner || '').toLowerCase(), ts: Date.now(), sk: softKey(ip, ua), c: o.country ? String(o.country).slice(0, 4) : null, dv: deviceOf(ua),
pl: placementOf(req.headers.referer), target: String(o.target || c.targetUrl || '').slice(0, 500), spent: Math.max(0, Math.round(Number(c.spent || 0) + Number(c.accrued || 0))), self: o.self ? 1 : 0 };
if (useDb()) {
await R.db.q('INSERT INTO ad_clicks (id, campaign_id, owner_email, cname, ctype, sk, country, device, placement, target, spent, is_self, ts, pushed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
[row.id, row.camp, row.owner, row.cname, row.type, row.sk, row.c, row.dv, row.pl, row.target, row.spent, row.self, row.ts]);
} else { const st = jload(); st.rows.push(Object.assign({ pushed: 0 }, row)); jcap(); jsave(); }
return row;
}
const fromDb = r => ({ id: r.id, camp: Number(r.campaign_id), cname: r.cname, type: r.ctype, owner: r.owner_email, ts: Number(r.ts), sk: r.sk, c: r.country, dv: r.device, pl: r.placement, target: r.target, spent: Number(r.spent) || 0, self: Number(r.is_self) ? 1 : 0 });
async function unpushed(n) {
if (useDb()) return (await R.db.q('SELECT * FROM ad_clicks WHERE pushed=0 ORDER BY ts LIMIT ?', [n])).map(fromDb);
return jload().rows.filter(r => !r.pushed).slice(0, n).map(r => { const x = Object.assign({}, r); delete x.pushed; return x; });
}
async function markPushed(ids) {
if (!ids.length) return;
if (useDb()) { await R.db.q('UPDATE ad_clicks SET pushed=1 WHERE id IN (?)', [ids]); return; }
const set = new Set(ids); for (const r of jload().rows) if (set.has(r.id)) r.pushed = 1; jsave();
}
async function prune() { // click rows only matter for the 30-day window; keep 120 days for questions
const cut = Date.now() - 120 * 86400e3;
if (useDb()) await R.db.q('DELETE FROM ad_clicks WHERE pushed=1 AND ts<?', [cut]);
else { const st = jload(); const n = st.rows.length; st.rows = st.rows.filter(r => !(r.pushed && r.ts < cut)); if (st.rows.length !== n) jsave(); }
}
// ---- LinkSpin calls ----
async function signedPost(pth, body, timeoutMs) {
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
const r = await fetch(URL_() + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 15000) });
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
if (!r.ok) { const e = new Error((j && j.error) || ('linkspin ' + r.status)); e.status = r.status; e.plain = !!(j && j.error); throw e; }
return j || {};
}
async function flush() {
if (!on() || flushing || Date.now() < nextAt) return { skipped: true };
flushing = true; let sent = 0;
try {
for (let round = 0; round < 20; round++) { // drain a backlog, 500 at a time; owners (own soft keys) ride on the first request
const rows = await unpushed(500); const owners = round === 0 ? takeOwners() : [];
if (!rows.length && !owners.length) break;
let res; try { res = await signedPost('/api/partner/clicks', { clicks: rows, owners }, 20000); } catch (e) { requeueOwners(owners); throw e; }
if (!res || res.ok !== true) { requeueOwners(owners); throw new Error('linkspin answered without ok'); }
if (rows.length) { await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now(); }
if (owners.length) stats.owners = (stats.owners || 0) + owners.length;
if (rows.length < 500) break;
}
fails = 0; nextAt = 0; return { sent };
} catch (e) {
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 3000 * Math.pow(2, Math.min(fails, 7)));
if (fails <= 3 || fails % 20 === 0) console.error('lsconv push', e.message);
return { error: e.message, sent };
} finally { flushing = false; }
}
// op summary is cached 60 s per email; any write clears that email's cache
async function summary(email, fresh) {
const e = String(email || '').toLowerCase();
const hit = cache.get(e); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.data;
const data = await signedPost('/api/partner/conv', { op: 'summary', email: e, days: 30 }, 8000);
cache.set(e, { at: Date.now(), data }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
return data;
}
async function goalOp(email, op, fields) {
const e = String(email || '').toLowerCase();
if (!['create', 'update', 'remove', 'test'].includes(op)) throw new Error('Unknown action.');
const body = Object.assign({ op, email: e }, fields || {});
const out = await signedPost('/api/partner/conv', body, 10000);
cache.delete(e); return out;
}
function adminView() { return { on: on(), url: URL_(), pushed: stats.pushed, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
module.exports = { signedPost, init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on, noteSession, isOwnerSk };
+195
View File
@@ -0,0 +1,195 @@
// Inbound registry rows from LinkSpin (2026-10-15, the reverse of lssync.js). Marty: someone whose FIRST contact is a
// LinkSpin member's link is placed right on LinkSpin, but InstantAdPay never heard of them, so a later InstantAdPay join
// without that link landed under another sponsor or the company. LinkSpin's iapsync.js now posts its rows here
// (POST /api/partner/registry, HMAC LS_SYNC_SECRET over ts + newline + raw body; see server.js).
//
// Per row {email, username, wallet, sponsorEmail, joinedAt, profile}:
// - FIRST-PLATFORM RULE: an email that already has an InstantAdPay account keeps its sponsor. Only EMPTY fields are
// filled: username (if free and allowed here), wallet (if no other account or linked position holds it), profile.
// A conflict is skipped and logged, never forced.
// - A new email becomes a waiting (shell) account, joinedVia 'linkspin', under its LinkSpin sponsor's InstantAdPay
// account. A sponsor not on InstantAdPay yet gets a shell too, from rows received in this or an earlier batch,
// climbing at most 25 levels (as LinkSpin's carry.js does). A sponsor whose row has not arrived is remembered
// (pending) and bound when it does, as long as the shell is still unclaimed and still has no sponsor.
// - Nothing here sends mail or notices, touches the chain or runs the sign-up anti-fraud checks (there is no request:
// no IP, no device). The checks run when the owner claims the shell at their first sign-in (server.js), and until
// then accounts.listAll leaves unclaimed shells out of every sweep that mails, counts or adopts members.
// - Loop guard: each email is muted in lssync while its row is applied, then lssync records the result as already
// pushed when it equals what LinkSpin sent, so it is not bounced back (see lssync.release). No-op rows change nothing.
// - SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row that carries a DELIBERATE change made on LinkSpin (sponsorSetBy
// adopt / rescue / release / expire / admin) is the one exception to the first-platform rule: it is applied, a clear
// back to the tank included, when the member is not bound on InstantAdPay's contract (no memberId, not on chain), the
// change is newer than our own deliberate change, and the two sides agreed before it (or we have no sponsor). Bound,
// diverged and race cases change nothing here and are logged for Admin > Members > Sponsor check. Applied quietly.
// - NETWORK TANK: a row's `tank` (LinkSpin's own adoptions of the person) is kept as remote state, so our waiting list
// hides someone adopted on LinkSpin and the two-adoptions limit counts both sites.
'use strict';
const SF = require('./sponsorfollow');
const prohibited = require('./prohibited'); // 2026-10-30: policy applied on ingest
const fs = require('fs');
const path = require('path');
let R = null, st = null, chain_ = Promise.resolve();
const MAX_UP = 25;
const FILE = () => path.join(R.dataDir, 'lsinbound.json');
const norm = v => String(v || '').trim().toLowerCase();
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
function load() {
if (st) return st;
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
if (!st || typeof st !== 'object') st = {};
st.rows = st.rows || {}; st.pending = st.pending || {}; st.log = st.log || [];
st.stats = Object.assign({ batches: 0, received: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, errors: 0 }, st.stats || {});
return st;
}
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('lsinbound save', e.message); } }
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync, follow (sponsorfollow glue), store (sponsorfollow store) }
function clean(x) {
if (!x || typeof x !== 'object') return null;
const email = norm(x.email); if (!EMAIL_RE.test(email) || email.length > 190) return null;
const username = norm(x.username).replace(/^@/, '') || null;
const wallet = /^0x[0-9a-f]{40}$/.test(norm(x.wallet)) ? norm(x.wallet) : null;
let sponsorEmail = norm(x.sponsorEmail); if (!EMAIL_RE.test(sponsorEmail) || sponsorEmail === email) sponsorEmail = null;
const profile = x.profile && typeof x.profile === 'object' ? x.profile : null;
const out = { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
if (SF.isDeliberate(x.sponsorSetBy) && Number(x.sponsorSetAt) > 0) { // a deliberate change on LinkSpin (sponsorfollow.js)
out.sponsorSetAt = Number(x.sponsorSetAt); out.sponsorSetBy = String(x.sponsorSetBy);
const pv = norm(x.sponsorPrevEmail); out.sponsorPrevEmail = EMAIL_RE.test(pv) ? pv : null;
out.sponsorSetOrigin = norm(x.sponsorSetOrigin).replace(/[^a-z]/g, '').slice(0, 20) || 'linkspin';
}
if (Object.prototype.hasOwnProperty.call(x, 'tank')) out.tank = SF.cleanTank(x.tank); // null = LinkSpin has no adoption of them now
return out;
}
const tokenOf = a => a.username || a.code;
// released / rescued / expired back to the tank on purpose here: an ordinary row must not refill the sponsor (sponsorfollow.js)
const emptiedOnPurpose = email => { const pv = R.store && R.store.get(email); return !!(pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail); };
function conflict(sum, email, kind, detail) { sum.conflicts++; note({ type: 'conflict', email, kind, detail: String(detail || '').slice(0, 120) }); }
// would binding `email` under `sp` close a loop (sp already sits below email)?
async function wouldCycle(email, sp) {
let cur = sp; const seen = new Set();
for (let i = 0; cur && i < 60; i++) {
if (cur.email === email) return true; if (seen.has(cur.email)) return true; seen.add(cur.email);
cur = await R.accounts.sponsorOf(cur.email);
}
return false;
}
// the sponsor's InstantAdPay account, building their shell (and theirs, upward) from known rows when needed
async function sponsorAccount(spEmail, depth, ctx) {
const sp = await R.accounts.byEmail(spEmail); if (sp) return sp;
if (depth >= MAX_UP || !load().rows[spEmail] || ctx.done.has(spEmail)) return null;
return place(spEmail, depth + 1, ctx);
}
// fill only what is empty; returns true when something was written
async function fill(a, r, sum) {
let wrote = false; const A = R.accounts;
if (r.username && !a.username) {
const other = await A.byUsername(r.username);
if (other && other.email !== a.email) conflict(sum, a.email, 'username-taken', r.username);
else { const x = await A.setUsername(a.email, r.username); if (x && x.error) conflict(sum, a.email, 'username', r.username + ': ' + x.error); else { sum.filled++; wrote = true; } }
}
if (r.wallet) {
if (!a.address) {
const other = await A.byAddress(r.wallet);
if (other && other.email !== a.email) conflict(sum, a.email, 'wallet-taken', r.wallet);
else { const x = await A.linkWallet(a.email, r.wallet); if (x && x.error) conflict(sum, a.email, 'wallet', r.wallet + ': ' + x.error); else { sum.filled++; wrote = true; } }
} else if (norm(a.address) !== r.wallet) conflict(sum, a.email, 'wallet-differs', r.wallet); // InstantAdPay's wallet stands
}
if (r.profile && A.setProfile) { // same rules as LinkSpin's side: https only, known socials, fills only what is empty
const pf = r.profile, ok = v => /^https:[/][/][^ ]+$/i.test(v) && v.length <= 300;
// prohibited-content policy on ingest (2026-10-30): a bio with a link or a prohibited term, or a social carrying one, is dropped, not stored
const cp = prohibited.cleanProfile(pf, 'InstantAdPay'); if (cp.dropped.length) console.log('lsinbound profile dropped', String(a.email).replace(/^(.).*(@.*)$/, '$1***$2'), cp.dropped.join(','));
const av = String(pf.avatarUrl || '').trim(); const bio = cp.bio || ''; let soc = null;
if (cp.socials) { const c = {}; for (const k of ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']) { const v = String(cp.socials[k] || '').trim(); if (ok(v)) c[k] = v; } if (Object.keys(c).length) soc = JSON.stringify(c); }
const upd = [!a.avatarUrl && ok(av) ? av : undefined, !a.bio && bio ? bio : undefined, !a.socials && soc ? soc : undefined];
if (upd.some(v => v !== undefined)) { const x = await A.setProfile(a.email, upd[0], upd[1], upd[2]); if (!(x && x.error)) { sum.filled++; wrote = true; } }
}
return wrote;
}
async function place(email, depth, ctx) {
const s = load(); const r = s.rows[email]; const A = R.accounts;
if (ctx.done.has(email)) return A.byEmail(email);
ctx.done.add(email); R.lssync.mute(email);
let a = await A.byEmail(email); let wrote = false;
if (!r) return a;
const inc = SF.incomingOf(r);
if (a && inc && R.follow) {
// a deliberate sponsor change made on LinkSpin: the follow rule decides (never on a member bound here)
const d = await R.follow.applyIncoming(email, r, { sponsorAccount: em => sponsorAccount(em, depth, ctx) });
if (d.apply) { ctx.sum.followed++; wrote = true; delete s.pending[email]; note({ type: 'follow', email, by: r.sponsorSetBy, sponsor: r.sponsorEmail || null, action: d.action }); }
else if (d.action !== 'same' && d.action !== 'ordinary') { ctx.sum.followKept++; note({ type: 'follow-kept', email, by: r.sponsorSetBy, action: d.action, detail: String(d.reason || '').slice(0, 120) }); }
a = await A.byEmail(email);
} else if (!a) {
let tok = '';
if (r.sponsorEmail) {
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
if (sp) tok = tokenOf(sp); else { s.pending[email] = r.sponsorEmail; ctx.sum.pendingSponsor++; }
}
const x = await A.ensure(email, tok, ctx.via || 'linkspin', ctx.refOf ? ctx.refOf(email) : 'linkspin'); // hubsync.js passes its own via (2026-11-12)
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
a = x.account;
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
// a new waiting account built from a deliberate change carries the same record, so its row does not echo back
if (x.created && inc && R.store && (!r.sponsorEmail || tok)) R.store.record(email, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'linkspin' });
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail && !emptiedOnPurpose(email)) {
// our own waiting account, still without a sponsor: this row (or a later one) names one
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
if (sp && sp.email !== email && !(await wouldCycle(email, sp))) { await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; wrote = true; }
else if (!sp) s.pending[email] = r.sponsorEmail;
}
if (await fill(a, r, ctx.sum)) wrote = true;
if (!wrote) ctx.sum.noop++;
return A.byEmail(email);
}
// shells waiting for a sponsor whose row has now arrived (or whose account now exists)
async function resolvePending(ctx) {
const s = load(); const A = R.accounts;
for (const [email, spEmail] of Object.entries(s.pending)) {
const a = await A.byEmail(email);
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef || emptiedOnPurpose(email)) { delete s.pending[email]; continue; } // claimed, bound or emptied on purpose meanwhile: leave it
const sp = await sponsorAccount(spEmail, 0, ctx); if (!sp) continue;
if (sp.email === email || await wouldCycle(email, sp)) { delete s.pending[email]; conflict(ctx.sum, email, 'sponsor-cycle', spEmail); continue; }
R.lssync.mute(email); ctx.done.add(email);
await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++;
note({ type: 'sponsored', email, sponsor: tokenOf(sp) });
}
}
async function handle(rows, opts) {
const s = load(); s.stats.batches++;
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
const ctx = { sum, done: new Set(), via: opts && opts.via, refOf: opts && opts.refOf }; const batch = [];
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
try {
for (const r of batch) {
try { await place(r.email, 0, ctx); }
catch (e) { sum.errors++; s.stats.lastError = { at: Date.now(), email: r.email, error: String(e.message).slice(0, 160) }; console.error('lsinbound', r.email, e.message); }
}
try { await resolvePending(ctx); } catch (e) { sum.errors++; s.stats.lastError = { at: Date.now(), error: 'pending: ' + String(e.message).slice(0, 160) }; }
} finally {
for (const email of ctx.done) await R.lssync.release(email, s.rows[email]); // loop guard: equal results are not echoed
}
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors', 'followed', 'followKept']) s.stats[k] = (s.stats[k] || 0) + sum[k];
s.last = Object.assign({ at: Date.now() }, sum); save();
return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts
}
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
// opts (hubsync.js only): { via, refOf(email) } names where a new waiting account came from; LinkSpin's posts pass none
function receive(rows, opts) { const run = chain_.then(() => handle(rows, opts)); chain_ = run.catch(() => {}); return run; }
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() });
}
// 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 };
+151
View File
@@ -0,0 +1,151 @@
// Conversion linkage, InstantAdPay half (Marty 2026-11-07, "Yes ship these"). REPORTING ONLY: this module never reads or changes a
// sponsor, a payout, credits or anything on chain. LinkSpin owns the counting; this keeps the click and tells it what happened.
// the click arrives as ?lsclk= or ?lsid= on any page: a first-party cookie iap.lsclk, 30 days, last click wins (the same life
// and last-touch rule as the sponsor cookie), plus the page's own copy sent with the code request, because the
// cookie is refused inside a traffic-exchange frame and never crosses browsers (the 2026-09-29 sponsor lesson)
// the account kept in its own table, ls_account_clicks, keyed by email: remembered when the code is requested, bound when the
// account is created (or a waiting LinkSpin shell is claimed). Its own table on purpose: accounts is not touched
// the events sign-up, wallet link, each package Purchase on the chain, by an account with a bound click. One row each in
// ls_events; its primary key is the idempotency key (join:<hash>, wallet:<hash>, purchase:<tx>:<log index>), so two
// app copies during a deploy can both try and only one row exists
// the delivery a loop in the background posts unsent rows to LinkSpin (POST /api/partner/conv op events, signed like lsconv), 100
// at a time, every ~5 s with backoff to 5 minutes. A row is marked sent only after LinkSpin answers, and LinkSpin
// dedupes by the same key, so a row sent by both copies, or twice, counts once
// Nothing here runs in the chain event handler's path or in a sign-up's path beyond one local write: LinkSpin down, slow or
// blocked changes nothing except that rows wait. No LS_SYNC_SECRET: rows wait too.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const lsconv = require('./lsconv');
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
const stats = { sent: 0, lastAt: null, lastError: null, errors: 0 };
const DAY = 86400000, WINDOW = 30 * DAY;
const useDb = () => !!(R && R.db && R.db.enabled());
const JFILE = () => path.join(R.dataDir, 'lsreport.json');
const norm = e => String(e || '').trim().toLowerCase();
const isId = v => /^(?:[a-f0-9]{10}|[aik][a-f0-9]{11})$/.test(String(v || ''));
const hash = email => crypto.createHash('sha256').update(norm(email)).digest('hex').slice(0, 24);
// the id in a page address, or '' (lsclk first: it is the id the landing tag and ad clicks carry)
const fromUrl = u => { const v = u.searchParams.get('lsclk') || u.searchParams.get('lsid') || ''; return isId(v) ? v : ''; };
const pick = (...vals) => { for (const v of vals) if (isId(v)) return String(v); return ''; };
const COOKIE = 'iap.lsclk';
const cookieHeader = (id, isProd) => COOKIE + '=' + id + '; Path=/; Max-Age=' + (30 * 86400) + '; ' + (isProd ? 'SameSite=None; Secure' : 'SameSite=Lax');
function init(deps) {
R = deps;
if (useDb()) ensureTables().catch(e => console.error('lsreport tables', e.message));
if (!deps.noTimers) {
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 5000); if (timer.unref) timer.unref(); }
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
}
}
// column names checked against MySQL 8 reserved words (none of email, click_id, ts, bound, k, ev, cents, ev_ts, tx, sk, pushed, outcome is reserved)
async function ensureTables() {
await R.db.q(`CREATE TABLE IF NOT EXISTS ls_account_clicks (
email VARCHAR(190) PRIMARY KEY,
click_id VARCHAR(16) NOT NULL,
ts BIGINT NOT NULL,
bound TINYINT NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await R.db.q(`CREATE TABLE IF NOT EXISTS ls_events (
k VARCHAR(120) PRIMARY KEY,
ev VARCHAR(10) NOT NULL,
email VARCHAR(190) NOT NULL,
click_id VARCHAR(16) NOT NULL,
cents INT NOT NULL DEFAULT 0,
ev_ts BIGINT NOT NULL,
tx VARCHAR(80) NULL,
sk VARCHAR(24) NULL,
pushed TINYINT NOT NULL DEFAULT 0,
outcome VARCHAR(12) NULL,
INDEX (pushed, ev_ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
}
// ---- JSON store (local runs) ----
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!jstate.clicks || !Array.isArray(jstate.events)) throw 0; } catch (e) { jstate = { clicks: {}, events: [] }; } return jstate; }
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 300); if (saveT.unref) saveT.unref(); }
// ---- the click on the account ----
async function clickOf(email) {
const e = norm(email);
if (useDb()) { const r = (await R.db.q('SELECT click_id, ts, bound FROM ls_account_clicks WHERE email=?', [e]))[0]; return r ? { click: r.click_id, ts: Number(r.ts), bound: Number(r.bound) ? 1 : 0 } : null; }
return jload().clicks[e] || null;
}
// at the code request: the click travels with the email, so verifying in another browser still finds it. Last click wins until bound.
async function remember(email, click) {
const e = norm(email); if (!e || e.length > 190 || !isId(click)) return false;
const now = Date.now();
if (useDb()) { await R.db.q('INSERT INTO ls_account_clicks (email, click_id, ts, bound) VALUES (?,?,?,0) ON DUPLICATE KEY UPDATE click_id=IF(bound=0,VALUES(click_id),click_id), ts=IF(bound=0,VALUES(ts),ts)', [e, click, now]); return true; }
const st = jload(); if (st.clicks[e] && st.clicks[e].bound) return false; st.clicks[e] = { click, ts: now, bound: 0 }; jsave(); return true;
}
// the account now exists: bind the click (this request's, else the remembered one), once, and queue the join
async function signup(email, click, sk) {
const e = norm(email); if (!e || e.length > 190) return false;
const row = await clickOf(e); if (row && row.bound) return false;
const c = isId(click) ? click : (row && Date.now() - row.ts <= WINDOW ? row.click : ''); if (!c) return false;
const now = Date.now();
if (useDb()) {
await R.db.q('INSERT IGNORE INTO ls_account_clicks (email, click_id, ts, bound) VALUES (?,?,?,0)', [e, c, now]);
const u = await R.db.q('UPDATE ls_account_clicks SET click_id=?, ts=?, bound=1 WHERE email=? AND bound=0', [c, now, e]);
if (!(u && u.affectedRows === 1)) return false;
} else { const st = jload(); st.clicks[e] = { click: c, ts: now, bound: 1 }; jsave(); }
await enqueue({ k: 'join:' + hash(e), ev: 'join', email: e, click: c, cents: 0, ts: now, sk: /^s:[a-f0-9]{20}$/.test(String(sk || '')) ? sk : null });
return true;
}
async function wallet(email) {
const e = norm(email); const row = await clickOf(e); if (!row || !row.bound) return false;
return enqueue({ k: 'wallet:' + hash(e), ev: 'wallet', email: e, click: row.click, cents: 0, ts: Date.now() });
}
// a Purchase chain event, already resolved to its account. Value = the USD price on the event. Linked positions sit on the same
// account, so they count as that account's purchases. Past the click window nothing is queued: LinkSpin would refuse it anyway
// (the bind is never earlier than the click, so more than 30 days after the bind is more than 30 days after the click).
async function purchase(ev, email) {
const e = norm(email); const cents = Number(ev && ev.priceCents) || 0; if (!e || cents <= 0 || !ev.tx) return false;
const row = await clickOf(e); if (!row || !row.bound) return false;
const ts = Number(ev.ts) || Date.now();
if (ts < row.ts - 60000 || ts - row.ts > WINDOW) return false; // before the sign-up, or past the window
return enqueue({ k: ('purchase:' + ev.tx + ':' + ev.li).slice(0, 120), ev: 'purchase', email: e, click: row.click, cents, ts, tx: String(ev.tx).slice(0, 80) });
}
async function enqueue(x) {
if (useDb()) { const r = await R.db.q('INSERT IGNORE INTO ls_events (k, ev, email, click_id, cents, ev_ts, tx, sk, pushed) VALUES (?,?,?,?,?,?,?,?,0)', [x.k, x.ev, x.email, x.click, x.cents, x.ts, x.tx || null, x.sk || null]); return !!(r && r.affectedRows === 1); }
const st = jload(); if (st.events.some(r => r.k === x.k)) return false; st.events.push(Object.assign({ pushed: 0 }, x)); if (st.events.length > 5000) st.events = st.events.slice(-4000); jsave(); return true;
}
// ---- delivery ----
async function unsent(n) {
if (useDb()) return (await R.db.q('SELECT k, ev, email, click_id, cents, ev_ts, tx, sk FROM ls_events WHERE pushed=0 ORDER BY ev_ts LIMIT ?', [n])).map(r => ({ k: r.k, ev: r.ev, email: r.email, click: r.click_id, cents: Number(r.cents) || 0, ts: Number(r.ev_ts), tx: r.tx, sk: r.sk }));
return jload().events.filter(r => !r.pushed).slice(0, n);
}
async function markSent(k, outcome) {
if (useDb()) { await R.db.q('UPDATE ls_events SET pushed=1, outcome=? WHERE k=?', [String(outcome || '').slice(0, 12) || null, k]); return; }
const r = jload().events.find(x => x.k === k); if (r) { r.pushed = 1; r.outcome = outcome; jsave(); }
}
async function flush() {
if (!lsconv.on() || flushing || Date.now() < nextAt) return { skipped: true };
flushing = true; let sent = 0;
try {
for (let round = 0; round < 10; round++) {
const rows = await unsent(100); if (!rows.length) break;
const res = await lsconv.signedPost('/api/partner/conv', { op: 'events', events: rows.map(r => ({ k: r.k, ev: r.ev, email: r.email, click: r.click, value: r.cents / 100, ts: r.ts, tx: r.tx || undefined, sk: r.sk || undefined })) }, 15000);
if (!res || res.ok !== true || !Array.isArray(res.results)) throw new Error('linkspin answered without results');
for (const a of res.results) { await markSent(a.k, a.result); sent++; stats.sent++; }
stats.lastAt = Date.now();
if (rows.length < 100) break;
}
fails = 0; nextAt = 0; return { sent };
} catch (e) {
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 5000 * Math.pow(2, Math.min(fails, 6)));
if (fails <= 3 || fails % 20 === 0) console.error('lsreport push', e.message);
return { error: e.message, sent };
} finally { flushing = false; }
}
async function prune() {
const now = Date.now(); const old = now - 60 * DAY, stale = now - 31 * DAY;
if (useDb()) { await R.db.q('DELETE FROM ls_events WHERE ev_ts<?', [old]); await R.db.q('DELETE FROM ls_account_clicks WHERE (bound=0 AND ts<?) OR ts<?', [stale, old]); return; }
const st = jload(); st.events = st.events.filter(r => r.ts >= old); for (const k of Object.keys(st.clicks)) { const c = st.clicks[k]; if (c.ts < old || (!c.bound && c.ts < stale)) delete st.clicks[k]; } jsave();
}
function adminView() { return { on: lsconv.on(), sent: stats.sent, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
module.exports = { init, ensureTables, fromUrl, pick, cookieHeader, COOKIE, isId, remember, signup, wallet, purchase, clickOf, flush, prune, adminView };
+123
View File
@@ -0,0 +1,123 @@
// LinkSpin registry sync (Marty 2026-10-08: "members in InstantAdPay synchronized with those waiting inside LinkSpin").
// Two paths, same signed POST to LinkSpin /api/partner/registry (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET):
// touch(email) right after an account changes (created, named, wallet linked, sponsor bound): that row goes within ~3 s
// tick() every 2 minutes: every account is hashed (username, wallet, sponsor, joined) against the last pushed
// hash in DATA_DIR/lssync.json and only changed rows go, 100 per request. Catches anything touch() missed.
// LinkSpin upserts the rows and creates shell accounts with their sponsor line, so a new InstantAdPay member is already
// "waiting" on LinkSpin before they ever sign in there. Nothing here moves money; the registry is identity + line only.
//
// Sponsor follow (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail /
// sponsorSetOrigin while the account's sponsor is the result of a deliberate change (tank adoption, rescue, release,
// window expiry, admin edit), and `tank` (this site's own adoptions of the person: count + the open one, or null).
// Rows without those facts hash exactly as before, so nothing is resent on deploy. Until LinkSpin answers proto 2 the
// hash of a row carrying the new facts is not recorded, so it is sent again once LinkSpin runs the new code.
'use strict';
const crypto = require('crypto');
const SF = require('./sponsorfollow');
const prohibited = require('./prohibited'); // 2026-10-30: a profile that fails the policy never leaves this site
const fs = require('fs');
const path = require('path');
let R = null, state = null, pending = new Map(), timer = null, ticking = false;
const muted = new Set(); // emails lsinbound.js is writing right now: their rows came FROM LinkSpin, hold them until it decides
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
const on = () => SECRET().length >= 32;
const FILE = () => path.join(R.dataDir, 'lssync.json');
function load() { if (state) return state; try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = { hashes: {}, pushed: 0, last: null, errors: 0 }; } return state; }
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
function init(deps) { R = deps; load(); }
async function rowFor(acct, byRef, tankMap) {
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
const row = { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
if (acct.joinedVia === 'btc4hits') row.origin = 'btc4hits'; // BTC4Hits import (2026-11-11): LinkSpin words its holding-tank mail for them
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
const T = R.tank && R.tank();
if (T) { try { row.tank = (tankMap ? tankMap.get(String(acct.email).toLowerCase()) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
return row;
}
const carriesNew = r => !!(r.sponsorSetBy || r.tank);
// the member's profile travels too (Marty 2026-10-11: no re-typing on LinkSpin; they can change it there later). Avatar as an
// absolute https URL so the other property can show it; socials as the parsed {platform: url} object.
const PUBLIC = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
function profileOf(a) {
if (a.profileQuarantined) return null; // quarantined (link planted on a brand-new free account): stays here, unseen, until Marty decides
const cp = prohibited.cleanProfile({ avatarUrl: a.avatarUrl, bio: a.bio, socials: a.socials }, 'InstantAdPay'); // policy applied on the way out too
const socials = cp.socials;
const av = String(a.avatarUrl || '').trim();
const avatarUrl = !av ? null : /^https:\/\//i.test(av) ? av : av.startsWith('/') ? PUBLIC() + av : null;
const bio = cp.bio;
// the BixPay partner link travels too (2026-10-29): LinkSpin shows it read-only ("Edit on InstantAdPay") and resolves the
// same way; only set when there is one, so rows without it keep the hash they had
const bixPartnerLink = String(a.bixPartnerLink || '').trim() || null;
if (!avatarUrl && !bio && !bixPartnerLink && !(socials && Object.keys(socials).length)) return null;
const out = { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
if (bixPartnerLink) out.bixPartnerLink = bixPartnerLink;
return out;
}
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16);
async function post(rows) {
const raw = JSON.stringify({ rows }); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
const r = await fetch(URL_() + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(20000) });
if (!r.ok) throw new Error('linkspin ' + r.status + ' ' + (await r.text()).slice(0, 120));
return r.json();
}
async function push(rows) {
const st = load(); let sent = 0;
for (let i = 0; i < rows.length; i += 100) {
const chunk = rows.slice(i, i + 100); const res = await post(chunk); sent += chunk.length;
const peerNew = Number(res && res.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1);
for (const r of chunk) { if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); } // an old LinkSpin ignored the new facts: send again later
}
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
}
// QUIET (Marty 2026-11-14, "join one = join all"): a waiting account the network hub made here (joinedVia 'hub', never signed
// in) is never pushed to LinkSpin. The hub tells LinkSpin itself, quietly; pushed from here, LinkSpin's registry route would
// link the wallet and its engine would switch payouts on and email them. Once they sign in here they sync like anyone.
const hubShell = a => !!a && a.joinedVia === 'hub' && R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a);
// an account just changed: send its row shortly (debounced so a join + username + wallet in a row go as one)
function touch(email) {
if (!on() || !email) return; pending.set(String(email).toLowerCase(), Date.now());
if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a && !hubShell(a)) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000);
}
// the reconcile pass: only rows whose hash changed since the last push
async function tick(force) {
if (!on() || ticking) return { skipped: true };
ticking = true;
try {
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email) || hubShell(a)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
const sent = rows.length ? await push(rows) : 0;
return { accounts: all.length, changed: rows.length, sent };
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
finally { ticking = false; }
}
// Reverse-sync loop guard (2026-10-15, see lsinbound.js): while a LinkSpin row is being applied its email is muted; afterwards,
// if the account now says exactly what LinkSpin sent (username, wallet, sponsor), its hash is recorded as already pushed, so
// it is never sent back. When InstantAdPay's facts differ (its sponsor binding stood, a wallet was skipped) the row goes
// back once; LinkSpin only fills empty fields, so that changes nothing there and its own hash stops a resend.
function mute(email) { muted.add(String(email || '').toLowerCase()); }
async function release(email, sent) {
const e = String(email || '').toLowerCase(); muted.delete(e); let same = false;
try {
const a = await R.accounts.byEmail(e);
if (a && sent) {
const r = await rowFor(a); const n = v => String(v || '').toLowerCase();
// a deliberate change from LinkSpin counts as the same only when we now carry that same record (applied, not refused)
const sameFollow = !sent.sponsorSetBy || (Number(r.sponsorSetAt) === Number(sent.sponsorSetAt) && String(r.sponsorSetBy) === String(sent.sponsorSetBy));
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail) && sameFollow) { load().hashes[e] = hashOf(r); save(); same = true; }
}
} catch (err) {}
if (pending.has(e) && !timer) { pending.delete(e); touch(e); } // a touch that queued while muted goes now (the hash check drops it when same)
return same;
}
// does LinkSpin know this email? (its row was pushed and recorded) - used by the link-farm admin list, never for a cascade
function knows(email) { const st = load(); return Object.prototype.hasOwnProperty.call(st.hashes || {}, String(email || '').toLowerCase()); }
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, last: st.last, errors: st.errors, pendingTouches: pending.size }; }
module.exports = { init, touch, tick, adminView, on, mute, release, knows };
+29 -5
View File
@@ -15,14 +15,38 @@ function key() {
}
function hasKey() { return !!key(); }
function send(to, subject, text) {
// Opt-out rule (2026-10-15, Spamhaus DBL listing): every email except sign-in
// codes and mail to the admin is skipped for anyone who unsubscribed, carries
// the signed unsubscribe link (appended unless the body already has one) and
// RFC 8058 one-click List-Unsubscribe headers. New senders inherit this.
function isAdmin(to) { const a = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); return !!a && String(to).trim().toLowerCase() === a; }
async function send(to, subject, text, html, opts) { // html optional (2026-10-01): sent alongside the plain text, never instead of it
const transactional = !!(opts && opts.transactional) || isAdmin(to);
let unsub = '';
if (!transactional) {
const drip = require('./drip');
try { if (await drip.isUnsubscribed(to)) return false; } catch (e) { console.error('mailer opt-out check', e.message); }
try { unsub = drip.unsubUrl(to); } catch (e) { console.error('mailer unsub link', e.message); }
}
if (unsub && !String(text).includes('/unsubscribe?')) text = text + '\n\n--\nStop these emails: ' + unsub;
if (unsub && html && !String(html).includes('/unsubscribe?')) {
const foot = '<p style="font-size:12px;color:#888;margin-top:24px">Stop these emails: <a href="' + unsub + '" style="color:#888">unsubscribe</a></p>';
html = /<\/body>/i.test(html) ? html.replace(/<\/body>/i, foot + '</body>') : html + foot;
}
return new Promise((resolve, reject) => {
const body = JSON.stringify({
const content = [{ type: 'text/plain', value: text }];
if (html) content.push({ type: 'text/html', value: html });
const msg = {
personalizations: [{ to: [{ email: to }] }],
from: FROM,
subject,
content: [{ type: 'text/plain', value: text }]
});
content
};
if (unsub) msg.headers = { 'List-Unsubscribe': '<' + unsub + '>', 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click' };
if (opts && opts.replyTo) msg.reply_to = { email: String(opts.replyTo) }; // help desk: replies thread back into the ticket
if (opts && opts.headers) msg.headers = Object.assign(msg.headers || {}, opts.headers);
const body = JSON.stringify(msg);
const req = https.request({ hostname: 'api.sendgrid.com', path: '/v3/mail/send', method: 'POST',
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body) }, timeout: 15000 },
@@ -41,7 +65,7 @@ function sendCode(to, code) {
return send(to, code + ' is your InstantAdPay sign-in code',
'Your sign-in code is: ' + code + '\n\n'
+ 'It works for 15 minutes. If you did not request it, ignore this email.\n\n'
+ 'InstantAdPay\nAdvertise and earn instantly. Locked in code, not promises.\nhttps://instantadpay.com');
+ 'InstantAdPay\nAdvertise and earn instantly. Locked in code, not promises.\nhttps://instantadpay.com', null, { transactional: true });
}
module.exports = { init, hasKey, send, sendCode };
+50
View File
@@ -0,0 +1,50 @@
// One-time claims shared by every running copy of the app (Marty, 2026-09-25).
//
// Why: a Coolify deploy starts the new container and only stops the old one once the new one
// is healthy, so for half a minute two copies of this app watch the chain. On 25 September
// both saw Marty's $5 purchase: two confirmation emails, and the Five Dollar Friday bonus
// granted twice (+100 and +100, 19 seconds apart). Every dedupe until now lived in process
// memory or a JSON file on the volume, neither of which a second process shares in time.
//
// This is the shared version: a row in MySQL that only one INSERT can win. `claim(key)` is
// true for exactly one caller across all instances, false for everyone else. Gate anything
// that must happen once per event, and never gate the in-memory feed (each instance keeps
// its own).
//
// Without a database (local QA, the JSON store) it degrades to a per-process Set, which is
// exactly the old behaviour: one instance, one memory.
'use strict';
let db = null;
const local = new Set();
function init(deps) { db = deps && deps.db; }
async function ensureTable() {
if (!db || !db.enabled()) return;
await db.q('CREATE TABLE IF NOT EXISTS event_marks (k VARCHAR(160) PRIMARY KEY, ts BIGINT NOT NULL) ENGINE=InnoDB');
}
// true = this caller owns the key; false = someone (possibly another instance) already does.
async function claim(key) {
key = String(key).slice(0, 160);
if (!db || !db.enabled()) { if (local.has(key)) return false; local.add(key); return true; }
try {
const r = await db.q('INSERT IGNORE INTO event_marks (k, ts) VALUES (?, ?)', [key, Date.now()]);
return !!(r && r.affectedRows === 1);
} catch (e) {
// The table missing, or the DB unreachable, must not silently double-send: log it and
// fall back to the per-process memory, which at least keeps ONE instance honest.
console.error('marks: claim fell back to memory for ' + key + ': ' + e.message);
if (local.has(key)) return false; local.add(key); return true;
}
}
// Keep the table from growing forever: marks older than 60 days are of no use, every event
// they guard has long since been handled.
async function prune() {
if (!db || !db.enabled()) return;
try { await db.q('DELETE FROM event_marks WHERE ts < ?', [Date.now() - 60 * 86400000]); } catch (e) {}
}
module.exports = { init, ensureTable, claim, prune };
+37 -13
View File
@@ -27,32 +27,49 @@ async function lastBroadcastAt(fromEmail) {
return mine.length ? Math.max(...mine) : 0;
}
// deliver one message to many recipients (already-resolved emails). Returns count.
async function deliver(fromMember, fromEmail, recipients, subject, body) {
//
// `kind` separates the two things that used to share this channel:
// 'broadcast' — a person wrote it to their team. Rare, and worth interrupting for.
// 'alert' — the system generated it AND the member loses money by not acting: a sale
// blocked because payouts are off, a payout that passed them by. Rare, and
// the whole reason this channel interrupts at all.
// 'notice' — the system generated it and nothing is required: a payout landed, a
// purchase confirmed. These arrive constantly, so they belong in the inbox
// and must never pop a modal. Before this split they did, which meant a
// member with a backlog of payout notices got a fresh popup after every
// single ad view.
//
// The line is not system-versus-human, it is "does this need you to do something".
async function deliver(fromMember, fromEmail, recipients, subject, body, kind) {
const k = ['notice', 'alert'].includes(kind) ? kind : 'broadcast';
const now = Date.now();
let n = 0;
if (db.enabled()) {
for (const to of recipients) {
await db.q("INSERT INTO sponsor_messages (from_member,from_email,to_email,subject,body,sent,kind) VALUES (?,?,?,?,?,?,'broadcast')",
[fromMember || 0, fromEmail, to, subject, body, now]);
await db.q("INSERT INTO sponsor_messages (from_member,from_email,to_email,subject,body,sent,kind) VALUES (?,?,?,?,?,?,?)",
[fromMember || 0, fromEmail, to, subject, body, now, k]);
n++;
}
} else {
if (!J.db) J.load();
for (const to of recipients) {
J.db.items.push({ id: J.db.nextId++, kind: 'broadcast', fromMember: fromMember || 0, fromEmail, toEmail: to, subject, body, sent: now, readTs: 0 });
J.db.items.push({ id: J.db.nextId++, kind: k, fromMember: fromMember || 0, fromEmail, toEmail: to, subject, body, sent: now, readTs: 0 });
n++;
}
J.save();
}
return n;
}
const isBroadcast = i => (i.kind || 'broadcast') === 'broadcast';
// Both kinds are inbox mail; only 'chat' is the separate two-way thread.
const isBroadcast = i => (i.kind || 'broadcast') !== 'chat';
// ...but only a human broadcast or a money-at-stake alert may interrupt with the modal.
const popsModal = i => ['broadcast', 'alert'].includes(i.kind || 'broadcast');
const isChat = i => i.kind === 'chat';
async function inbox(email) {
const e = String(email || '').toLowerCase();
if (db.enabled()) {
const rows = await db.q(`SELECT id, from_member, subject, body, sent, read_ts FROM sponsor_messages
WHERE to_email=? AND kind='broadcast' ORDER BY sent DESC LIMIT 100`, [e]);
WHERE to_email=? AND kind<>'chat' ORDER BY sent DESC LIMIT 100`, [e]);
return rows.map(r => ({ id: r.id, fromMember: r.from_member, subject: r.subject, body: r.body,
sent: Number(r.sent), read: !!r.read_ts }));
}
@@ -77,6 +94,13 @@ async function sendChat(fromMember, fromEmail, toEmail, body) {
return { id, sent: now };
}
// messages between two members (both directions), id > afterId, oldest→newest
// last message from one member to another, any kind (0 if never)
async function lastFrom(fromEmail, toEmail) {
const f = String(fromEmail || '').toLowerCase(), t = String(toEmail || '').toLowerCase();
if (db.enabled()) { const r = await db.q('SELECT MAX(sent) s FROM sponsor_messages WHERE from_email=? AND to_email=?', [f, t]); return Number((r[0] && r[0].s) || 0); }
if (!J.db) J.load();
return J.db.items.filter(i => i.fromEmail === f && i.toEmail === t).reduce((m, i) => Math.max(m, i.sent || 0), 0);
}
async function thread(aEmail, bEmail, afterId = 0, limit = 300) {
const a = String(aEmail || '').toLowerCase(), b = String(bEmail || '').toLowerCase();
if (db.enabled()) {
@@ -138,7 +162,7 @@ async function threadList(email) {
async function unreadCount(email) {
const e = String(email || '').toLowerCase();
if (db.enabled()) {
const r = await db.q("SELECT COUNT(*) n FROM sponsor_messages WHERE to_email=? AND kind='broadcast' AND read_ts IS NULL", [e]);
const r = await db.q("SELECT COUNT(*) n FROM sponsor_messages WHERE to_email=? AND kind<>'chat' AND read_ts IS NULL", [e]);
return r[0].n;
}
if (!J.db) J.load();
@@ -148,15 +172,15 @@ async function unreadCount(email) {
async function newestUnread(email) {
const e = String(email || '').toLowerCase();
if (db.enabled()) {
const rows = await db.q(`SELECT id, from_member, subject, body, sent FROM sponsor_messages
WHERE to_email=? AND kind='broadcast' AND read_ts IS NULL ORDER BY sent DESC LIMIT 1`, [e]);
const rows = await db.q(`SELECT id, from_member, subject, body, sent, kind FROM sponsor_messages
WHERE to_email=? AND kind IN ('broadcast','alert') AND read_ts IS NULL ORDER BY sent DESC LIMIT 1`, [e]);
if (!rows.length) return null;
const r = rows[0];
return { id: r.id, fromMember: r.from_member, subject: r.subject, body: r.body, sent: Number(r.sent) };
return { id: r.id, fromMember: r.from_member, subject: r.subject, body: r.body, sent: Number(r.sent), kind: r.kind };
}
if (!J.db) J.load();
const u = J.db.items.filter(i => i.toEmail === e && isBroadcast(i) && !i.readTs).sort((a, b) => b.sent - a.sent)[0];
return u ? { id: u.id, fromMember: u.fromMember, subject: u.subject, body: u.body, sent: u.sent } : null;
const u = J.db.items.filter(i => i.toEmail === e && popsModal(i) && !i.readTs).sort((a, b) => b.sent - a.sent)[0];
return u ? { id: u.id, fromMember: u.fromMember, subject: u.subject, body: u.body, sent: u.sent, kind: u.kind || 'broadcast' } : null;
}
async function markRead(email, id) {
const e = String(email || '').toLowerCase();
@@ -170,5 +194,5 @@ async function markRead(email, id) {
return { ok: true };
}
module.exports = { init, lastBroadcastAt, deliver, inbox, unreadCount, newestUnread, markRead,
module.exports = { init, lastFrom, lastBroadcastAt, deliver, inbox, unreadCount, newestUnread, markRead,
sendChat, thread, markChatRead, chatUnread, threadList };
+184
View File
@@ -0,0 +1,184 @@
// 1,000-member milestone drop (Marty, 2026-10-10): when the account count reaches the target, every member whose wallet is
// ACTIVATED on chain (payouts switched on: the account's address maps to an on-chain member record with the activated
// flag, and that member id is not on the no-payout list) receives `milestonePol` POL from a dedicated hot wallet, and is
// told. Everyone else is told they missed it and how to be in the next one: link a wallet (no wallet yet) or switch on
// payouts (wallet linked, not activated).
//
// Snapshot first, then pay: eligibility is frozen the moment the count crosses the target, so nothing linked afterwards
// counts. Payments go one at a time from IAP_MILESTONE_KEY over the site's own RPC list (chain.getConfig().rpcs), each
// row carrying its tx hash; a row is never sent twice (status due -> sent -> paid | failed). Notices are in-app
// (kind 'notice') plus email: the paid email is transactional (everyone paid gets it), the missed-it email respects the
// newsletter opt-in like every other nudge. One Telegram proof post at the start and one at the end (mirrored to Discord
// by telegramSend), never one per payment. The total lands in the P&L as a rewards cost against Receiver A.
//
// Modes (site config milestoneMode): off | dry | armed. dry = snapshot and show, send nothing. State: DATA_DIR/milestone-1000.json.
'use strict';
const fs = require('fs'), path = require('path');
let R = {}, DATA_DIR = '.', ethers = null, paying = false;
const FILE = () => path.join(DATA_DIR, 'milestone-1000.json');
const blank = () => ({ v: 1, status: 'idle', target: 1000, pol: 1, snapshotAt: 0, countAt: 0, rows: [], others: { noWallet: [], notActivated: [], suspended: 0 }, notified: { paidStart: 0, paidEnd: 0, missed: 0 }, log: [] });
const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } };
const save = s => { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(s)); fs.renameSync(f + '.tmp', f); };
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const logLine = (S, t) => { S.log.push({ at: Date.now(), t: String(t).slice(0, 300) }); if (S.log.length > 400) S.log = S.log.slice(-400); };
const r4 = n => Math.round(Number(n) * 1e4) / 1e4;
function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; }
const cfg = () => { const sc = (R.siteConfig && R.siteConfig()) || {}; return { mode: ['off', 'dry', 'armed'].includes(sc.milestoneMode) ? sc.milestoneMode : 'off', target: Number(sc.milestoneTarget) || 1000, pol: Number(sc.milestonePol) > 0 ? Number(sc.milestonePol) : 1 }; };
const keyOk = () => /^0x[0-9a-fA-F]{64}$/.test(String(process.env.IAP_MILESTONE_KEY || '').trim());
function wallet() {
if (!keyOk()) return null; if (!ethers) ethers = require('ethers');
const c = R.chain.getConfig(); const rpcs = (c.rpcs || []).filter(Boolean); if (!rpcs.length) return null;
const provider = new ethers.JsonRpcProvider(rpcs[0], Number(c.chainId) || 137);
return { w: new ethers.Wallet(String(process.env.IAP_MILESTONE_KEY).trim(), provider), provider, explorer: c.explorer || 'https://polygonscan.com', chainId: Number(c.chainId) || 137 };
}
async function balance() { const W = wallet(); if (!W) return null; try { return Number(ethers.formatEther(await W.provider.getBalance(W.w.address))); } catch (e) { return null; } }
const address = () => { const W = wallet(); return W ? W.w.address : null; };
// how many accounts exist right now (the number Marty watches on the admin Overview)
async function accountCount() { const all = await R.accounts.listAll(100000); return all.length; }
// freeze the eligibility list: activated on chain, not on the no-payout list, not suspended
async function snapshot(force) {
const S = load(); const C = cfg();
if (S.status !== 'idle' && !force) return S;
const all = await R.accounts.listAll(100000); const bad = R.noPayoutSet ? R.noPayoutSet() : new Set();
const rows = [], noWallet = [], notActivated = []; let suspended = 0; const seenAddr = new Set();
for (const a of all) {
if (a.suspended) { suspended++; continue; }
const addr = String(a.address || '').toLowerCase();
if (!/^0x[0-9a-f]{40}$/.test(addr)) { noWallet.push(a.email); continue; }
if (seenAddr.has(addr)) { notActivated.push(a.email); continue; } // the same wallet on a second account never pays twice
let id = 0, activated = false, err = null;
for (let t = 0; t < 3 && !err; t++) { try { id = await R.chain.memberIdByAccount(addr); if (id) { const m = await R.chain.member(id); activated = !!(m && m.activated); } break; } catch (e) { if (t === 2) err = String(e.message || e).slice(0, 120); } }
if (err) { rows.push({ email: a.email, username: a.username || null, address: addr, memberId: 0, status: 'check', error: err, pol: C.pol }); continue; }
if (!id || !activated || bad.has(Number(id))) { notActivated.push(a.email); continue; }
seenAddr.add(addr);
rows.push({ email: a.email, username: a.username || null, address: addr, memberId: id, flags: Array.isArray(a.flags) && a.flags.length ? a.flags : undefined, status: 'due', pol: C.pol, tx: null });
}
Object.assign(S, { status: 'snapshot', target: C.target, pol: C.pol, snapshotAt: Date.now(), countAt: all.length, rows, others: { noWallet, notActivated, suspended } });
logLine(S, 'snapshot: ' + all.length + ' accounts, ' + rows.filter(r => r.status === 'due').length + ' eligible, ' + rows.filter(r => r.status === 'check').length + ' unchecked (rpc), ' + notActivated.length + ' wallet not activated, ' + noWallet.length + ' no wallet');
save(S); return S;
}
// re-check rows the snapshot could not read from the chain (rpc trouble); they join as due or move to the missed list
async function recheck() {
const S = load(); const bad = R.noPayoutSet ? R.noPayoutSet() : new Set(); let fixed = 0;
for (const r of S.rows.filter(x => x.status === 'check')) {
try { const id = await R.chain.memberIdByAccount(r.address); const m = id ? await R.chain.member(id) : null;
if (id && m && m.activated && !bad.has(Number(id))) { r.memberId = id; r.status = 'due'; delete r.error; } else { r.status = 'skip'; S.others.notActivated.push(r.email); } fixed++; } catch (e) { r.error = String(e.message || e).slice(0, 120); }
}
if (fixed) logLine(S, 'recheck: ' + fixed + ' rows resolved'); save(S); return S;
}
const link = () => (R.site || 'https://instantadpay.com') + '/my#wallet';
function paidCopy(r, S, W) {
const subject = '1,000 members. We just sent you ' + S.pol + ' POL.';
const tx = W.explorer + '/tx/' + r.tx;
const p1 = 'InstantAdPay passed 1,000 members today. To mark it, every member whose wallet was activated with payouts on at that moment received ' + S.pol + ' POL, sent straight to the wallet on your account.';
const p2 = 'Yours is on chain: ' + tx;
const p3 = 'Thank you for building with us. The next milestone will do the same, so keep that wallet on your account.';
return { subject, text: [p1, '', p2, '', p3].join('\n'), html: '<p>' + esc(p1) + '</p><p><a href="' + esc(tx) + '">Your payment on Polygonscan</a></p><p>' + esc(p3) + '</p>' };
}
function missedCopy(kind, S) {
const subject = 'You missed the 1,000-member POL drop. Here is how to be in the next one.';
const p1 = 'InstantAdPay passed 1,000 members today, and every member whose wallet was activated with payouts on received ' + S.pol + ' POL on the spot.';
const p2 = kind === 'noWallet' ? 'Your account had no wallet linked, so there was nowhere to send yours.' : 'Your account had a wallet linked, but payouts were not switched on, so the drop could not reach you.';
const p3 = kind === 'noWallet' ? 'Link a wallet on your Wallet tab (one free signature, it cannot move funds), then switch on payouts. The next milestone pays everyone who has done both.' : 'Switch on payouts from your Wallet tab. It is one small transaction that activates your position, and from then on every payout, sponsor commission and milestone reaches you automatically.';
return { subject, text: [p1, '', p2, '', p3, '', link()].join('\n'), html: '<p>' + esc(p1) + '</p><p>' + esc(p2) + '</p><p>' + esc(p3) + '</p><p><a href="' + esc(link()) + '"><b>Open your Wallet tab</b></a></p>' };
}
// pay every due row, one at a time; safe to call again (rows already sent or paid are never resent)
async function pay() {
if (paying) return { error: 'already paying' }; paying = true;
try {
const S = load(); const C = cfg(); if (!['snapshot', 'paying'].includes(S.status)) return { error: 'nothing to pay (status ' + S.status + ')' };
if (C.mode !== 'armed') return { error: 'mode is ' + C.mode + ', not armed' };
const W = wallet(); if (!W) return { error: 'no milestone wallet key (IAP_MILESTONE_KEY)' };
const due = S.rows.filter(r => r.status === 'due'); if (!due.length) { return finish(S, W); }
if (S.status === 'snapshot') {
const need = r4(due.length * S.pol) + 0.05, have = await balance(); // the snapshot is frozen; the announcement waits for the funding
if (have == null || have < need) { if (!S.waitLogged || Date.now() - S.waitLogged > 1800000) { logLine(S, 'waiting for funds: wallet holds ' + have + ' POL, needs ' + need); S.waitLogged = Date.now(); save(S); } return { waiting: 'funds', have, need }; }
S.status = 'paying'; S.payStart = Date.now(); save(S);
await post('\u{1F389} <b>InstantAdPay just passed ' + S.target.toLocaleString() + ' members.</b>\nTo mark it, ' + due.length + ' members whose wallets are activated with payouts on are each receiving <b>' + S.pol + ' POL</b> right now, straight to the wallet on their account. Not activated yet? Switch on payouts on your Wallet tab and you are in the next one.\n' + (R.site || 'https://instantadpay.com') + '/my#wallet');
S.notified.paidStart = Date.now(); save(S); }
let bal = await balance(); if (bal == null) return { error: 'could not read the wallet balance' };
for (const r of S.rows) {
if (r.status !== 'due') continue;
if (bal < Number(r.pol) + 0.01) { logLine(S, 'paused: balance ' + bal + ' POL below the next payment'); save(S); return { paused: 'low balance', balance: bal }; }
try {
const tx = await W.w.sendTransaction({ to: r.address, value: ethers.parseEther(String(r.pol)) });
r.status = 'sent'; r.tx = tx.hash; r.sentAt = Date.now(); save(S);
let rc = null; try { rc = await tx.wait(1, 120000); } catch (e) { if (!(e && e.code === 'TIMEOUT')) throw e; }
if (rc && rc.status === 1) { r.status = 'paid'; r.paidAt = Date.now(); bal -= Number(r.pol); save(S); notifyPaid(r, S, W).catch(() => {}); }
else if (rc) { r.status = 'failed'; r.error = 'reverted'; save(S); }
// a timeout leaves the row 'sent' with its hash; settle() picks it up on the next tick
} catch (e) {
const msg = String(e && (e.shortMessage || e.message) || e);
if (/insufficient funds/i.test(msg)) { r.status = 'due'; logLine(S, 'paused: insufficient funds'); save(S); return { paused: 'insufficient funds' }; }
r.status = 'due'; r.error = msg.slice(0, 160); logLine(S, 'send error for ' + r.email + ': ' + msg.slice(0, 120)); save(S);
return { paused: 'rpc', error: msg.slice(0, 160) }; // leave the rest for the next tick rather than hammer a failing node
}
}
return finish(S, W);
} finally { paying = false; }
}
// rows left 'sent' by a receipt timeout: read the receipt now
async function settle() {
const S = load(); const W = wallet(); if (!W) return; let n = 0;
for (const r of S.rows.filter(x => x.status === 'sent' && x.tx)) {
try { const rc = await W.provider.getTransactionReceipt(r.tx); if (!rc) continue; if (rc.status === 1) { r.status = 'paid'; r.paidAt = Date.now(); notifyPaid(r, S, W).catch(() => {}); } else { r.status = 'failed'; r.error = 'reverted'; } n++; } catch (e) {}
}
if (n) save(S); return n;
}
async function finish(S, W) {
S = load(); if (S.rows.some(r => r.status === 'due' || r.status === 'sent')) return { pending: true };
if (S.status === 'done') return { done: true };
const paid = S.rows.filter(r => r.status === 'paid'), failed = S.rows.filter(r => r.status === 'failed'); const total = r4(paid.reduce((n, r) => n + Number(r.pol), 0));
S.status = 'done'; S.doneAt = Date.now(); logLine(S, 'done: ' + paid.length + ' paid (' + total + ' POL), ' + failed.length + ' failed'); save(S);
await post('✅ <b>' + S.target.toLocaleString() + '-member drop complete.</b> ' + paid.length + ' activated members received ' + S.pol + ' POL each, ' + total + ' POL in all, every payment on chain from ' + W.explorer + '/address/' + W.w.address + '. Missed it? Switch on payouts on your Wallet tab: the next milestone pays everyone who has.');
S = load(); S.notified.paidEnd = Date.now(); save(S);
if (R.ledger && total > 0) { try { R.ledger.put({ dir: 'out', amount: total, note: S.target.toLocaleString() + '-member milestone: ' + S.pol + ' POL to ' + paid.length + ' activated members', kind: 'cost', category: 'rewards', wallet: 'feeA', asset: 'POL' }); } catch (e) {} }
notifyMissed().catch(e => console.error('milestone missed-notify', e.message));
return { done: true, paid: paid.length, total };
}
async function post(html) { try { if (R.telegram) await R.telegram(html); } catch (e) {} }
async function notifyPaid(r, S, W) {
if (r.notified) return; const c = paidCopy(r, S, W);
try { if (R.message) await R.message(r.email, c.subject, c.html); } catch (e) {}
try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) await R.mailer.send(r.email, c.subject, c.text, c.html); } catch (e) {}
const S2 = load(); const row = S2.rows.find(x => x.email === r.email); if (row) { row.notified = Date.now(); save(S2); }
}
// the missed-it nudge for everyone not paid: in-app notice always, email only with the newsletter opt-in (like every nudge)
async function notifyMissed() {
const S = load(); if (S.notified.missed) return { done: true }; let n = 0;
for (const kind of ['noWallet', 'notActivated']) {
const c = missedCopy(kind, S);
for (const email of S.others[kind] || []) {
try { if (R.message) await R.message(email, c.subject, c.html); n++; } catch (e) {}
try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey() && R.optedIn && await R.optedIn(email)) await R.mailer.send(email, c.subject, c.text, c.html); } catch (e) {}
}
}
const S2 = load(); S2.notified.missed = Date.now(); logLine(S2, 'missed-it notices: ' + n); save(S2); return { sent: n };
}
// every 2 minutes: watch the count while armed or dry, and keep paying/settling once a snapshot exists
async function tick() {
const C = cfg(); if (C.mode === 'off') return;
let S = load();
if (S.status === 'idle') { const n = await accountCount(); if (n < C.target) return { waiting: n }; S = await snapshot(); if (C.mode === 'dry') return { dry: true, eligible: S.rows.filter(r => r.status === 'due').length }; }
if (S.rows.some(r => r.status === 'check')) await recheck();
if (C.mode !== 'armed') return { dry: true };
await settle();
return pay();
}
async function view() {
const S = load(); const C = cfg(); const W = wallet();
const by = s => S.rows.filter(r => r.status === s).length;
return { mode: C.mode, target: C.target, pol: C.pol, status: S.status, snapshotAt: S.snapshotAt, countAt: S.countAt, countNow: await accountCount().catch(() => null),
wallet: W ? W.w.address : null, balance: await balance(), keyPresent: keyOk(),
eligible: S.rows.filter(r => ['due', 'sent', 'paid', 'failed'].includes(r.status)).length, due: by('due'), sent: by('sent'), paid: by('paid'), failed: by('failed'), unchecked: by('check'),
needPol: r4(S.rows.filter(r => r.status === 'due').length * S.pol), missed: { noWallet: (S.others.noWallet || []).length, notActivated: (S.others.notActivated || []).length, suspended: S.others.suspended || 0 },
notified: S.notified, rows: S.rows.map(r => ({ email: r.email, username: r.username, memberId: r.memberId, status: r.status, tx: r.tx || null, error: r.error || null, flags: r.flags || null })), log: S.log.slice(-40) };
}
function reset() { const S = blank(); save(S); return S; } // only while nothing was paid: the admin route checks
module.exports = { init, tick, snapshot, recheck, pay, settle, notifyMissed, view, reset, address, balance, cfg };
+53
View File
@@ -0,0 +1,53 @@
// The missed-payout notice, whole chain in one message (Marty, 2026-09-19).
//
// A purchase pays three tiers up the sponsor line. When a tier's rightful recipient is not
// qualified, the contract passes that share up until it finds someone who is, or hands it to
// the company. Every hop is an on-chain event: PassedUp (who was skipped, and why) and TierPaid
// (who finally got it, and how many hops up). Until now the Telegram notice reported one tier
// per message; this composes ONE message per purchase that shows every tier's walk, every
// person passed, and what it added up to. The point is that the people passed over see, in
// numbers, exactly what qualifying would have paid them.
//
// Pure: takes the events of one transaction plus a name resolver; returns the text or null.
'use strict';
const SHARE = { 1: 0.5, 2: 0.2, 3: 0.1 }; // tier shares of the purchase, for a tier nobody caught
const NEED = { 2: 2, 3: 5 }; // qualifying buyers a tier requires
function fmtPol(wei) {
try { return (Number(BigInt(String(wei)) / 10n ** 14n) / 1e4).toFixed(4); } catch (e) { return '0'; }
}
// txEvents: every indexed event sharing the tx. who(id) -> '#id @name'. had(id, tier) -> qualifying
// buyers that member had at the time (a number) or null when unknown.
function composeMissed(txEvents, who, had, site) {
const buy = txEvents.find(e => e.type === 'Purchase');
const skips = txEvents.filter(e => e.type === 'PassedUp');
if (!buy || !skips.length) return null;
const price = '$' + Math.round((buy.priceCents || 0) / 100);
const lines = ['\u{1F62C} <b>Missed payouts</b> on ' + who(buy.buyerId) + "'s " + price + ' purchase:'];
const passed = new Set(); let walked = 0;
for (const tier of [2, 3]) {
const sk = skips.filter(s => Number(s.tier) === tier).sort((x, y) => Number(x.li || 0) - Number(y.li || 0)); // walk order: nearest first
if (!sk.length) continue;
const paid = txEvents.find(e => e.type === 'TierPaid' && Number(e.tier) === tier);
const pol = paid ? Number(fmtPol(paid.amountWei)) : Number(fmtPol(BigInt(String(buy.paidWei || 0)) * BigInt(Math.round(SHARE[tier] * 100)) / 100n));
walked += pol;
const hops = sk.map(s => {
passed.add(s.skippedId);
let why;
if (s.reason === 'unqualified') { const n = had(s.skippedId, tier); why = (n == null ? 'not qualified' : n + ' of ' + NEED[tier] + ' qualifying buyers'); }
else if (s.reason === 'send-failed') why = 'wallet refused the payment';
else why = String(s.reason || 'passed');
return who(s.skippedId) + ' (' + why + ')';
});
const end = paid ? 'paid to ' + who(paid.recipientId) : 'nobody above was qualified, so the company kept it';
lines.push('Level ' + tier + ' · <b>' + pol.toFixed(4) + ' POL</b>: ' + hops.join(' → ') + ' → ' + end);
}
const n = passed.size;
lines.push('<b>' + walked.toFixed(4) + ' POL walked past ' + n + ' ' + (n === 1 ? 'person' : 'people') + ' on one ' + price + ' sale.</b>');
lines.push('Qualify before the next one: <a href="' + site + '">' + site.replace(/^https:\/\//, '') + '</a>');
return lines.join('\n');
}
module.exports = { composeMissed, fmtPol };
+35 -5
View File
@@ -58,7 +58,8 @@ async function pushCampaign(c, opts = {}) {
const kind = nasKind(c.type);
if (!kind) return { skipped: 'type' };
const budgetLeft = c.budget - (c.spent || 0);
const assigned = Math.max(1, Math.floor(budgetLeft * impressionsPerCredit(c.type)));
const window = c.dailyCap ? Math.min(c.dailyCap, budgetLeft) : budgetLeft; // capped campaigns start with one day's allowance
const assigned = Math.max(1, Math.floor(window * impressionsPerCredit(c.type)));
const token = 'iap_' + crypto.randomBytes(8).toString('hex'); // manage token = Username
const now = new Date();
const days = Number(opts.days || 30);
@@ -74,7 +75,8 @@ async function pushCampaign(c, opts = {}) {
(Username, Subject, Body, WebsiteURL, assigned, remaining, hits, approved, Date, adtype,
Name, Email, PaymentDetails, EDate, sp, width, height, BannerURL, pid, ref_by, catid)
VALUES (?,?,?,?,?,?,0,1,?,?,?,?,?,?,'',?,?,?,?,0,?)`,
[token, c.title || null, c.type === 'text' ? (c.body || null) : null, c.targetUrl,
// clicks route through our redirect so they count and carry the network site as the referrer
[token, c.title || null, c.type === 'text' ? (c.body || null) : null, 'https://instantadpay.com/api/ads/click/' + c.id,
assigned, assigned, now, kind.adtype,
opts.name || 'InstantAdPay member', opts.email || 'ads@instantadpay.com',
'InstantAdPay campaign #' + c.id, edate,
@@ -98,14 +100,31 @@ async function readServed(nasAdId) {
return { assigned, remaining, served, clicks: Number(rows[0].hits) || 0 };
}
// stop a syndicated ad (budget spent, paused, or expired) — remaining:0 halts serving.
// Stop a syndicated ad (budget spent, paused, or expired). NAS has no stop flag: its
// serving query only picks rows with remaining>0, so zeroing that counter is the only
// way to halt an ad.
//
// THE TRAP (found 2026-09-17): served is derived as assigned-remaining, so zeroing also
// makes a stopped ad read back as 100% DELIVERED. That inflated every stopped campaign's
// reported delivery, and worse, reconcileNas charges members for the difference — so
// pausing a campaign could bill for impressions that were never served. A naturally
// exhausted ad also ends at remaining=0, so the two cases are indistinguishable
// afterwards. The true figure therefore has to be captured BEFORE the stop.
async function deactivate(nasAdId) {
if (!enabled()) return { skipped: 'flag-off' };
let served = null;
try { const s = await readServed(nasAdId); if (s) served = s.served; } catch (e) {}
await q('UPDATE sponsorads SET remaining=0, EDate=NOW() WHERE ID=?', [Number(nasAdId)]);
return { ok: true };
return { ok: true, served }; // callers MUST persist this as the final served count
}
// top up a syndicated ad with more impressions (buy-more-views / reactivate).
// point an existing NAS ad at our click redirect (migration for rows pushed before 2026-09-10)
async function setClickUrl(nasAdId, campaignId) {
if (!enabled()) return { skipped: 'flag-off' };
await q('UPDATE sponsorads SET WebsiteURL=? WHERE ID=?', ['https://instantadpay.com/api/ads/click/' + Number(campaignId), Number(nasAdId)]);
return { ok: true };
}
async function topUp(nasAdId, addImpressions, days) {
if (!enabled()) return { skipped: 'flag-off' };
await q(`UPDATE sponsorads SET assigned=assigned+?, remaining=remaining+?, approved=1,
@@ -114,4 +133,15 @@ async function topUp(nasAdId, addImpressions, days) {
return { ok: true };
}
module.exports = { 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 };
+60
View File
@@ -0,0 +1,60 @@
// The network sites list for the footer's "Part of the network" line (Marty 2026-11-14 trust pack).
// One source: the hub's public GET /v1/network-sites (HUB_URL). Cached 10 minutes, refreshed in the background, never waits on a
// slow hub (2.5 s timeout), and falls back to the same built-in list. Never RM Circle, never the games.
// The same file lives in every network site (InstantAdPay, LinkSpin, Downline Banners, VBB, Stack POL).
const FALLBACK = [
{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' },
{ id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
];
const TTL = 10 * 60 * 1000;
let cache = { at: 0, list: FALLBACK, from: 'fallback' };
let inflight = null;
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
function clean(list) {
if (!Array.isArray(list)) return null;
const ok = list.filter(s => s && typeof s.name === 'string' && /^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(s.url || '')))
.slice(0, 30).map(s => ({ id: String(s.id || s.name).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 30), name: String(s.name).slice(0, 60), url: String(s.url).replace(/\/+$/, '') }));
return ok.length ? ok : null;
}
function refresh() {
if (inflight || process.env.NETWORK_SITES_HUB === '0') return inflight;
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
inflight = fetch(hubUrl() + '/v1/network-sites', { signal: ac.signal })
.then(r => (r.ok ? r.json() : null))
.then(j => { const l = clean(j); if (l) cache = { at: Date.now(), list: l, from: 'hub' }; else cache.at = Date.now(); })
.catch(() => { cache.at = Date.now() - TTL + 60 * 1000; }) // hub down: try again in a minute, keep the last good list
.finally(() => { clearTimeout(t); inflight = null; });
return inflight;
}
function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list; }
// Tracked links (Marty 2026-11-14: "make sure each of these sites is its own traffic source and link spun so we can track it"): each
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', stackpol: 'nwsp', earnerscorner: 'nwec' };
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
function selfId(req, l) {
const env = String(process.env.NETWORK_SITE_ID || '').trim().toLowerCase(); if (env) return env;
const h = String((req && req.headers && (req.headers['x-forwarded-host'] || req.headers.host)) || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
const m = h && (l || list()).find(s => hostOf(s.url) === h); return m ? m.id : '';
}
// the LinkSpin-tracked link to site `id` sent from site `from` (from = id: the site's own promo kit); extra = { s1: member username, s2: one path segment }
function tracked(id, from, extra) {
const code = CODES[id]; if (!code || !from) return '';
const q = new URLSearchParams({ src: from }); for (const [k, v] of Object.entries(extra || {})) if (v) q.set(k, String(v));
return linksBase() + '/r/' + code + '?' + q.toString();
}
function withGo(l, me) { return l.map(s => { const go = me && s.id !== me ? tracked(s.id, me) : ''; return go ? Object.assign({}, s, { go }) : s; }); }
// GET /api/network-sites: public, cacheable, the same answer on every page
function handle(req, res) {
const l = list();
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' });
res.end(JSON.stringify(withGo(l, selfId(req, l))));
}
module.exports = { list, handle, refresh, tracked, selfId, withGo, CODES, FALLBACK, _state: () => cache };
+230
View File
@@ -0,0 +1,230 @@
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
//
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
// P mints a token bound to R, the state and the email, and sends the browser
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
// (so nobody can push their own token into someone else's browser), and spends
// the nonce (a second use is refused). The email must already be a member
// here; then R makes an ordinary session and redirects to the relative path.
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
// bots and non-page fetches never bounce.
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
//
// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email
// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
const enabled = () => SECRET().length >= 32;
const TTL = 60 * 1000; // token life
const SKEW = 30 * 1000; // clock skew allowed between the two servers
const STATE_AGE = 300; // seconds: the state cookie
const GO_STATE_AGE = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15)
const WALLET_RE = /^0x[0-9a-f]{40}$/;
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest();
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
function safePath(to, dflt) {
const d = dflt == null ? '/' : dflt;
const s = String(to == null ? '' : to);
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
}
function mint(o) {
const now = o.now || Date.now();
const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
if (o.name) t.name = String(o.name).slice(0, 40);
const body = b64u(JSON.stringify(t));
return 'v1.' + body + '.' + b64u(mac(body));
}
// -> { ok, email, to, n, exp } or { error: reason }
function verify(tok, o) {
if (!enabled()) return { error: 'off' };
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
if (!m) return { error: 'malformed' };
const want = mac(m[1]), got = unb64u(m[2]);
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
const now = (o && o.now) || Date.now();
if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' };
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
const st = String((o && o.st) || '');
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
}
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
const used = new Map(); let fileLoaded = false, tableReady = null;
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
function loadFile() {
if (fileLoaded) return; fileLoaded = true;
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
}
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
async function spend(n, exp) {
const now = Date.now(); loadFile(); prune(now);
if (used.has(n)) return false;
used.set(n, Number(exp) + SKEW); saveFile();
const db = C && C.db;
if (db && db.enabled && db.enabled()) {
try {
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
await tableReady;
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
}
return true;
}
// crawlers, link previews and headless browsers never bounce
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
function cookies(req) {
const out = {};
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
return out;
}
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); }
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
// -> true when the request was one of ours and has been answered
async function handle(req, res, u) {
if (!C || req.method !== 'GET') return false;
const p = u.pathname;
const peerName = NAMES[C.peer] || C.peer;
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
if (goTo && (goTo === C.peer || walletBase(goTo))) {
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
const to = safePath(u.searchParams.get('to'), '/');
const plain = base + to;
if (!enabled() || isBot(req)) return go(res, plain);
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) return go(res, plain);
if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link
return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to));
}
if (p === '/sso/start') {
const to = safePath(u.searchParams.get('to'), C.defaultPath);
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
const via = String(u.searchParams.get('via') || '');
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
let s = null; try { s = await C.member(req); } catch (e) {}
if (s && (s.email || s.address)) return go(res, to); // already signed in here
const c = cookies(req);
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
const st = crypto.randomBytes(16).toString('hex');
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
}
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
const clear = [ck('nsso.back', '', 0, true)];
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
}
if (p === '/sso/check') {
const st = String(u.searchParams.get('st') || '');
const to = safePath(u.searchParams.get('to'), '/');
const r = String(u.searchParams.get('r') || '');
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) {
if (u.searchParams.get('m') === 'go' && !isBot(req)) { // a deliberate tap: sign in here first, then /sso/resume finishes the trip
log('check: not signed in here, asking to sign in', null, 'for ' + forName);
const back = new URLSearchParams({ st, to }); if (r) back.set('r', r);
return go(res, C.signinPath(C.defaultPath), [ck('nsso.back', back.toString(), BACK_AGE, true)]);
}
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
}
let w = null;
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
log('token issued', s.email, 'for ' + forName);
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
}
if (p === '/sso/in') {
const c = cookies(req);
const set = [ck('nsso.st', '', 0, true)];
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
return go(res, C.signinPath(v.to), set);
}
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
log('signed in from ' + (NAMES[v.iss] || peerName), v.email);
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
}
if (p === '/api/sso/status') {
const c = cookies(req); const set = [];
let s = null; try { s = await C.member(req); } catch (e) {}
const signedIn = !!(s && (s.email || s.address));
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
return sendJson(res, out, set);
}
return false;
}
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
const pendingBack = req => !!cookies(req)['nsso.back'];
module.exports = { init, handle, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
+366
View File
@@ -0,0 +1,366 @@
// Level-4 override (Marty, decided 2026-10-17, approved to build for real 2026-10-23; design in memory iap-level4-override):
// 3% of every purchase goes to the buyer's 4th upline on the CONTRACT sponsor chain when that member has 5+ qualifying
// buyers (the contract's own buyerCount, the same bar as level 3); an unqualified 4th upline is skipped and the hunt
// climbs (cap 25 hops, mirroring the contract's HOP_CAP). Exactly one recipient per purchase, so it never costs more than
// 3%; company ids (overrideHouseIds) keep it. Funded off-chain from the company's 20% and paid weekly with the contract's
// award(toMemberId) from a pre-funded payer wallet, purchases from overrideGoLive forward only (no back-pay).
//
// MODES (site setting overrideMode):
// 'off' nothing at all.
// 'dryrun' (default) the Monday who-would-be-paid report to Marty's private Telegram. No money moves.
// 'live' pays, but ONLY when overrideGoLive is set AND a payer key is present (env OVERRIDE_PAYER_KEY or
// OVERRIDE_PAYER_KEY_FILE). Missing either one: it reports as a dry run and says why it did not pay.
//
// MONEY SAFETY (why each piece exists):
// - Every "do this once" is a claim that only one running copy of the app can win: an exclusive file create on the
// shared volume (fs 'wx'), plus a row in event_marks when MySQL is on. A deploy runs two copies for ~30 s (the
// 2026-09-25 double Friday bonus); a claim that cannot be checked counts as LOST (fail closed), never as won.
// - A week's plan (who gets how much) is computed once, written to the volume and never recomputed, so a later read
// of buyer counts cannot change an amount that is already being paid.
// - A payout row is marked 'sending' on disk BEFORE the transaction is sent and gets its tx hash the moment the node
// accepts it. A row whose answer was lost is 'review': it is never sent again automatically. The chain index can
// settle it (an AwardPaid from the payer wallet to that member for that exact amount), or the admin does.
// - Amounts under the dust minimum (overrideDustPol, default 0.01 POL) and pre-flight failures (award() would revert,
// no gas spent) are carried to the next week's plan.
// - Hard cap per week (overridePayCapPol, default 100 POL): a plan over the cap is held whole, nothing is sent.
// - The wallet must hold the week's total plus gas for every send, or nothing is sent and Marty is told.
// - Weeks are paid in order; a week that is held or needs review stops the later weeks until it is resolved.
'use strict';
const fs = require('fs');
const path = require('path');
let ethersLib = null; try { ethersLib = require('ethers'); } catch (e) { /* optional: the payer stays off without it */ }
const PCT = 3, MIN_BUYERS = 5, HOP_CAP = 25, LEVEL = 4;
const GAS_LIMIT = 150000n; // award(): reentrancy guard + member read + capped-gas send + event, ~60k; generous headroom
const WEI = 10n ** 18n;
// ---- Central-time week math (pure, shared by every instance) ----
const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
const CT_HOUR = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', hourCycle: 'h23' });
function weekOf(ts) { // the Monday (YYYY-MM-DD, Central) of the week holding ts
const parts = Object.fromEntries(CT.formatToParts(new Date(ts)).map(p => [p.type, p.value]));
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[parts.weekday];
return new Date(Date.UTC(+parts.year, +parts.month - 1, +parts.day - back)).toISOString().slice(0, 10);
}
const ctMidnight = day => { // ms at 00:00 America/Chicago on YYYY-MM-DD (CDT = UTC-5, CST = UTC-6)
for (const off of [5, 6]) { const t = Date.parse(day + 'T0' + off + ':00:00Z'); if (new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', hour: '2-digit', hourCycle: 'h23' }).format(new Date(t)) === '00') return t; }
return Date.parse(day + 'T05:00:00Z');
};
const addDays = (day, n) => new Date(Date.parse(day + 'T12:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const weekBounds = monday => ({ from: ctMidnight(monday), to: ctMidnight(addDays(monday, 7)) });
// the week may be settled from 9 AM Central on the Monday after it
const payableAt = monday => ctMidnight(addDays(monday, 7)) + 9 * 3600000;
const polStr = wei => { const w = BigInt(wei); const s = (w * 10000n / WEI).toString().padStart(5, '0'); return s.slice(0, -4) + '.' + s.slice(-4); };
const toWei = pol => { const [a, b = ''] = String(pol).trim().split('.'); return BigInt(a || '0') * WEI + BigInt((b + '0'.repeat(18)).slice(0, 18) || '0'); };
function create() {
let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null, db = null, now = () => Date.now();
let BRAND = 'InstantAdPay', SITE_URL = 'https://instantadpay.com', HOUSE_DEFAULT = '1', payerOverride = null;
const lastError = { at: 0, msg: '' };
function init(o) {
DATA_DIR = o.dataDir; chain = o.chain; siteConfig = o.siteConfig || siteConfig; notify = o.notify || null; db = o.db || null;
if (o.brand) BRAND = o.brand; if (o.siteUrl) SITE_URL = o.siteUrl; if (o.houseDefault) HOUSE_DEFAULT = String(o.houseDefault);
if (o.payer) payerOverride = o.payer; // tests: a fake signer, never the real chain
if (o.now) now = o.now;
}
const cfg = () => {
const s = siteConfig();
const num = (v, d) => { const n = Number(v); return v === undefined || v === '' || !isFinite(n) ? d : n; };
return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || HOUSE_DEFAULT).split(',').map(x => Number(x.trim())).filter(Boolean),
goLive: Number(s.overrideGoLive || 0), dustWei: toWei(Math.max(0, num(s.overrideDustPol, 0.01)).toFixed(18)), capWei: toWei(Math.max(0, num(s.overridePayCapPol, 100)).toFixed(18)) };
};
// ---- the payer wallet (OVERRIDE_PAYER_KEY; never logged, never returned) ----
function keyHex() {
let k = String(process.env.OVERRIDE_PAYER_KEY || '').trim();
if (!k && process.env.OVERRIDE_PAYER_KEY_FILE) { try { k = fs.readFileSync(process.env.OVERRIDE_PAYER_KEY_FILE, 'utf8').trim(); } catch (e) {} }
if (!k) return null; if (!k.startsWith('0x')) k = '0x' + k;
return /^0x[0-9a-fA-F]{64}$/.test(k) ? k : null;
}
let realPayer = null;
function payer() {
if (payerOverride) return payerOverride;
const k = keyHex(); if (!k || !ethersLib) return null;
if (realPayer) return realPayer;
const c = chain.getConfig(); const urls = (c.rpcs && c.rpcs.length) ? c.rpcs : [c.rpc]; let idx = 0;
const wallet = () => new ethersLib.Wallet(k, new ethersLib.JsonRpcProvider(urls[idx % urls.length], Number(c.chainId), { staticNetwork: true }));
const ctr = w => new ethersLib.Contract(chain.getConfig().contract, ['function award(uint32 toMemberId) payable'], w);
const address = new ethersLib.Wallet(k).address;
realPayer = {
address,
balance: async () => { try { return await wallet().provider.getBalance(address); } catch (e) { idx++; throw e; } },
fees: async () => { const g = await chain.suggestedFees(); return { maxPriorityFeePerGas: BigInt(g.maxPriorityFeePerGas), maxFeePerGas: BigInt(g.maxFeePerGas) }; },
// a revert here (unknown member, a wallet that refuses POL) costs nothing and sends nothing
preflight: async (id, wei) => { await ctr(wallet()).award.staticCall(Number(id), { value: BigInt(wei) }); },
send: async (id, wei, fees) => { const tx = await ctr(wallet()).award(Number(id), Object.assign({ value: BigInt(wei), gasLimit: GAS_LIMIT }, fees)); return { hash: tx.hash, wait: () => tx.wait(1) }; }
};
return realPayer;
}
function liveState() {
const c = cfg(), why = [];
if (c.mode !== 'live') why.push('overrideMode is ' + c.mode + ', not live');
if (!c.goLive) why.push('overrideGoLive is not set');
if (!payerOverride && !keyHex()) why.push('no payer key (OVERRIDE_PAYER_KEY)');
if (!payerOverride && !ethersLib) why.push('ethers is not installed');
return { ready: !why.length, why };
}
// ---- one-time claims, fail closed ----
const dir = (...p) => path.join(DATA_DIR, 'override', ...p);
const mkdirp = d => { try { fs.mkdirSync(d, { recursive: true }); } catch (e) {} };
const safe = k => String(k).replace(/[^a-zA-Z0-9_.:-]/g, '_').replace(/:/g, '__').slice(0, 150);
async function claim(key) {
if (db && db.enabled && db.enabled()) {
try { const r = await db.q('INSERT IGNORE INTO event_marks (k, ts) VALUES (?, ?)', ['ov:' + String(key).slice(0, 150), now()]); if (!(r && r.affectedRows === 1)) return false; }
catch (e) { lastError.at = now(); lastError.msg = 'claim ' + key + ': ' + e.message; return false; }
}
mkdirp(dir('claims'));
try { fs.closeSync(fs.openSync(dir('claims', safe(key)), 'wx')); return true; }
catch (e) { if (e.code !== 'EEXIST') { lastError.at = now(); lastError.msg = 'claim file ' + key + ': ' + e.message; } return false; }
}
const claimed = key => fs.existsSync(dir('claims', safe(key)));
// ---- payout store: one small JSON file per week header and per (week, member) row, each with a single writer ----
const readJ = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { return null; } };
const writeJ = (f, o) => { mkdirp(path.dirname(f)); const tmp = f + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(o)); fs.renameSync(tmp, f); };
const getWeek = wk => readJ(dir('weeks', wk, 'week.json'));
const putWeek = (wk, patch) => { const cur = getWeek(wk) || { week: wk }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'week.json'), o); return o; };
const getRow = (wk, id) => readJ(dir('weeks', wk, 'm' + id + '.json'));
const putRow = (wk, id, patch) => { const cur = getRow(wk, id) || { week: wk, memberId: id }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'm' + id + '.json'), o); return o; };
const rowsOf = wk => { try { return fs.readdirSync(dir('weeks', wk)).filter(f => /^m\d+\.json$/.test(f)).map(f => readJ(dir('weeks', wk, f))).filter(Boolean).sort((a, b) => a.memberId - b.memberId); } catch (e) { return []; } };
const plannedWeeks = () => { try { return fs.readdirSync(dir('weeks')).filter(w => /^\d{4}-\d{2}-\d{2}$/.test(w)).sort(); } catch (e) { return []; } };
// ---- who gets the override on one purchase ----
const memo = new Map();
async function mem(id) {
const c = memo.get(id); if (c && now() - c.t < 600000) return c.v;
const m = await chain.member(id); const v = { sponsorId: m.sponsorId || 0, buyerCount: m.buyerCount || 0 };
memo.set(id, { t: now(), v }); return v;
}
// { recipientId, hops, skipped: [{id, buyers}] } or { recipientId: 0, reason }
async function recipientFor(buyerId) {
const ups = []; let cur = buyerId;
for (let i = 0; i < LEVEL - 1 + HOP_CAP; i++) { const s = (await mem(cur)).sponsorId; if (!s || s === cur) break; ups.push(s); cur = s; }
if (ups.length < LEVEL) return { recipientId: 0, reason: 'line shorter than ' + LEVEL + ' levels' };
const skipped = [], house = cfg().house;
for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) {
const id = ups[i];
if (house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped };
const b = (await mem(id)).buyerCount;
if (b >= MIN_BUYERS) return { recipientId: id, hops: i - (LEVEL - 1), skipped };
skipped.push({ id, buyers: b });
}
return { recipientId: 0, reason: 'no qualified upline within ' + HOP_CAP + ' hops', skipped };
}
// every Purchase in the full-history index (chain.recentEvents keeps the whole history in memory; the file is the fallback)
function purchases() {
try { if (chain && chain.recentEvents) return chain.recentEvents(1e9).filter(e => e.type === 'Purchase'); } catch (e) {}
try { return (JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'chain-index.json'), 'utf8')).events || []).filter(e => e.type === 'Purchase'); } catch (e) { return []; }
}
// purchases in [from, to) (and from overrideGoLive on): one row per purchase + totals per recipient
async function report(from, to) {
const c = cfg(); const rows = [], per = {};
for (const p of purchases()) {
if (p.ts < from || p.ts >= to || (c.goLive && p.ts < c.goLive)) continue;
const wei = BigInt(p.paidWei || '0') * BigInt(PCT) / 100n, usd = Math.round((p.priceCents || 0) * PCT) / 10000; // dollars: price cents x 3% / 100
const r = await recipientFor(p.buyerId).catch(e => ({ recipientId: 0, reason: 'read failed: ' + e.message, readFailed: true }));
rows.push({ tx: p.tx, ts: p.ts, buyerId: p.buyerId, priceCents: p.priceCents, overrideWei: wei.toString(), overrideUsd: usd, recipientId: r.recipientId, hops: r.hops || 0, skipped: r.skipped || [], reason: r.reason || '', readFailed: !!r.readFailed });
if (r.recipientId) { const o = per[r.recipientId] = per[r.recipientId] || { recipientId: r.recipientId, purchases: 0, wei: 0n, usdCents: 0 }; o.purchases++; o.wei += wei; o.usdCents += (p.priceCents || 0) * PCT / 100; }
}
const recipients = Object.values(per).map(o => ({ recipientId: o.recipientId, purchases: o.purchases, wei: o.wei.toString(), pol: Number(o.wei) / 1e18, usd: Math.round(o.usdCents) / 100 })).sort((a, b) => b.usd - a.usd || a.recipientId - b.recipientId);
const paidUsd = recipients.reduce((n, o) => n + o.usd, 0), keptUsd = rows.filter(x => !x.recipientId).reduce((n, x) => n + x.overrideUsd, 0);
return { mode: c.mode, from, to, purchases: rows.length, readFailures: rows.filter(x => x.readFailed).length, recipients,
totals: { wouldPayUsd: Math.round(paidUsd * 100) / 100, wouldPayPol: recipients.reduce((n, o) => n + o.pol, 0), companyKeepsUsd: Math.round(keptUsd * 100) / 100, salesUsd: rows.reduce((n, x) => n + x.priceCents, 0) / 100 }, rows };
}
// last full week, or the week containing `day`
async function week(day) {
const monday = day ? weekOf(Date.parse(day + 'T12:00:00Z')) : weekOf(now() - 7 * 86400000);
const b = weekBounds(monday);
return Object.assign(await report(b.from, b.to), { week: monday, status: weekStatus(monday) });
}
// ---- planning: freeze who gets how much for one closed week (single writer via claim) ----
// carried rows from earlier weeks roll into this plan; under-dust totals are carried again
async function plan(wk) {
if (getWeek(wk)) return getWeek(wk);
const b = weekBounds(wk);
if (now() < b.to) return null; // not closed yet
const r = await report(b.from, b.to);
if (r.readFailures) { lastError.at = now(); lastError.msg = 'week ' + wk + ': ' + r.readFailures + ' sponsor reads failed, plan postponed'; return null; } // never plan on a partial read
if (!await claim('plan:' + wk)) return getWeek(wk); // another copy is planning (or did)
putWeek(wk, { state: 'planning', created: now(), from: b.from, to: b.to, purchases: r.purchases, salesUsd: r.totals.salesUsd, companyKeepsUsd: r.totals.companyKeepsUsd });
const per = {};
for (const o of r.recipients) per[o.recipientId] = { wei: BigInt(o.wei), usd: o.usd, purchases: o.purchases, carriedIn: 0n, carriedFrom: [] };
for (const w of plannedWeeks().filter(w => w < wk)) for (const row of rowsOf(w)) {
if (row.state !== 'carried') continue;
const o = per[row.memberId] = per[row.memberId] || { wei: 0n, usd: 0, purchases: 0, carriedIn: 0n, carriedFrom: [] };
o.wei += BigInt(row.amountWei); o.usd = Math.round((o.usd + (row.usd || 0)) * 100) / 100; o.carriedIn += BigInt(row.amountWei); o.carriedFrom.push(w);
putRow(w, row.memberId, { state: 'rolled', rolledInto: wk });
}
const dust = cfg().dustWei; let total = 0n, n = 0;
for (const [id, o] of Object.entries(per)) {
const st = o.wei < dust ? 'carried' : 'pending'; if (st === 'pending') { total += o.wei; n++; }
putRow(wk, Number(id), { amountWei: o.wei.toString(), usd: o.usd, purchases: o.purchases, carriedInWei: o.carriedIn.toString(), carriedFrom: o.carriedFrom, state: st, note: st === 'carried' ? 'under the ' + polStr(dust) + ' POL minimum, carried to next week' : '' });
}
return putWeek(wk, { state: n ? 'planned' : 'paid', totalWei: total.toString(), recipients: n, planned: now() });
}
// settle rows whose send answer was lost, from the chain index only (AwardPaid from the payer to that member, that amount)
function reconcile(wk, pay) {
if (!pay || !chain.recentEvents) return;
const b = weekBounds(wk), used = overrideTxs(true);
for (const row of rowsOf(wk)) {
if (row.state !== 'review' && row.state !== 'sent') continue;
const hit = chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && e.toId === row.memberId && String(e.amountWei) === String(row.amountWei)
&& String(e.from || '').toLowerCase() === String(pay.address).toLowerCase() && e.ts >= b.to
&& (row.txHash ? String(e.tx).toLowerCase() === String(row.txHash).toLowerCase() : !used.has(String(e.tx).toLowerCase())));
if (hit) putRow(wk, row.memberId, { state: 'paid', txHash: hit.tx, note: 'confirmed from the chain index' });
}
}
// admin decision for a stuck row: 'carry' (you checked the payer wallet and nothing went out) or 'paid' with the tx,
// which must be an AwardPaid in the chain index from the payer wallet to that member for that exact amount
async function resolve(wk, memberId, action, tx) {
const r = getRow(wk, Number(memberId)); if (!r) return { error: 'no such row' };
if (!['review', 'failed', 'sending', 'sent'].includes(r.state)) return { error: 'row is ' + r.state + ', nothing to resolve' };
if (action === 'carry') { putRow(wk, r.memberId, { state: 'carried', note: 'admin: nothing went out, carried to next week (was ' + r.state + ')' }); return finishWeek(wk); }
if (action === 'paid') {
const p = (payerOverride || keyHex()) ? payer() : null;
const hit = p && chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && String(e.tx).toLowerCase() === String(tx || '').toLowerCase());
if (!hit || hit.toId !== r.memberId || String(hit.amountWei) !== String(r.amountWei) || String(hit.from).toLowerCase() !== String(p.address).toLowerCase()) return { error: 'that tx is not an AwardPaid from the payer wallet to #' + r.memberId + ' for ' + polStr(r.amountWei) + ' POL in the chain index' };
putRow(wk, r.memberId, { state: 'paid', txHash: hit.tx, note: 'admin: confirmed tx' }); return finishWeek(wk);
}
return { error: 'action must be carry or paid' };
}
// ---- paying one planned week (live only) ----
async function pay(wk) {
const live = liveState(); if (!live.ready) return { week: wk, paid: 0, why: live.why };
let w = getWeek(wk); if (!w) return { week: wk, why: ['not planned'] };
if (w.state === 'planning') return { week: wk, why: ['plan is being written (or a plan write stopped halfway: needs review if this lasts)'] };
const p = payer(); reconcile(wk, p);
let rows = rowsOf(wk).filter(r => r.state === 'pending');
if (!rows.length) return finishWeek(wk);
const c = cfg(); const total = rows.reduce((n, r) => n + BigInt(r.amountWei), 0n);
if (total > c.capWei) { putWeek(wk, { state: 'held', heldWhy: 'over the weekly cap: ' + polStr(total) + ' POL planned, cap ' + polStr(c.capWei) + ' POL' }); await alertOnce(wk, 'cap', '⛔ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPlanned ' + polStr(total) + ' POL is over the weekly cap of ' + polStr(c.capWei) + ' POL. Nothing was sent. Raise overridePayCapPol or review the plan, then press Pay this week now in admin.'); return { week: wk, held: 'cap' }; }
let fees, bal;
try { fees = await p.fees(); bal = BigInt(await p.balance()); } catch (e) { lastError.at = now(); lastError.msg = 'payer read: ' + e.message; return { week: wk, why: ['payer read failed: ' + e.message] }; }
const gas = BigInt(rows.length) * GAS_LIMIT * fees.maxFeePerGas;
if (bal < total + gas) { putWeek(wk, { state: 'held', heldWhy: 'payer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL, needs ' + polStr(total + gas) + ' (payouts ' + polStr(total) + ' + gas ' + polStr(gas) + ')' }); await alertOnce(wk, 'balance', '⚠️ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPayer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL; this week needs ' + polStr(total + gas) + ' POL (' + polStr(total) + ' payouts + up to ' + polStr(gas) + ' gas). Nothing was sent. Fund it and it pays on the next check (or press Pay this week now).'); return { week: wk, held: 'balance' }; }
putWeek(wk, { state: 'paying', heldWhy: '' });
let sent = 0;
for (const r0 of rows) {
if (!await claim('pay:' + wk + ':' + r0.memberId)) continue; // another copy owns this row
const r = getRow(wk, r0.memberId); if (!r || r.state !== 'pending') continue;
try { await p.preflight(r.memberId, r.amountWei); }
catch (e) { putRow(wk, r.memberId, { state: 'carried', note: 'award() would revert (' + String(e.reason || e.shortMessage || e.message).slice(0, 100) + '); nothing sent, carried to next week' }); continue; }
putRow(wk, r.memberId, { state: 'sending', sendingAt: now() }); // on disk BEFORE the send
let tx;
try { tx = await p.send(r.memberId, r.amountWei, fees); }
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'send error, may or may not have gone out: ' + String(e.shortMessage || e.message).slice(0, 140) }); continue; }
putRow(wk, r.memberId, { state: 'sent', txHash: tx.hash });
console.log('override: week ' + wk + ' #' + r.memberId + ' ' + polStr(r.amountWei) + ' POL tx ' + tx.hash);
try { const rc = await tx.wait(); if (rc && Number(rc.status) === 1) { putRow(wk, r.memberId, { state: 'paid', paidAt: now() }); sent++; } else putRow(wk, r.memberId, { state: 'failed', note: 'reverted on chain (no POL moved except gas); needs review' }); }
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'sent, receipt not confirmed: ' + String(e.message).slice(0, 120) }); }
}
return Object.assign(await finishWeek(wk), { sentNow: sent });
}
async function finishWeek(wk) {
// a send that stopped halfway (no answer in 15 minutes) is never retried: it becomes review
for (const r of rowsOf(wk)) {
if (r.state === 'sending' && now() - (r.sendingAt || r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'the app stopped during the send; it may or may not have gone out' });
if (r.state === 'sent' && now() - (r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'sent, no receipt and not in the chain index after 15 minutes' });
}
reconcile(wk, (payerOverride || keyHex()) ? payer() : null);
const rows = rowsOf(wk); const open = rows.filter(r => ['pending', 'sending', 'sent', 'review', 'failed'].includes(r.state));
if (open.length) {
const stuck = open.filter(r => r.state === 'review' || r.state === 'failed'); // in-flight rows of another copy are not stuck
if (stuck.length) await alertOnce(wk, 'review', '\u{1F50E} <b>Level-4 override needs review</b> · ' + BRAND + ' · week of ' + wk + '\n' + stuck.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL: ' + r.state + (r.txHash ? ' ' + txLink(r.txHash) : '') + ' ' + (r.note || '')).join('\n') + '\nNothing is re-sent automatically. Check the payer wallet on the explorer, then resolve it in admin.');
return { week: wk, state: (getWeek(wk) || {}).state, open: open.length };
}
const w = putWeek(wk, { state: 'paid', done: now() });
await summaryPaid(wk);
return { week: wk, state: w.state };
}
const txLink = h => { const c = chain.getConfig(); return (c.explorer ? c.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + h; };
async function alertOnce(wk, kind, text) { if (!notify) return; if (!await claim('tg:' + wk + ':' + kind)) return; await notify(text, null).catch(() => {}); }
async function summaryPaid(wk) {
if (!notify || !await claim('tg:' + wk + ':paid')) return;
const w = getWeek(wk) || {}, rows = rowsOf(wk), paid = rows.filter(r => r.state === 'paid'), carried = rows.filter(r => r.state === 'carried');
const tot = paid.reduce((n, r) => n + BigInt(r.amountWei), 0n), usd = paid.reduce((n, r) => n + (r.usd || 0), 0);
await notify('\u{1F4B8} <b>Level-4 override PAID</b> · ' + BRAND + ' · week of ' + wk + '\n' + (w.purchases || 0) + ' purchases, $' + Number(w.salesUsd || 0).toFixed(2) + ' sales\n'
+ 'Paid ' + polStr(tot) + ' POL (about $' + usd.toFixed(2) + ' at purchase prices) to ' + paid.length + ' member' + (paid.length === 1 ? '' : 's') + '; company keeps $' + Number(w.companyKeepsUsd || 0).toFixed(2) + ' of the 3%.\n'
+ (paid.map(r => '#' + r.memberId + ': ' + polStr(r.amountWei) + ' POL ($' + (r.usd || 0).toFixed(2) + ') <a href="' + txLink(r.txHash) + '">tx</a>').join('\n') || 'Nobody qualified this week.')
+ (carried.length ? '\nCarried to next week (under the minimum or the wallet refused): ' + carried.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL').join(', ') : '')
+ '\nDetails: ' + SITE_URL + '/api/admin/override?week=' + wk, null).catch(() => {});
}
// weeks the live payer is responsible for: from the go-live week to the last closed one, in order
function dueWeeks(force) {
const c = cfg(); if (!c.goLive) return [];
const out = []; let wk = weekOf(c.goLive);
while (true) { const b = weekBounds(wk); if (now() < b.to) break; if (!force && now() < payableAt(wk)) break; out.push(wk); wk = addDays(wk, 7); if (out.length > 520) break; }
return out;
}
// settle every due week in order; stop at the first one that is not fully paid
async function payDue(opts) {
const o = opts || {}; const results = [];
if (!liveState().ready) return { ready: false, why: liveState().why, results };
for (const wk of dueWeeks(o.force)) {
if (o.week && wk > o.week) break;
let w = getWeek(wk);
if (!w) w = await plan(wk);
if (!w) { results.push({ week: wk, why: ['not planned yet: ' + (lastError.msg || 'waiting')] }); break; }
if (w.state === 'paid') { await summaryPaid(wk); results.push({ week: wk, state: 'paid' }); continue; }
const r = await pay(wk); results.push(r);
if ((getWeek(wk) || {}).state !== 'paid') break;
}
return { ready: true, results };
}
function weekStatus(wk) {
const w = getWeek(wk); if (!w) return { week: wk, state: claimed('plan:' + wk) ? 'planning' : 'not planned' };
const rows = rowsOf(wk);
return { week: wk, state: w.state, heldWhy: w.heldWhy || '', totalWei: w.totalWei, totalPol: w.totalWei ? polStr(w.totalWei) : '0',
rows: rows.map(r => ({ memberId: r.memberId, pol: polStr(r.amountWei), amountWei: r.amountWei, usd: r.usd, purchases: r.purchases, state: r.state, txHash: r.txHash || '', tx: r.txHash ? txLink(r.txHash) : '', note: r.note || '', carriedFrom: r.carriedFrom || [], rolledInto: r.rolledInto || '' })) };
}
async function payerStatus() {
const c = cfg(), live = liveState(); const out = { mode: c.mode, ready: live.ready, why: live.why, goLive: c.goLive || 0, capPol: polStr(c.capWei), dustPol: polStr(c.dustWei), house: c.house, keyPresent: !!(payerOverride || keyHex()), lastError: lastError.msg ? lastError : null };
const p = (payerOverride || keyHex()) ? payer() : null;
if (p) { out.address = p.address; try { out.balancePol = polStr(await p.balance()); } catch (e) { out.balanceError = e.message; } }
return out;
}
// AwardPaid txs this payer made (for the Earnings label and the payout email): tx -> { week, memberId }
let txCache = { at: 0, map: new Map() };
function overrideTxs(fresh) {
if (!fresh && now() - txCache.at < 30000) return txCache.map;
const m = new Map(); for (const wk of plannedWeeks()) for (const r of rowsOf(wk)) if (r.txHash) m.set(String(r.txHash).toLowerCase(), { week: wk, memberId: r.memberId });
txCache = { at: now(), map: m }; return m;
}
const txInfo = tx => { return overrideTxs(true).get(String(tx || '').toLowerCase()) || null; };
// ---- the scheduler: every 30 minutes ----
async function tick() {
const c = cfg(); if (c.mode === 'off') return;
const live = liveState();
if (live.ready) { try { await payDue(); } catch (e) { lastError.at = now(); lastError.msg = 'payDue: ' + e.message; console.error('override pay', e.message); } return; }
// dry run (or 'live' that is not ready): the Monday report, once per week across every copy of the app
const parts = Object.fromEntries(CT_HOUR.formatToParts(new Date(now())).map(p => [p.type, p.value]));
if (parts.weekday !== 'Mon' || Number(parts.hour) < 9 || !notify) return;
const r = await week(); if (r.readFailures) return; // try again in 30 minutes rather than report a partial week
if (!await claim('tg:' + r.week + ':dry')) return;
let st = {}; try { st = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'override-dryrun.json'), 'utf8')); } catch (e) {}
st.lastWeek = r.week; st.reports = Object.assign(st.reports || {}, { [r.week]: { totals: r.totals, recipients: r.recipients, purchases: r.purchases } });
try { fs.writeFileSync(path.join(DATA_DIR, 'override-dryrun.json'), JSON.stringify(st)); } catch (e) {}
const top = r.recipients.slice(0, 8).map(o => '#' + o.recipientId + ': $' + o.usd.toFixed(2) + ' (' + o.pol.toFixed(2) + ' POL, ' + o.purchases + ' buys)').join('\n');
await notify('\u{1F4CA} <b>Level-4 override, DRY RUN</b> · ' + BRAND + ' · week of ' + r.week + '\n' + r.purchases + ' purchases, $' + r.totals.salesUsd.toFixed(2) + ' sales\n'
+ 'Would pay $' + r.totals.wouldPayUsd.toFixed(2) + ' (' + r.totals.wouldPayPol.toFixed(2) + ' POL) to ' + r.recipients.length + ' members; company keeps $' + r.totals.companyKeepsUsd.toFixed(2) + ' of the 3%.\n'
+ (top || 'Nobody qualified this week.') + '\nNo money moved' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
}
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg };
}
const main = create();
module.exports = Object.assign(main, { create, weekOf, ctMidnight, weekBounds, payableAt, polStr, toWei, PCT, MIN_BUYERS, HOP_CAP, LEVEL, GAS_LIMIT });
+77
View File
@@ -0,0 +1,77 @@
// PassiveDrip PTC bridge (2026-09-30). Every InstantAdPay verified-visit campaign is listed on PassiveDrip's
// paid-to-click page under the house account; PassiveDrip members view it for coins, and the visits they deliver
// count against the campaign here exactly like visits delivered in our own viewer.
//
// Loop (every PD_SYNC_MIN minutes, 90 s after boot):
// 1. POST <bridge>?a=ptc_sync {campaigns:[{id, title, desc, url, visitsLeft}]} (HMAC-signed) -> PD upserts rows by
// our campaign id, pauses any row we no longer list, keeps ONE live row per target URL.
// 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).
'use strict';
const fs = require('fs'), path = require('path'), http = require('http'), https = require('https'), crypto = require('crypto');
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) {} }
function bridge(action, method, body) {
return new Promise((resolve, reject) => {
const raw = body ? JSON.stringify(body) : '';
const ts = Math.floor(Date.now() / 1000);
const sig = crypto.createHmac('sha256', process.env.PD_BRIDGE_SECRET.trim()).update(ts + '\n' + method + '\n' + action + '\n' + raw).digest('hex');
const u = new URL(process.env.PD_BRIDGE_URL.trim()); u.searchParams.set('a', action);
const req = (u.protocol === 'http:' ? http : https).request(u, { method, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw), 'X-PD-Ts': String(ts), 'X-PD-Sig': sig, 'User-Agent': 'instantadpay-pdsync' }, timeout: 25000 }, res => {
let d = ''; res.on('data', c => d += c); res.on('end', () => { try { const j = JSON.parse(d); if (res.statusCode !== 200 || j.error) return reject(new Error('bridge ' + action + ': HTTP ' + res.statusCode + ' ' + (j.error || d.slice(0, 120)))); resolve(j); } catch (e) { reject(new Error('bridge ' + action + ': bad response ' + d.slice(0, 120))); } });
});
req.on('error', reject); req.on('timeout', () => req.destroy(new Error('bridge timeout'))); req.end(raw);
});
}
// what PassiveDrip should list: every active, worldwide visits campaign with visits still to deliver
// (Spooky Doors door packs and Golden Doors stay behind the doors while the season runs: doorOnly)
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)) * synN() }))
.filter(c => c.visitsLeft > 0);
}
async function sync() {
if (!enabled() || running) return { skipped: true };
running = true;
const t = { at: Date.now(), pushed: 0, applied: 0, closed: 0, note: '' };
try {
const camps = await listing(); t.pushed = camps.length;
const r = await bridge('ptc_sync', 'POST', { campaigns: camps });
t.pdLive = r.live; t.pdPaused = r.paused;
const served = await bridge('ptc_served', 'GET');
for (const row of (served.rows || [])) {
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
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();
} catch (e) { t.note = String(e.message).slice(0, 160); console.error('pdsync', e.message); }
finally { S.last = t; save(); running = false; }
return t;
}
function status() { return { enabled: enabled(), bridge: enabled() ? process.env.PD_BRIDGE_URL.replace(/\?.*$/, '') : null, last: S.last, tracked: Object.keys(S.served).length }; }
// the member's own PassiveDrip line for the Games card (2026-10-01): bridge action 'member', read only
async function member(memberId, email) {
if (!enabled()) return null;
const j = await bridge('member', 'POST', { memberId: Number(memberId) || 0, email: String(email || '').toLowerCase() });
return j && j.ok ? j : null;
}
module.exports = { enabled, init, sync, status, listing, member };
+132
View File
@@ -0,0 +1,132 @@
// Pipeline (Marty, 2026-09-15): a follow-up board for sponsors. One screen where every prospect
// and every direct sits in a column by what they have actually done. Nobody drags a card: the
// site moves it when the event fires (wallet linked, payouts on, first buy, buyers counted).
// The sponsor adds what the site cannot know: a note, a follow-up date, an outcome tag.
// Built before launch, shown as "coming soon" until site setting pipelineMode = on
// (preview = only the admin account sees the live board, for testing and the training video).
// Dual-mode store like the other modules (MySQL when DATABASE_URL is set, JSON on the volume).
const fs = require('fs');
const path = require('path');
const db = require('./db');
let DATA_DIR = null, accounts = null, coach = null, chain = null;
// linked positions (Qualified Start) belong to the member and their buyers count toward badges, but the contract
// pays level 2 and 3 to the MAIN wallet only when that wallet's own buyerCount reaches 2 and 5. The card shows both
// numbers; the stage and the advice follow the main wallet, because that is what gets paid (Marty's audit, 2026-09-15)
const posCache = new Map();
async function positionBuyers(email) {
let ids = []; try { ids = (await accounts.positions(email)).map(p => p.memberId).filter(Boolean); } catch (e) {}
let n = 0;
for (const id of ids) {
const c = posCache.get(id); let v = c && Date.now() - c.t < 60000 ? c.v : null;
if (v == null) { try { v = (await chain.member(id)).buyerCount || 0; } catch (e) { v = 0; } posCache.set(id, { t: Date.now(), v }); }
n += v;
}
return { count: n, positions: ids.length };
}
const DAY = 86400000;
// columns, in order. Prospects live in the first and last; directs land by coaching rung.
const STAGES = [
{ key: 'talking', label: 'Talking to', hint: 'People you have reached out to who have not joined yet.' },
{ key: 'joined', label: 'Joined', hint: 'Joined free. Next: link a wallet.' },
{ key: 'wallet', label: 'Wallet linked', hint: 'Next: switch on payouts, one free transaction.' },
{ key: 'payouts', label: 'Payouts on', hint: 'Next: a first package. $20 or more counts for you.' },
{ key: 'bought', label: 'Bought', hint: 'Your qualifying buyer. Next: their first person.' },
{ key: 'building', label: 'Building', hint: 'They have buyers of their own. Coach them to their two.' },
{ key: 'later', label: 'Later', hint: 'Parked: not now, no response, not interested.' }
];
const TAGS = ['', 'hot', 'later', 'no response', 'not interested'];
const RUNG_STAGE = ['joined', 'wallet', 'payouts', 'bought', 'building', 'building', 'building'];
const PARKED = new Set(['later', 'no response', 'not interested']);
// ---- stores: one row per (owner, person) ----
const J = {
db: null,
FILE: () => path.join(DATA_DIR, 'pipeline.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = {}; } },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
async notes(owner) { if (!this.db) this.load(); return Object.values(this.db).filter(r => r.owner === owner); },
async put(owner, person, f) { if (!this.db) this.load(); const k = owner + '|' + person; this.db[k] = Object.assign(this.db[k] || { owner, person }, f, { updated: Date.now() }); this.save(); return this.db[k]; }
};
const rowR = r => ({ owner: r.owner_email, person: r.person, note: r.note || '', followUp: r.follow_up ? Number(r.follow_up) : null, tag: r.tag || '', updated: Number(r.updated) });
const D = {
async notes(owner) { return (await db.q('SELECT * FROM pipeline_notes WHERE owner_email=?', [owner])).map(rowR); },
async put(owner, person, f) {
await db.q('INSERT INTO pipeline_notes (owner_email,person,note,follow_up,tag,updated) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE note=VALUES(note), follow_up=VALUES(follow_up), tag=VALUES(tag), updated=VALUES(updated)',
[owner, person, f.note, f.followUp || null, f.tag || '', Date.now()]);
return rowR((await db.q('SELECT * FROM pipeline_notes WHERE owner_email=? AND person=?', [owner, person]))[0]);
}
};
const impl = () => db.enabled() ? D : J;
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; coach = opts.coach; chain = opts.chain; }
// who may see the live board: mode on = everyone; preview = the admin account only
function visible(mode, email, adminEmail) {
if (mode === 'on') return true;
if (mode === 'preview') return !!(email && adminEmail && String(email).toLowerCase() === String(adminEmail).toLowerCase());
return false;
}
async function board(email) {
const owner = String(email || '').toLowerCase();
const now = Date.now(); const eod = new Date(); eod.setHours(23, 59, 59, 999);
const notes = {}; for (const n of await impl().notes(owner)) notes[n.person] = n;
const cards = [];
// prospects: the sponsor's own list of people they have talked to
for (const p of await coach.prospects(owner)) {
const n = notes['p:' + p.id] || {};
let stage = 'talking';
if (p.status === 'not now') stage = 'later';
if (p.status === 'joined') stage = 'joined';
if (p.status === 'bought') stage = 'bought';
if (PARKED.has(n.tag)) stage = 'later';
cards.push({ key: 'p:' + p.id, kind: 'prospect', name: p.name, contact: p.contact || '', status: p.status, stage,
since: p.updated || p.created || now, lastSeen: 0, quietDays: Math.floor((now - (p.updated || p.created || now)) / DAY),
stalled: false, next: p.status === 'contacted' || p.status === 'interested' ? 'Send your link and ask for a yes' : 'Reach out once',
say: 'Hey ' + p.name + ', here is the link I mentioned. Free to join with an email, and I will walk you through the first three steps: {{link}}',
note: n.note || p.note || '', followUp: n.followUp || p.nextTs || null, tag: n.tag || '' });
}
// directs: stage from what they have actually done (the coaching rung)
const levels = await accounts.downline(owner, 1);
for (const m of (levels[0] ? levels[0].members : [])) {
let c = null; try { c = await coach.describe(m, now); } catch (e) {}
const n = notes[m.email] || {};
const pb = c && c.rung >= 3 ? await positionBuyers(m.email) : { count: 0, positions: 0 };
const buyersMain = c ? c.buyerCount || 0 : 0, buyersAll = buyersMain + pb.count;
const rung = c ? c.rung : 0;
const RR = coach.RUNGS[rung];
// when positions carry buyers the main wallet does not, say exactly what the contract needs
const gap = pb.count && rung >= 3 && rung < 6 ? ' The contract pays level ' + (buyersMain < 2 ? '2' : '3') + ' to their main wallet only when that wallet has ' + (buyersMain < 2 ? 2 : 5) + ' qualifying buyers of its own: ' + buyersMain + ' now, plus ' + pb.count + ' on linked positions that count for badges only.' : '';
const stage = PARKED.has(n.tag) && rung < 3 ? 'later' : RUNG_STAGE[rung] || 'joined';
cards.push({ key: m.email, kind: 'member', email: m.email, name: m.username ? '@' + m.username : (m.memberId ? 'member #' + m.memberId : 'member'),
memberId: m.memberId || 0, stage, rung, rungLabel: RR.label, since: m.created || now,
lastSeen: m.lastSeen || 0, quietDays: c ? c.quietDays : 0, stalled: !!(c && c.stalled && rung < 6),
buyers: buyersAll, buyersMain, buyersPositions: pb.count, positions: pb.positions, bought: !!(c && c.counted),
next: RR.next + gap, say: RR.say.replace('{{name}}', m.username || 'there'),
note: n.note || '', followUp: n.followUp || null, tag: n.tag || '' });
}
const due = cards.filter(c => c.followUp && c.followUp <= eod.getTime()).sort((a, b) => a.followUp - b.followUp);
const columns = STAGES.map(s => ({ key: s.key, label: s.label, hint: s.hint,
cards: cards.filter(c => c.stage === s.key).sort((a, b) => (b.stalled - a.stalled) || (a.followUp || 9e15) - (b.followUp || 9e15) || b.since - a.since) }));
return { stages: STAGES, tags: TAGS, columns, due, counts: { total: cards.length, stalled: cards.filter(c => c.stalled).length, due: due.length } };
}
async function save(email, body) {
const owner = String(email || '').toLowerCase();
const person = String(body.key || '').trim().toLowerCase().slice(0, 190);
if (!person) return { error: 'Pick who to update.' };
// only people on the sponsor's own board
const ok = person.startsWith('p:') ? (await coach.prospects(owner)).some(p => 'p:' + p.id === person)
: await accounts.isDownlineOf(owner, person, 1);
if (!ok) return { error: 'Not on your board.' };
const tag = TAGS.includes(String(body.tag || '').toLowerCase()) ? String(body.tag || '').toLowerCase() : '';
let followUp = null;
if (body.followUp) { const t = /^\d{4}-\d{2}-\d{2}$/.test(body.followUp) ? Date.parse(body.followUp + 'T12:00:00') : Number(body.followUp); if (t && !isNaN(t)) followUp = t; }
const note = String(body.note || '').trim().slice(0, 1000);
const row = await impl().put(owner, person, { note, followUp, tag });
return { ok: true, note: row };
}
module.exports = { init, STAGES, TAGS, visible, board, save };
+108
View File
@@ -0,0 +1,108 @@
// Prohibited-content policy, one module shared by InstantAdPay and LinkSpin (keep the two copies identical).
// 2026-10-30: an SEO backlink farm opened 106 free accounts, each with a casino or local-business bio and a
// website link, and Google indexed that text under our domains through the public walls. Rules (Marty):
// - profile fields are not a free backlink: a bio may not carry a URL or a domain-looking token;
// - gambling, adult, pharma, weapons and link-selling terms are refused in every member-set text field
// (bio, social links, line banner, wall offers, campaign names, headlines, copy and target URLs);
// - case-insensitive and Unicode aware (NFC, lower-cased, letter/number boundaries, so "Essex" never hits "sex").
// Pure functions, no state, no dependencies.
'use strict';
// One entry per term or phrase; spaces match any run of whitespace. Grouped for the Terms page and the admin.
const LIST = {
gambling: ['casino', 'casinos', 'cassino', 'cassinos', 'slots', 'slot gacor', 'betting', 'sportsbook', 'sportsbooks', 'bookmaker', 'bookmakers', 'bookie',
'lottery', 'lotteries', 'lotto', 'poker', 'baccarat', 'roulette', 'blackjack', 'jackpot', 'togel', 'judi', 'judi online', 'apostas', 'apuestas',
'nổ hũ', 'cá cược', 'đổi thưởng', 'xổ số', 'kèo', 'nhà cái', 'soi kèo', 'game bài', 'tài xỉu', 'bắn cá'],
adult: ['porn', 'porno', 'pornography', 'sex', 'sexy', 'escort', 'escorts', 'erotic', 'erotica', 'xxx', 'onlyfans', 'nude', 'nudes', 'hentai', 'cam girl', 'cam girls', 'sex cam', 'hookup', 'hookups'],
pharma: ['viagra', 'cialis', 'levitra', 'pharmacy', 'pharmacies', 'prescription', 'prescriptions', 'steroids', 'anabolic', 'cannabis', 'marijuana', 'weed', 'cbd', 'kratom', 'opioid', 'opioids',
'xanax', 'adderall', 'tramadol', 'oxycodone', 'ketamine', 'cocaine', 'mdma', 'psilocybin', 'vape', 'vaping'],
weapons: ['firearm', 'firearms', 'guns', 'gun shop', 'gun store', 'ammunition', 'ammo', 'rifle', 'rifles', 'pistol', 'pistols', 'handgun', 'handguns', 'silencer', 'suppressor', 'explosives'],
linkfarm: ['backlink', 'backlinks', 'seo service', 'seo services', 'seo agency', 'link building', 'link-building', 'guest post', 'guest posts', 'guest posting', 'pbn', 'buy links', 'sell links', 'dofollow']
};
const ALL = Object.values(LIST).reduce((a, b) => a.concat(b), []);
const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const ZW = /[​-‏⁠]/g; // zero-width joiners hide nothing
const strip = s => String(s == null ? '' : s).normalize('NFC').replace(ZW, '');
const norm = s => strip(s).toLowerCase();
// Boundary = anything that is not a letter or a number (works for every script, unlike \b).
const TERM_RE = new RegExp('(?<![\\p{L}\\p{N}])(?:' + ALL.map(t => esc(norm(t)).replace(/\s+/g, '\\s+')).join('|') + ')(?![\\p{L}\\p{N}])', 'u');
// Common gTLDs plus the ccTLDs link farms actually use. A short two-letter list keeps "Mr.Li" style text out of it.
const TLDS = 'com|net|org|info|biz|io|co|app|xyz|me|tv|us|uk|vn|de|fr|ru|in|id|br|es|it|nl|ca|au|eu|ch|at|be|pt|pl|cz|se|no|fi|dk|ie|nz|za|ng|ke|eg|tr|ua|il|ae|sa|pk|bd|lk|np|kh|la|mm|my|sg|ph|th|jp|kr|cn|tw|hk|mx|ar|cl|pe|to|ly|cc|gg|ai|pw|ws|tk|ml|ga|cf|gq|su|'
+ 'site|online|store|shop|club|top|pro|live|link|page|dev|fun|vip|one|tech|space|website|cloud|digital|agency|company|email|news|blog|life|world|today|zone|guru|ninja|game|games|team|network|money|cash|gold|bid|trade|win|bet|casino|poker|mobi|name|tel|travel|jobs|pics|photo|video|press|media|art|design|studio|capital|finance|exchange|solutions|services|systems|tools|works|center|group|global|international|institute|academy|school|education|university|church|community|social|chat|dating|love|wiki|review|reviews|directory|guide|help|support|rocks|ventures|holdings|partners|limited|ltd|llc|inc|asia|africa|london|nyc|tokyo|berlin|paris|best|buzz|click|host|hosting|lol|monster|wtf|ooo|icu|sbs|cfd|cyou|rest|bar|cam|surf|run|fit|health|care|dog|cat|pet|pets|wine|beer|vodka|bio|eco|green|energy|solar|car|cars|auto|bike|tires|taxi|limo|rent|rentals|house|homes|realty|estate|land|city|town|place|map|earth|fund|loans|credit|insure|legal|law|lawyer|attorney|tax|accountant|consulting|marketing|promo|sale|deals|discount|coupons|gift|gifts|toys|baby|kids|mom|family|wedding|party|events|tickets|show|theater|film|movie|music|band|dance|yoga|golf|football|soccer|hockey|tennis|racing';
// Schemes and www. are matched in any case; a bare domain token (or an email address) only with its TLD in lower case, so a
// missed space after a period ("ads.One day") is not mistaken for a link while real spam domains (typed lower case) are caught.
const SCHEME_RE = /(?:https?:\/\/|ftp:\/\/|(?<![\p{L}\p{N}])www\.)/iu;
const DOMAIN_RE = new RegExp('(?<![\\p{L}\\p{N}])[\\p{L}\\p{N}-]{1,63}(?:\\.[\\p{L}\\p{N}-]{1,63})*\\.(?:' + TLDS + ')(?![\\p{L}\\p{N}])', 'u');
// The matching prohibited term, or null.
function match(text) { const m = TERM_RE.exec(norm(text)); return m ? m[0].replace(/\s+/g, ' ') : null; }
// True when the text carries a URL or a domain-looking token (http(s)://, www., word.tld).
function hasUrl(text) { const t = strip(text); return SCHEME_RE.test(t) || DOMAIN_RE.test(t); }
const BIO_LINK_MSG = 'Links go in the social fields, not the bio.';
const blockedMsg = site => 'That content is not allowed on ' + (site || 'InstantAdPay/LinkSpin') + ' profiles (see Terms).';
const blockedAdMsg = site => 'That content is not allowed on ' + (site || 'InstantAdPay/LinkSpin') + ' (see Terms, Prohibited content).';
// Bio rule: no links, no prohibited terms. Returns { ok: true } or { error, reason }.
function checkBio(bio, site) {
const t = String(bio || '');
if (!t.trim()) return { ok: true };
if (hasUrl(t)) return { error: BIO_LINK_MSG, reason: 'url' };
const term = match(t);
if (term) return { error: blockedMsg(site), reason: 'term:' + term };
return { ok: true };
}
// Any other member-set text (social URL, banner target, campaign name, headline, copy): prohibited terms only.
// Pass profile: true for profile fields (the message names profiles), else the ad message is used.
function checkText(text, site, opts) {
const term = match(text);
if (!term) return { ok: true };
return { error: (opts && opts.profile) ? blockedMsg(site) : blockedAdMsg(site), reason: 'term:' + term };
}
// Several fields at once: { name: value, ... } -> first failure, with the field named in `field`.
function checkFields(fields, site, opts) {
for (const k of Object.keys(fields || {})) {
const v = fields[k]; if (v == null || v === '') continue;
const r = checkText(Array.isArray(v) ? v.join(' ') : String(v), site, opts);
if (r.error) return Object.assign({ field: k }, r);
}
return { ok: true };
}
// Profile ingest (registry sync from the other property, or a saved profile replayed): the parts of a profile that may be
// stored. A bio with a link or a prohibited term is dropped (null); a social URL carrying a prohibited term is dropped.
function cleanProfile(pf, site) {
const out = { avatarUrl: null, bio: null, socials: null, dropped: [] };
if (!pf || typeof pf !== 'object') return out;
const av = String(pf.avatarUrl || '').trim(); if (/^https:\/\/[^\s]+$/i.test(av) && av.length <= 300) out.avatarUrl = av;
const bio = String(pf.bio || '').trim().slice(0, 600);
if (bio) { const r = checkBio(bio, site); if (r.ok) out.bio = bio; else out.dropped.push('bio:' + r.reason); }
const src = pf.socials && typeof pf.socials === 'object' ? pf.socials : (typeof pf.socials === 'string' ? safeJson(pf.socials) : null);
if (src) {
const c = {};
for (const k of Object.keys(src)) {
const v = String(src[k] || '').trim(); if (!v) continue;
const r = checkText(v, site, { profile: true }); if (r.ok) c[k] = v; else out.dropped.push('socials.' + k + ':' + r.reason);
}
if (Object.keys(c).length) out.socials = c;
}
return out;
}
function safeJson(s) { try { const o = JSON.parse(s); return o && typeof o === 'object' ? o : null; } catch (e) { return null; } }
// Terms-page wording, one line per group (kept here so both sites say the same thing).
const POLICY = [
'gambling, casinos, betting, lotteries and sweepstakes',
'adult or sexual content',
'drugs and prescription pharmaceuticals',
'weapons',
'hate or harassment',
'malware, phishing and counterfeit goods',
'misleading financial promises',
'accounts created to place links in profile fields (link farming), which are removed without notice together with their profile text'
];
// One log line per refusal, with the email masked (never the text itself at full length).
function logRefusal(where, email, r) {
try { console.log('prohibited-content refused', where, String(email || '-').replace(/^(.).*(@.*)$/, '$1***$2'), r && r.field ? 'field=' + r.field : '', r && r.reason ? r.reason : ''); } catch (e) {}
}
module.exports = { LIST, ALL, POLICY, match, hasUrl, checkBio, checkText, checkFields, cleanProfile, logRefusal, BIO_LINK_MSG, blockedMsg, blockedAdMsg };
+102
View File
@@ -0,0 +1,102 @@
// Partner promo codes (Marty, 2026-09-12): a reusable code per partner site owner that gives
// members who redeem it free ad credits (earned-grade) on top of whatever they already get.
// Redeemed automatically when someone joins through a link carrying ?promo=CODE, or typed into
// the dashboard. One redemption per code per account; every redemption is logged; optional
// cap (max uses) and expiry; codes can be switched off. Storage: MySQL promo_codes +
// promo_redemptions, or DATA_DIR/promos.json.
const fs = require('fs');
const path = require('path');
const db = require('./db');
let DATA_DIR = null;
const norm = c => String(c || '').trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 24);
// The drip (Marty, 2026-09-19): a code's credits arrive in STEPS installments, the first on the
// day it is redeemed and one more on each day the member finishes their daily ad set. Whatever
// is still unclaimed WINDOW_DAYS after redemption is never paid.
const STEPS = 5;
const WINDOW_DAYS = 30;
const stepOf = credits => Math.ceil(Number(credits) / STEPS);
const J = {
db: { v: 1, codes: {}, redemptions: [] },
FILE() { return path.join(DATA_DIR, 'promos.json'); },
load() { try { this.db = Object.assign(this.db, JSON.parse(fs.readFileSync(this.FILE(), 'utf8'))); } catch (e) {} },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
async get(code) { return this.db.codes[code] || null; },
async list() { return Object.values(this.db.codes).sort((a, b) => b.created - a.created); },
async put(c) { this.db.codes[c.code] = Object.assign(this.db.codes[c.code] || {}, c); this.save(); return this.db.codes[c.code]; },
async uses(code) { return this.db.redemptions.filter(r => r.code === code).length; },
async redeemed(code, email) { return this.db.redemptions.some(r => r.code === code && r.email === email); },
async addRedemption(r) { this.db.redemptions.push(r); this.save(); },
async redemptions(code, n) { return this.db.redemptions.filter(r => !code || r.code === code).slice(-(n || 200)).reverse(); },
async forEmail(email) { return this.db.redemptions.filter(r => r.email === email); },
async markPaid(code, email, paid, lastDay) { const r = this.db.redemptions.find(x => x.code === code && x.email === email); if (r) { r.paid = paid; r.lastDay = lastDay; this.save(); } }
};
const D = {
async get(code) { const r = await db.q('SELECT * FROM promo_codes WHERE code=?', [code]); return r[0] ? row(r[0]) : null; },
async list() { return (await db.q('SELECT * FROM promo_codes ORDER BY created DESC')).map(row); },
async put(c) {
await db.q('INSERT INTO promo_codes (code,credits,partner,note,max_uses,expires,active,created,funder) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE funder=VALUES(funder), credits=VALUES(credits), partner=VALUES(partner), note=VALUES(note), max_uses=VALUES(max_uses), expires=VALUES(expires), active=VALUES(active)',
[c.code, c.credits, c.partner || null, c.note || null, c.maxUses || 0, c.expires || 0, c.active ? 1 : 0, c.created || Date.now(), c.funder || null]);
return this.get(c.code);
},
async uses(code) { const r = await db.q('SELECT COUNT(*) n FROM promo_redemptions WHERE code=?', [code]); return Number(r[0].n); },
async redeemed(code, email) { const r = await db.q('SELECT 1 FROM promo_redemptions WHERE code=? AND email=?', [code, email]); return r.length > 0; },
async addRedemption(r) { await db.q('INSERT IGNORE INTO promo_redemptions (code,email,credits,via,ts,paid,last_day,expires,ref) VALUES (?,?,?,?,?,?,?,?,?)', [r.code, r.email, r.credits, r.via, r.ts, r.paid || 0, r.lastDay || '', r.expires || 0, r.ref || null]); },
async forEmail(email) { return (await db.q('SELECT * FROM promo_redemptions WHERE email=?', [email])).map(x => ({ code: x.code, email: x.email, credits: Number(x.credits), via: x.via, ts: Number(x.ts), paid: Number(x.paid) || 0, lastDay: x.last_day || '', expires: Number(x.expires) || 0, ref: x.ref || '' })); },
async markPaid(code, email, paid, lastDay) { await db.q('UPDATE promo_redemptions SET paid=?, last_day=? WHERE code=? AND email=?', [paid, lastDay, code, email]); },
async redemptions(code, n) { const rows = code ? await db.q('SELECT * FROM promo_redemptions WHERE code=? ORDER BY ts DESC LIMIT ?', [code, Number(n) || 200]) : await db.q('SELECT * FROM promo_redemptions ORDER BY ts DESC LIMIT ?', [Number(n) || 200]); return rows.map(r => ({ code: r.code, email: r.email, credits: Number(r.credits), via: r.via, ts: Number(r.ts) })); }
};
const row = r => ({ code: r.code, funder: r.funder || null, credits: Number(r.credits), partner: r.partner || '', note: r.note || '', maxUses: Number(r.max_uses) || 0, expires: Number(r.expires) || 0, active: !!Number(r.active), created: Number(r.created) });
const impl = () => db.enabled() ? D : J;
function init(opts) { DATA_DIR = opts.dataDir; if (!db.enabled()) J.load(); }
async function create(c) {
const code = norm(c.code); if (!code || code.length < 3) return { error: 'Code must be 3 to 24 letters or numbers.' };
const credits = Math.floor(Number(c.credits)); if (!(credits > 0) || credits > 100000) return { error: 'Credits must be between 1 and 100,000.' };
const cur = await impl().get(code);
const saved = await impl().put({ code, credits, funder: c.funder ? String(c.funder).toLowerCase() : (cur && cur.funder) || null, partner: String(c.partner || '').slice(0, 80), note: String(c.note || '').slice(0, 200), maxUses: Math.max(0, Math.floor(Number(c.maxUses) || 0)), expires: c.expires ? Number(new Date(c.expires)) || 0 : 0, active: c.active !== false && c.active !== 0 && c.active !== '0', created: cur ? cur.created : Date.now() });
return { ok: true, code: saved };
}
async function setActive(code, active) { const c = await impl().get(norm(code)); if (!c) return { error: 'No such code.' }; await impl().put(Object.assign(c, { active: !!active })); return { ok: true }; }
// why a code cannot be used right now, or null when it can (email optional: skips the per-account check)
async function check(code, email) {
const k = norm(code); if (!k) return { error: 'Enter a promo code.' };
const c = await impl().get(k); if (!c || !c.active) return { error: 'That promo code is not valid.' };
if (c.expires && Date.now() > c.expires) return { error: 'That promo code has expired.' };
if (email && await impl().redeemed(k, email)) return { error: 'You already used that promo code.' };
if (c.maxUses && (await impl().uses(k)) >= c.maxUses) return { error: 'That promo code has been fully redeemed.' };
return null;
}
// redeem for an account: records the redemption; the caller then pays what is due today with
// payDue(). via = 'link' | 'dashboard'; ref = the site the ?promo= link was opened from.
async function redeem(code, email, via, ref) {
const k = norm(code); const e = String(email || '').toLowerCase();
const bad = await check(k, e); if (bad) return bad;
const c = await impl().get(k);
const ts = Date.now();
await impl().addRedemption({ code: k, email: e, credits: c.credits, via: via || 'dashboard', ts, paid: 0, lastDay: '', expires: ts + WINDOW_DAYS * 86400000, ref: String(ref || '').slice(0, 80) });
return { ok: true, credits: c.credits, step: stepOf(c.credits), steps: STEPS, code: k, partner: c.partner, funder: c.funder || null };
}
// Pay every installment that is due today for this member. pay(rec, amount, n) moves the credits
// (and charges a funder) and returns true when it did; a false leaves the installment for another
// day. day is the member's calendar day (Central), so one installment per day, never two.
async function payDue(email, day, pay) {
const e = String(email || '').toLowerCase(); const out = [];
for (const r of await impl().forEmail(e)) {
if (!r.expires || r.paid >= r.credits || r.lastDay === day || Date.now() > r.expires) continue;
const c = await impl().get(r.code); if (!c) continue;
const amount = Math.min(stepOf(r.credits), r.credits - r.paid);
const n = Math.floor(r.paid / stepOf(r.credits)) + 1;
if (!(await pay(Object.assign({}, r, { funder: c.funder || null, partner: c.partner }), amount, n))) continue;
await impl().markPaid(r.code, e, r.paid + amount, day);
out.push({ code: r.code, amount, n, of: STEPS, total: r.credits, partner: c.partner });
}
return out;
}
async function adminView() {
const codes = await impl().list();
for (const c of codes) c.uses = await impl().uses(c.code);
return { codes, recent: await impl().redemptions(null, 100) };
}
async function byFunder(email) { return (await impl().list()).filter(c => c.funder === String(email || '').toLowerCase()); }
module.exports = { init, create, setActive, check, redeem, payDue, adminView, norm, byFunder, STEPS, WINDOW_DAYS };
+358 -10
View File
@@ -1,22 +1,34 @@
<!doctype html>
<html lang="en">
<html lang="en" data-theme-base="dark">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>Admin | InstantAdPay</title>
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
<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=20260910g">
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
<style>
.adm-table{width:100%;table-layout:auto}
.adm-table th{cursor:pointer;user-select:none;white-space:nowrap}
#trfSources th,#trfAngles th{white-space:normal;text-align:center;line-height:1.2;vertical-align:bottom}
#trfSources td:not(:first-child),#trfAngles td:not(:first-child){text-align:center;font-variant-numeric:tabular-nums}
.adm-table th.sort-asc::after{content:' \25B2';font-size:9px;color:var(--mint)}
.adm-table th.sort-desc::after{content:' \25BC';font-size:9px;color:var(--mint)}
.adm-table.kv th{cursor:default;color:var(--muted);font-weight:500}
.adm-table.kv th.sort-asc::after,.adm-table.kv th.sort-desc::after{content:''}
.adm-table td.act,.adm-table th:last-child{width:1%;white-space:nowrap} /* the action column keeps its full width; text columns give way */
.adm-table td:first-child{overflow-wrap:anywhere;word-break:break-word}
.adm-table th,.adm-table td{padding:8px 10px;text-align:left;vertical-align:top;border-bottom:1px solid var(--line);font-size:13.5px}
.adm-table td.when{white-space:nowrap}
.adm-table th{color:var(--muted);font-size:11.5px;text-transform:uppercase;letter-spacing:.08em}
.adm-table .act{white-space:nowrap}
.adm-table .act button{margin-right:6px}
.st{display:inline-block;border-radius:999px;padding:2px 9px;font-size:11.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase}
.st.active{background:rgba(67,232,195,.14);color:var(--mint)}
.st.paused{background:rgba(255,178,56,.14);color:var(--amber)}
.st.out{background:rgba(255,255,255,.08);color:var(--muted)}
.house-tag{display:inline-block;border:1px solid rgba(157,125,255,.5);color:var(--violet);border-radius:6px;padding:1px 6px;font-size:10.5px;font-weight:700;margin-left:6px;vertical-align:middle}
.st.active{background:var(--mint-soft-2);color:var(--mint)}
.st.paused{background:var(--amber-soft);color:var(--amber)}
.st.out{background:var(--muted-soft);color:var(--muted)}
.house-tag{display:inline-block;border:1px solid var(--violet-line);color:var(--violet);border-radius:6px;padding:1px 6px;font-size:10.5px;font-weight:700;margin-left:6px;vertical-align:middle}
.adm-form p{margin:0 0 10px}
.adm-form label.small{display:block;margin-bottom:4px}
.trunc{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;vertical-align:bottom}
@@ -24,7 +36,7 @@
.ph-chips{display:inline-flex;gap:6px;flex-wrap:wrap;margin-left:6px;vertical-align:middle}
.ph-chips .chip-t{padding:2px 10px;font-size:11.5px;font-family:var(--mono);text-transform:none;letter-spacing:0;cursor:pointer;background:transparent}
.drip-steps{display:grid;gap:12px}
.drip-step{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:rgba(4,8,7,.4)}
.drip-step{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:var(--ground-soft)}
.drip-step .ds-head{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:8px}
.drip-step .ds-n{font-family:var(--mono);font-size:12px;color:var(--mint);letter-spacing:.08em}
.drip-step .ds-when{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}
@@ -50,6 +62,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">
@@ -85,8 +105,14 @@
<button data-pane="house" type="button"><svg viewBox="0 0 24 24"><path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8M7 13v5a2 2 0 0 0 4 0v-3"/></svg>House ads</button>
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h10"/></svg>All campaigns</button>
<button data-pane="members" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg>Members</button>
<button data-pane="support" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.1-2.4 3.7"/><path d="M12 17v.5"/></svg>Support<span class="pill" id="supBadge" hidden></span></button>
<button data-pane="kb" type="button"><svg viewBox="0 0 24 24"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H20v15H6.5A2.5 2.5 0 0 0 4 20.5z"/><path d="M4 20.5A2.5 2.5 0 0 0 6.5 21H20v-3"/><path d="M9 8h7M9 11.5h5"/></svg>Knowledge base</button>
<button data-pane="reports" type="button"><svg viewBox="0 0 24 24"><path d="M12 3l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg>Reports<span class="pill" id="repBadge" hidden></span></button>
<button data-pane="traffic" type="button"><svg viewBox="0 0 24 24"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>Traffic</button>
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
<button data-pane="releases" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg>Releases</button>
<button data-pane="pnl" type="button"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg>P&amp;L</button>
<button data-pane="gamepass" type="button"><svg viewBox="0 0 24 24"><rect x="2.5" y="7" width="19" height="11" rx="5.5"/><path d="M7 11v3M5.5 12.5h3"/><circle cx="15.5" cy="11.5" r="1.1"/><circle cx="18" cy="13.5" r="1.1"/></svg>Game Pass</button>
<button data-pane="settings" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>Settings</button>
</nav>
<div class="bo-links">
@@ -106,6 +132,7 @@
<button id="boBurger" aria-label="Menu" type="button">☰</button>
<h2 id="boTitle" style="margin:0">Overview</h2>
<span class="small muted" id="chainLine"></span>
<span class="seg theme-seg" id="boTheme" role="group" aria-label="Theme"><button type="button" data-theme="light" title="Light theme">Light</button><button type="button" data-theme="dark" title="Dark theme">Dark</button><button type="button" data-theme="auto" title="Follow the device">Auto</button></span>
</header>
<main class="bo-content">
@@ -116,6 +143,7 @@
<div class="statx c-violet"><div><div class="nv" id="ovActive">0</div><div class="lb">Active campaigns</div><span class="chip flat" id="ovCampSub"></span></div></div>
<div class="statx c-amber"><div><div class="nv" id="ovReports">0</div><div class="lb">Open reports</div><span class="chip flat" id="ovBurnSub"></span></div></div>
<div class="statx"><div><div class="nv" id="ovDrips">0</div><div class="lb">Follow-ups in flight</div><span class="chip flat" id="ovDripSub"></span></div></div>
<div class="statx c-cyan"><div><div class="nv" id="ovBix">0</div><div class="lb">BixPay partner links</div><span class="chip flat" id="ovBixSub"></span></div></div>
</div>
<div class="grid c2" style="margin-top:16px">
<div class="card">
@@ -192,6 +220,7 @@
<div id="hVisitsRow" hidden>
<p><input id="hVisitTitle" maxlength="80" placeholder="Headline (what members see before visiting)" style="width:100%"></p>
<p><input id="hVisitCount" type="number" min="20" placeholder="How many verified visits?" style="width:100%"></p>
<p><select id="hVisitPlace" style="width:100%"><option value="all">Everywhere (Earn tab, refuels, Spooky Doors)</option><option value="doors">Behind Spooky Doors (doors only, in season)</option><option value="golden">Golden Spooky Door (doors only, bonus candy)</option></select></p>
<p class="small muted" id="hVisitHint"></p>
</div>
<p id="hErr" class="small" style="color:var(--bad)" hidden></p>
@@ -214,6 +243,11 @@
</div>
<div class="pane" id="pane-campaigns" hidden>
<div class="card">
<div class="card-head"><h3>Login-ad line</h3><span class="sub" id="lqSub">paid reservations waiting for a slot</span></div>
<p class="small muted" style="margin:0 0 10px">When every member slot is taken, a member can pay now to reserve the next one. The oldest paid reservation starts the moment a slot frees (on expiry, on a pause, and on a one-minute check), before any paused slot can come back. Estimated starts assume every live slot runs its full term. Cancel gives the full price back as purchased credits.</p>
<div class="tablewrap"><table class="adm-table" id="lqTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>All campaigns</h3><span class="sub" id="campSub">newest first</span></div>
<p style="margin:0 0 10px"><input id="campFilter" placeholder="Filter by owner, name, type or status" style="width:100%"></p>
@@ -222,15 +256,104 @@
</div>
<div class="pane" id="pane-members" hidden>
<div class="card" id="memSearchCard">
<div class="card-head"><h3>Find a member</h3><span class="sub">matches as you type; Enter opens the first match</span></div>
<div style="display:flex;gap:8px;flex-wrap:wrap"><input id="memSearch" autocomplete="off" placeholder="Start typing a name, username, email, member # or wallet…" style="flex:1;min-width:240px"><button type="button" class="btn small" id="memOpen">Open</button></div>
<div id="memHits" hidden style="margin-top:6px;border:1px solid var(--line);border-radius:10px;overflow:hidden"></div>
<p class="small" id="memSearchMsg" hidden style="margin:8px 0 0"></p>
</div>
<div class="card" id="memCard" hidden>
<div class="card-head"><h3 id="mcName">Member</h3><span class="sub" id="mcSub"></span></div>
<div style="display:flex;gap:8px;flex-wrap:wrap;margin:0 0 12px">
<button type="button" class="btn small sec" id="mcBack">&larr; Back to list</button>
<button type="button" class="btn small sec" data-mcact="username">Set username</button>
<button type="button" class="btn small sec" data-mcact="sponsor">Set sponsor</button>
<button type="button" class="btn small sec" data-mcact="wallet">Swap main wallet</button>
<button type="button" class="btn small sec" data-mcact="credits">Grant credits</button>
<button type="button" class="btn small sec" data-mcact="message">Message (inbox + email)</button>
<a class="btn small sec" id="mcWall" href="#" target="_blank" rel="noopener">Public wall</a>
<button type="button" class="btn small sec" data-mcact="delete" style="margin-left:auto">Delete account</button>
</div>
<div id="mcBody"></div>
</div>
<div class="card">
<div class="card-head"><h3>Holding tank</h3><span class="sub" id="tankAdmSub">free members with no sponsor, and who adopted whom</span></div>
<div class="tablewrap"><table class="adm-table" id="tankWait"></table></div>
<p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p>
<div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Sponsor check: InstantAdPay and LinkSpin</h3><span class="sub" id="scSub">members on both sites whose sponsor differs</span></div>
<p class="small muted">Deliberate changes (a tank adoption, a rescue, a release, the end of an adoption window, an admin edit) follow to the other site until the member is bound on that site's contract. Everything else keeps the first sponsor. To settle a difference, pick the side whose sponsor is right: it is applied on the other site, unless the member is already bound there.</p>
<p><button class="btn small" id="scRun" type="button">Run the check</button></p>
<div class="tablewrap"><table class="adm-table" id="scTable"></table></div>
<details style="margin-top:10px"><summary class="small muted">Recent sponsor follow activity on both sites</summary><div class="tablewrap"><table class="adm-table" id="scLog"></table></div></details>
</div>
<div class="card">
<div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div>
<p style="margin:0 0 10px"><input id="memFilter" placeholder="Filter by email, username, member # or sponsor" style="width:100%"></p>
<p style="margin:0 0 10px"><div class="card" id="fraudBox" style="margin-bottom:12px"><p class="small muted">Loading duplicate signals…</p></div>
<input id="memFilter" placeholder="Filter by email, username, member # or sponsor" style="width:100%"></p>
<p class="small muted">Sponsor = the token the account joined under (username, share code, or member #). Editing it re-points free referrals and future purchases. On-chain sponsorship is permanent once activated.</p>
<div class="tablewrap"><table class="adm-table" id="memTable"></table></div>
</div>
<div class="card" id="spamCard">
<div class="card-head"><h3>Link-farm list</h3><span class="sub" id="spamSub">daily scan at 06:30 Central</span></div>
<p class="small muted">Free accounts (no package, no wallet) that carry a link plus a farm signal: a prohibited term in the profile, a sign-in that ended within 15 minutes of the sign-up, or no sponsor. Nothing is deleted on its own. Delete uses the normal member delete (on-chain members are refused) and never touches LinkSpin; the "also on LinkSpin" column is there so you can decide. Allow keeps an email off this list for good.</p>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0 0 10px"><button class="btn small" id="spamRun" type="button">Scan now</button><button class="btn small sec" id="spamDelete" type="button">Delete selected</button><span class="small muted" id="spamAllow"></span></p>
<div class="tablewrap"><table class="adm-table" id="spamTable"></table></div>
</div>
</div>
<div class="pane" id="pane-support" hidden>
<div id="spList">
<div class="card">
<div class="card-head"><h3>Support desk</h3><span class="sub" id="spSub">tickets from Help, /support and the chatbot</span></div>
<div class="chips" id="spStatus" style="margin-top:4px"></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
<select id="spPlatform" class="small"><option value="">All platforms</option><option value="iap">InstantAdPay</option><option value="linkspin">LinkSpin</option></select>
<select id="spCategory" class="small"></select>
<input id="spQ" class="small" placeholder="Search ref, email, name, subject" style="flex:1;min-width:200px">
</p>
<div class="tablewrap"><table class="adm-table" id="spTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Saved replies</h3><span class="sub">insert them from any ticket's reply box</span></div>
<div id="spTpls"></div>
<p style="display:flex;gap:10px;flex-wrap:wrap;margin:10px 0 0"><button type="button" class="btn small sec" id="spTplAdd">+ Add a saved reply</button><button type="button" class="btn small" id="spTplSave">Save saved replies</button></p>
</div>
<p class="small muted">New tickets and member replies ping your private Telegram chat (site setting supportTelegramChat) and email ADMIN_EMAIL, at most one ping per ticket every 10 minutes. Your replies email the requester and, for members, land in their Help tab as a quiet inbox notice.</p>
</div>
<div id="spView" hidden></div>
</div>
<div class="pane" id="pane-kb" hidden>
<div id="kbList">
<div class="card">
<div class="card-head"><h3>Knowledge base</h3><span class="sub" id="kbSub">what the chat assistant answers from</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
<input id="kbQ" class="small" placeholder="Search title, questions, answer, tags" style="flex:1;min-width:200px">
<select id="kbSrc" class="small"><option value="">All sources</option><option value="canned">From the code</option><option value="faq">FAQ</option><option value="ticket">From tickets</option><option value="admin">Added here</option></select>
<button type="button" class="btn small" id="kbNew">+ New entry</button>
</p>
<div class="tablewrap"><table class="adm-table" id="kbTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Try a question</h3><span class="sub">which entry answers it, and what the AI is given</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;margin:0"><input id="kbTry" class="small" placeholder="Ask it the way a member would" style="flex:1;min-width:200px"><button type="button" class="btn small sec" id="kbTryGo">Test</button></p>
<div id="kbTryOut" class="small"></div>
</div>
<p class="small muted">Instant answers (a pattern is set) reply on their own with no AI call. For every other question the closest entries go to the AI as its knowledge base, and when nothing fits it says it is not sure and points to support. In a ticket, "Save as KB entry" under your reply turns it into a draft here. Entries from the code follow chatbot.js and kb-seed.js until you edit them.</p>
</div>
<div id="kbEdit" class="card" hidden></div>
</div>
<div class="pane" id="pane-reports" hidden>
<div class="card">
<div class="card-head"><h3>Counters audit</h3><span class="sub" id="audSub">views vs delivery logs, charges vs shows</span></div>
<p class="small muted" style="margin:0 0 8px">Every format's recorded views are reconciled against the log that proves delivery, login days charged against days shown, and featured bookings checked for views. Runs daily and alerts you on Telegram; run it any time here.</p>
<div style="margin:0 0 8px"><button type="button" class="btn small sec" id="audRun">Run now</button></div>
<div class="tablewrap"><table class="adm-table" id="audTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Ad reports</h3><span class="sub">members flagging ads</span></div>
<div class="tablewrap"><table class="adm-table" id="repTable"></table></div>
@@ -241,6 +364,147 @@
</div>
</div>
<div class="pane" id="pane-traffic" hidden>
<div class="card"><div class="card-head"><h3>Games to members</h3><span class="sub" id="stSub">the $5 welcome offer after a game win</span></div><div class="tablewrap"><table class="adm-table" id="trfStarter"></table></div></div>
<div class="card"><div class="card-head"><h3>Login-ad showings</h3><span class="sub" id="lsSub">sign-in interstitials per day, dashboard vs games</span></div><div class="tablewrap"><table class="adm-table" id="trfLogin"></table></div></div>
<div class="card" id="trfBixCard"><div class="card-head"><h3>BixPay clicks</h3><span class="sub" id="bixSub">taps on "Get your BixPay card" by surface (the range picked below)</span></div>
<p class="muted small" style="margin:0 0 10px">Every BixPay button and banner goes through /go/bixpay, which counts the tap and opens the member's resolved partner link (own, else a sponsor's, else the network link). Sign-ups are not counted here: the BIX portal shows each partner their directs and levels.</p>
<div class="grid c2"><div class="tablewrap"><table class="adm-table" id="trfBix"></table></div><div class="tablewrap"><table class="adm-table" id="trfBixMembers"></table></div></div></div>
<div class="card">
<div class="card-head"><h3>Where visitors come from</h3><span class="sub" id="trfSub"></span></div>
<div class="chips" id="trfRange" style="margin:0 0 10px"><button type="button" class="chip-t" data-days="7">7 days</button><button type="button" class="chip-t on" data-days="30">30 days</button><button type="button" class="chip-t" data-days="90">90 days</button><button type="button" class="chip-t" data-days="365">Year</button></div>
<p class="muted small" style="margin:0 0 10px">Page views are public-page loads by referring domain (crawlers skipped; our own pages and no referrer count as direct). Join-page views are invite-link opens. Signups, registered and $20+ buyers are accounts whose first-touch source was that domain; legacy arrivals show as legacy:brand:domain.</p>
<p style="margin:0 0 6px;display:flex;gap:8px;align-items:center"><input class="tfilter small" data-for="trfSources" placeholder="Filter sources" style="max-width:260px"><span class="tfilter-count muted small"></span></p><div class="tablewrap"><table class="adm-table" id="trfSources"></table></div>
</div>
<div class="grid c2">
<div class="card"><div class="card-head"><h3>Landing pages</h3><span class="sub">page views by page</span></div><p style="margin:0 0 6px;display:flex;gap:8px;align-items:center"><input class="tfilter small" data-for="trfPaths" placeholder="Filter pages" style="max-width:260px"><span class="tfilter-count muted small"></span></p><div class="tablewrap"><table class="adm-table" id="trfPaths"></table></div></div>
<div class="card"><div class="card-head"><h3>Angles</h3><span class="sub">join-page hook copy</span></div><p style="margin:0 0 6px;display:flex;gap:8px;align-items:center"><input class="tfilter small" data-for="trfAngles" placeholder="Filter angles" style="max-width:260px"><span class="tfilter-count muted small"></span></p><div class="tablewrap"><table class="adm-table" id="trfAngles"></table></div></div>
</div>
<div class="card"><div class="card-head"><h3>By day</h3><span class="sub">page views, signups</span></div><p style="margin:0 0 6px;display:flex;gap:8px;align-items:center"><input class="tfilter small" data-for="trfDaily" placeholder="Filter days" style="max-width:260px"><span class="tfilter-count muted small"></span></p><div class="tablewrap"><table class="adm-table" id="trfDaily"></table></div></div>
<div class="card" id="promoAdmin">
<div class="card-head"><h3>Partner promo codes</h3><span class="sub">free ad credits for members who redeem a partner's code</span></div>
<p class="muted small" style="margin:0 0 10px">Give a site owner a code. Their members redeem it on a join link (<code>instantadpay.com/join/martbost?promo=CODE</code>) or in the "Have a promo code?" box on the Overview. One use per account; uses and the last redemptions are listed below.</p>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;align-items:end">
<label class="small">Code<input id="pcCode" type="text" placeholder="TRAFFICWAVE" style="text-transform:uppercase"></label>
<label class="small">Credits<input id="pcCredits" type="number" min="1" placeholder="250"></label>
<label class="small">Partner<input id="pcPartner" type="text" placeholder="site or owner"></label>
<label class="small">Max uses (0 = unlimited)<input id="pcMax" type="number" min="0" value="0"></label>
<label class="small">Expires (optional)<input id="pcExpires" type="date"></label>
<button type="button" class="btn small" id="pcSave">Save code</button>
</div>
<p class="small" id="pcMsg" hidden style="margin:8px 0 0"></p>
<div class="tablewrap" style="margin-top:12px"><table class="adm-table" id="pcTable"></table></div>
<div class="tablewrap" style="margin-top:12px"><table class="adm-table" id="pcRecent"></table></div>
</div>
</div>
<div class="pane" id="pane-blog" hidden>
<div class="card" id="blogList">
<div class="card-head"><h3>Articles</h3><span class="sub" id="blSub"></span></div>
<p class="muted small" style="margin:0 0 10px">Coaching and teaching stories, published at <a href="/blog" target="_blank" rel="noopener">instantadpay.com/blog</a>. Every published post gets its own page with a title tag, description, canonical link, social preview card, structured data, and a spot in the sitemap and RSS feed. Drafts are visible only to you (open one from its row to preview the real page).</p>
<p class="small muted" id="blSyndNote" hidden style="margin:0 0 10px"></p>
<p><button type="button" class="btn small" id="blNew">New article</button></p>
<div class="tablewrap"><table class="adm-table" id="blTable"></table></div>
</div>
<div class="card" id="blogEditor" hidden>
<div class="card-head"><h3 id="blEdTitle">New article</h3><span class="sub" id="blEdSub"></span></div>
<div style="display:grid;gap:10px">
<label class="small">Title (the headline and the browser title; under 60 characters shows whole in search results) <span id="blTitleCount" class="muted"></span><input id="blTitle" type="text" maxlength="140" placeholder="The thimble and the bucket"></label>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
<label class="small">URL slug (letters, numbers, dashes)<input id="blSlug" type="text" maxlength="80" placeholder="auto from the title"></label>
<label class="small">Tags (comma separated; the first one shows as the category)<input id="blTags" type="text" maxlength="200" placeholder="mindset, team building"></label>
</div>
<label class="small">Excerpt (the meta description and the card text; 120 to 160 characters is ideal) <span id="blExcCount" class="muted"></span><textarea id="blExcerpt" maxlength="300" rows="2" style="width:100%"></textarea></label>
<div style="display:grid;grid-template-columns:1fr auto;gap:8px;align-items:end">
<label class="small">Cover image (1200x630 works best; it becomes the social preview card)<input id="blCover" type="text" placeholder="/uploads/... or https://..."></label>
<span><button type="button" class="btn small sec" id="blCoverBtn">Upload</button><input type="file" id="blCoverFile" accept="image/png,image/jpeg,image/webp" hidden></span>
</div>
<p class="small muted" id="blCoverInfo" style="margin:-4px 0 0"></p>
<div>
<div class="ed-bar" aria-label="Formatting">
<button type="button" data-bl="bold" title="Bold"><b>B</b></button>
<button type="button" data-bl="italic" title="Italic"><i>I</i></button>
<button type="button" data-blblock="h2" title="Section heading">H2</button>
<button type="button" data-blblock="h3" title="Sub heading">H3</button>
<button type="button" data-blblock="p" title="Paragraph">P</button>
<button type="button" data-blblock="blockquote" title="Quote">Quote</button>
<button type="button" data-bl="insertUnorderedList" title="Bullet list">&bull; List</button>
<button type="button" data-bl="insertOrderedList" title="Numbered list">1. List</button>
<button type="button" id="blLinkBtn" title="Insert link">&#128279; Link</button>
<button type="button" id="blImgBtn" title="Insert image">&#128444; Image</button><input type="file" id="blImgFile" accept="image/png,image/jpeg,image/webp,image/gif" hidden>
<button type="button" id="blHtmlBtn" title="Edit the HTML directly">&lt;/&gt;</button>
</div>
<div id="blBody" class="ed-body" contenteditable="true" data-ph="Write the article. Headings break it up; short paragraphs read better on phones." style="min-height:360px;line-height:1.6"></div>
<textarea id="blHtml" class="ed-body" hidden style="min-height:360px;font-family:var(--mono);font-size:13px"></textarea>
<p class="small muted" style="margin:6px 0 0"><span id="blWords">0 words</span> &middot; 600 or more gives a page something to rank on; one idea per section.</p>
</div>
<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
<button type="button" class="btn small" id="blSaveDraft">Save draft</button>
<button type="button" class="btn small" id="blPublish">Publish</button>
<button type="button" class="btn small sec" id="blUnpublish" hidden>Back to draft</button>
<a class="btn small sec" id="blPreview" href="#" target="_blank" rel="noopener" hidden>Open page</a>
<button type="button" class="btn small sec" id="blClose">Close</button>
<button type="button" class="btn small sec" id="blDelete" hidden style="margin-left:auto">Delete</button>
</div>
<p class="small" id="blMsg" hidden></p>
</div>
</div>
</div>
<div class="pane" id="pane-releases" hidden>
<div class="grid c2">
<div class="card">
<div class="card-head"><h3>Release note</h3><span class="sub">what shipped; shows on /whats-new and every Overview</span></div>
<div style="display:grid;gap:8px">
<input type="hidden" id="rnId">
<label class="small">Title<input id="rnTitle" type="text" maxlength="120" placeholder="Achievement badges post to Telegram"></label>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
<label class="small">Date<input id="rnDate" type="date"></label>
<label class="small">Tags (new, improved, fixed)<input id="rnTags" type="text" placeholder="new, improved"></label>
</div>
<label class="small">Details (plain text; start a line with "- " for a bullet)<textarea id="rnBody" rows="6" style="width:100%"></textarea></label>
<div style="display:flex;gap:8px"><button type="button" class="btn small" id="rnSave">Save note</button><button type="button" class="btn small sec" id="rnClear">Clear</button></div>
</div>
</div>
<div class="card">
<div class="card-head"><h3>Roadmap item</h3><span class="sub">what is coming; "done" hides it from the public list</span></div>
<div style="display:grid;gap:8px">
<input type="hidden" id="rmId">
<label class="small">Title<input id="rmTitle" type="text" maxlength="120" placeholder="Second daily ad set"></label>
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px">
<label class="small">Status<select id="rmStatus"><option value="planned">planned</option><option value="building">building</option><option value="done">done</option></select></label>
<label class="small">ETA (free text)<input id="rmEta" type="text" placeholder="this week"></label>
<label class="small">Order<input id="rmOrder" type="number" min="1" placeholder="1"></label>
</div>
<label class="small">One-line note<input id="rmNote" type="text" maxlength="600" placeholder="why it matters"></label>
<div style="display:flex;gap:8px"><button type="button" class="btn small" id="rmSave">Save item</button><button type="button" class="btn small sec" id="rmClear">Clear</button></div>
</div>
</div>
</div>
<div class="grid c2">
<div class="card"><div class="card-head"><h3>Notes</h3><span class="sub" id="rnSub"></span></div><div class="tablewrap"><table class="adm-table" id="rnTable"></table></div></div>
<div class="card"><div class="card-head"><h3>Roadmap</h3><span class="sub" id="rmSub"></span></div><div class="tablewrap"><table class="adm-table" id="rmTable"></table></div></div>
</div>
<div class="card" id="updCard">
<div class="card-head"><h3>Email an update to members</h3><span class="sub" id="updSub"></span></div>
<p class="small muted" style="margin:0 0 10px">Pick the notes to include, add a line or two in your own words, preview, send yourself a test, then send. Plain text from no-reply@instantadpay.com, one member at a time. The default audience is members who ticked the newsletter box at sign-up (the Sendy list is the record); unsubscribes are skipped. Nothing goes out until you press Send.</p>
<div class="grid c2">
<div style="display:grid;gap:8px">
<label class="small">Subject<input id="updSubject" type="text" maxlength="150" placeholder="What is new on InstantAdPay this week"></label>
<label class="small">Intro (optional, plain text)<textarea id="updIntro" rows="4" style="width:100%" placeholder="Quick one. Three things shipped since my last note, and the third one is the one to try today."></textarea></label>
<label class="small">Closing (after the notes, e.g. your sign-off)<textarea id="updClosing" rows="2" style="width:100%" placeholder="See you Monday.&#10;&#10;Marty"></textarea></label>
<label class="small">Audience<select id="updAudience"></select></label>
<div style="display:flex;gap:8px;flex-wrap:wrap"><button type="button" class="btn small sec" id="updSaveDraft">Save draft</button><button type="button" class="btn small sec" id="updPreview">Preview</button><button type="button" class="btn small sec" id="updTest">Send test to me</button><button type="button" class="btn small" id="updSend">Send</button></div>
<pre id="updPre" class="small" hidden style="white-space:pre-wrap;background:var(--ink-faint);border:1px solid var(--line);border-radius:10px;padding:10px;max-height:320px;overflow:auto"></pre>
</div>
<div>
<div class="small muted" style="margin:0 0 6px">Release notes to include (newest first; notes since your last send are pre-ticked)</div>
<div id="updNotes" style="display:grid;gap:4px;max-height:260px;overflow:auto"></div>
<div class="small muted" style="margin:12px 0 6px">Recent sends</div>
<div class="tablewrap"><table class="adm-table" id="updLog"></table></div>
</div>
</div>
</div>
<p class="small muted">Public page: <a href="/whats-new" target="_blank" rel="noopener">instantadpay.com/whats-new</a></p>
</div>
<div class="pane" id="pane-pnl" hidden>
<div class="card">
<div class="card-head"><h3>Profit and loss</h3><span class="sub">read from the chain index; periods are by block (about 43,200 Polygon blocks a day)</span></div>
@@ -252,19 +516,102 @@
<div class="card-head"><h3>Where the money went</h3><span class="sub">per period</span></div>
<div class="tablewrap"><table class="adm-table" id="pnlSplit"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Game payouts</h3><span class="sub">all time, running total</span></div>
<div class="tablewrap"><table class="adm-table" id="pnlGames"></table></div>
<p class="small muted" style="margin:10px 0 0">Marketing spend: every POL send from each game's own payout wallet to a player, read from Polygon since the wallet's first transaction. Top-ups, moves between our wallets and returns to the fee wallets are left out. None of it passes through the ad contract, so it is not in the lines to the left.</p>
<details style="margin-top:10px"><summary class="small">PolHunter detail (its own ledger)</summary>
<div class="tablewrap"><table class="adm-table" id="pnlHunt"></table></div></details>
</div>
<div class="card">
<div class="card-head"><h3>Wallets</h3><span class="sub">live balances</span></div>
<div class="tablewrap"><table class="adm-table" id="pnlWallets"></table></div>
<p class="small muted" style="margin:10px 0 0">Fixed monthly cost (USD) for the net line: <input type="number" id="pnlFixed" min="0" step="1" style="width:110px"> <button class="btn small sec" type="button" id="pnlFixedSave">Save</button></p>
</div>
</div>
<div class="card">
<div class="card-head"><h3>Wallet ledger</h3><span class="sub">money in and out that the chain cannot explain</span></div>
<p class="small muted" style="margin:0 0 10px">The lines above come from contract events and live balances. Anything else that moves through a receiver goes here: outside income, money drawn out and spent, and your own funds parked for safekeeping. <b>Revenue</b> counts toward profit. <b>Draw</b> is house profit spent on something. <b>Transfer</b> moves the balance only and is never counted as earnings.</p>
<div id="pnlRecon" class="small" style="margin-bottom:10px"></div>
<div class="tablewrap"><table class="adm-table" id="pnlLedger"></table></div>
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin-top:12px">
<select id="ldDir"><option value="in">Money in</option><option value="out">Money out</option></select>
<select id="ldKind"><option value="revenue">Revenue</option><option value="cost">Cost</option><option value="draw">Draw</option><option value="transfer">Transfer</option></select>
<select id="ldCat" hidden><option value="advertising">Advertising</option><option value="games">Game marketing</option><option value="rewards">Player rewards</option><option value="software">Software and hosting</option><option value="other">Other cost</option></select>
<select id="ldWallet"><option value="feeA">Receiver A</option><option value="feeB">Receiver B</option><option value="engine">Engine</option><option value="hunt">PolHunter</option><option value="outside">Outside wallet</option></select>
<input type="number" id="ldAmount" min="0" step="0.0001" placeholder="Amount in POL">
<input type="number" id="ldUsd" min="0" step="0.01" placeholder="USD (optional)">
<input type="date" id="ldDate">
</div>
<div class="grid" style="grid-template-columns:1fr auto;gap:8px;margin-top:8px">
<input type="text" id="ldNote" maxlength="200" placeholder="What was this for? e.g. RM Circle #139 Culmen to Apex">
<button class="btn small" type="button" id="ldAdd">Add line</button>
</div>
</div>
<div class="card">
<div class="card-head"><h3>Tax summary</h3><span class="sub">income versus advertising and other costs, for one year</span></div>
<p class="small muted" style="margin:0 0 10px">Income is the platform's share of every package sale, valued at that sale's own dollar price, plus outside revenue. Sales to your own positions are left out. Costs are the ledger's Cost lines; game wallet top-ups are recorded there automatically as Player rewards. Draws and transfers are your money, not expenses, so they are listed apart.</p>
<p><select id="taxYear"></select> <button class="btn small" type="button" id="taxRun">Show</button> <button class="btn small sec" type="button" id="taxCsv" hidden>Copy CSV for your accountant</button></p>
<div id="taxOut" class="small"></div>
<textarea id="taxCsvText" hidden rows="6" style="width:100%;margin-top:8px" readonly></textarea>
</div>
<div class="card">
<div class="card-head"><h3>Automatic credit burner</h3><span class="sub">settles pending campaign spend on-chain from the engine wallet</span></div>
<p class="small" id="burnerLine">…</p>
<p><button class="btn small sec" type="button" id="burnerRun">Run now</button></p>
</div>
<div class="card">
<div class="card-head"><h3>Level 4 override</h3><span class="sub">3% of each purchase to the qualified 4th upline, paid weekly from the payer wallet</span></div>
<p class="small" id="ovPayer">…</p>
<div id="ovWeeks" class="small"></div>
<p><select id="ovWeek"></select> <button class="btn small sec" type="button" id="ovShow">Show week</button> <button class="btn small" type="button" id="ovPay" hidden>Pay this week now</button></p>
<div id="ovOut" class="small"></div>
</div>
</div>
<div class="pane" id="pane-gamepass" hidden>
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-top:0" id="gpStats"><p class="small muted">…</p></div>
<div class="grid c2" style="margin-top:16px">
<div class="card">
<div class="card-head"><h3>This week</h3><span class="sub" id="gpWeekSub"></span></div>
<div id="gpWeek" class="small">…</div>
</div>
<div class="card">
<div class="card-head"><h3>Pass Tournament</h3><span class="sub" id="gpTourSub"></span></div>
<div id="gpTour" class="small">…</div>
<p style="margin:12px 0 0;display:flex;gap:8px;flex-wrap:wrap"><button class="btn small sec" id="gpTourRun" type="button">Settle last week now</button></p>
</div>
</div>
<div class="card">
<div class="card-head"><h3>By pass tier</h3><span class="sub" id="gpTiersSub"></span></div>
<div id="gpTiers" class="small">…</div>
</div>
<div class="card" id="gpTestCard">
<div class="card-head"><h3>Tier test and preview</h3><span class="sub" id="gpTestSub">admin only · your own account</span></div>
<div id="gpTest" class="small">…</div>
</div>
<div class="card">
<div class="card-head"><h3>Pass sales</h3><span class="sub" id="gpSalesSub"></span></div>
<div id="gpSales" class="small">…</div>
</div>
<div class="card">
<div class="card-head"><h3>Comp a pass</h3><span class="sub">support: one pass period, recorded as no sale</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0"><input id="gpCompEmail" placeholder="member email" style="max-width:260px"><select id="gpCompTier"><option value="weekly">Game Pass (weekly)</option><option value="explorer">Explorer (monthly)</option><option value="champion">Champion (monthly)</option><option value="sovereign">Sovereign (monthly)</option><option value="legend">Legend (yearly)</option></select><input id="gpCompWhy" placeholder="why" style="max-width:220px"><button class="btn small" id="gpComp" type="button">Give one pass period</button><button class="btn small sec" id="gpRevoke" type="button">End this tier now (refund)</button></p>
</div>
<p class="small muted">Every pass is paid by a new package purchase of at least its price (since 2026-10-22; credits never buy a pass). The *PriceCredits settings are the pass price in cents. Settings live in Settings &rsaquo; Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Tiers above weekly: sovTiers (1/0, the sale switch for all of them; off = members never see them and the admin tests them in Tier test and preview above, never on the member card), gamePassExplorerEnabled / gamePassChampionEnabled / gamePassSovereignEnabled / gamePassLegendEnabled (0 stops one tier), gamePassExplorerPriceCredits (2000), gamePassChampionPriceCredits (5000), gamePassSovereignPriceCredits (10000), gamePassLegendPriceCredits (25000); since 2026-10-25 every tier price equals a one-click package ($5, $20, $50, $100, $250), gamePassExplorerDays / gamePassChampionDays / gamePassSovereignDays (30), gamePassLegendDays (365), passTournamentTierSales (1 = their sales feed the tournament pool; default 0). Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.</p>
</div>
<div class="pane" id="pane-settings" hidden>
<div class="card" id="kitCard">
<div class="card-head"><h3>Refuel Kit</h3><span class="sub" id="kitSub">monthly members-only banners: unlocked by a counted refuel (needs refuelStreak on)</span></div>
<p class="small muted">Five base images per month for this site's own program: 728x90, 300x250, 468x60, 160x600, 1200x630. Each member's @name and a QR to their own link are drawn on top: keep the right end clear on 728x90 and 468x60 (QR) with room for the name left of it, the bottom-right corner on 300x250 and 1200x630, and the bottom 170 px on 160x600. No income claims in any banner. Release on the 1st; a member unlocks the month's kit with their next counted refuel.</p>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center"><input id="kitMonth" placeholder="YYYY-MM" style="max-width:110px"><input id="kitTheme" placeholder="Theme (e.g. Harvest)" style="max-width:240px">
<button class="btn small" id="kitSave" type="button">Save kit</button><button class="btn small sec" id="kitPlaceholder" type="button">Use placeholder art (public/banners)</button></p>
<div id="kitSizes"></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px">Preview <select id="kitPrevSize"></select><input id="kitPrevName" placeholder="username" style="max-width:160px"><label class="small"><input type="checkbox" id="kitPrevGif" style="width:auto"> animated</label><button class="btn small sec" id="kitPreview" type="button">Preview</button></p>
<div id="kitPrevBox"></div>
<div id="kitList" class="small"></div>
<div id="kitBox"></div>
</div>
<div class="card">
<div class="card-head"><h3>Follow-up emails</h3><span class="sub" id="dripSub">sent to every new free member, hours after sign-up</span></div>
<p class="small muted">One card per email. Placeholders fill in per reader: click a chip to drop it where your cursor is.
@@ -305,7 +652,8 @@
</div>
</div>
<script src="/assets/common.js?v=20260910c"></script>
<script src="/assets/admin.js?v=20260910b"></script>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
</body>
</html>
+108
View File
@@ -0,0 +1,108 @@
// Admin > Knowledge base (2026-10-20, kb.js on the server): list, search, add, edit and delete the
// entries the chat assistant answers from, try a question against them, and take a support reply
// straight into a new entry (admin.js calls IAPKB.compose from a ticket's "Save as KB entry").
(function () {
const $ = IAP.$;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function api(path, body, method) {
const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
const r = await (await fetch(path, opts)).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
return r;
}
const ctDay = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', year: 'numeric' }) : '';
const SRC = { canned: 'from the code', faq: 'FAQ', ticket: 'from a ticket', admin: 'added here' };
let entries = [], filter = { q: '', src: '' }, wired = false;
function wire() {
if (wired) return; wired = true;
let t = null;
$('kbQ').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => { filter.q = $('kbQ').value.trim(); load().catch(e => IAP.status(e.message, 'bad')); }, 300); });
$('kbSrc').addEventListener('change', () => { filter.src = $('kbSrc').value; draw(); });
$('kbNew').addEventListener('click', () => compose({}));
$('kbTable').addEventListener('click', e => { const tr = e.target.closest('[data-kbid]'); if (tr) edit(tr.dataset.kbid).catch(err => IAP.status(err.message, 'bad')); });
const go = async () => {
const q = $('kbTry').value.trim(); if (!q) return $('kbTry').focus();
const r = await api('/api/admin/kb/test', { question: q });
$('kbTryOut').innerHTML = (r.fast ? '<p style="margin:6px 0"><b>Instant answer:</b> ' + esc(r.fast.title) + ' <span class="mono muted">' + esc(r.fast.id) + '</span> (no AI call)</p>' : '<p style="margin:6px 0">No instant answer, so this goes to the AI with:</p>')
+ (r.ranked.length ? '<ol style="margin:4px 0 0 18px;padding:0">' + r.ranked.map(h => '<li' + (h.used ? '' : ' class="muted"') + '><a href="#" data-kbopen="' + esc(h.id) + '">' + esc(h.title) + '</a> <span class="mono">' + h.score + '</span>' + (h.used ? ' <b>used</b>' : '') + '</li>').join('') + '</ol>'
: '<p class="muted" style="margin:4px 0">No entry matches, so the assistant is told to say it is not sure and point to support.</p>');
};
$('kbTryGo').addEventListener('click', () => go().catch(e => IAP.status(e.message, 'bad')));
$('kbTry').addEventListener('keydown', e => { if (e.key === 'Enter') go().catch(err => IAP.status(err.message, 'bad')); });
$('kbTryOut').addEventListener('click', e => { const a = e.target.closest('[data-kbopen]'); if (a) { e.preventDefault(); edit(a.dataset.kbopen).catch(err => IAP.status(err.message, 'bad')); } });
}
async function load() {
wire();
$('kbEdit').hidden = true; $('kbList').hidden = false;
const r = await api('/api/admin/kb' + (filter.q ? '?q=' + encodeURIComponent(filter.q) : ''));
entries = r.entries || [];
$('kbSub').textContent = (r.stamp ? r.stamp.count : entries.length) + ' entries' + (r.stamp && r.stamp.updated ? ' · last change ' + r.stamp.updated : '');
draw();
}
function draw() {
const rows = entries.filter(e => !filter.src || e.source === filter.src);
$('kbTable').innerHTML = '<tr><th>Entry</th><th>Asked as</th><th>Source</th><th>Updated</th></tr>'
+ (rows.length ? rows.map(e => '<tr data-kbid="' + esc(e.id) + '" style="cursor:pointer"><td><b>' + esc(e.title) + '</b>' + (e.score != null ? ' <span class="small muted mono">' + e.score + '</span>' : '')
+ '<div class="small muted">' + esc(String(e.answer).slice(0, 140)) + (String(e.answer).length > 140 ? '…' : '') + '</div>'
+ ((e.tags || []).length ? '<div class="small" style="margin-top:3px">' + e.tags.map(t => '<span class="house-tag" style="margin:0 4px 0 0">' + esc(t) + '</span>').join('') + '</div>' : '') + '</td>'
+ '<td class="small">' + (e.questions || []).slice(0, 3).map(esc).join('<br>') + ((e.questions || []).length > 3 ? '<br><span class="muted">+' + (e.questions.length - 3) + ' more</span>' : '') + '</td>'
+ '<td class="small">' + esc(SRC[e.source] || e.source) + (e.pattern ? '<div class="muted">instant</div>' : '') + (e.ticketRef ? '<div class="mono muted">' + esc(e.ticketRef) + '</div>' : '') + (e.edited && e.source !== 'admin' && e.source !== 'ticket' ? '<div class="muted">edited</div>' : '') + '</td>'
+ '<td class="small muted" style="white-space:nowrap">' + esc(ctDay(e.updated)) + '</td></tr>').join('')
: '<tr><td colspan="4" class="muted">No entries here.</td></tr>');
}
async function edit(id) { const r = await api('/api/admin/kb/' + encodeURIComponent(id)); compose(r.entry); }
// e: an existing entry (has id), or a prefill for a new one ({ title, questions, answer, tags, source, ticketRef })
function compose(e) {
wire();
e = e || {};
const isNew = !e.id;
$('kbList').hidden = true; $('kbEdit').hidden = false;
$('kbEdit').innerHTML = '<div class="card-head"><h3>' + (isNew ? 'New entry' : 'Edit entry') + '</h3><span class="sub mono">' + (isNew ? (e.ticketRef ? 'from ' + esc(e.ticketRef) : '') : esc(e.id) + ' · ' + esc(SRC[e.source] || e.source) + (e.ticketRef ? ' · ' + esc(e.ticketRef) : '') + ' · updated ' + esc(ctDay(e.updated))) + '</span></div>'
+ (e.source === 'ticket' && isNew ? '<p class="small" style="margin:0 0 10px;color:var(--amber,#ffb238)">Taken from a support reply. Take out names, emails, member numbers and anything about this one account before saving: entries are shown to the assistant for every member who asks something similar.</p>' : '')
+ (!isNew && (e.source === 'canned' || e.source === 'faq') && !e.edited ? '<p class="small muted" style="margin:0 0 10px">This entry comes from the code (chatbot.js or kb-seed.js) and follows it when the code changes. Saving it here makes it yours: later code changes to this entry are not applied.</p>' : '')
+ '<div style="display:grid;gap:10px">'
+ '<label class="small">Title<input id="kbTitle" maxlength="200" style="width:100%" value="' + esc(e.title || '') + '" placeholder="Can I use my regular Coinbase account?"></label>'
+ '<label class="small">Question variants, one per line (how members actually ask it)<textarea id="kbQs" rows="4" style="width:100%">' + esc((e.questions || []).join('\n')) + '</textarea></label>'
+ '<label class="small">Answer (plain words, no em dashes, never a promise of income; full https links)<textarea id="kbAns" rows="8" maxlength="4000" style="width:100%">' + esc(e.answer || '') + '</textarea></label>'
+ '<label class="small">Tags, comma separated<input id="kbTags" style="width:100%" value="' + esc((e.tags || []).join(', ')) + '" placeholder="coinbase, exchange account, wallet"></label>'
+ '<label class="small"><input type="checkbox" id="kbHandoff"' + (e.handoff ? ' checked' : '') + '> Offer "Send this to support" under this answer</label>'
+ '<details' + (e.pattern ? ' open' : '') + '><summary class="small">Instant answer (advanced)</summary>'
+ '<p class="small muted" style="margin:6px 0">A regular expression (case-insensitive). When a question matches it, this answer is sent as is, with no AI call. The lowest order number wins when several match; the code seeds use 10, 20, 30 and so on. Leave it empty to answer through the AI only.</p>'
+ '<div style="display:grid;grid-template-columns:1fr 110px;gap:8px"><input id="kbPat" class="mono small" value="' + esc(e.pattern || '') + '" placeholder="(coinbase account|regular coinbase)"><input id="kbOrd" class="small" type="number" value="' + (e.order == null ? '' : esc(e.order)) + '" placeholder="order"></div></details>'
+ '</div>'
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 0"><button type="button" class="btn small" id="kbSave">' + (isNew ? 'Add entry' : 'Save') + '</button><button type="button" class="btn small sec" id="kbCancel">Cancel</button>'
+ (isNew ? '' : '<button type="button" class="btn small sec" id="kbDel" style="margin-left:auto">Delete</button>') + '</p>';
$('kbCancel').addEventListener('click', () => { load().catch(err => IAP.status(err.message, 'bad')); });
$('kbSave').addEventListener('click', async () => {
const b = $('kbSave'); if (b.disabled) return; b.disabled = true;
try {
const body = { title: $('kbTitle').value, questions: $('kbQs').value.split('\n'), answer: $('kbAns').value, tags: $('kbTags').value.split(','),
handoff: $('kbHandoff').checked, pattern: $('kbPat').value, order: $('kbOrd').value, source: e.source, ticketRef: e.ticketRef };
if (isNew) await api('/api/admin/kb', body); else await api('/api/admin/kb/' + encodeURIComponent(e.id), body, 'PUT');
IAP.status(isNew ? 'Entry added. The assistant uses it from the next question.' : 'Entry saved.', 'ok');
await load();
} catch (err) { IAP.status(err.message, 'bad'); } finally { b.disabled = false; }
});
if ($('kbDel')) $('kbDel').addEventListener('click', async () => {
if (!(await IAP.confirmBox('Delete "' + (e.title || e.id) + '"? The assistant stops using it right away.', { ok: 'Delete', cancel: 'Keep it' }))) return;
try { await api('/api/admin/kb/' + encodeURIComponent(e.id), undefined, 'DELETE'); IAP.status('Entry deleted.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); }
});
$('kbTitle').focus();
}
// a support reply, tidied into a draft: the greeting and sign-off go, the member's words become the question
function fromTicket(t, question, reply) {
const q = String(question || '').replace(/^[\s\S]*?\bMe: /, '').split(/\nAssistant: /)[0].replace(/\s+/g, ' ').trim().slice(0, 300);
const a = String(reply || '').replace(/^\s*(hi|hello|hey|dear|good (morning|afternoon|evening))\b[^\n]*\n+/i, '')
.replace(/\n+\s*(thanks|thank you|cheers|best|regards|kind regards|talk soon|marty)\b[\s\S]{0,80}$/i, '').trim();
const title = String(t.subject || '').replace(/^Chat:\s*/i, '').trim().slice(0, 200) || q.slice(0, 120);
const tags = String(t.category || '').toLowerCase().split(/\s*&\s*|\s*,\s*/).filter(x => x && x !== 'other');
return { title, questions: q ? [q] : [], answer: a, tags, source: 'ticket', ticketRef: t.ref };
}
window.IAPKB = { load: () => load(), compose, fromTicket };
})();
+40
View File
@@ -0,0 +1,40 @@
// Admin > Settings > Refuel Kit (2026-10-24). The SAME file ships in InstantAdPay and LinkSpin. Upload one month's base art
// (five sizes, this site's own program), preview the personalization (@name + QR to the member's link), then release it.
// Keep the QR corner and the name strip clear in the art (see the layout note on the card).
(function () {
const $ = id => document.getElementById(id);
if (!$('kitBox')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const say = m => { $('kitSub').textContent = m; };
const api = async (url, opt) => { const r = await fetch(url, Object.assign({ cache: 'no-store' }, opt || {})); const j = await r.json().catch(() => ({})); if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status)); return j; };
const post = (url, body) => api(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
const nextMonth = () => { const d = new Date(); const ct = new Date(d.toLocaleString('en-US', { timeZone: 'America/Chicago' })); ct.setDate(1); ct.setMonth(ct.getMonth() + 1); return ct.getFullYear() + '-' + String(ct.getMonth() + 1).padStart(2, '0'); };
let sizes = [];
async function load() {
try {
const d = await api('/api/admin/kits'); sizes = d.sizes;
if (!$('kitMonth').value) $('kitMonth').value = nextMonth();
$('kitList').innerHTML = d.kits.length ? d.kits.map(k => '<div style="border:1px solid var(--line,#ccd);border-radius:8px;padding:10px;margin:8px 0">'
+ '<b>' + esc(k.label) + '</b> ' + (k.theme ? '&middot; ' + esc(k.theme) + ' ' : '') + '<span class="small muted">(' + esc(k.month) + ')</span> '
+ (k.released ? '<span class="badge">released</span>' : '<span class="badge amber">draft</span>') + '<div class="small" style="margin:6px 0">'
+ k.sizes.map(s => s.size + ': ' + (s.ready ? 'ready' : '<b>missing</b>')).join(' &middot; ') + '</div>'
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small sec" type="button" data-kedit="' + esc(k.month) + '" data-theme="' + esc(k.theme) + '">Edit</button>'
+ '<button class="btn small' + (k.released ? ' sec' : '') + '" type="button" data-krel="' + esc(k.month) + '" data-on="' + (k.released ? '0' : '1') + '"' + (!k.complete && !k.released ? ' disabled title="upload all five sizes first"' : '') + '>' + (k.released ? 'Unrelease' : 'Release to members') + '</button></div></div>').join('') : '<p class="small muted">No kits yet.</p>';
$('kitList').querySelectorAll('[data-kedit]').forEach(b => b.addEventListener('click', () => { $('kitMonth').value = b.dataset.kedit; $('kitTheme').value = b.dataset.theme; say('editing ' + b.dataset.kedit); }));
$('kitList').querySelectorAll('[data-krel]').forEach(b => b.addEventListener('click', async () => { try { await post('/api/admin/kits', { month: b.dataset.krel, released: b.dataset.on === '1' }); load(); } catch (e) { say(e.message); } }));
$('kitSizes').innerHTML = sizes.map(s => '<label class="small" style="display:block;margin:4px 0">' + s + ' <input type="file" accept="image/png,image/jpeg,image/gif" data-ksize="' + s + '"></label>').join('');
$('kitSizes').querySelectorAll('[data-ksize]').forEach(inp => inp.addEventListener('change', async () => {
const f = inp.files && inp.files[0]; if (!f) return; const m = $('kitMonth').value.trim();
try { await api('/api/admin/kits/upload?month=' + encodeURIComponent(m) + '&size=' + inp.dataset.ksize, { method: 'POST', headers: { 'Content-Type': f.type }, body: f }); say(inp.dataset.ksize + ' uploaded for ' + m); load(); } catch (e) { say(e.message); }
}));
$('kitPrevSize').innerHTML = sizes.map(s => '<option>' + s + '</option>').join('');
} catch (e) { say('Could not load: ' + e.message); }
}
$('kitSave').addEventListener('click', async () => { try { await post('/api/admin/kits', { month: $('kitMonth').value.trim(), theme: $('kitTheme').value }); say('saved'); load(); } catch (e) { say(e.message); } });
$('kitPlaceholder').addEventListener('click', async () => { try { const r = await post('/api/admin/kits/placeholder', { month: $('kitMonth').value.trim() }); say('placeholder art: ' + r.sizes.join(', ')); load(); } catch (e) { say(e.message); } });
$('kitPreview').addEventListener('click', () => {
const q = 'month=' + encodeURIComponent($('kitMonth').value.trim()) + '&size=' + encodeURIComponent($('kitPrevSize').value) + '&username=' + encodeURIComponent($('kitPrevName').value || 'yourname') + ($('kitPrevGif').checked ? '&variant=gif' : '') + '&t=' + Date.now();
$('kitPrevBox').innerHTML = '<img alt="preview" style="max-width:100%;border:1px solid var(--line-strong)" src="/api/admin/kits/preview?' + q + '">';
});
load();
})();
+64
View File
@@ -0,0 +1,64 @@
// Admin > Members > Sponsor check (2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
// Lists members on both sites whose sponsor differs (or is set on one side only), with when and how each side's sponsor
// was set and whether each side is bound on its contract. "Use X's sponsor" applies X's sponsor on the OTHER site; the
// server refuses when the member is already bound there. Nothing runs until the admin presses "Run the check".
(function () {
const $ = id => document.getElementById(id);
if (!$('scRun')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit', invited: 'the member named who invited them' };
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
function side(f) {
if (!f) return '<span class="muted">no account</span>';
const sp = f.sponsorEmail ? esc(f.sponsorName || f.sponsorEmail) + '<br><span class="small muted">' + esc(f.sponsorEmail) + '</span>' : f.deadLink ? '<span class="badge amber">dead link: ' + esc(f.sponsorRef) + '</span>' : '<span class="muted">none (in the tank)</span>';
const how = [];
if (f.prov) how.push('<b>' + esc(HOW[f.prov.by] || f.prov.by) + '</b> ' + esc(day(f.prov.at)) + (f.prov.origin ? ' on ' + esc(NAME[f.prov.origin] || f.prov.origin) : '') + (f.prov.prevEmail ? ', before: ' + esc(f.prov.prevEmail) : ''));
else how.push('no deliberate change on record; account made ' + esc(day(f.created)) + (f.joinedVia ? ' via ' + esc(f.joinedVia) : '') + (f.joinedRef ? ' (' + esc(f.joinedRef) + ')' : ''));
for (const a of (f.adoptions || []).slice(-3)) how.push('tank: ' + esc(a.status) + ' by ' + esc(a.adopter) + ' ' + esc(day(a.ts)));
if (f.remoteTank && f.remoteTank.open) how.push('adopted on the other site by ' + esc(f.remoteTank.adopterEmail));
if (f.pending) how.push('<span class="badge amber">follow waiting: ' + esc(f.pending.why || '') + '</span>');
for (const l of (f.log || []).filter(x => x.conflict).slice(0, 2)) how.push('<span class="badge amber">' + esc(l.action) + '</span> ' + esc(l.reason || '') + ' ' + esc(day(l.ts)));
const bound = f.bound ? '<span class="badge">bound on chain' + (f.memberId ? ': member #' + f.memberId : '') + (f.activation ? ', on-chain sponsor #' + f.activation.sponsorId + ', block ' + f.activation.block : '') + '</span>' : '<span class="muted small">not bound on chain' + (f.wallet ? ' (wallet linked)' : '') + '</span>';
return sp + '<div class="small" style="margin-top:4px">' + how.join('<br>') + '</div><div style="margin-top:4px">' + bound + '</div>';
}
let last = null;
async function run() {
$('scRun').disabled = true; $('scSub').textContent = 'checking both sites...';
try {
const r = await (await fetch('/api/admin/sponsor-check', { cache: 'no-store' })).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
last = r;
if (r.peerError) { $('scSub').textContent = 'could not read the other site: ' + r.peerError; $('scTable').innerHTML = ''; return; }
const differ = r.rows.filter(x => x.kind === 'differ').length;
$('scSub').textContent = r.shared + ' on both sites, ' + r.same + ' match, ' + differ + ' differ, ' + (r.rows.length - differ) + ' set on one side only (' + day(r.at) + ')';
$('scTable').innerHTML = '<tr><th>Member</th><th>InstantAdPay sponsor</th><th>LinkSpin sponsor</th><th>Settle it</th></tr>' + (r.rows.length ? r.rows.map(x => {
const iapBound = !!(x.iap && x.iap.bound), lsBound = !!(x.ls && x.ls.bound);
return '<tr><td>' + esc(x.username ? '@' + x.username : '') + '<br><span class="small muted">' + esc(x.email) + '</span><br><span class="small muted">' + esc(x.kind === 'differ' ? 'different sponsors' : x.kind === 'iap-only' ? 'sponsor on InstantAdPay only' : 'sponsor on LinkSpin only') + '</span></td>'
+ '<td>' + side(x.iap) + '</td><td>' + side(x.ls) + '</td><td class="act">'
+ '<button class="btn small sec" data-scuse="instantadpay" data-email="' + esc(x.email) + '"' + (lsBound ? ' disabled title="bound on the LinkSpin contract: its sponsor there cannot change"' : '') + '>Use InstantAdPay\'s sponsor</button><br>'
+ '<button class="btn small sec" style="margin-top:6px" data-scuse="linkspin" data-email="' + esc(x.email) + '"' + (iapBound ? ' disabled title="bound on the InstantAdPay contract: its sponsor there cannot change"' : '') + '>Use LinkSpin\'s sponsor</button></td></tr>';
}).join('') : '<tr><td colspan="4" class="muted">Every shared member has the same sponsor on both sites.</td></tr>');
const logs = [].concat((r.follow && r.follow.recent) || []).map(l => Object.assign({ where: r.here }, l)).concat(((r.peerFollow && r.peerFollow.recent) || []).map(l => Object.assign({ where: r.here === 'linkspin' ? 'instantadpay' : 'linkspin' }, l))).sort((a, b) => b.ts - a.ts).slice(0, 60);
$('scLog').innerHTML = '<tr><th>When</th><th>Site</th><th>Member</th><th>What</th><th>From</th><th>To</th><th>Why</th></tr>' + (logs.length ? logs.map(l => '<tr><td class="when">' + esc(day(l.ts)) + '</td><td>' + esc(NAME[l.where] || l.where) + '</td><td class="small">' + esc(l.email || '') + '</td><td>' + (l.conflict ? '<span class="badge amber">' + esc(l.action) + '</span>' : esc(l.action)) + (l.by ? ' <span class="small muted">' + esc(HOW[l.by] || l.by) + '</span>' : '') + '</td><td class="small">' + esc(l.from || '-') + '</td><td class="small">' + esc(l.to || '(tank)') + '</td><td class="small muted">' + esc(l.reason || '') + '</td></tr>').join('') : '<tr><td colspan="7" class="muted">nothing yet</td></tr>');
} catch (e) { $('scSub').textContent = e.message; say(e.message, 'bad'); }
finally { $('scRun').disabled = false; }
}
$('scRun').addEventListener('click', run);
document.addEventListener('click', async e => {
const b = e.target.closest('[data-scuse]'); if (!b || b.disabled) return;
const use = b.dataset.scuse, email = b.dataset.email; const row = last && last.rows.find(x => x.email === email); if (!row) return;
const from = use === 'instantadpay' ? row.iap : row.ls; const target = use === 'instantadpay' ? 'LinkSpin' : 'InstantAdPay';
const who = from && from.sponsorEmail ? (from.sponsorName || from.sponsorEmail) : 'no sponsor (back to the holding tank)';
let ok = false;
try { ok = await IAP.confirmBox('Set ' + email + "'s sponsor on " + target + ' to ' + who + '? The other site keeps what it has. This is refused if the member is already bound on the ' + target + ' contract.', { title: 'Use ' + NAME[use] + "'s sponsor", ok: 'Apply on ' + target, cancel: 'Cancel' }); } catch (err) { ok = false; }
if (!ok) return;
b.disabled = true;
try {
const r = await (await fetch('/api/admin/sponsor-check/resolve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, use }) })).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
say('Done: ' + email + ' now has ' + who + ' on ' + target + '.', 'ok'); await run();
} catch (err) { say(err.message, 'bad'); b.disabled = false; }
});
})();
+908 -20
View File
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
// BixPay guide (/bixpay, 2026-10-29): the CTA carries the viewer's resolved partner link (their own when signed in, else the
// member whose ?ref brought them here or whose sponsor cookie they carry, else the network link), always through the counted
// /go/bixpay link. The server already folded ?ref into the sponsor cookie; the ref is passed along too so the first view resolves.
// In-app browsers (Gmail, Telegram, Facebook webviews): BIX's register page runs a Cloudflare check that often fails there, and
// the invite token lives only in the URL, so a member who then reopens BIX elsewhere registers with no sponsor (bizventures,
// 2026-10-29: referrer N/A). Those viewers get a notice with the link to copy into a real browser.
(function () {
var cta = document.getElementById('bixCta'), using = document.getElementById('bixUsing'), soon = document.getElementById('bixSoon');
var box = document.getElementById('bixInApp'), boxLink = document.getElementById('bixInAppLink'), boxCopy = document.getElementById('bixInAppCopy');
if (!cta) return;
function inApp() {
var u = navigator.userAgent || '';
if (/FBAN|FBAV|FB_IAB|Instagram|Line\/|Twitter|Snapchat|GSA\/|Telegram|\bwv\b|WebView/i.test(u)) return true;
return /iPhone|iPad|iPod/.test(u) && !/Safari\//.test(u); // an iOS web view: no Safari token
}
var ref = '';
try { ref = new URLSearchParams(location.search).get('ref') || ''; } catch (e) { ref = ''; }
fetch('/api/public/bixpay' + (ref ? '?ref=' + encodeURIComponent(ref) : ''), { credentials: 'same-origin' }).then(function (r) { return r.json(); }).then(function (d) {
if (!d || !d.live) { if (soon) soon.hidden = false; cta.href = '/my#wallet'; if (using) using.textContent = 'Sign in to your dashboard and open the Wallet tab.'; return; }
cta.href = d.go;
if (using) using.textContent = d.whose === 'you' ? 'The button opens your own BixPay partner link.' : d.whose === 'sponsor' ? 'The button opens ' + d.name + "'s BixPay partner link." + (d.signedIn ? ' Add yours in Members > Profile.' : '') : 'The button opens the network’s BixPay partner link.' + (d.signedIn ? ' Add yours in Members > Profile.' : '');
if (box && inApp()) {
box.hidden = false;
if (boxLink) boxLink.textContent = d.go;
if (boxCopy) boxCopy.addEventListener('click', function () {
var done = function () { boxCopy.textContent = 'Copied'; setTimeout(function () { boxCopy.textContent = 'Copy link'; }, 2000); };
var select = function () { try { var r = document.createRange(); r.selectNodeContents(boxLink); var s = window.getSelection(); s.removeAllRanges(); s.addRange(r); boxCopy.textContent = 'Selected: copy it'; } catch (e) {} }; // no native dialogs
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(d.go).then(done, select);
else select();
});
}
}).catch(function () {});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+19
View File
@@ -0,0 +1,19 @@
// public blog pages: the shared nav (with wallet status) and footer, nothing else
(function () { try { IAP.renderNav(location.pathname.indexOf('/leaderboard') === 0 ? 'leaderboard' : 'blog'); } catch (e) {} })();
// Viral links (2026-09-21): a signed-in member sees this article's address with their own ?ref= on the
// end, and the share buttons carry it too. Whoever opens it is tagged to them like an invite link.
(async function () {
try {
const share = document.querySelector('p.share'); if (!share) return;
const me = await (await fetch('/api/me')).json();
const tok = me && me.signedIn && (me.username || me.refCode); if (!tok) return;
const link = 'https://instantadpay.com' + location.pathname + '?ref=' + encodeURIComponent(tok);
share.querySelectorAll('a').forEach(a => { a.href = a.href.replace(encodeURIComponent('https://instantadpay.com' + location.pathname), encodeURIComponent(link)); });
const bar = document.createElement('div');
bar.id = 'viralBar';
bar.style.cssText = 'margin-top:18px;padding:12px 14px;border:1px solid var(--line);border-radius:12px;background:var(--ink-faint);display:flex;gap:10px;align-items:center;flex-wrap:wrap';
bar.innerHTML = '<div style="flex:1;min-width:220px"><div class="eyebrow" style="margin:0 0 4px">Your link for this article</div><div class="mono small" style="overflow-wrap:anywhere">' + link.replace(/[&<>]/g, '') + '</div><div class="muted small" style="margin-top:4px">Share this and anyone who joins from it is yours, same as your invite link.</div></div><button class="btn small" type="button">Copy link</button>';
bar.querySelector('button').onclick = async () => { try { await navigator.clipboard.writeText(link); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy failed.', 'bad'); } };
share.parentNode.insertBefore(bar, share);
} catch (e) {}
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

+122
View File
@@ -0,0 +1,122 @@
// Chasing Unicorns (Marty, 2026-11-12): a promo-tool lead magnet. A fake earnings dashboard where every button, tile and popup
// is one of the classic scam warning signs; clicking one reveals it and scores the visitor's "scam radar", and the ending
// contrasts the unicorn with how InstantAdPay works. Shared as /chasing-unicorns?ref=<username> (the viral ?ref= link sets the
// sponsor cookie server-side). Nothing here touches an account: it is all made up on the page.
(function () {
var $ = function (id) { return document.getElementById(id); };
var usd = function (n) { return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); };
var calm = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var FLAGS = {
daily: { name: 'A fixed daily return', short: 'Guaranteed % a day on your deposit',
h: 'Nobody pays a fixed 3% a day.', p: 'That is over 4 million percent a year, compounded. No business earns that. The only way to pay a fixed daily return is with the next person\'s deposit.',
tell: 'Your "interest" is a line of code adding to a number. Watch it: it goes up even though nothing happened.', do: 'Ask what the product is and who buys it. If the answer is "the return", walk away.' },
withdraw: { name: 'Withdrawals that never arrive', short: 'Always "processing"',
h: 'Withdrawal processing... forever.', p: 'Deposits are instant. Withdrawals need "verification", a "maintenance window", a new minimum. That is how a site with no money buys time.',
tell: 'The balance on screen is not money. Money is what lands in your own wallet or bank.', do: 'Withdraw a small amount early. If $20 is a hostage negotiation, you have your answer.' },
vip: { name: 'Pay to unlock your own money', short: 'Upgrade or "release fee" first',
h: 'Pay $199 to unlock your own $25,000?', p: 'The "upgrade", the "tax", the "release fee", a "small miner fee" or "gas fee". It always sounds minor next to the balance waiting for you. It is the oldest trick: the balance is bait, and the fee is the real product. Some sites are free right up until the countdown ends, then everybody gets the fee at once.',
tell: 'If the money were there, they would take the fee out of it. They want new money from you instead.', do: 'Never pay to withdraw. A real balance pays its own fees.' },
team: { name: 'The product is recruiting', short: 'Paid mainly for sign-ups',
h: '+$500 per sign-up. Paid with what?', p: 'If you earn for bringing people in and nobody is buying anything real, the money for your bonus comes from the people you brought in.',
tell: 'A team bonus with no product is your friends\' deposits with your name on them.', do: 'Ask: if nobody new joined tomorrow, where would the money come from?' },
clock: { name: 'The clock is always ticking', short: 'Countdowns and "spots left"',
h: 'The countdown resets. It always does.', p: 'Urgency is there to stop you thinking and to get you recruiting before you check anything. Watch the timer: when it hits zero, it starts over.',
tell: 'A good opportunity is still there after you sleep on it. A bad one needs you not to.', do: 'Wait 48 hours and search the name plus "withdrawal" and "scam" first.' },
coin: { name: 'Paid in their own coin', short: 'Tokens you cannot sell anywhere real',
h: '48,000 UYP, worth whatever they say.', p: 'A token you can only "sell" back on their own site is Monopoly money with better branding. They print it, they price it, they decide when you can sell.',
tell: '"Soon x100" is a promise from the people holding all the supply.', do: 'Check whether it trades anywhere real, with real volume, and who holds most of it.' },
keys: { name: 'Anything that touches your keys', short: '"Connect wallet to claim"',
h: 'Connect wallet to claim? That is the scam.', p: 'Claim pages ask you to sign an approval that lets them spend your tokens. Some ask for your seed phrase outright. Nobody legit ever needs either.',
tell: 'One signature can empty a wallet. The "airdrop" is the bait.', do: 'Never type a seed phrase into a website. Read what a signature approves before you sign it.' },
proof: { name: 'Fake social proof', short: 'People "cashing out" every few seconds',
h: '"Dave from Denver just withdrew $19,350."', p: 'These popups are a few lines of code picking a random name and a random amount. They are on scam sites because they work on all of us.',
tell: 'A popup is not a receipt. A transaction you can look up is.', do: 'Ask for a payment you can verify yourself, on a public ledger, not a screenshot.' }
};
var ORDER = ['daily', 'withdraw', 'vip', 'team', 'clock', 'coin', 'keys', 'proof'];
var seen = [];
// the visitor's sponsor rides the share link (?ref=), so the join button and the share line keep it
var ref = (new URLSearchParams(location.search).get('ref') || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
// where the page link was posted (?src=massifly, ?src=leasedadspace...) rides into the join, so a sign-up says which channel
var chan = (new URLSearchParams(location.search).get('src') || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 18);
var srcTag = chan ? 'unicorns-' + chan : 'chasing-unicorns';
$('joinBtn').href = '/join?src=' + srcTag;
if (ref) {
$('joinBtn').href = '/join/' + ref + '?src=' + srcTag;
$('ledgerBtn').href = '/ledger?ref=' + ref;
$('shareLink').textContent = 'https://instantadpay.com/chasing-unicorns?ref=' + ref;
}
// radar
var dots = $('dots'); ORDER.forEach(function () { dots.appendChild(document.createElement('i')); });
function renderRadar() {
[].forEach.call(dots.children, function (d, i) { d.className = i < seen.length ? 'on' : ''; });
$('score').textContent = seen.length + ' of 8';
$('endH').textContent = seen.length === 8 ? 'Scam radar: 8 of 8. You are a unicorn hunter.' : 'Your scam radar: ' + seen.length + ' of 8 red flags spotted';
$('flags').innerHTML = ORDER.map(function (k) { var f = FLAGS[k]; return '<li class="' + (seen.indexOf(k) >= 0 ? 'on' : '') + '"><b>' + f.name + '</b><span class="fine">' + f.short + '</span></li>'; }).join('');
document.querySelectorAll('[data-flag]').forEach(function (b) { b.classList.toggle('done', seen.indexOf(b.getAttribute('data-flag')) >= 0); });
if (seen.length >= 3) $('after').hidden = false;
}
renderRadar();
// the reveal card
var lastFocus = null;
function reveal(k) {
var f = FLAGS[k]; if (!f) return;
if (seen.indexOf(k) < 0) seen.push(k);
renderRadar();
$('cardK').textContent = 'Red flag ' + seen.length + ' of 8 spotted: ' + f.name;
$('cardH').textContent = f.h; $('cardP').textContent = f.p;
$('cardTell').textContent = f.tell; $('cardDo').textContent = 'What to do: ' + f.do;
$('cardNext').textContent = seen.length === 8 ? 'See my result' : 'Keep hunting';
lastFocus = document.activeElement; $('veil').hidden = false; $('cardNext').focus();
}
function closeCard(toEnd) {
$('veil').hidden = true;
if (toEnd || seen.length === 8) $('end').scrollIntoView({ behavior: calm ? 'auto' : 'smooth', block: 'start' });
else if (lastFocus) lastFocus.focus();
}
document.querySelectorAll('[data-flag]').forEach(function (b) { b.addEventListener('click', function () { reveal(b.getAttribute('data-flag')); }); });
$('cardNext').addEventListener('click', function () { closeCard(false); });
$('cardEnd').addEventListener('click', function () { closeCard(true); });
$('veil').addEventListener('click', function (e) { if (e.target === $('veil')) closeCard(false); });
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !$('veil').hidden) closeCard(false); });
$('showAll').addEventListener('click', function () { ORDER.forEach(function (k) { if (seen.indexOf(k) < 0) seen.push(k); }); renderRadar(); $('after').scrollIntoView({ behavior: calm ? 'auto' : 'smooth', block: 'start' }); });
$('copyShare').addEventListener('click', function () {
var t = $('shareLink').textContent, b = $('copyShare');
navigator.clipboard.writeText(t).then(function () { b.textContent = 'Copied'; }, function () { var r = document.createRange(); r.selectNodeContents($('shareLink')); var s = getSelection(); s.removeAllRanges(); s.addRange(r); b.textContent = 'Press Ctrl+C'; });
});
// the ticking balance: 3% a day of $25,000, out of thin air
var START = 25000, perSec = START * 0.03 / 86400, t0 = performance.now(), midnight = new Date(); midnight.setHours(0, 0, 0, 0);
function tick() {
var gain = (performance.now() - t0) / 1000 * perSec;
$('bal').textContent = usd(START + gain);
$('rate').textContent = '+3.00% daily compound interest · +' + usd(gain) + ' since you opened this page';
$('today').textContent = usd((Date.now() - midnight.getTime()) / 1000 * perSec);
}
tick(); setInterval(tick, calm ? 1000 : 100);
// the countdown that starts over at zero, and spots that never run out
var LEN = 600, end = Date.now() + LEN * 1000, spots = 3;
setInterval(function () {
var left = Math.round((end - Date.now()) / 1000);
if (left <= 0) { end = Date.now() + LEN * 1000; left = LEN; spots = 3; }
else if (left % 89 === 0 && spots > 1) spots--;
$('clock').textContent = String(Math.floor(left / 60)).padStart(2, '0') + ':' + String(left % 60).padStart(2, '0');
$('spots').textContent = 'Only ' + spots + ' VIP spot' + (spots === 1 ? '' : 's') + ' left';
}, 1000);
// fake "cash out" popups every few seconds: random made-up names and amounts
var who = ['Jessica from Ohio', 'Mike in Texas', 'Priya from London', 'Carlos in Miami', 'Ahmed from Dubai', 'Linda in Phoenix', 'Tom from Sydney', 'Grace in Toronto', 'Dave from Denver', 'Nina in Berlin', 'Kwame from Accra', 'Rosa in Manila'];
var what = ['just withdrew', 'just cashed out', 'just earned', 'just got a team bonus of'];
function pop() {
var n = who[Math.floor(Math.random() * who.length)], amt = Math.round((Math.random() * 40000 + 1500) / 10) * 10;
$('pAv').textContent = n.charAt(0);
$('pT').innerHTML = n + ' ' + what[Math.floor(Math.random() * what.length)] + ' <b>' + usd(amt) + '</b> ' + (1 + Math.floor(Math.random() * 9)) + ' min ago';
$('proof').classList.add('on');
setTimeout(function () { $('proof').classList.remove('on'); }, 4500);
}
setTimeout(function () { pop(); setInterval(pop, 8000); }, 3000);
})();
+63 -2
View File
@@ -1,4 +1,6 @@
// 24/7 assistant widget: floating bubble, slide-up panel, /api/chat.
// Hand-off (help desk, 2026-10-16): when the answer cannot help, or they ask for a person, the widget offers
// "Send this to support", which files the last few turns as a ticket (members: their Help pane; signed out: their email).
(function () {
const root = document.createElement('div');
root.id = 'iapChat';
@@ -7,10 +9,11 @@
+ '<div class="ch-head"><b>Ask anything</b><span class="ch-sub">Real answers, around the clock</span>'
+ '<button id="iapChatClose" aria-label="Close chat" type="button">×</button></div>'
+ '<div class="ch-msgs" id="iapChatMsgs">'
+ '<div class="ch-m bot">Hey. Ask me how the payments work, what the packages buy, or anything else. Straight answers only, no income hype.</div>'
+ '<div class="ch-m bot">Hey. Ask me how the payments work, what the packages buy, or anything else. Straight answers only, no income hype. Need a person instead? Tap <b>Send this to support</b> below, or use the <a href="/support" style="color:inherit;text-decoration:underline">support page</a>.</div>'
+ '</div>'
+ '<div class="ch-input"><input id="iapChatIn" placeholder="Type your question…" maxlength="600">'
+ '<button id="iapChatSend" type="button">Send</button></div>'
+ '<div style="text-align:center;font-size:12px;padding:4px 0 8px"><a href="#" id="iapChatHuman" style="color:inherit;opacity:.75">Need a person? Send this to support</a></div>'
+ '</div>';
document.body.appendChild(root);
@@ -18,6 +21,7 @@
const msgs = $('iapChatMsgs');
const input = $('iapChatIn');
let history = [];
const turns = []; // { who: 'me' | 'bot', text } for the support hand-off
const add = (text, who) => {
const d = document.createElement('div');
@@ -29,11 +33,18 @@
msgs.scrollTop = msgs.scrollHeight;
return d;
};
function offerHandoff() {
if (msgs.querySelector('.ch-handoff')) return;
const d = document.createElement('div'); d.className = 'ch-m bot ch-handoff';
d.innerHTML = '<button type="button" class="btn small" style="margin:0">Send this to support</button>';
d.querySelector('button').addEventListener('click', handoff);
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
}
async function send() {
const q = input.value.trim();
if (!q) return;
input.value = '';
add(q, 'me');
add(q, 'me'); turns.push({ who: 'me', text: q });
const wait = add('…', 'bot');
try {
const r = await (await fetch('/api/chat', { method: 'POST',
@@ -41,12 +52,61 @@
body: JSON.stringify({ message: q, history: history.slice(-4).join(' | ') }) })).json();
wait.remove();
add(r.reply || r.error || 'No answer came back. Try again.', 'bot');
if (r.reply) turns.push({ who: 'bot', text: r.reply });
history.push('Q: ' + q, 'A: ' + (r.reply || ''));
if (r.handoff) offerHandoff();
} catch (e) {
wait.remove();
add('Connection hiccup. Try that again.', 'bot');
offerHandoff();
}
}
async function post(body) {
const g = window.IAP && IAP.guard;
if (g) await g.formSettled();
return (await fetch('/api/support/chatbot', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.assign({ transcript: turns.slice(-8), fts: g ? g.FORM_TS : 0, fage: g ? Date.now() - g.FORM_TS : 0 }, body)) })).json();
}
function done(r) {
const old = msgs.querySelector('.ch-handoff'); if (old) old.remove();
const f = msgs.querySelector('.ch-hform'); if (f) f.remove();
add(r.member ? 'Sent to support as ticket ' + r.ref + '. Marty will reply in Help in your dashboard and by email: ' + location.origin + r.link
: 'Sent to support as ticket ' + r.ref + '. We emailed you a private link to follow it, and Marty will reply there: ' + location.origin + r.link, 'bot');
}
async function handoff(e) {
if (e && e.preventDefault) e.preventDefault();
if (msgs.querySelector('.ch-hform')) return;
let me = null; try { me = await (await fetch('/api/me')).json(); } catch (err) {}
if (me && me.signedIn && me.email) {
const ok = window.IAP && IAP.confirmBox ? await IAP.confirmBox('Send this chat to support as a ticket? Marty will reply in Help in your dashboard and by email.', { ok: 'Send it', cancel: 'Not now' }) : true;
if (!ok) return;
try { const r = await post({}); if (r.error) throw new Error(r.error); done(r); } catch (err) { add(err.message || 'Could not send it. Try the Help tab in your dashboard.', 'bot'); }
return;
}
// signed out: an email so Marty can reply, plus the same invisible walls as sign-up
const d = document.createElement('div'); d.className = 'ch-m bot ch-hform';
d.innerHTML = 'Where should Marty reply?'
+ '<input class="hp-field" type="text" tabindex="-1" aria-hidden="true" autocomplete="off" id="iapChatHp">'
+ '<input id="iapChatEmail" type="email" placeholder="your email" maxlength="190" autocomplete="email" style="width:100%;margin-top:6px;box-sizing:border-box">'
+ '<input id="iapChatNote" placeholder="anything to add (optional)" maxlength="600" style="width:100%;margin-top:6px;box-sizing:border-box">'
+ '<div id="iapChatCheck" hidden style="margin-top:6px"></div>'
+ '<button type="button" class="btn small" id="iapChatGo" style="margin-top:8px">Send to support</button> <span class="small" id="iapChatErr"></span>';
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
$('iapChatEmail').focus();
$('iapChatGo').addEventListener('click', async () => {
const btn = $('iapChatGo'); if (btn.disabled) return; btn.disabled = true; $('iapChatErr').textContent = '';
try {
let pick = null, r = null;
for (let i = 0; i < 4; i++) {
r = await post({ email: $('iapChatEmail').value.trim(), note: $('iapChatNote').value.trim(), hp_field_x9: window.IAP && IAP.guard ? IAP.guard.hpValue($('iapChatHp')) : '', pick });
if (r.challenge && window.IAP && IAP.guard) { pick = await IAP.guard.iconCheck($('iapChatCheck'), r.challenge, r.error); continue; }
break;
}
if (!r || r.error) throw new Error((r && r.error) || 'Could not send it.');
done(r);
} catch (err) { $('iapChatErr').textContent = err.message; btn.disabled = false; }
});
}
$('iapChatBtn').addEventListener('click', () => {
const p = $('iapChatPanel');
p.hidden = !p.hidden;
@@ -54,5 +114,6 @@
});
$('iapChatClose').addEventListener('click', () => { $('iapChatPanel').hidden = true; });
$('iapChatSend').addEventListener('click', send);
$('iapChatHuman').addEventListener('click', handoff);
input.addEventListener('keydown', e => { if (e.key === 'Enter') send(); });
})();
+216 -11
View File
@@ -29,10 +29,13 @@ window.IAP = (function () {
nav.innerHTML = '<div class="wrap">'
+ '<span class="logo-wrap"><a class="logo" href="/"><img src="/logo.png" alt="InstantAdPay" style="height:30px;display:block"></a><span class="byline">Brought to you by the <b>Crypto Team Build Network</b></span></span>'
+ '<span class="links">'
+ '<a href="/" data-p="home">How it works</a>'
+ '<a href="/#ladder" data-p="pricing">Ad packages</a>'
+ '<a href="/#how" data-p="home">How it works</a>'
+ '<a href="/presentation" data-p="presentation">Presentation</a>'
+ '<a href="/#packages" data-p="pricing">Ad packages</a>'
+ '<a href="/ledger" data-p="ledger">Live ledger</a>'
+ '<a href="/leaderboard" data-p="leaderboard">Leaderboard</a>'
+ '<a href="/contract" data-p="contract">The contract</a>'
+ '<a href="/support" data-p="support">Support</a>'
+ '<a href="/my" data-p="my">Members</a>'
+ '</span><span id="navWallet" class="muted">…</span></div>';
document.body.prepend(nav);
@@ -53,10 +56,37 @@ window.IAP = (function () {
f.style.cssText = 'border-top:1px solid var(--line);margin-top:48px;padding:26px 22px;text-align:center;color:var(--muted);font-size:13px';
f.innerHTML = '<div>© ' + new Date().getFullYear() + ' InstantAdPay</div>'
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
+ '<a href="/">How it works</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a>'
+ '<a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/disclaimer">Disclaimer</a></div>';
+ '<a href="/">How it works</a><a href="/presentation">Presentation</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a>'
+ '<a href="/facts">Platform facts</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a></div>'
+ '<div style="margin-top:10px">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</div>';
document.body.appendChild(f);
renderNetworkLine(f);
}
// "Part of the network" (Marty 2026-11-14 trust pack): the list comes from the hub through /api/network-sites, built-in copy if not
const NET_FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(a => ({ id: a[0], name: a[1], url: a[2] }));
let netList = null;
async function networkSites() {
if (!netList) netList = fetch('/api/network-sites').then(r => r.json()).then(l => (Array.isArray(l) && l.length ? l : NET_FALLBACK)).catch(() => NET_FALLBACK);
return netList;
}
function renderNetworkLine(host) {
if (!host || host.querySelector('.netline')) return;
const d = document.createElement('div'); d.className = 'netline';
d.style.cssText = 'margin-top:10px;display:flex;gap:6px 14px;justify-content:center;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
host.appendChild(d);
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[ch]);
const paint = list => {
d.innerHTML = '<b>Part of the network</b><span>One account across the network:</span>' + list.map(s => (s.id === 'iap' || /instantadpay\.com/.test(s.url))
? '<span aria-current="page" style="font-weight:700;color:var(--ink)">' + esc(s.name) + ' (you are here)</span>'
: '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join('');
};
paint(NET_FALLBACK);
networkSites().then(paint);
}
// pages with their own footer (the members area) get the network line too
function decorateFooters() { document.querySelectorAll('footer.bo-pagefoot').forEach(f => { const w = document.createElement('div'); w.style.width = '100%'; f.appendChild(w); renderNetworkLine(w); }); }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', decorateFooters); else decorateFooters();
async function refreshNavWallet() {
try {
const me = await (await fetch('/api/me')).json();
@@ -90,7 +120,7 @@ window.IAP = (function () {
case 'AdminPaid': return '🏛 platform fee settled: ' + pol(ev.amountWei);
case 'BuyerCounted': return '⭐ ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer(s)';
case 'MemberActivated': return '👤 ' + nm(ev.id) + ' activated a payout wallet';
case 'AwardPaid': return '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
case 'AwardPaid': return ev.override ? '🏅 Level 4 override' + (ev.overrideWeek ? ' (week of ' + ev.overrideWeek + ')' : '') + ': ' + pol(ev.amountWei) + ' → ' + nm(ev.toId) : '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
case 'CreditsConsumed': return '📣 ' + nm(ev.memberId) + ' ran ads: −' + ev.amount.toLocaleString() + ' credits';
case 'PriceCached': return '🔮 oracle price refreshed';
case 'FallbackPriceUsed': return '🔮 cached price bridged an oracle gap';
@@ -109,12 +139,18 @@ window.IAP = (function () {
}
// Render one served ad into #<elId>. Silent if no inventory.
// report an ad (auto-approved ads need a member-facing flag → admin notified)
function reportAd(campaignId) {
// 2026-09-16: was a native prompt() with 'broken' pre-filled, so a stray tap on OK filed a
// "broken" report with no note (campaign #27). Now the site dialog, no default, reason validated.
const REPORT_REASONS = ['broken', 'inappropriate', 'spam', 'scam', 'other'];
async function reportAd(campaignId) {
if (!campaignId) return;
const reason = (prompt('Report this ad. Reason: broken, inappropriate, spam, scam, or other', 'broken') || '').trim().toLowerCase();
if (!reason) return;
const note = prompt('Anything to add? (optional)') || '';
fetch('/api/report-ad', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ campaignId, reason, note }) })
const raw = await ask({ title: 'Report this ad', text: 'What is wrong with it? Type one: broken, inappropriate, spam, scam, or other.', placeholder: 'e.g. broken', ok: 'Next' });
if (raw === null) return;
const reason = String(raw || '').trim().toLowerCase();
if (!REPORT_REASONS.includes(reason)) { status('Pick one of: broken, inappropriate, spam, scam, or other.', 'bad'); return; }
const note = await ask({ title: 'Report: ' + reason, text: 'Tell the admin what you saw, so it can be fixed. Optional, but it helps.', type: 'textarea', ok: 'Send report' });
if (note === null) return;
fetch('/api/report-ad', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ campaignId, reason, note: String(note || '').slice(0, 500) }) })
.then(() => status('Thanks — this ad was reported to the admin for review.', 'ok'))
.catch(() => status('Could not send the report. Try again.', 'bad'));
}
@@ -143,5 +179,174 @@ window.IAP = (function () {
el.hidden = false;
} catch (e) {}
}
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, $ };
// ── sign-up code request with the invisible guard fields (form age + honeypot)
// and the icon check the server asks for only after an IP trips a limit ──
const FORM_TS = Date.now();
function iconCheck(host, ch, note) {
return new Promise(resolve => {
host.hidden = false;
host.innerHTML = '<div class="small" style="margin:0 0 8px">' + (note ? esc(note) + ' ' : '') + 'Tap the <b>' + esc(ch.prompt) + '</b>.</div>'
+ '<div class="icon-check">' + ch.options.map(o => '<button type="button" class="ic-btn">' + esc(o) + '</button>').join('') + '</div>';
host.querySelectorAll('.ic-btn').forEach(b => b.addEventListener('click', () => { host.innerHTML = ''; host.hidden = true; resolve(b.textContent); }, { once: true }));
});
}
// honeypot fields (join + sign-in): read-only until a trusted focus, so browser autofill and
// password managers leave them alone; a value that appeared without a trusted event is ignored
function armHoneypots() {
document.querySelectorAll('.hp-field').forEach(el => {
if (el.dataset.armed) return; el.dataset.armed = '1'; el.readOnly = true;
const touch = e => { if (e.isTrusted) { el.readOnly = false; el.dataset.touched = '1'; } };
el.addEventListener('focus', touch); el.addEventListener('input', touch); el.addEventListener('keydown', touch);
});
}
armHoneypots(); document.addEventListener('DOMContentLoaded', armHoneypots);
const hpValue = el => (el && el.dataset.touched === '1') ? (el.value || '') : '';
// The server refuses a code request that arrives within a couple of seconds of the page loading,
// because a script fills a form instantly and a person does not. A returning member whose email
// is already autofilled has nothing to type, taps straight away, and gets told off for being
// quick (Marty, 2026-09-23). So the page waits out the remainder itself: the person sees the
// normal sending state, and anything posting at the endpoint without a page behind it still
// fails the same check.
const MIN_FORM_MS = 2400; // the server wants 2000; leave headroom for clock skew in transit
function formSettled() {
const left = MIN_FORM_MS - (Date.now() - FORM_TS);
return left > 0 ? new Promise(r => setTimeout(r, left)) : Promise.resolve();
}
async function requestCode(email, opts) {
const o = opts || {};
let pick = null;
await formSettled();
for (let i = 0; i < 4; i++) {
const r = await (await fetch('/api/auth/email/start', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, fts: FORM_TS, fage: Date.now() - FORM_TS, hp_field_x9: hpValue(o.honeypot), pick, ref: o.ref || null, angle: o.angle || null, lsclk: o.lsclk || null }) })).json(); // ref = the join page's own link token, so the sponsor survives a lost cookie
if (r.challenge && o.host) { pick = await iconCheck(o.host, r.challenge, r.error); continue; }
if (r.error) throw new Error(r.error);
return r;
}
throw new Error('Could not verify. Refresh the page and try again.');
}
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
// ── founding-week checklist, read from the live account. Shared by /launch and
// the dashboard mark. Two items are the member's own call and persist locally.
const LAUNCH_KEY = 'iap.launch.manual';
const manualSet = () => { try { return new Set(JSON.parse(localStorage.getItem(LAUNCH_KEY) || '[]')); } catch (e) { return new Set(); } };
function launchToggle(key) { const s = manualSet(); if (s.has(key)) s.delete(key); else s.add(key); try { localStorage.setItem(LAUNCH_KEY, JSON.stringify([...s])); } catch (e) {} }
function launchChecks(me) {
const m = me || {}, man = manualSet();
const bc = Number(m.buyerCount || 0), refs = (m.referrals || []).length;
return [
{ key: 'username', title: 'Pick your username', done: !!m.username, href: '/my#profile', cta: 'Profile',
how: 'Profile tab. It becomes your invite link and your public page, and it is permanent.',
why: 'Every link, banner and video you hand out this week carries it. Change it later and the links you already sent die.' },
{ key: 'wallet', title: 'Link your wallet', done: !!m.address, href: '/my#wallet', cta: 'Wallet',
how: 'Wallet tab, Connect, sign the free message. MetaMask recommended. Never held crypto? The wallet guide in Training walks through buying POL with a card.',
why: 'Payouts go to this address. No wallet, nowhere to pay you.' },
{ key: 'payouts', title: 'Switch on payouts', done: !!m.memberId, href: '/my#wallet', cta: 'Wallet',
how: 'Wallet tab, one small transaction. It registers your address with the contract.',
why: 'The contract binds each buyer to their sponsor at their first purchase. If payouts are off when your first person buys, that commission is not yours.' },
{ key: 'level2', title: 'Qualify: open level 2', done: bc >= 2, href: '/my#buy', cta: 'Buy packages',
how: 'Two of your people buy a $20 or more package. Or use Qualified Start: add two positions from extra wallets in your own MetaMask and buy a $20 package from each (about $23 of POL in each wallet).',
why: 'Until you have two qualifying buyers, every level 2 payment from your team climbs past you.',
note: 'Qualifying buyers so far: <b>' + bc + '</b> of 2.' },
{ key: 'level3', title: 'The leader play: open all three levels', done: bc >= 5, href: '/my#buy', cta: 'Qualified Start',
how: 'Five qualifying buyers, real or Qualified Start, up to five linked positions. Once qualified, buy from your main wallet so your sponsor is paid in full.',
why: 'A leader whose team goes three deep this week collects level 3 from day one instead of watching those 10% payments pass upward. Optional for members, the play for leaders.',
note: 'Qualifying buyers so far: <b>' + bc + '</b> of 5.' },
{ key: 'banner', title: 'Upload your line banner', done: !!m.lineBannerUrl, href: '/my#profile', cta: 'Profile',
how: 'Profile tab, line banner. It shows on the welcome tour to everyone in your next three levels.',
why: 'Your first advertising to your own team, free, and it is live the moment they join.' },
{ key: 'links', title: 'Copy your links and pick a play', done: man.has('links'), manual: true,
how: 'Promo tools, Your links: the invite link and the five angle links, plus the matching hook videos. Then read the plays page and choose one.',
why: 'On launch day you send links, not explanations. Having them ready is the whole difference between a launch and a scramble.' },
{ key: 'two', title: 'Place your first two', done: refs >= 2, href: '/my#line', cta: 'My line',
how: 'Two people you have actually talked to, joined through your link, walked through items 1 to 3 on their own accounts.',
why: 'Your first two are the shape of your whole line. Choose them, do not wait for them.',
note: 'Joined through you so far: <b>' + refs + '</b>.' }
];
}
// In-page dialogs instead of window.prompt / confirm. Mobile Safari shows a red "Suppress dialogs"
// option on the second native pop-up in a row and, once tapped, swallows every later prompt on the
// site until reload. ask() resolves the typed value (null on cancel); confirmBox() resolves true/false.
function dialog(o) {
return new Promise(resolve => {
const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200';
const field = o.type === 'none' ? '' : o.type === 'textarea'
? '<textarea id="dlgInput" rows="5" style="width:100%;margin-top:12px">' + esc(o.value) + '</textarea>'
: '<input id="dlgInput" type="' + (o.type === 'number' ? 'number' : 'text') + '" ' + (o.type === 'number' ? 'inputmode="decimal" min="0" step="any" ' : '') + 'value="' + esc(o.value) + '" placeholder="' + esc(o.placeholder) + '" style="width:100%;margin-top:12px" autocomplete="off">';
back.innerHTML = '<div class="modal-card" role="dialog" aria-modal="true">' + (o.title ? '<h3 style="margin:0 0 8px">' + esc(o.title) + '</h3>' : '')
+ (o.text ? '<p class="muted small" style="margin:0;white-space:pre-line">' + esc(o.text) + '</p>' : '') + field
+ '<div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px;flex-wrap:wrap">' + (o.noCancel ? '' : '<button type="button" class="btn sec small" id="dlgCancel">' + esc(o.cancel || 'Cancel') + '</button>') + '<button type="button" class="btn small" id="dlgOk">' + esc(o.ok || 'OK') + '</button></div></div>';
document.body.appendChild(back);
const inp = back.querySelector('#dlgInput');
const done = v => { document.removeEventListener('keydown', onKey); back.remove(); resolve(v); };
const okv = () => done(o.type === 'none' ? true : (inp ? inp.value : ''));
const onKey = e => { if (e.key === 'Escape') { e.preventDefault(); done(o.type === 'none' ? false : null); } else if (e.key === 'Enter' && o.type !== 'textarea') { e.preventDefault(); okv(); } };
document.addEventListener('keydown', onKey);
back.querySelector('#dlgOk').addEventListener('click', okv);
if (back.querySelector('#dlgCancel')) back.querySelector('#dlgCancel').addEventListener('click', () => done(o.type === 'none' ? false : null));
back.addEventListener('click', e => { if (e.target === back) done(o.type === 'none' ? false : null); });
setTimeout(() => { if (inp) { inp.focus(); if (inp.select && o.type !== 'textarea') inp.select(); } else back.querySelector('#dlgOk').focus(); }, 30);
});
}
function ask(o) { return dialog(Object.assign({ type: 'text', value: '', placeholder: '' }, o || {})); }
function confirmBox(text, o) { return dialog(Object.assign({ type: 'none', text, ok: 'Yes', cancel: 'No' }, o || {})); }
// ── appearance (2026-11-01): Light / Dark / Auto, mirrored from LinkSpin. The head script (themehead.js) owns window.IAPTheme and
// localStorage iap.theme; this paints every .theme-seg on the page (member-area header, Profile pane, admin header), saves a
// click to the account when signed in (POST /api/my/profile {theme}), and at sign-in lets the account value win over the local
// one (a local choice is pushed up when the account has none yet). Pages without a .theme-seg still get the theme from the head script.
const THEME_VALUES = ['light', 'dark', 'auto'];
function storedTheme() { try { const v = localStorage.getItem('iap.theme'); return THEME_VALUES.includes(v) ? v : null; } catch (e) { return null; } }
function paintTheme() { const c = window.IAPTheme ? IAPTheme.get() : 'dark'; document.querySelectorAll('.theme-seg [data-theme]').forEach(b => { const on = b.dataset.theme === c; b.classList.toggle('on', on); b.setAttribute('aria-pressed', on ? 'true' : 'false'); }); }
const saveTheme = v => fetch('/api/my/profile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ theme: v }) }).catch(() => {});
function themeSync(m) { if (!window.IAPTheme) return; const acct = m && m.signedIn && THEME_VALUES.includes(m.theme) ? m.theme : null; const local = storedTheme(); if (acct) { if (acct !== local) IAPTheme.set(acct, true); } else if (m && m.signedIn && local) saveTheme(local); paintTheme(); }
// the controls only exist on signed-in surfaces (member-area shell, admin), so a click always tries the save; signed out it is a harmless 401
document.addEventListener('click', e => { const b = e.target.closest && e.target.closest('.theme-seg [data-theme]'); if (!b || !window.IAPTheme) return; const v = b.dataset.theme; IAPTheme.set(v); saveTheme(v); });
window.addEventListener('iap-theme', paintTheme);
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', paintTheme); else paintTheme();
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $, themeSync, paintTheme,
guard: { FORM_TS, iconCheck, hpValue, formSettled } }; // guard: the sign-up walls, reused by the support form and the chatbot hand-off
})();
// shown inside someone else's frame (traffic exchanges, 2026-10-03): sign-in, join and off-site links open in a new tab,
// because browsers refuse our session cookie inside another site's frame
(function () {
var framed = false; try { framed = window.top !== window.self; } catch (e) { framed = true; }
if (!framed) return;
// the sponsor this page was opened for (?ref=, /join/<tok>, /wall/<tok>); its cookie was refused in the frame, so the
// new tab gets it in the link and the viral-link rule sets it there
var ref = ''; try { ref = new URLSearchParams(location.search).get('ref') || (location.pathname.match(/^\/(?:join|wall)\/([^/?#]+)/) || [])[1] || ''; } catch (e) {}
ref = String(ref).toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
document.addEventListener('click', function (e) {
var a = e.target && e.target.closest && e.target.closest('a[href]'); if (!a) return;
var h = a.getAttribute('href') || ''; if (h.charAt(0) === '#' || /^javascript:/i.test(h)) return;
var sign = a.host === location.host && /^\/(my|join|signin|login|from|admin)(\/|$)/.test(a.pathname);
if (sign && ref && a.pathname === '/my' && !/[?&]ref=/.test(a.search)) a.search = (a.search ? a.search + '&' : '?') + 'ref=' + ref;
if (sign || a.host !== location.host) { a.target = '_blank'; a.rel = 'noopener'; }
}, true);
})();
// Level 4 override copy (2026-10-23): blocks marked data-when="override-live" stay hidden until the site setting
// overrideMode is 'live' and overrideGoLive is set; [data-ov-start] gets the start date in Central time
(function () {
var els = document.querySelectorAll('[data-when="override-live"]'); if (!els.length || !window.IAP) return;
IAP.getConfig().then(function (c) {
if (String(c.overrideMode || '') !== 'live' || !Number(c.overrideGoLive)) return;
var d = new Date(Number(c.overrideGoLive)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'long', day: 'numeric', year: 'numeric' });
document.querySelectorAll('[data-ov-start]').forEach(function (e) { e.textContent = d; });
els.forEach(function (e) { e.hidden = false; });
}).catch(function () {});
})();
// Network links (2026-11-13): a click on a link to LinkSpin goes through /go/linkspin, which signs a signed-in member in over there and is a
// plain redirect for everyone else. Rewritten at click time only, so links people copy to share stay clean. data-nogo opts a link out.
(function () {
if (window.__netlinks) return; window.__netlinks = 1;
const HOSTS = ['linkspin.app', 'www.linkspin.app'];
document.addEventListener('click', e => {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
if (!a || a.hasAttribute('download') || a.hasAttribute('data-nogo')) return;
let u; try { u = new URL(a.href); } catch (x) { return; }
if (u.protocol !== 'https:' || !HOSTS.includes(u.hostname)) return;
a.href = '/go/linkspin?to=' + encodeURIComponent(u.pathname + u.search + u.hash);
}, true);
})();
+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(); }
});
});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

+81
View File
@@ -0,0 +1,81 @@
/* Spooky Doors door: one verified visit (a member's page or ad), then back to the street with a signed receipt. */
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
var q = new URLSearchParams(location.search); var tok = q.get('t') || '';
var nonce = '', tokRet = '', game = 'spookydoors'; try { var claims = JSON.parse(atob(tok.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'))); nonce = claims.nonce || ''; tokRet = claims.ret || ''; if (claims.game === 'roadagent') game = 'roadagent'; } catch (e) {}
// Road Agent (2026-10-07) uses the same door as a fuel stop; the words change, the round trip does not
var RA = game === 'roadagent';
var W = RA ? { back: 'Back to the highway', unit: 'Fuel stop', name: 'Road Agent', home: 'https://roadagent.app/play', open: 'Open this page from a fuel stop in Road Agent.', waiting: 'Pulling into the fuel stop…', treat: ' has fuel for you.', treatSomeone: 'Visit counted. Fuel loaded.', house: 'A house ad: a smaller fuel bonus while the sponsors’ ads are resting. Stay on this page.', capTitle: 'That is tonight’s fuel stops', cap: 'You have used every fuel stop for today. Your scrap is safe, and the pumps open again at midnight Central.', none: 'This stop is closed: there are no sponsor pages or videos left for you right now. No fuel here, and this stop does not count. Head back and try again later.', noneTitle: 'Pumps are closed' }
: { back: 'Back to the street', unit: 'Door', name: 'Spooky Doors', home: 'https://spookydoors.com/play', open: 'Open this page by knocking on a door in Spooky Doors.', waiting: 'Someone is coming to the door…', treat: ' has a treat for you.', treatSomeone: 'Visit counted. Someone has a treat for you.', house: 'A house ad: a smaller treat while the street’s ads are resting. Stay on this page.', capTitle: 'That is tonight’s doors', cap: 'You have knocked on every door for today. Your candy is safe, and the doors open again at midnight Central.', none: 'The lights are out at this house: there are no member pages or videos left for you right now. No candy here, and this door does not count. Head back and try the next house.', noneTitle: 'Nobody’s home' };
if (RA) { document.body.classList.add('ra'); var bb0 = document.getElementById('sdBrand'); if (bb0) bb0.textContent = W.name; var t0 = document.getElementById('sdTitle'); if (t0) t0.textContent = W.waiting; document.title = 'Fuel stop · Road Agent verified visit'; var kk = document.querySelector('#sdFrame h1'); if (kk) { kk.textContent = 'Fuel stop'; kk.nextElementSibling.textContent = 'Pulling in...'; } }
// every dead end on this page keeps a way back to the street
var gameHome = tokRet ? tokRet.split('?')[0] : W.home;
var dwell = 8, left = 8, timer = null;
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); }
function msg(title, text, backUrl, auto) {
$('sdFrame').innerHTML = '<div class="dr-msg"><div class="in"><h1>' + esc(title) + '</h1><p>' + esc(text) + '</p></div></div>';
$('sdDone').hidden = true; $('sdCheck').hidden = true; $('sdRow').hidden = true;
var b = $('sdBack'); b.hidden = false; var to = backUrl || gameHome; b.textContent = W.back; b.onclick = function () { location.href = to; };
if (auto && backUrl) setTimeout(function () { location.href = backUrl; }, 2500);
}
function api(p, body) { return fetch(p, body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : {}).then(function (r) { return r.json(); }); }
function ring() { $('sdN').textContent = left; $('sdRing').style.setProperty('--p', ((dwell - left) / dwell * 100) + '%'); }
function tick() {
if (document.hidden) return; // the timer only runs while the page is in front
var vid = document.getElementById('sdVideo'); if (vid && (vid.paused || vid.ended && left > 1)) return; // a video must actually be playing
left--; if (left > 0) return ring();
clearInterval(timer); ring(); $('sdHint').textContent = 'One quick check to count the visit:';
challenge();
}
function challenge() {
api('/api/door/challenge?n=' + encodeURIComponent(nonce)).then(function (c) {
if (c.early) { setTimeout(challenge, (c.wait || 1) * 1000 + 300); return; }
if (c.error) { $('sdHint').textContent = c.error; return; }
$('sdPrompt').textContent = 'Tap the ' + c.prompt + ':'; var w = $('sdOpts'); w.innerHTML = '';
c.options.forEach(function (em, i) { var b = document.createElement('button'); b.type = 'button'; b.textContent = em; b.setAttribute('aria-label', 'Option ' + (i + 1)); b.addEventListener('click', function () { answer(i); }); w.appendChild(b); });
$('sdCheck').hidden = false;
});
}
function answer(i) {
api('/api/door/done', { n: nonce, answer: i }).then(function (r) {
if (r.error) {
if (r.retry) return challenge();
if (r.cap && r.ret) return msg(W.capTitle, W.cap, r.ret, true);
$('sdHint').textContent = r.error; $('sdCheck').hidden = true; var bb = $('sdBack'); bb.hidden = false; bb.onclick = function () { location.href = gameHome; }; return;
}
$('sdCheck').hidden = true; $('sdHint').textContent = r.golden ? 'Visit counted. Golden Door! ' + (r.host ? '@' + r.host + ' has' : 'Someone has') + ' a treat for you, plus ' + (r.bonus || 0) + ' bonus candy.' : r.house ? 'Visit counted. A smaller treat from ' + (r.program || 'the house') + ' is on its way.' : r.host ? 'Visit counted. @' + r.host + W.treat : W.treatSomeone;
var b = $('sdDone'); b.disabled = false; b.textContent = W.back; b.onclick = function () { location.href = r.ret; };
setTimeout(function () { location.href = r.ret; }, 1200);
});
}
if (!tok) return msg(RA ? 'No fuel stop here' : 'No door here', W.open);
api('/api/door/open?t=' + encodeURIComponent(tok)).then(function (r) {
if (r.error) return msg('Door link problem', r.error);
if (r.done) { location.href = r.ret; return; }
if (r.none) return r.why === 'cap'
? msg(W.capTitle, W.cap + ' Your regular InstantAdPay visits are not affected.', r.ret, true)
: msg(W.noneTitle, W.none, r.ret, true);
dwell = r.dwell || 8; left = Math.max(1, dwell - (r.elapsed || 0));
if (r.doors && r.doors.cap) { var ch = $('sdDoors'); ch.textContent = W.unit + ' ' + Math.min(r.doors.cap, (r.doors.used || 0) + 1) + ' of ' + r.doors.cap; ch.hidden = false; }
var who = r.house ? 'House ad' : r.host ? '@' + r.host + (RA ? '’s stop' : '’s door') : (RA ? 'A sponsor’s stop' : 'A member’s door');
if (r.golden) { document.body.classList.add('gold'); $('sdGold').hidden = false; who = 'Golden Door! ' + who; } // gold variant: bonus candy on this one
if (r.mode === 'video') { // no member pages left: a member video ad instead
$('sdTitle').textContent = who + ': ' + (r.title || 'member video'); $('sdUrl').textContent = 'video ad';
$('sdHint').textContent = 'You have visited every member page running right now, so this ' + (RA ? 'stop' : 'door') + ' is a short member video. Keep it playing.';
var v = document.createElement('video'); v.id = 'sdVideo'; v.src = r.video.url; v.autoplay = true; v.muted = true; v.playsInline = true; v.setAttribute('playsinline', ''); v.loop = true; v.controls = false;
v.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000';
$('sdFrame').innerHTML = ''; $('sdFrame').appendChild(v);
var un = document.createElement('button'); un.type = 'button'; un.textContent = 'Tap for sound'; un.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:2;padding:8px 12px;border-radius:8px;border:0;background:rgba(0,0,0,.6);color:#fff;font:600 12px system-ui';
un.onclick = function () { v.muted = false; v.play().catch(function () {}); un.remove(); }; $('sdFrame').appendChild(un);
v.play().catch(function () { $('sdHint').textContent = 'Tap the video to start it. The timer runs while it plays.'; v.onclick = function () { v.play(); }; });
ring(); timer = setInterval(tick, 1000); return;
}
$('sdTitle').textContent = who + ': ' + (r.title || 'member site'); try { $('sdUrl').textContent = new URL(r.target).hostname; } catch (e) {}
if (r.house) $('sdHint').textContent = W.house;
if (r.golden) $('sdHint').textContent = 'A Golden Door: this one comes with ' + (r.bonus || 0) + ' bonus candy. Stay on this page; the timer only runs while it is in front.';
var f = document.createElement('iframe'); f.src = r.target; f.setAttribute('referrerpolicy', 'no-referrer'); f.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups'); $('sdFrame').innerHTML = ''; $('sdFrame').appendChild(f);
var o = $('sdOpen'); o.href = r.target; o.hidden = false;
ring(); timer = setInterval(tick, 1000);
}).catch(function () { msg(RA ? 'Could not open the fuel stop' : 'Could not open the door', RA ? 'Check your connection and go back to the highway.' : 'Check your connection and go back to the street.'); });
})();
+82
View File
@@ -0,0 +1,82 @@
// 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)
// a link to the other site goes through this site's /go/<other> hop (network sign-in, 2026-11-12): the member arrives signed in
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 '/go/' + (FROM === 'iap' ? 'linkspin' : 'iap') + '?to=' + encodeURIComponent(u.pathname + u.search + u.hash); } 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:var(--warn,#e8a317)}.er-dot.green{background:var(--ok,#2fa36b)}.er-dot.amber{background:var(--warn,#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 ? 'var(--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
})();
+37
View File
@@ -0,0 +1,37 @@
/* /friday status strip (Marty, 2026-09-25). External file on purpose: the site's CSP blocks
inline scripts, which is how the first deploy shipped a strip stuck on "Checking". */
(function () {
var el = document.getElementById('frState');
if (!el) return;
function n(x) { return Number(x || 0).toLocaleString('en-US'); }
// the minute (Central) when the next Friday starts, found by scanning rather than assumed,
// so a daylight-saving change cannot put the countdown an hour out
function startsAt(dayKey) {
var now = Date.now();
for (var m = 0; m < 8 * 1440; m++) {
var t = now + m * 60000;
var d = new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
if (d === dayKey) return t;
}
return null;
}
function render(f) {
if (!f || !f.on) { el.innerHTML = '<span class="fr-tag">Paused</span><span>Five Dollar Friday is not running right now. Join free and you will hear when it is back.</span>'; return; }
if (f.live) {
var t = f.today || {};
el.className = 'fr-state live';
el.innerHTML = '<span class="fr-tag">Live now</span><span><b>It is Five Dollar Friday.</b> Bonus runs until midnight Central.</span>'
+ '<span><span class="fr-num">' + n(t.packs) + '</span> pack' + (t.packs === 1 ? '' : 's') + ' so far today</span>'
+ '<span><span class="fr-num">' + n(t.bonusCredits) + '</span> bonus credits issued</span>';
return;
}
var at = f.nextFriday ? startsAt(f.nextFriday) : null;
var left = at ? Math.max(0, at - Date.now()) : 0;
var hrs = Math.floor(left / 3600000), mins = Math.floor((left % 3600000) / 60000), days = Math.floor(hrs / 24);
var when = at ? (days >= 1 ? days + ' day' + (days === 1 ? '' : 's') + ' ' + (hrs % 24) + 'h' : hrs + 'h ' + mins + 'm') : '';
el.className = 'fr-state';
el.innerHTML = '<span class="fr-tag">Next</span><span><b>Next Five Dollar Friday: ' + (f.nextLabel || f.nextFriday || 'soon') + '.</b> Starts at midnight Central' + (when ? ', in ' + when : '') + '.</span>'
+ '<span>Join now so your account is ready before it starts.</span>';
}
fetch('/api/friday').then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }).then(render);
})();
+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="/go/linkspin?to=%2Fcredits%3Ffrom%3Diap%26task%3Drefuel%23refuel" 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();
})();
+235
View File
@@ -0,0 +1,235 @@
/* InstantAdPay in-game sign-in kit (2026-10-03). Served by instantadpay.com, loaded by each game's own /signin page,
so a player signs in (or opens a free InstantAdPay account) without leaving the game. Talks to /api/game/auth/*
from the player's browser; the game only ever receives its normal hand-off token, which it opens at /auth.
Host page sets theme through CSS variables on .iapsi (--si-*). Usage:
IAPSignin.mount(el, { game: 'driprunner', ref: 'skycash', oneTap: 'https://instantadpay.com/api/my/driprunner' });
IAPSignin.enter('wallet'); // nudge: opens InstantAdPay in a new tab, already signed in
After a fresh sign-in (never on a remembered pass) the kit shows the InstantAdPay login ad before the hand-off,
same as the dashboard: sponsor card, Open Ad (a counted click), 10 s countdown, then Continue. Any ad error,
or no ad to show, goes straight to the game. mount option loginAd: false switches it off (2026-10-18). */
(function () {
var IAP = 'https://instantadpay.com';
try { var me = document.currentScript && document.currentScript.src; if (me) IAP = new URL(me).origin; } catch (e) {}
var PASS_KEY = 'iap.gamepass', DEV_KEY = 'iap.gdev';
function ls(k, v) { try { if (v === undefined) return localStorage.getItem(k); if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch (e) { return null; } }
function devId() { var d = ls(DEV_KEY); if (!/^[a-f0-9]{32}$/.test(d || '')) { d = ''; var a = new Uint8Array(16); (window.crypto || window.msCrypto).getRandomValues(a); for (var i = 0; i < 16; i++) d += ('0' + a[i].toString(16)).slice(-2); ls(DEV_KEY, d); } return d; }
function getPass() { try { var p = JSON.parse(ls(PASS_KEY) || 'null'); return p && p.p && p.exp > Date.now() ? p : null; } catch (e) { return null; } }
// the one-tap link carries the inviter's ref too, so a new player who taps it still gets their sponsor (2026-10-05)
function oneTapUrl(opt) { var u = String(opt.oneTap || ''), r = String(opt.ref || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); if (!r || /[?&]ref=/.test(u)) return u; return u + (u.indexOf('?') < 0 ? '?' : '&') + 'ref=' + encodeURIComponent(r); }
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }
function post(path, body) {
return fetch(IAP + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), credentials: 'omit' })
.then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { j._status = r.status; return j; }); })
.catch(function () { return { _status: 0, error: 'Could not reach InstantAdPay. Check your connection and try again.' }; });
}
var CSS = '.iapsi{--a:var(--si-accent,#7c5cff);--ai:var(--si-accent-ink,#fff);--ink:var(--si-ink,#f2efff);--mu:var(--si-muted,#b7b0d6);--fl:var(--si-field,rgba(255,255,255,.06));--ln:var(--si-line,rgba(255,255,255,.18));color:var(--ink);font-family:var(--si-font,system-ui,sans-serif);display:grid;gap:14px}'
+ '.iapsi h2{margin:0;font-size:22px;line-height:1.2}.iapsi p{margin:0;color:var(--mu);font-size:14.5px;line-height:1.5}.iapsi b{color:var(--ink)}'
+ '.iapsi label.f{display:grid;gap:6px;font-size:13px;color:var(--mu)}.iapsi input.t{font:inherit;font-size:17px;padding:12px 14px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);color:var(--ink);width:100%;box-sizing:border-box}'
+ '.iapsi input.t:focus{outline:2px solid var(--a);outline-offset:1px}.iapsi input.code{letter-spacing:.4em;text-align:center;font-size:22px}'
+ '.iapsi .go{font:inherit;font-weight:700;font-size:16px;padding:13px 16px;border:0;border-radius:12px;background:var(--a);color:var(--ai);cursor:pointer;width:100%}.iapsi .go[disabled]{opacity:.55;cursor:default}'
+ '.iapsi .lk{background:none;border:0;padding:0;font:inherit;font-size:13.5px;color:var(--mu);text-decoration:underline;cursor:pointer}.iapsi .lk[disabled]{opacity:.5;cursor:default;text-decoration:none}'
+ '.iapsi form{display:grid;gap:12px;margin:0}.iapsi .row{display:flex;gap:14px;flex-wrap:wrap;justify-content:space-between}.iapsi label.ck{display:flex!important;gap:10px;align-items:flex-start;font-size:13px;color:var(--mu);margin:0}.iapsi .ck input{margin:3px 0 0;width:auto!important;flex:0 0 auto;height:auto;padding:0}.iapsi .ck span{flex:1}.iapsi .err:empty{display:none}'
+ '.iapsi .err{color:var(--si-bad,#ff8a8a);font-size:14px;min-height:1px}.iapsi .fine{font-size:12px;color:var(--mu)}.iapsi .fine a{color:var(--mu)}'
+ '.iapsi .hp{position:absolute;left:-9999px;width:1px;height:1px;opacity:0}.iapsi .chal{display:flex;gap:8px;flex-wrap:wrap}.iapsi .chal button{font-size:26px;width:52px;height:52px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);cursor:pointer}'
// login-ad gate (full screen, above the game page)
+ '.iapla{position:fixed;inset:0;z-index:2147483000;display:flex;flex-direction:column;background:var(--si-ground,#0d0b1a);color:var(--si-ink,#f2efff);font-family:var(--si-font,system-ui,sans-serif)}'
+ '.iapla-bar{display:flex;align-items:center;gap:10px 14px;flex-wrap:wrap;padding:10px 16px;background:var(--si-panel,#17142b);border-bottom:1px solid var(--si-line,rgba(255,255,255,.18))}'
+ '.iapla-brand{font-weight:800;font-size:15px;white-space:nowrap}.iapla-brand em{color:var(--si-accent,#7c5cff);font-style:normal}.iapla-note{flex:1;min-width:140px;font-size:13px;color:var(--si-muted,#b7b0d6)}'
+ '.iapla-timer{font-weight:700;font-size:14px;border:1px solid var(--si-line,rgba(255,255,255,.3));border-radius:999px;padding:4px 12px;white-space:nowrap}.iapla-timer.done{color:var(--si-accent,#7c5cff);border-color:var(--si-accent,#7c5cff)}'
+ '.iapla-btn{font:inherit;font-weight:700;font-size:14px;padding:9px 14px;border:0;border-radius:10px;background:var(--si-accent,#7c5cff);color:var(--si-accent-ink,#fff);cursor:pointer;text-decoration:none;white-space:nowrap}'
+ '.iapla-btn.sec{background:transparent;color:var(--si-ink,#f2efff);border:1px solid var(--si-line,rgba(255,255,255,.3))}.iapla-btn[disabled]{opacity:.55;cursor:default}.iapla-btn.big{font-size:17px;padding:13px 22px}'
+ '.iapla-frame{flex:1;border:0;width:100%;background:#fff;min-height:0}.iapla-body{flex:1;display:grid;place-items:center;padding:24px 16px;overflow:auto}'
+ '.iapla-card{max-width:560px;text-align:center;display:grid;gap:16px;justify-items:center}.iapla-card p{margin:0;font-size:14px;line-height:1.5;color:var(--si-muted,#b7b0d6)}'
+ '.iapla-eye{font-size:12px;letter-spacing:.12em;text-transform:uppercase}.iapla-card img{max-width:100%;max-height:50vh;border-radius:12px;border:1px solid var(--si-line,rgba(255,255,255,.18))}'
+ '.iapla-link{display:inline-block;font-size:20px;font-weight:700;color:var(--si-ink,#f2efff);background:var(--si-field,rgba(255,255,255,.06));border:1px solid var(--si-line,rgba(255,255,255,.18));border-radius:14px;padding:18px 22px}'
+ '.iapla [hidden]{display:none!important}';
function styleOnce() { if (document.getElementById('iapsiCss')) return; var s = document.createElement('style'); s.id = 'iapsiCss'; s.textContent = CSS; document.head.appendChild(s); }
// the login ad after a fresh sign-in. `then` (the hand-off) always runs exactly once: when the gate is done,
// when there is no ad, or on any error or a slow answer, so an ad can never hold a player out of the game.
function loginAd(game, then) {
var over = false; function go() { if (over) return; over = true; try { then(); } catch (e) {} }
var ctl = null; try { ctl = new AbortController(); } catch (e) {}
var slow = setTimeout(function () { if (ctl) try { ctl.abort(); } catch (e) {} go(); }, 7000);
fetch(IAP + '/api/game/ads/login?game=' + encodeURIComponent(game || ''), { credentials: 'omit', signal: ctl ? ctl.signal : undefined })
.then(function (r) { return r.ok ? r.json() : {}; })
.then(function (j) { clearTimeout(slow); if (over) return; var ad = j && j.ad; if (!ad || !ad.targetUrl) return go(); gate(ad, go); })
.catch(function () { clearTimeout(slow); go(); });
}
function gate(ad, go) {
var abs = function (u) { return /^https?:/i.test(u) ? u : IAP + u; };
var click = abs(ad.targetUrl), site = ad.siteUrl || click, framed = !!ad.frameable, started = false, t = null;
var g = document.createElement('div'); g.className = 'iapla'; g.setAttribute('role', 'dialog'); g.setAttribute('aria-label', 'Login sponsor');
g.innerHTML = '<div class="iapla-bar"><span class="iapla-brand">Instant<em>AdPay</em></span>'
+ '<span class="iapla-note" data-st>Login ad sponsor. Tap "Open Ad" to begin.</span>'
+ '<span class="iapla-timer" data-tm hidden></span>'
+ '<a class="iapla-btn sec" data-tab target="_blank" rel="noopener" hidden>Open site in a new tab \u2197</a>'
+ '<button class="iapla-btn" type="button" data-go hidden>Continue to the game</button></div>'
+ '<iframe class="iapla-frame" data-fr hidden sandbox="allow-scripts allow-same-origin allow-forms allow-popups" referrerpolicy="no-referrer" title="Sponsor site"></iframe>'
+ '<div class="iapla-body" data-bd><div class="iapla-card"><p class="iapla-eye">Today\'s login sponsor</p>'
+ (ad.imageUrl ? '<img src="' + esc(ad.imageUrl) + '" alt="sponsor ad">' : '<span class="iapla-link">' + esc(ad.title || 'Visit today\'s sponsor') + '</span>')
+ '<button class="iapla-btn big" type="button" data-open>Open Ad</button>'
+ '<p>' + (framed ? 'The sponsor\'s page opens right here under this bar. When the timer hits zero, your Continue button appears beside it.'
: 'This sponsor\'s site opens in a new tab. The timer counts down here; come back when it hits zero to continue to the game.') + '</p></div></div>';
var q = function (k) { return g.querySelector('[data-' + k + ']'); };
var st = q('st'), tm = q('tm'), tab = q('tab'), btn = q('go'), fr = q('fr'), bd = q('bd'), open = q('open');
function finish() { clearInterval(t); document.removeEventListener('securitypolicyviolation', csp); try { g.remove(); } catch (e) {} go(); }
// a game page whose CSP refuses the frame: offer the sponsor in a new tab instead (the timer keeps running)
function csp(ev) {
if (!started || !framed || !/frame|child|default/.test(String(ev.violatedDirective || ev.effectiveDirective || ''))) return;
var b = String(ev.blockedURI || '');
fr.hidden = true; bd.hidden = true; tab.hidden = false;
tab.href = (!b || b.indexOf(IAP) === 0) ? click : site; // blocked before our click relay ran: the tab is the counted click
st.textContent = 'This game cannot show the sponsor here. Open it in a new tab; the timer runs here.';
}
document.addEventListener('securitypolicyviolation', csp);
open.addEventListener('click', function () {
if (started) return; started = true; open.disabled = true;
if (framed) {
fr.src = click; // the click relay counts it, then redirects inside the frame
fr.hidden = false; bd.hidden = true; tab.href = site; tab.hidden = false;
st.textContent = 'Today\'s sponsor. Have a look; your Continue button appears when the timer ends.';
} else {
try { window.open(click, '_blank'); } catch (e) {} // the click relay counts it
st.textContent = 'The sponsor opened in a new tab. View it and come back; the timer runs here.';
}
var left = Math.max(1, Number(ad.dwell) || 10);
tm.hidden = false; tm.textContent = 'Time remaining: ' + left + 's';
t = setInterval(function () {
left -= 1;
if (left > 0) { tm.textContent = 'Time remaining: ' + left + 's'; return; }
clearInterval(t); tm.textContent = 'Time is up'; tm.className = 'iapla-timer done';
st.textContent = 'Thanks for the look. Your game is ready.'; btn.hidden = false;
try { btn.focus(); } catch (e) {}
}, 1000);
});
btn.addEventListener('click', finish);
document.body.appendChild(g);
}
function mount(el, opt) {
styleOnce(); opt = opt || {};
var game = opt.game, ref = String(opt.ref || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 40), src = String(opt.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30);
var fts = Date.now(), email = '', newsletter = true, resendAt = 0, timer = null;
var onToken = opt.onToken || function (t) { location.href = '/auth?t=' + encodeURIComponent(t); };
el.classList.add('iapsi');
function err(m) { var e = el.querySelector('.err'); if (e) e.textContent = m || ''; }
function busy(on) { var b = el.querySelector('.go'); if (b) { b.disabled = !!on; if (on) b.dataset.l = b.textContent, b.textContent = 'One moment…'; else if (b.dataset.l) b.textContent = b.dataset.l; } }
function done(r) {
if (r.pass) { var prev = getPass(); ls(PASS_KEY, JSON.stringify({ p: r.pass, exp: Date.now() + 29 * 86400000, email: email || (prev && prev.email) || '', name: r.username || (prev && prev.name) || '' })); }
if (r.needUsername) return stepName(r);
if (r.token) { // a fresh sign-in: the login ad first (fails open to the hand-off)
if (opt.loginAd === false) return onToken(r.token);
el.innerHTML = '<h2>You are in</h2><p>One moment\u2026</p>';
try { return loginAd(game, function () { onToken(r.token); }); } catch (e) { return onToken(r.token); }
}
err('Something went wrong. Try again.');
}
function stepEmail(msg) {
el.innerHTML = '<h2>' + esc(opt.title || 'Sign in to play') + '</h2>'
+ '<p>Use your email. We send you a 6-digit code, no password. New here? This also opens your free <b>InstantAdPay</b> account, the home of every game in the network.</p>'
+ '<form novalidate><label class="f">Email<input class="t" type="email" name="email" autocomplete="email" inputmode="email" required value="' + esc(email) + '"></label>'
+ '<input class="hp" type="text" name="hp_field_x9" tabindex="-1" autocomplete="off" aria-hidden="true">'
+ '<label class="ck"><input type="checkbox" name="nl"' + (newsletter ? ' checked' : '') + '><span>Keep me posted with the InstantAdPay newsletter (tips and updates). You can unsubscribe anytime.</span></label>'
+ '<div class="err" role="alert"></div><button class="go" type="submit">Send my code</button></form>'
+ (opt.oneTap ? '<div class="row"><a class="lk" href="' + esc(oneTapUrl(opt)) + '">Already signed in to InstantAdPay here? One tap</a></div>' : '')
+ '<p class="fine">By continuing you agree to the InstantAdPay <a href="' + IAP + '/terms" target="_blank" rel="noopener">Terms</a> and <a href="' + IAP + '/privacy" target="_blank" rel="noopener">Privacy</a> policy.</p>';
var f = el.querySelector('form'); if (msg) err(msg);
f.addEventListener('submit', function (ev) { ev.preventDefault(); send(null); });
setTimeout(function () { var i = f.email; if (i && !email) try { i.focus(); } catch (e) {} }, 50);
}
function send(pick) {
var f = el.querySelector('form');
if (f && f.email) { email = String(f.email.value || '').trim(); newsletter = !!(f.nl && f.nl.checked); }
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return err('Enter the email you use (or want to use) for InstantAdPay.');
err(''); busy(true);
post('/api/game/auth/start', { game: game, email: email, ref: ref, src: src, fts: fts, fage: Date.now() - fts, hp_field_x9: (f && f.hp_field_x9 && f.hp_field_x9.value) || '', pick: pick || '', dev: devId() }).then(function (r) {
busy(false);
if (r.challenge) return stepChallenge(r.challenge, r.error);
if (r.ok) { resendAt = Date.now() + 60000; return stepCode(r.devCode); }
if (/already sent/i.test(r.error || '')) { resendAt = Date.now() + 60000; return stepCode(null, r.error); }
err(r.error || 'Could not send the code. Try again.');
});
}
function stepChallenge(ch, msg) {
el.innerHTML = '<h2>Quick check</h2><p>' + esc(msg || 'Before we send your code:') + ' Tap the <b>' + esc(ch.prompt) + '</b>.</p><div class="chal">'
+ ch.options.map(function (o) { return '<button type="button" data-o="' + esc(o) + '">' + esc(o) + '</button>'; }).join('') + '</div><div class="err" role="alert"></div>'
+ '<button class="lk" type="button" data-back>Use a different email</button>';
el.querySelectorAll('[data-o]').forEach(function (b) { b.addEventListener('click', function () { send(b.getAttribute('data-o')); }); });
el.querySelector('[data-back]').addEventListener('click', function () { stepEmail(); });
}
function stepCode(devCode, msg) {
el.innerHTML = '<h2>Check your email</h2><p>We sent a 6-digit code to <b>' + esc(email) + '</b>. It can take a minute. Not there? Check spam or promotions.</p>'
+ '<form novalidate><label class="f">Code<input class="t code" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="[0-9]*" value="' + esc(devCode || '') + '"></label>'
+ '<div class="err" role="alert"></div><button class="go" type="submit">Sign in</button></form>'
+ '<div class="row"><button class="lk" type="button" data-again>Send a new code</button><button class="lk" type="button" data-back>Use a different email</button></div>';
var f = el.querySelector('form'), again = el.querySelector('[data-again]'); if (msg) err(msg);
clearInterval(timer);
function tick() { var s = Math.ceil((resendAt - Date.now()) / 1000); again.disabled = s > 0; again.textContent = s > 0 ? 'Send a new code (' + s + 's)' : 'Send a new code'; if (s <= 0) clearInterval(timer); }
tick(); timer = setInterval(tick, 1000);
again.addEventListener('click', function () { clearInterval(timer); send(null); });
el.querySelector('[data-back]').addEventListener('click', function () { clearInterval(timer); stepEmail(); });
f.code.addEventListener('input', function () { f.code.value = f.code.value.replace(/\D/g, '').slice(0, 6); if (f.code.value.length === 6) f.requestSubmit ? f.requestSubmit() : verify(); });
f.addEventListener('submit', function (ev) { ev.preventDefault(); verify(); });
setTimeout(function () { try { f.code.focus(); } catch (e) {} }, 50);
}
function verify() {
var f = el.querySelector('form'); var code = String((f && f.code && f.code.value) || '').trim();
if (!/^\d{6}$/.test(code)) return err('Enter the 6 digits from the email.');
err(''); busy(true);
post('/api/game/auth/verify', { game: game, email: email, code: code, ref: ref, src: src, newsletter: newsletter, dev: devId() }).then(function (r) {
busy(false);
if (r.ok) { clearInterval(timer); return done(r); }
if (/expired|too many/i.test(r.error || '')) { clearInterval(timer); return stepEmail(r.error); }
err(r.error || 'That did not work. Try again.');
});
}
function stepName(r) {
el.innerHTML = '<h2>Pick your username</h2><p>This is your name in every game, on the leaderboards and in your invite link. Choose carefully: it cannot be changed later.</p>'
+ '<form novalidate><label class="f">Username<input class="t" name="u" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="20" placeholder="3 to 20 letters, numbers or _"></label>'
+ '<div class="err" role="alert"></div><button class="go" type="submit">Save and play</button></form>';
var f = el.querySelector('form');
f.u.addEventListener('input', function () { f.u.value = f.u.value.replace(/[^A-Za-z0-9_]/g, '').slice(0, 20); });
f.addEventListener('submit', function (ev) {
ev.preventDefault(); var name = f.u.value.trim();
if (!/^[A-Za-z0-9_]{3,20}$/.test(name)) return err('Usernames are 3 to 20 letters, numbers, or underscores.');
if (/^\d+$/.test(name)) return err('Usernames need at least one letter.');
var pass = getPass(); if (!pass) return stepEmail('Your sign-in expired. Start again with your email.');
err(''); busy(true);
post('/api/game/auth/username', { game: game, pass: pass.p, username: name }).then(function (x) { busy(false); if (x.ok) return done(x); err(x.error || 'That name did not work. Try another.'); });
});
setTimeout(function () { try { f.u.focus(); } catch (e) {} }, 50);
}
// signed in on this device before (the 29-day pass): one tap, no code (Dallas 2026-10-19: "only a name and login with
// InstantAdPay, it should take care of the rest"). Remembered sign-ins skip the login ad, as before.
function stepResume(saved) {
var who = saved.name ? '@' + saved.name : (saved.email || 'your InstantAdPay account');
el.innerHTML = '<h2>' + esc(opt.title || 'Sign in to play') + '</h2><p>You are signed in on this device as <b>' + esc(who) + '</b>.</p>'
+ '<div class="err" role="alert"></div><button class="go" type="button" data-go>Continue as ' + esc(who) + '</button>'
+ '<div class="row"><button class="lk" type="button" data-other>Use a different account</button></div>';
el.querySelector('[data-go]').addEventListener('click', function () {
err(''); busy(true);
post('/api/game/auth/resume', { game: game, pass: saved.p }).then(function (x) {
busy(false);
if (x.ok && x.pass) ls(PASS_KEY, JSON.stringify({ p: x.pass, exp: Date.now() + 29 * 86400000, email: saved.email || '', name: x.username || saved.name || '' }));
if (x.ok && x.needUsername) return stepName(x);
if (x.ok && x.token) return onToken(x.token);
ls(PASS_KEY, null); stepEmail(x.error || 'Your sign-in expired. Start again with your email.');
});
});
el.querySelector('[data-other]').addEventListener('click', function () { ls(PASS_KEY, null); stepEmail(); });
}
var saved = opt.resume === false ? null : getPass();
if (saved) stepResume(saved); else stepEmail();
}
// nudge: open InstantAdPay in a new tab already signed in (the pass posts in a form, never in a URL)
function enter(to) {
var pass = getPass();
if (!pass) { window.open(IAP + '/my' + (to ? '#' + to : ''), '_blank', 'noopener'); return; }
var f = document.createElement('form'); f.method = 'POST'; f.action = IAP + '/api/game/enter'; f.target = '_blank'; f.style.display = 'none';
[['p', pass.p], ['to', to || 'overview']].forEach(function (kv) { var i = document.createElement('input'); i.type = 'hidden'; i.name = kv[0]; i.value = kv[1]; f.appendChild(i); });
document.body.appendChild(f); f.submit(); setTimeout(function () { f.remove(); }, 1000);
}
window.IAPSignin = { mount: mount, enter: enter, hasPass: function () { return !!getPass(); }, forget: function () { ls(PASS_KEY, null); }, origin: IAP };
})();
+36
View File
@@ -0,0 +1,36 @@
/* InstantAdPay "More games" strip (2026-10-03). Served by instantadpay.com and loaded by every network game, so the list
of games lives in one place (/api/public/games: live games, Spooky Doors only while its season runs). Each card goes
through /g/<slug>?from=<this game>, which counts the hop and lands a signed-in member straight in the game.
Theme with CSS variables on the container (--gs-*). Usage:
IAPGames.strip(el, { current: 'driprunner', title: 'More games' }); */
(function () {
var IAP = 'https://instantadpay.com';
try { var me = document.currentScript && document.currentScript.src; if (me) IAP = new URL(me).origin; } catch (e) {}
var CSS = '.iapgs{--ink:var(--gs-ink,#f2efff);--mu:var(--gs-muted,#b7b0d6);--card:var(--gs-card,rgba(255,255,255,.06));--ln:var(--gs-line,rgba(255,255,255,.16));--hot:var(--gs-hot,#ff8a1f);color:var(--ink);font-family:var(--gs-font,inherit);text-align:left}'
+ '.iapgs .gs-h{font-size:12px;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:var(--mu);margin:0 0 8px}'
+ '.iapgs .gs-row{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(150px,1fr);gap:10px;overflow-x:auto;scroll-snap-type:x mandatory;padding-bottom:4px;-webkit-overflow-scrolling:touch}'
+ '.iapgs a.gs-c{scroll-snap-align:start;display:flex;flex-direction:column;text-decoration:none;color:var(--ink);background:var(--card);border:1px solid var(--ln);border-radius:12px;overflow:hidden;min-width:0}'
+ '.iapgs a.gs-c:hover,.iapgs a.gs-c:focus-visible{border-color:var(--ink)}'
+ '.iapgs .gs-c img{display:block;width:100%;aspect-ratio:1200/630;object-fit:cover;background:#000}'
+ '.iapgs .gs-t{padding:8px 10px 10px;display:grid;gap:3px}.iapgs .gs-t b{font-size:14px;line-height:1.2}'
+ '.iapgs .gs-t small{font-size:12px;line-height:1.35;color:var(--mu)}.iapgs .gs-t em{font-style:normal;font-size:10.5px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;color:var(--mu)}'
+ '.iapgs .gs-t em.hot{color:var(--hot)}';
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }
var cache = null;
function list() { if (!cache) cache = fetch(IAP + '/api/public/games', { credentials: 'omit' }).then(function (r) { return r.json(); }).then(function (j) { return (j && j.games) || []; }).catch(function () { cache = null; return []; }); return cache; }
function strip(el, opt) {
if (!el) return Promise.resolve(0); opt = opt || {};
if (!document.getElementById('iapgsCss')) { var s = document.createElement('style'); s.id = 'iapgsCss'; s.textContent = CSS; document.head.appendChild(s); }
return list().then(function (games) {
var g = games.filter(function (x) { return x.slug !== opt.current; });
if (!g.length) { el.hidden = true; return 0; }
el.classList.add('iapgs'); el.hidden = false;
el.innerHTML = '<p class="gs-h">' + esc(opt.title || 'More games') + '</p><div class="gs-row">' + g.map(function (x) {
return '<a class="gs-c" href="' + IAP + '/g/' + x.slug + '?from=' + encodeURIComponent(opt.current || '') + '"><img src="' + esc(x.art) + '" alt="" loading="lazy" style="object-position:' + esc(x.artPos || 'center') + '">'
+ '<span class="gs-t"><em' + (x.seasonal ? ' class="hot"' : '') + '>' + esc(x.tag) + '</em><b>' + esc(x.name) + '</b><small>' + esc(x.line) + '</small></span></a>';
}).join('') + '</div>';
return g.length;
});
}
window.IAPGames = { strip: strip, list: list, origin: IAP };
})();
+34
View File
@@ -0,0 +1,34 @@
// Public games page (2026-10-10): every game in the network, live ones first, then the ones with an opening date.
// Data: /api/public/games/all. Play links go to each game's own site (the game signs the visitor in with InstantAdPay).
// A ?ref=<username> on this page is kept by the site's viral-link handling and carried onto the Join button.
(function () {
var esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]; }); };
var ref = ''; try { ref = new URLSearchParams(location.search).get('ref') || ''; } catch (e) {}
if (ref) { var j = document.getElementById('gJoin'); if (j) j.href = '/join/' + encodeURIComponent(ref); } // the sponsored join page itself (bare /join used to 404, Diann 2026-10-11)
function card(g) {
var soon = !g.live && g.opens;
var ribbon = g.season ? '<span class="ribbon">Limited time · ends ' + esc(g.season.ends) + '</span>' : soon ? '<span class="ribbon soon">' + esc(g.opens) + '</span>' : '';
var play = g.live && g.open ? '<a class="btn" href="' + esc(g.open) + '" target="_blank" rel="noopener">Play</a>' : '<span class="btn" aria-disabled="true">' + esc(g.opens || 'Opens soon') + '</span>';
var site = g.host ? '<span class="host">' + esc(g.host) + '</span>' : '';
var art = g.video ? '<video controls playsinline preload="none" poster="' + esc(g.poster || g.art || '') + '" src="' + esc(g.video) + '" style="width:100%;height:100%;object-fit:cover;display:block;background:#000"></video>' : (g.art ? '<img src="' + esc(g.art) + '" alt="" loading="lazy"' + (g.artPos ? ' style="object-position:' + esc(g.artPos) + ' center"' : '') + '>' : '');
return '<div class="gcard"><div class="art">' + art + ribbon + '</div>' +
'<div class="body"><span class="tag">' + esc(g.tag || '') + '</span><h3>' + esc(g.name) + '</h3><p>' + esc(g.blurb || '') + '</p>' +
(g.pays ? '<div class="pays">Pays: <b>' + esc(g.pays) + '</b></div>' : '') +
'<div class="row">' + play + site + '</div></div></div>';
}
fetch('/api/public/games/all').then(function (r) { return r.json(); }).then(function (d) {
var games = (d && d.games) || [];
var live = games.filter(function (g) { return g.live; }), soon = games.filter(function (g) { return !g.live; });
var L = document.getElementById('gLive'), S = document.getElementById('gSoon');
if (!games.length) { document.getElementById('gEmpty').hidden = false; return; }
if (live.length) L.innerHTML = '<h2 class="gsec">Open now · ' + live.length + ' game' + (live.length === 1 ? '' : 's') + '</h2><div class="ggrid">' + live.map(card).join('') + '</div>';
if (soon.length) S.innerHTML = '<h2 class="gsec">Opening next</h2><div class="ggrid">' + soon.map(card).join('') + '</div>';
}).catch(function () { document.getElementById('gEmpty').hidden = false; });
// featured warriors from the PolyWarriors market (2026-10-10): the rarest listings, with the forged art
fetch('/api/public/pw-featured').then(function (r) { return r.json(); }).then(function (d) {
var f = (d && d.featured) || []; if (!f.length) return; var S = document.getElementById('gSoon'); var host = document.createElement('div'); host.id = 'gFeatured';
host.innerHTML = '<h2 class="gsec">From the PolyWarriors market <small style="letter-spacing:0;text-transform:none;font-size:11px"> <a href="' + esc(d.market) + '" target="_blank" rel="noopener">open the market</a></small></h2><div class="fgrid">' + f.map(function (x) {
return '<a class="fcard" href="' + esc(x.url) + '" target="_blank" rel="noopener" style="--rc:' + esc(x.color) + '"><div class="fpic"><img src="' + esc(x.image) + '" alt="" loading="lazy"><span class="ftag">' + esc(x.rarity) + '</span>' + (x.forSale ? '<span class="fsale">For sale</span>' : '') + '</div><div class="fb"><b>' + esc(x.name) + ' #' + String(x.serial).padStart(4, '0') + '</b>' + (x.forge ? '<small>Forged ' + esc(x.forge.grade) + ' ' + esc(x.forge.score) + '</small>' : '') + (x.forSale ? '<span class="fp">' + esc(x.price) + ' POL</span>' : '') + '</div></a>'; }).join('') + '</div>';
S.parentNode.insertBefore(host, S.nextSibling);
}).catch(function () {});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

+31 -4
View File
@@ -16,7 +16,8 @@
const { products } = await (await fetch('/api/catalog')).json();
const wrap = document.getElementById('tiles');
wrap.innerHTML = '';
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' };
products.sort((a, b) => a.priceCents - b.priceCents);
for (const p of products) {
const bonus = p.creditAmount - p.priceCents; // credits above 1cr/cent = bulk bonus
const div = document.createElement('div');
@@ -44,7 +45,7 @@
IAP.status('Confirm the purchase in your wallet…');
// resolve the sponsor at buy time: a code referrer who activated since
// page load still gets locked in
const spNow = await (await fetch('/api/sponsor')).json();
const spNow = await (await fetch('/api/sponsor?intent=buy')).json(); // intent=buy: never held (Marty 2026-10-27)
const r = await IAPWallet.buy(Number(btn.dataset.id), spNow.sponsorId || 0, btn.dataset.cost);
if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.');
IAP.status('Purchase settled on-chain. Credits are yours, payouts delivered. Watch it on the ledger.', 'ok');
@@ -53,6 +54,24 @@
IAP.status('Purchase failed: ' + (e.message || e), 'bad');
} finally { btn.disabled = false; }
}
// Five Dollar Friday strip under the stats: the live wave on Fridays, the next date otherwise
async function loadFriday() {
try { const f = await (await fetch('/api/friday')).json(); const el = document.getElementById('fdfStrip'); if (!f.on || !el) return; el.hidden = false;
el.innerHTML = f.live && f.today
? '<b>\u{1F4B5} It\u2019s Five Dollar Friday.</b> ' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' bought so far today, ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Any pack from $5 earns +' + f.pct + '% credits until midnight Central. <a href="/my">Get yours</a>'
: '<b>\u{1F4B5} Five Dollar Friday:</b> every Friday, any ad package from $5 up earns +' + f.pct + '% bonus credits, and the whole network buys on the same day. Next one: ' + (f.nextLabel || 'soon') + '. <a href="/my">Join free and line yours up</a>';
} catch (e) {}
}
loadFriday();
// Wired Wednesday strip: the live wave on Wednesdays, the next date otherwise
async function loadWednesday() {
try { const f = await (await fetch('/api/wednesday')).json(); const el = document.getElementById('wwStrip'); if (!f.on || !el) return; el.hidden = false;
el.innerHTML = f.live && f.today
? '<b>⚡ It’s Wired Wednesday.</b> ' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' bought so far today, ' + Number(f.today.bonusCredits || 0).toLocaleString() + ' bonus credits wired in. Any pack from $' + f.minUsd + ' earns +' + f.pct + '% credits the second it settles, until midnight Central. <a href="/my">Get yours</a>'
: '<b>⚡ Wired Wednesday:</b> every Wednesday, any ad package from $' + f.minUsd + ' up earns +' + f.pct + '% bonus credits, wired into your balance the second it settles. Next one: ' + (f.nextLabel || 'soon') + '. <a href="/wednesday">How it works</a>';
} catch (e) {}
}
loadWednesday();
async function loadStats() {
try {
const s = await (await fetch('/api/stats')).json();
@@ -69,11 +88,19 @@
const inner = IAP.$('tickerInner');
inner.innerHTML = events.map(ev => '<span>' + IAP.describeEvent(ev, c) + '</span>').join('');
IAP.$('ticker').hidden = false;
// readable pace (Marty, 2026-09-12): about 70 px per second no matter how much text is loaded,
// instead of a fixed 42 s for the whole strip; pause while a finger or pointer rests on it
const wrap = IAP.$('ticker');
const secs = Math.max(30, Math.round((inner.scrollWidth + wrap.clientWidth) / 70));
inner.style.animationDuration = secs + 's';
const pause = on => { inner.style.animationPlayState = on ? 'paused' : 'running'; };
wrap.addEventListener('mouseenter', () => pause(true)); wrap.addEventListener('mouseleave', () => pause(false));
wrap.addEventListener('touchstart', () => pause(true), { passive: true }); wrap.addEventListener('touchend', () => pause(false), { passive: true });
} catch (e) {}
}
// level cycler: chips + generation highlighting + auto-advance
const LVL = {
1: { pct: '50%', desc: 'Level 1 is open to every member: your direct referrals each pay you 50 percent of every package they ever buy, straight to your wallet.' },
1: { pct: '50%', desc: 'Activate with the $20 starter package and switch on payouts from your wallet. From then on your direct referrals each pay you 50 percent of every package they ever buy, in POL, straight to your wallet. Until you activate, you earn ad credits, not POL.' },
2: { pct: '20%', desc: 'Bring 2 buyers of $20 or more and level 2 unlocks: 20 percent of every package your referrals’ referrals buy, on every purchase, forever.' },
3: { pct: '10%', desc: 'At 5 qualifying buyers, level 3 opens the third generation: 10 percent of everything they buy. Eight positions deep in this picture, and it keeps growing.' }
};
@@ -127,7 +154,7 @@
setB($id('dcB3'), l3open, qualifies ? (5 - d) + ' more buyer(s)' : 'needs $20+ buyers');
$id('dcQualNote').textContent = qualifies
? 'Buyers of $20 or more count toward your qualification. 2 unlock level 2, 5 unlock level 3.'
: 'Heads up: $5 packages pay your level 1 but do not qualify buyers, so levels 2 and 3 stay locked in this scenario.';
: 'Heads up: packages under $20 pay your level 1 but do not qualify buyers, so levels 2 and 3 stay locked in this scenario.';
};
['dcDirects', 'dcPkg', 'dcSpread'].forEach(x => $id(x).addEventListener('input', recalc));
recalc();
+144 -67
View File
@@ -1,67 +1,144 @@
// Invite / lead-capture page: /join/<token>[?v=<angle>]
// Email first (code sign-in creates the account), wallet later inside the
// member area. The angle only changes the hook copy; the sponsor cookie was
// set by the server when this page was served.
(function () {
const $ = id => document.getElementById(id);
const ANGLES = {
instant: { eyebrow: 'Same-transaction payouts', h: 'Paid before the page <em>reloads.</em>', lead: 'What if your commission landed before the thank-you page finished loading? On InstantAdPay that is not a metaphor. A smart contract on Polygon splits every ad package the moment it sells.' },
adspend: { eyebrow: 'For marketers who buy traffic', h: 'You were buying <em>ads anyway.</em>', lead: 'Every ad dollar you ever spent went one direction: out. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Seven formats, dwell-timed views, packages from $5.' },
free: { eyebrow: 'Costs nothing to try', h: 'Watch first. <em>Spend never.</em>', lead: 'Join free, view a few ads, earn credits, and run your first campaign for zero dollars. Upgrade only if you want more reach.' },
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and nothing is ever held.' },
two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open <em>level two.</em>', lead: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written as constants in a verified contract.' }
};
const v = new URLSearchParams(location.search).get('v');
const a = v && ANGLES[v];
if (a) { $('jnEyebrow').textContent = '· ' + a.eyebrow; $('jnHead').innerHTML = a.h; $('jnLead').textContent = a.lead; }
async function api(path, body) {
const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json();
if (r.error) throw new Error(r.error);
return r;
}
const err = m => { const e = $('jnErr'); e.textContent = m || ''; e.hidden = !m; };
function busy(btn, fn) {
return async () => { if (btn.disabled) return; btn.disabled = true; err(''); try { await fn(); } catch (e) { err(e.message || 'Something went wrong.'); } finally { btn.disabled = false; } };
}
const send = busy($('jnSend'), async () => {
const r = await api('/api/auth/email/start', { email: $('jnEmail').value });
$('jnCodeRow').hidden = false; $('jnVerify').hidden = false; $('jnSend').hidden = true; $('jnResend').hidden = false;
if (r.devCode) $('jnCode').value = r.devCode;
IAP.status(r.sent ? 'Code sent. Check your inbox (and spam, the first time).' : 'Dev mode: code filled in.', 'ok');
$('jnCode').focus();
});
$('jnSend').addEventListener('click', send);
$('jnResend').addEventListener('click', busy($('jnResend'), async () => {
const r = await api('/api/auth/email/start', { email: $('jnEmail').value });
if (r.devCode) $('jnCode').value = r.devCode;
IAP.status('Fresh code sent.', 'ok');
}));
$('jnVerify').addEventListener('click', busy($('jnVerify'), async () => {
await api('/api/auth/email/verify', { email: $('jnEmail').value, code: $('jnCode').value, newsletter: !!$('jnNews').checked, followups: !!$('jnNews').checked });
IAP.status('You are in. Taking you to your dashboard…', 'ok');
location.href = '/my?welcome=1'; // dashboard runs the username step + welcome tour on arrival
}));
$('jnEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('jnVerify').hidden ? $('jnSend') : $('jnVerify')).click(); });
$('jnCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('jnVerify').click(); });
// sponsor line
fetch('/api/sponsor').then(r => r.json()).then(sp => {
if (sp && sp.invited && sp.name) {
$('jnSponName').textContent = sp.name;
if (sp.avatarUrl) { $('jnSponImg').src = sp.avatarUrl; $('jnSponImg').hidden = false; }
$('jnSpon').hidden = false;
}
}).catch(() => {});
// package ladder (dollar constants + live POL quote)
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
fetch('/api/catalog').then(r => r.json()).then(c => {
const wrap = $('jnLadder'); if (!wrap || !c.products) return;
wrap.innerHTML = c.products.filter(p => p.active !== false).map(p =>
'<div class="jn-pk"><div class="n">' + (NAMES[p.id] || 'Package ' + p.id) + '</div><div class="p">' + IAP.fmtUsd(p.priceCents) + '</div><div class="c">' + Number(p.creditAmount).toLocaleString() + ' credits</div>'
+ (p.costWei ? '<div class="small muted">' + IAP.fmtPol(p.costWei) + ' POL now</div>' : '') + '</div>').join('');
}).catch(() => {});
fetch('/api/stats').then(r => r.json()).then(s => {
if (s && s.onchainMembers) $('jnStats').textContent = s.onchainMembers.toLocaleString() + (s.onchainMembers === 1 ? ' member' : ' members') + ' on-chain so far.';
}).catch(() => {});
})();
// Invite / lead-capture page: /join/<token>[?v=<angle>]
// Email first (code sign-in creates the account), wallet later inside the
// member area. The angle only changes the hook copy; the sponsor cookie was
// set by the server when this page was served.
(function () {
const $ = id => document.getElementById(id);
const LEG = (brand, seg) => seg === 'adv'
? { eyebrow: 'For former ' + brand + ' advertisers', h: 'Your next ad budget <em>pays you back.</em>',
lead: brand + ' is closed. The people who bought ads there are exactly who InstantAdPay was built for: real ad packages from $5, seven formats, and every package in your line paid out by a verified contract on Polygon in the same transaction.',
points: ['Welcome-back credits land the moment your account exists: enough to run a real banner or text campaign today, on us.', 'Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits. Views are timed on the server, so a real person saw your ad.', 'When anyone in your line buys ads, the contract pays you in that same transaction. Public on Polygonscan, nothing held, nothing to withdraw.'],
cta: 'Claim your welcome-back credits', sub: 'Free account by email. No password, no wallet today. Use the email you had on ' + brand + ': the credits are tied to it.', video: false }
: { eyebrow: 'For former ' + brand + ' members', h: 'Same daily habit. <em>Real payouts on-chain.</em>',
lead: 'You viewed ads on ' + brand + '. Here you view ads to earn credits, run your own campaign with them for free, and when anyone in your line buys ads you are paid in POL to your own wallet in the same transaction.',
points: ['Welcome-back credits on day one, so your first campaign runs before you have viewed a single ad.', 'Join with just an email. No password, no wallet today. Link a wallet later, only when you want payouts switched on.', 'Every payout is a public transaction on Polygon. Nothing is held, so there is nothing to withdraw and nothing to wait for.'],
cta: 'Claim your welcome-back credits', sub: 'Free account by email. Use the email you had on ' + brand + ': the credits are tied to it.', video: false };
const ANGLES = {
'fw-adv': LEG('Faucet Wave', 'adv'), 'fw-earn': LEG('Faucet Wave', 'earn'), 't1-adv': LEG('Tier One Ads', 'adv'), 't1-earn': LEG('Tier One Ads', 'earn'),
play: { eyebrow: 'If you have time to play', h: 'If you have time to play a game, <em>you have time to build a business.</em>', lead: 'You play games on your phone anyway. These free games pay real Polygon to your wallet, on chain, where anyone can check it. That is the trust tool: people believe what they see paid.',
points: ['A whole collection of free games on one page: a brick breaker, a word puzzle, match three, a cyberpunk battler, a runner and more.', 'First clears and wins pay real Polygon to the wallet on your InstantAdPay account, and every payout is a public transaction anyone can check.', 'Share your games link instead of just playing. When a friend plays, gets paid and joins, they join your team.'],
cta: 'Join free and get your own games link', sub: 'Free account by email. No password, no wallet today. Your games link and invite link are live the moment you are in.', games: true },
instant: { eyebrow: 'Same-transaction payouts', h: 'Paid before the page <em>reloads.</em>', lead: 'What if your commission landed before the thank-you page finished loading? On InstantAdPay that is not a metaphor. A smart contract on Polygon splits every ad package the moment it sells.',
points: ['A verified contract splits every package in the same transaction it sells: 50 percent to the sponsor, 20 and 10 up the line, 20 to the platform.', 'It lands in your own wallet in seconds. There is no balance to withdraw because nothing is ever held.', 'Every payment is public on Polygonscan, so you can check the claim before you spend a dollar.'],
cta: 'See a payout land in seconds', sub: 'Free account by email. No password, no wallet today. Your invite link is live the moment you are in.' },
adspend: { eyebrow: 'For marketers who buy traffic', h: 'You were buying <em>ads anyway.</em>', lead: 'Every ad dollar you ever spent went one direction: out. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Seven formats, dwell-timed views, packages from $5.',
points: ['Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits.', 'Views are timed on the server, so a real person saw your ad. Banners and text also run across a partner ad network.', 'When anyone in your line buys ads, the contract pays you in that same transaction.'],
cta: 'Put your next ad dollar where it pays you back', sub: 'Free account by email. See every format and the live rates before you buy anything.' },
free: { eyebrow: 'Costs nothing to try', h: 'Watch first. <em>Spend never.</em>', lead: 'Join free, view a few ads, earn credits, and run your first campaign for zero dollars. Upgrade only if you want more reach.',
points: ['Join with just an email. No password, no wallet today.', 'View a few ads each day and earn credits you can spend on your own banner or text campaign.', 'Buy a package only if you want more reach. They start at $5, and every payout on them is public.'],
cta: 'Start for free. No card, no wallet.', sub: 'Type your email and we send a 6-digit code. That is the whole signup.' },
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and nothing is ever held.',
points: ['Every payout is a public transaction on Polygon. Click it, read it, verify it yourself.', 'The contract holds zero balance. It splits and sends in the same transaction, with no pause switch and no upgrade path.', 'No back office means nobody can delay, reverse or review your commission.'],
cta: 'Check the ledger yourself, then decide', sub: 'Free account by email. The public ledger and the verified contract are one click from your dashboard.' },
two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open <em>level two.</em>', lead: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written as constants in a verified contract.',
points: ['Every direct buyer pays you 50 percent from their very first package.', 'Two qualifying buyers open level two at 20 percent. Five open level three at 10 percent. Constants in a verified contract.', 'Until a level opens, its share climbs to the next qualified member above, so the plan rewards the people who build.'],
cta: 'Start your line. Two buyers is the target.', sub: 'Free account by email. Your invite link and the team-building plays are waiting inside.' },
// Build Wide (2026-10-15): the buildwide promo video, vertical on phones and 16:9 on wider screens
wide: { eyebrow: 'Build wide', h: 'Width unlocks <em>depth.</em>', lead: 'Watch the fifty percent land, then the deeper levels open.', file: 'buildwide', portraitOnPhones: true,
points: ['Every direct buyer pays you 50 percent of their package, in the same transaction it sells.', 'Two direct buyers of $20 or more open level two at 20 percent. Five open level three at 10 percent.', 'A level you have not opened yet passes its share up the line. Going wide first is what opens the deeper levels.'],
cta: 'Start wide. Join free.', sub: 'Free account by email. No password, no wallet today. Your invite link is live the moment you are in.' }
};
// ?name=First personalises the page (site-owner links, Marty 2026-09-12): letters, spaces, hyphens,
// apostrophes only, 30 chars. On the company placement links it says the top spot is reserved.
const who = String(new URLSearchParams(location.search).get('name') || '').replace(/[^A-Za-z\u00C0-\u024F' -]/g, '').trim().slice(0, 30);
if (who) {
const top = /^\/join\/(company|top)$/i.test(location.pathname);
const h = $('jnHello');
if (h) { h.textContent = who + (top ? ', your spot directly under the company at the top is reserved for you. Activate with the $20 package to claim it.' : ', this invitation is for you.'); h.hidden = false; }
}
const v = new URLSearchParams(location.search).get('v') || (document.cookie.match(/(?:^|; )iap\.angle=([^;]+)/) || [])[1] || '';
const a = v && ANGLES[v];
if (a) {
document.body.classList.add('squeeze'); // server sets it too; this covers cached HTML
$('jnEyebrow').textContent = '· ' + a.eyebrow; $('jnHead').innerHTML = a.h; $('jnLead').textContent = a.lead;
if (a.cta) { $('jnCapH').textContent = a.cta; $('jnCapSub').textContent = a.sub || ''; }
// the matching hook video + this angle's three points replace the worked example
const VID = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
const vid = $('jnVideo');
if (a.video === false) vid.hidden = true;
else {
const file = a.file || v; // a hook whose uploaded video carries another name (wide -> promo/buildwide.*)
const tall = a.portraitOnPhones && window.matchMedia && window.matchMedia('(max-width: 640px)').matches;
vid.src = VID + file + (tall ? '-portrait' : '') + '.mp4'; vid.poster = VID + file + (tall ? '-portrait' : '') + '.jpg';
if (tall) { vid.style.aspectRatio = '9/16'; vid.style.maxWidth = '380px'; vid.style.margin = '0 auto'; vid.style.maxHeight = '78vh'; }
}
$('jnPoints').innerHTML = (a.points || []).map(t => '<li>' + t.replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c])) + '</li>').join('');
$('jnMock').hidden = true; $('jnAngle').hidden = false; $('jnPoints').hidden = false;
// play angle (2026-10-13): a big button to the public games page, carrying this page's invite token as ?ref
if (a.games && !document.getElementById('jnGames')) {
const tok = (location.pathname.match(/^\/join\/([^/?#]+)/) || [])[1] || '';
const g = document.createElement('p'); g.id = 'jnGames'; g.style.cssText = 'margin:14px 0 4px;text-align:center';
const btn = document.createElement('a'); btn.className = 'btn'; btn.href = '/games' + (tok && !/^(company|top)$/i.test(tok) ? '?ref=' + encodeURIComponent(tok) : '');
btn.target = '_blank'; btn.rel = 'noopener'; btn.textContent = 'Play the free games'; btn.style.cssText = 'display:inline-block;font-size:1.1em;padding:14px 28px';
const note = document.createElement('div'); note.className = 'small muted'; note.style.marginTop = '8px'; note.textContent = 'Opens the games page. Play free, then join below to get paid and get your own link.';
g.appendChild(btn); g.appendChild(note); vid.after(g);
}
}
async function api(path, body) {
const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json();
if (r.error) throw new Error(r.error);
return r;
}
const err = m => { const e = $('jnErr'); e.textContent = m || ''; e.hidden = !m; };
function busy(btn, fn) {
return async () => { if (btn.disabled) return; btn.disabled = true; err(''); try { await fn(); } catch (e) { err(e.message || 'Something went wrong.'); } finally { btn.disabled = false; } };
}
const pageClick = (() => { const q = new URLSearchParams(location.search); return q.get('lsclk') || q.get('lsid') || ''; })(); // the LinkSpin click in this page's address: travels with the requests, the cookie may be refused in a frame (reporting only)
const codeOpts = () => ({ honeypot: $('jnWebsite'), host: $('jnCheck'), ref: linkTok, angle: v || '', lsclk: pageClick }); // the page's own token rides with the code request (cookie may be blocked in a frame)
const send = busy($('jnSend'), async () => {
const r = await IAP.requestCode($('jnEmail').value, codeOpts());
$('jnCodeRow').hidden = false; $('jnVerify').hidden = false; $('jnSend').hidden = true; $('jnResend').hidden = false;
if (r.devCode) $('jnCode').value = r.devCode;
// the last thing they see before the account is created: who they are joining under
if (sponsorName) { $('jnUnder').textContent = 'Joining under ' + sponsorName + '. Not who invited you? Open their invite link first, then come back for the code.'; $('jnUnder').hidden = false; }
IAP.status(r.sent ? 'Code sent. Check your inbox (and spam, the first time).' : 'Dev mode: code filled in.', 'ok');
$('jnCode').focus();
});
// framed: the code would arrive but the sign-in cookie would be refused, so the sign-up continues in a full window
// with the email filled in (the link carries the invite token, so the sponsor holds)
let framed = false; try { framed = window.top !== window.self; } catch (e) { framed = true; }
$('jnSend').addEventListener('click', framed ? () => { const t = new URL(location.href); const em = ($('jnEmail').value || '').trim(); if (em) t.searchParams.set('email', em); window.open(t.toString(), '_blank', 'noopener'); IAP.status('Opened InstantAdPay in a new tab. Finish joining there.', 'ok'); } : send);
try { const em = new URLSearchParams(location.search).get('email'); if (em && $('jnEmail') && !$('jnEmail').value) $('jnEmail').value = em.slice(0, 120); } catch (e) {}
$('jnResend').addEventListener('click', busy($('jnResend'), async () => {
const r = await IAP.requestCode($('jnEmail').value, codeOpts());
if (r.devCode) $('jnCode').value = r.devCode;
IAP.status('Fresh code sent.', 'ok');
}));
$('jnVerify').addEventListener('click', busy($('jnVerify'), async () => {
await api('/api/auth/email/verify', { email: $('jnEmail').value, code: $('jnCode').value, newsletter: !!$('jnNews').checked, followups: !!$('jnNews').checked, ref: linkTok, lsclk: pageClick });
IAP.status('You are in. Taking you to your dashboard…', 'ok');
location.href = '/my?welcome=1'; // dashboard runs the username step + welcome tour on arrival
}));
$('jnEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('jnVerify').hidden ? $('jnSend') : $('jnVerify')).click(); });
$('jnCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('jnVerify').click(); });
// sponsor line (the link opened most recently sets the sponsor; it locks at account creation)
let sponsorName = '';
const linkTok = (location.pathname.match(/^\/join\/([^/?#]+)/) || [])[1] || '';
// Shown inside another site (a traffic-exchange frame)? Browsers refuse our cookies there, so the invitation
// could be lost. Offer the full window; the link carries the token, so the top-level visit sets the cookie.
try { if (window.top !== window.self) { const n = document.createElement('p'); n.className = 'small'; n.style.cssText = 'margin:0 0 10px;padding:10px 12px;border:1px solid var(--line-strong);border-radius:10px;background:var(--mint-soft)';
n.innerHTML = '<b>Viewing this inside another site?</b> <a href="' + location.href.replace(/"/g, '') + '" target="_top" rel="noopener">Open InstantAdPay in a full window</a> so your invitation stays attached to your account.';
const row = $('jnEmail') && $('jnEmail').closest('p'); if (row) row.parentNode.insertBefore(n, row); } } catch (e) {}
fetch('/api/sponsor' + (linkTok ? '?ref=' + encodeURIComponent(linkTok) : '')).then(r => r.json()).then(sp => {
if (sp && sp.invited && sp.name) {
sponsorName = sp.name;
$('jnSponName').textContent = sp.name + (sp.own ? ' (this is your own invite page; visitors see your name here)' : '');
if (sp.avatarUrl) { $('jnSponImg').src = sp.avatarUrl; $('jnSponImg').hidden = false; }
if (sp.cobrand && sp.bio && $('jnSponBio')) { $('jnSponBio').textContent = sp.bio; $('jnSponBio').hidden = false; $('jnSpon').classList.add('cobrand'); }
$('jnSpon').hidden = false;
}
}).catch(() => {});
// package ladder (dollar constants + live POL quote)
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' };
fetch('/api/catalog').then(r => r.json()).then(c => {
const wrap = $('jnLadder'); if (!wrap || !c.products) return;
wrap.innerHTML = c.products.filter(p => p.active !== false).sort((a, b) => a.priceCents - b.priceCents).map(p =>
'<div class="jn-pk"><div class="n">' + (NAMES[p.id] || 'Package ' + p.id) + '</div><div class="p">' + IAP.fmtUsd(p.priceCents) + '</div><div class="c">' + Number(p.creditAmount).toLocaleString() + ' credits</div>'
+ (p.costWei ? '<div class="small muted">' + IAP.fmtPol(p.costWei) + ' POL now</div>' : '') + '</div>').join('');
}).catch(() => {});
fetch('/api/stats').then(r => r.json()).then(s => {
if (s && s.onchainMembers) $('jnStats').textContent = s.onchainMembers.toLocaleString() + (s.onchainMembers === 1 ? ' member' : ' members') + ' on-chain so far.';
}).catch(() => {});
})();
+11
View File
@@ -0,0 +1,11 @@
// partner kit pages (/partners/<slug>): copy buttons + toast (2026-09-29)
(function(){
var toast=document.getElementById('toast'),tm;
function say(t){toast.textContent=t;toast.classList.add('on');clearTimeout(tm);tm=setTimeout(function(){toast.classList.remove('on')},1400)}
function copy(text,btn){
function fallback(){var r=document.createRange();var el=btn.previousElementSibling||btn.parentElement;r.selectNodeContents(el);var s=getSelection();s.removeAllRanges();s.addRange(r);say('Select and copy')}
try{navigator.clipboard.writeText(text).then(function(){say('Copied')},fallback)}catch(e){fallback()}
}
document.querySelectorAll('[data-copy]').forEach(function(b){b.addEventListener('click',function(){copy(b.getAttribute('data-copy'),b)})});
document.querySelectorAll('[data-copy-el]').forEach(function(b){b.addEventListener('click',function(){var el=document.getElementById(b.getAttribute('data-copy-el'));copy(el.textContent,b)})});
})();
+114
View File
@@ -0,0 +1,114 @@
// Founding week checklist: members only; every item reads from the live account
// (IAP.launchChecks in common.js is shared with the dashboard's "launch ready" mark).
(async function () {
const $ = id => document.getElementById(id);
try { await IAP.renderNav('training'); } catch (e) {}
let me = null, cfg = {};
try { me = await (await fetch('/api/me')).json(); } catch (e) {}
// buyerCount and the referral list live on the dashboard endpoint; merge it in
if (me && me.signedIn) { try { const d = await (await fetch('/api/my/dashboard')).json(); if (d && !d.error) me = Object.assign({}, me, d, { signedIn: true, email: me.email }); } catch (e) {} }
try { cfg = await IAP.getConfig(); } catch (e) {}
const signedIn = !!(me && me.signedIn && me.email);
$('gate').style.display = signedIn ? 'none' : 'block';
$('body').style.display = signedIn ? 'block' : 'none';
if (!signedIn) return;
const pb = $('printBtn'); if (pb) pb.addEventListener('click', () => window.print());
const tok = me.username || me.refCode || me.memberId;
if (tok) document.querySelectorAll('[data-link]').forEach(el => { el.textContent = location.origin + '/join/' + tok; });
// launch week swipes: four promoter emails, the member's link + FOUNDER code filled in (Marty, 2026-09-15)
const LINK = location.origin + '/join/' + (tok || '') + '?promo=FOUNDER';
const SW = [
{ when: 'Day 1 · six days out', subject: 'Something opens Monday. I am bringing a few people in early.', body: `Quick one, because I want you positioned before this goes public.
I have been inside a new advertising platform for a week. It pays sponsors in the same transaction a package is bought, wallet to wallet, on the Polygon ledger where anyone can check it. No back office. No payday. I have watched the payouts land.
It opens to everyone Monday, September 21 at 9 AM Central. Founding members are in now, and the people they bring in before then are the ones the launch traffic lands under.
Joining is free with an email. This week the code FOUNDER gives you 500 ad credits to run a campaign on day one:
{link}
No income is promised. It is an ad platform with a referral program. But the payment mechanics are real and public, and that is why I am in.
Look before Monday. I will walk you through the first three steps.`},
{ when: 'Day 2 · five days out', subject: 'Five hundred free credits, and what you can do with them', body: `Yesterday I sent you a link. Here is what is on the other side of it.
You join free with your email. Every day you view a short set of ads and earn credits. Credits run your own ads: banners, text ads, video ads, solo mailings, verified visits, across the whole network.
This week the FOUNDER code adds 500 credits on top the moment you join, enough to launch a real campaign pointed at whatever you are promoting. Watch it deliver before Monday, when everyone else arrives.
The other half is simple. When someone you invite buys an ad package, the contract pays you 50 percent instantly. Level two gets 20 percent, level three 10 percent. Same transaction, on the public ledger.
{link}
Use the code before it expires Monday morning. Then tell me you are in and I will show you the checklist.`},
{ when: 'Day 4 · the weekend', subject: 'The two people you bring in this weekend', body: `The doors open Monday morning and I am spending the weekend getting my first people set up. I want you to be one of them.
Here is why the weekend matters. Everyone who joins now is a founding member. The traffic that arrives Monday lands under whoever is already in and set up. Two people under you before Monday, and your line is built when the wave hits.
Setup takes ten minutes: username, link a wallet, switch on payouts. Then share your link. The site gives you posts, swipes, banners and a leaderboard with weekly credit prizes for the top sponsors.
Join with the FOUNDER code and the 500 credits are yours:
{link}
Message me when you are in and I will go through the checklist with you before Monday.`},
{ when: 'Day 6 · Sunday evening', subject: 'Doors open tomorrow at 9 AM Central', body: `Last note before the launch.
InstantAdPay opens to the public tomorrow, Monday, at 9 AM Central. After that the FOUNDER code is gone. Tonight it still gives you 500 free ad credits.
If you join tonight you are in as a founding member with a campaign already funded and your link ready when the first wave arrives. If you wait, you join the wave.
Free to join, real advertising, and every payment lands in your own wallet the second it happens, on a ledger anyone can read. No income promises. Just mechanics you can verify.
{link}
I will be online from 8 AM tomorrow walking people through the first three steps. Get in tonight and you are ahead of them.`}
];
// short posts and a DM for the same days, one per day, link + code included
const POSTS = [
{ when: 'Day 1 · six days out', text: `Something I have been inside for a week opens to the public Monday, September 21 at 9 AM Central. An ad platform that pays sponsors in the same transaction a package is bought, on the Polygon ledger where anyone can check it. Free to join. Code FOUNDER gives you 500 ad credits before then. No income promises, just mechanics you can verify. {link}` },
{ when: 'Day 2 · five days out', text: `500 free ad credits for joining before Monday. View a short daily set of ads, earn more, run banners, text ads, video ads and solo mailings across the network. When someone you invite buys a package, the contract pays you 50 percent instantly, wallet to wallet. Code FOUNDER. {link}` },
{ when: 'Day 4 · the weekend', text: `The doors open Monday morning. Everyone joining this weekend is a founding member, and the launch traffic lands under whoever is already set up. Ten minutes to set up, 500 credits with code FOUNDER, and a leaderboard that pays weekly credit prizes to the top sponsors. {link}` },
{ when: 'Day 6 · Sunday evening', text: `Doors open tomorrow, 9 AM Central. Tonight the FOUNDER code still gives you 500 free ad credits; tomorrow it is gone. Free to join, real advertising, every payment on a public ledger. Get in tonight and you are ahead of the wave. {link}` },
{ when: 'Text or DM · any day', text: `Hey, I am in something that opens publicly Monday and I am bringing a few people in early. Free to join, real advertising, every payment lands in your own wallet the second it happens. Use code FOUNDER for 500 free credits. Ten minutes to set up and I will walk you through it: {link}` }
];
const pl = $('postList');
if (pl) {
pl.innerHTML = POSTS.map((s, i) => '<div class="swipe"><div class="cap"><span>' + s.when + '</span><button type="button" class="btn sec" data-post="' + i + '">Copy post</button></div><pre>' + s.text.replace('{link}', LINK).replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</pre></div>').join('');
pl.querySelectorAll('[data-post]').forEach(b => b.addEventListener('click', async () => {
const t = POSTS[Number(b.dataset.post)].text.replace('{link}', LINK);
try { await navigator.clipboard.writeText(t); b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy post'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); }
}));
}
const wrap = $('swipeList');
if (wrap) {
wrap.innerHTML = SW.map((s, i) => '<div class="swipe"><div class="cap"><span>Email ' + (i + 1) + ' · ' + s.when + '</span><button type="button" class="btn sec" data-swipe="' + i + '">Copy email</button></div><div class="subj">Subject: ' + s.subject + '</div><pre>' + s.body.replace('{link}', LINK).replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</pre></div>').join('');
wrap.querySelectorAll('[data-swipe]').forEach(b => b.addEventListener('click', async () => {
const s = SW[Number(b.dataset.swipe)]; const text = 'Subject: ' + s.subject + '\n\n' + s.body.replace('{link}', LINK);
try { await navigator.clipboard.writeText(text); b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy email'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); }
}));
}
// launch moment (admin: Settings > launchAt, ISO 8601 with offset)
const at = cfg.launchAt ? new Date(cfg.launchAt) : null;
if (at && !isNaN(at)) {
$('lwWhen').hidden = false;
$('lwWhenAt').textContent = at.toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
const tick = () => { const ms = at - Date.now(); if (ms <= 0) { $('lwWhenIn').textContent = 'doors are open'; return; }
const d = Math.floor(ms / 86400000), h = Math.floor(ms % 86400000 / 3600000), m = Math.floor(ms % 3600000 / 60000);
$('lwWhenIn').textContent = (d ? d + 'd ' : '') + h + 'h ' + m + 'm to go'; };
tick(); setInterval(tick, 30000);
}
function render() {
const items = IAP.launchChecks(me);
const done = items.filter(i => i.done).length;
$('lwDone').textContent = done; $('lwBar').style.width = Math.round(done / items.length * 100) + '%';
$('chk').innerHTML = items.map((i, n) => '<li class="' + (i.done ? 'done' : '') + '"><div class="box">' + (i.done ? '✓' : (n + 1)) + '</div>'
+ '<div><h3>' + i.title + '</h3><p>' + i.how + '</p><div class="why">' + i.why + '</div>' + (i.note ? '<p class="small" style="margin-top:4px">' + i.note + '</p>' : '') + '</div>'
+ '<div class="act">' + (i.manual ? '<button class="btn small ' + (i.done ? 'sec' : '') + '" type="button" data-manual="' + i.key + '">' + (i.done ? 'Undo' : 'Mark done') + '</button>' : '<a class="btn small sec" href="' + i.href + '">' + i.cta + '</a>') + '</div></li>').join('');
$('chk').querySelectorAll('[data-manual]').forEach(b => b.addEventListener('click', () => { IAP.launchToggle(b.dataset.manual); render(); }));
}
render();
})();
+2077 -202
View File
File diff suppressed because it is too large Load Diff
+71
View File
@@ -0,0 +1,71 @@
// Promo tools > Network sites (Marty 2026-11-14): the promo kits of the other network sites, read live from each site's own public
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on Downline Banners or Viral Banner Blitz shows here
// at once. Usernames are network-wide: the member's InstantAdPay username is their sponsor link on those sites even if they never
// visited them. Nothing is stored here.
window.IAPNetKits = (function () {
const SITES = [
{ key: 'dlb', name: 'Downline Banners', feed: 'https://downlinebanners.com/api/promo-kit', blurb: 'One global line of $5 banner spots on Polygon. A spot buys 300 guaranteed views on the board and a place in the line; every sale is split on-chain in the same transaction. Nothing is promised: a spot is paid only when spots sell after it.' },
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' }
];
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const $ = id => document.getElementById(id);
let user = '', cur = '', cache = {}, txt = [];
try { cur = localStorage.getItem('iap.netkit') || ''; } catch (e) {}
if (!SITES.some(s => s.key === cur)) cur = SITES[0].key;
function setUser(u) { if (u && u !== user) { user = u; cache = {}; } }
async function copy(t, btn) {
try { await navigator.clipboard.writeText(t); } catch (e) { const a = document.createElement('textarea'); a.value = t; document.body.appendChild(a); a.select(); try { document.execCommand('copy'); } catch (e2) {} a.remove(); }
if (window.IAP && IAP.status) IAP.status('Copied.', 'ok');
if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1300); }
}
const cb = (t, label, cls) => { txt.push(t); return '<button type="button" class="btn small ' + (cls == null ? 'sec' : cls) + '" data-nkc="' + (txt.length - 1) + '">' + esc(label || 'Copy') + '</button>'; };
function pick() {
const p = $('nkPick'); if (!p) return;
p.innerHTML = SITES.map(s => '<button type="button" class="chip-t' + (s.key === cur ? ' on' : '') + '" data-nk="' + s.key + '">' + esc(s.name) + '</button>').join('');
p.querySelectorAll('[data-nk]').forEach(b => b.addEventListener('click', () => { cur = b.dataset.nk; try { localStorage.setItem('iap.netkit', cur); } catch (e) {} pick(); show(); }));
}
function render(site, k) {
txt = [];
const by = {}; const angles = [];
(k.creatives || []).forEach(c => { if (!by[c.angle]) { by[c.angle] = []; angles.push(c); } by[c.angle].push(c); });
let h = '<p class="muted small" style="margin:0 0 12px">' + esc(site.blurb) + '</p>';
// tracked links (2026-11-14): the site's LinkSpin network link, credited here to InstantAdPay as the site that sent the visit
const strip = (label, url, cls) => '<div class="promo-strip" style="padding:0 0 12px"><div><span class="eyebrow" style="margin:0 0 4px">' + esc(label) + '</span><div class="mono small" style="overflow-wrap:anywhere">' + esc(url) + '</div></div><span>' + cb(url, 'Copy link', cls) + '</span></div>';
const fromHere = u => String(u).replace(/([?&]src=)[a-z0-9]+/i, '$1iap');
h += k.links.map(l => strip(l.label, l.url, '') + (l.tracked ? strip(l.label + ', tracked', fromHere(l.tracked), 'sec') : '')).join('');
if (k.links.some(l => l.tracked)) h += '<p class="muted small" style="margin:0 0 12px">A tracked link goes through LinkSpin first, so the network can see the visit came from InstantAdPay, then opens the same page with your username. Use either one.</p>';
h += '<div class="card-head" style="margin-top:6px"><h3>Creatives</h3><span class="sub">every HTML snippet already links to you</span></div>';
angles.forEach(a => {
h += '<details class="promo-block nk-set"' + (a === angles[0] ? ' open' : '') + '><summary class="pb-head" style="cursor:pointer"><span class="lab"><b>' + esc(a.angleLabel) + '</b></span> <span class="muted small">' + by[a.angle].length + ' sizes</span></summary><div class="nk-grid">'
+ by[a.angle].map(c => '<figure class="nk-fig"><a href="' + esc(c.url) + '" target="_blank" rel="noopener"><img src="' + esc(c.url) + '" alt="' + esc(k.name + ', ' + c.label) + '" width="' + c.w + '" height="' + c.h + '" loading="lazy" style="max-width:' + Math.min(c.w, c.w > 600 ? 420 : c.w) + 'px"></a>'
+ '<figcaption class="small"><b>' + esc(c.label) + '</b> <span class="muted">' + c.w + '×' + c.h + '</span></figcaption><div class="pb-actions"><a class="btn small sec" href="' + esc(c.url) + '" target="_blank" rel="noopener" download>Download</a> ' + cb(c.url, 'Copy URL') + ' ' + cb(c.html, 'Copy HTML') + '</div></figure>').join('')
+ '</div></details>';
});
h += '<div class="card-head" style="margin-top:14px"><h3>Short lines</h3><span class="sub">chats, comments, text ads, signatures</span></div>'
+ k.lines.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
h += '<div class="card-head" style="margin-top:14px"><h3>Headlines</h3></div>' + k.headlines.map(t => '<div class="promo-block"><div class="pb-text"><b>' + esc(t) + '</b></div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
h += '<div class="card-head" style="margin-top:14px"><h3>Email</h3><span class="sub">plain text, paste it into any mailer</span></div><div class="promo-block"><div class="pb-head"><span class="lab">Subject:</span> ' + esc(k.email.subject) + '</div><div class="pb-text">' + esc(k.email.body) + '</div><div class="pb-actions">' + cb(k.email.subject, 'Copy subject') + ' ' + cb(k.email.body, 'Copy email', '') + '</div></div>';
h += '<div class="card-head" style="margin-top:14px"><h3>Social posts</h3></div>' + k.posts.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t, 'Copy post') + '</div></div>').join('');
if (k.note) h += '<p class="muted small" style="margin:12px 0 0">' + esc(k.note) + '</p>';
if (k.promotePage) h += '<p class="small" style="margin:8px 0 0">The same kit is on <a href="' + esc(k.promotePage + '?u=' + encodeURIComponent(user)) + '" target="_blank" rel="noopener">' + esc(k.name) + ' &rsaquo; Promote</a>.</p>';
return h;
}
async function show() {
const box = $('nkBody'); if (!box) return;
const site = SITES.find(s => s.key === cur);
if (!user) { box.innerHTML = '<p class="muted">Pick a username first: it becomes your link on every network site.</p>'; return; }
box.innerHTML = '<p class="muted small">Loading the ' + esc(site.name) + ' kit...</p>';
try {
if (!cache[cur]) {
const r = await fetch(site.feed + '?u=' + encodeURIComponent(user), { cache: 'no-store' });
if (!r.ok) throw new Error('HTTP ' + r.status);
cache[cur] = await r.json();
}
if (cur !== site.key) return;
box.innerHTML = render(site, cache[cur]);
box.querySelectorAll('[data-nkc]').forEach(b => b.addEventListener('click', () => copy(txt[Number(b.dataset.nkc)], b)));
} catch (e) { box.innerHTML = '<p class="muted">Could not load the ' + esc(site.name) + ' kit right now. Try again in a minute.</p>'; }
}
function load(u) { if (u) setUser(u); pick(); show(); }
return { load, setUser, SITES };
})();

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