From 4d6a0f2f838e2e31590132b10e1df8ad53c79572 Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 16 Oct 2026 08:18:09 -0500 Subject: [PATCH] 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 --- chatbot.js | 5 +- docs/GAME-PASS-RELEASE.md | 50 ++++++ docs/GAME-PASS.md | 214 +++++++++++++++++++++++++ gamepass.js | 319 ++++++++++++++++++++++++++++++++++++++ public/admin.html | 23 ++- public/assets/admin.js | 38 ++++- public/assets/my.js | 60 ++++++- public/my.html | 5 +- qa/gamepass.mjs | 215 +++++++++++++++++++++++++ qa/run.sh | 3 + qa/walk.mjs | 12 +- server.js | 118 ++++++++++++-- 12 files changed, 1044 insertions(+), 18 deletions(-) create mode 100644 docs/GAME-PASS-RELEASE.md create mode 100644 docs/GAME-PASS.md create mode 100644 gamepass.js create mode 100644 qa/gamepass.mjs diff --git a/chatbot.js b/chatbot.js index bad8ae8..cf582f0 100644 --- a/chatbot.js +++ b/chatbot.js @@ -20,8 +20,10 @@ function key() { function enabled() { return !!key(); } // ---- canned answers: instant, free, always in voice ---- -const KNOWLEDGE_DATE = '2026-10-15'; // bump whenever the canned answers / prompt are brought up to date +const KNOWLEDGE_DATE = '2026-10-16'; // bump whenever the canned answers / prompt are brought up to date const CANNED = [ + { re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i, + a: 'The Game Pass is $5 for 7 days and covers all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the Pass badge. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Buy it in Members > Games > Game Pass: it costs 500 purchased credits (credits from a package you bought; earned credits do not count). If you have none, buy a $5 package and the pass starts the moment it settles, and you keep every credit of the package for your ads. Buying while a pass is active adds 7 days.' }, { re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i, a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' }, { re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i, @@ -160,6 +162,7 @@ FACTS: - VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through ', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends. - BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin. - PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members. +- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL NINE games (linked positions share it). Paid with 500 PURCHASED-grade credits (ads.gamePurchase purchasedOnly, the PolyWarriors mint rule; earned credits never buy a pass); with no purchased credits the pass waits and a $5 package bought meanwhile starts it automatically (the member keeps the package credits). Buying while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit. - 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. diff --git a/docs/GAME-PASS-RELEASE.md b/docs/GAME-PASS-RELEASE.md new file mode 100644 index 0000000..a6fd408 --- /dev/null +++ b/docs/GAME-PASS-RELEASE.md @@ -0,0 +1,50 @@ +# 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. It costs 500 purchased credits, the credits from a package you bought. If you + have none, buy a $5 package and the pass starts the moment it settles; you keep every credit of that package for your ads. Buying + 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". diff --git a/docs/GAME-PASS.md b/docs/GAME-PASS.md new file mode 100644 index 0000000..4dbac06 --- /dev/null +++ b/docs/GAME-PASS.md @@ -0,0 +1,214 @@ +# Game Pass: draft spec (2026-10-16) + +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. +- 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=&m=&e=&ts=&sig=` 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: `, headers `X-Game-Ts: ` and +> `X-Game-Sig: HMAC-SHA256(secret, ts + '\n' + rawBody)` hex (sign the exact bytes you send). +> - `GET /api/partner/tournament/pending?game=&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` lists `{ week, place, email, memberId, wallet, pol }` rows still unpaid, and the paying +> game calls `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. Which faucet pays is a +> settings/ops decision, not yet wired: until it is, Admin > Game Pass shows the unpaid rows. +> 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` skips the credit charge. + +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:`). 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: `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:')`) 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); the Games pane lists unpaid rows until a faucet is wired. +- 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). diff --git a/gamepass.js b/gamepass.js new file mode 100644 index 0000000..5a53a4f --- /dev/null +++ b/gamepass.js @@ -0,0 +1,319 @@ +// Game Pass (2026-10-16): the $5 weekly pass across all nine games, 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') +// - waiting orders order -> { status, email, ts, tx } (a $5+ package bought while an order waits fulfils it: the pwpasses pattern) +// - 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). +'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']; +const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' }; +const 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) +const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6; + +let R = null; // deps from server.js +let passes, orders, prizes; // durable persisted maps (server.js open-tokens store, DURABLE set) +let L = null; // the cap ledger: { members: { email: { days: {}, deferred: {}, weeks: {} } }, refs: { 'game:ref': {...} } } +let saveTimer = null; + +// ---- Central time (no tz lib; same arithmetic as leaderboard.js) ---- +function ctParts(ts) { + const s = new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' }); + const m = /(\w{3}), (\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/.exec(s); + return { wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(m[1]), y: +m[4], mo: +m[2], d: +m[3], h: +m[5] % 24, mi: +m[6] }; +} +function ctMidnight(ts) { const p = ctParts(ts); const guess = Date.UTC(p.y, p.mo - 1, p.d, 5, 0, 0); const q = ctParts(guess); return (q.h === 0 && q.d === p.d) ? guess : guess + 3600000; } +function weekStart(ts) { const p = ctParts(ts); const mid = ctMidnight(ts); return mid - ((p.wd + 6) % 7) * 86400000; } +const dayKey = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ }); +const weekKey = ts => dayKey(weekStart(ts)); +const dayLabel = key => new Date(key + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); + +// ---- settings (Admin > Settings, no deploy) ---- +function cfg() { + const sc = R.siteConfig(); + const n = (k, d) => { const raw = sc[k]; if (raw === undefined || raw === null || String(raw).trim() === '') return d; const v = Number(raw); return Number.isFinite(v) ? v : d; }; + const start = String(sc.capsStartDate || '').trim(); + return { + enabled: ['1', 'true', 'on', 'yes'].includes(String(sc.gamePassEnabled).trim().toLowerCase()), + price: Math.max(1, Math.round(n('gamePassPriceCredits', 500))), + days: Math.max(1, Math.round(n('gamePassDays', 7))), + free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) }, + pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) }, + start: /^\d{4}-\d{2}-\d{2}$/.test(start) ? start : '', + pct: Math.max(0, n('passTournamentPct', 5)), + gamesChat: String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(), + gamesTopic: String(sc.telegramGamesTopicId || '').trim(), + }; +} +const enforcedOn = (c, day) => !!(c.start && day >= c.start); + +// ---- ledger file ---- +const FILE = () => path.join(R.dataDir, 'gamepass-ledger.json'); +function load() { try { L = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { L = null; } if (!L || typeof L !== 'object') L = { members: {}, refs: {} }; L.members = L.members || {}; L.refs = L.refs || {}; } +function save() { saveTimer = null; try { fs.writeFileSync(FILE(), JSON.stringify(L)); } catch (e) { console.error('gamepass ledger save', e.message); } } +function touch() { if (!saveTimer) saveTimer = setTimeout(save, 500); } +function member(e) { return (L.members[e] = L.members[e] || { days: {}, deferred: {}, weeks: {} }); } +function dayRow(M, day) { + return (M.days[day] = M.days[day] || { daily: 0, total: 0, carried: 0, dropped: 0, deferredOut: 0, grants: 0, hits: { daily: 0, total: 0 }, + tier: { free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 } }, + would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 } }); // would = what the caps would have done before capsStartDate +} + +function init(deps) { + R = deps; + passes = R.persistedMap('gamepass'); + orders = R.persistedMap('gporders'); + prizes = R.persistedMap('gpprizes'); + load(); +} + +// ---- the pass ---- +function rec(e) { return passes.get(e) || null; } +function flag(email, now) { const p = rec(String(email || '').toLowerCase()); const t = now || Date.now(); const until = p && Number(p.until) || 0; return { active: until > t, until: until || null }; } +function extend(e, via, extra, now) { + const c = cfg(); const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] }; + const base = Math.max(t, Number(cur.until) || 0); + const until = base + c.days * 86400000; + const bought = [Object.assign({ ts: t, via, usd: c.price / 100, days: c.days }, extra || {})].concat(cur.bought || []).slice(0, 200); + passes.set(e, Object.assign({}, cur, { until, bought, ts: t })); + return { until, days: c.days }; +} +function waitingOrder(e) { for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e) return Object.assign({ order: k }, o); return null; } +function comp(email, why) { const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }); return { active: true, until: x.until, days: x.days }; } // support comp: counts as no sale + +// GET /api/my/gamepass +function view(email, now) { + 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); + const caps = capsFor(e, t); + return { enabled: c.enabled, active: f.active, until: f.until, 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) } }; +} + +// POST /api/my/gamepass/buy. `charge(price, label)` runs ads.gamePurchase(purchasedOnly) and resolves { ok } | { error: 'short', ... } | { error }. +async function buy(email, charge, now) { + const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); + if (!c.enabled) return { error: 'The Game Pass is not open yet.' }; + const r = await charge(c.price, 'Game Pass (' + c.days + ' days)'); + if (r && r.ok) { + const x = extend(e, 'credits', { credits: c.price, campaignId: r.campaignId || null }, t); + console.log('gamepass bought with credits', e, c.price, 'until', new Date(x.until).toISOString()); + return { ok: true, active: true, until: x.until, days: c.days, paid: 'credits' }; + } + if (r && r.error === 'short') { + // no purchased-grade credits on a position: the pass waits for a $5 package (bought while the order waits, it fulfils it) + let w = waitingOrder(e); + if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t }); w = Object.assign({ order: k }, orders.get(k)); } + return { ok: false, needPay: true, payUrl: '/my?from=gamepass#buy', order: w.order, price: c.price, usd: c.price / 100, available: r.available || 0, need: r.need || c.price, + message: 'The pass is paid with purchased credits. Buy a $' + (c.price / 100) + ' package and the pass starts the moment it settles; you keep every credit of the package for your ads.' }; + } + return { error: (r && r.error) || 'The purchase did not go through. Nothing was taken.' }; +} + +// a package purchase landing on chain fulfils this account's waiting order (one pass per purchase of $5 or more) +async function onEvent(ev) { + if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null; + const c = cfg(); if ((ev.priceCents || 0) < c.price) return null; + const a = (ev.devEmail && !R.isProd) ? { email: ev.devEmail } : await R.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null; + const e = String(a.email).toLowerCase(); + const p = passes.get(e); if (p && (p.bought || []).some(b => b.tx && b.tx === ev.tx)) return null; // each purchase counts once + const w = waitingOrder(e); if (!w) return null; + orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents: ev.priceCents, paidAt: Date.now() })); + const x = extend(e, 'package', { tx: ev.tx, cents: ev.priceCents, order: w.order }, ev.ts || Date.now()); + console.log('gamepass fulfilled by package', e, 'tx', String(ev.tx).slice(0, 12), 'until', new Date(x.until).toISOString()); + return { order: w.order, until: x.until }; +} + +// ---- the caps ---- +function capsFor(email, now, game) { + const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const day = dayKey(t); const pass = flag(e, t).active; + const lim = pass ? c.pass : c.free; const M = L.members[e]; const D = M && M.days[day]; + const used = { daily: r6(D ? D.daily : 0), total: r6(D ? D.total : 0) }; + const out = { daily: lim.daily, total: lim.total, used, day, enforced: enforcedOn(c, day), pass }; + if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0)); + return out; +} + +// POST /api/partner/polgrant. Returns { allowed, deferred, pass, day } (+ carried, capHit, enforced, repeat). +function grant(o) { + const e = String(o.email || '').toLowerCase(); const game = String(o.game || '').toLowerCase(); const kind = o.kind === 'progress' ? 'progress' : 'daily'; + const pol = r6(o.pol); const ref = String(o.ref || '').slice(0, 120); const t = o.now || Date.now(); const day = dayKey(t); + if (!e || !GAMES.includes(game) || !ref || !(pol >= 0)) return { error: 'memberId/email, game, kind, pol and ref are required' }; + const key = game + ':' + ref; + const prev = L.refs[key]; + if (prev) return { allowed: prev.allowed, deferred: prev.deferred, pass: prev.pass, day: prev.day, carried: prev.carried || 0, capHit: prev.capHit || null, enforced: !!prev.enforced, repeat: true, voided: !!prev.voided }; + const c = cfg(); const pass = flag(e, t).active; const lim = pass ? c.pass : c.free; const enforced = enforcedOn(c, day); + const M = member(e); const D = dayRow(M, day); const tier = D.tier[pass ? 'pass' : 'free']; + let totalRem = Math.max(0, r6(lim.total - D.total)), dailyRem = Math.max(0, r6(lim.daily - D.daily)); + // carry-forward: progress POL deferred on an EARLIER day for this game is paid first, inside today's total cap + let carried = 0; const q = M.deferred[game] || []; + for (const d of q) { + if (d.day >= day || d.left <= 0) continue; + const take = enforced ? Math.min(d.left, Math.max(0, r6(totalRem - carried))) : d.left; + if (take <= 0) break; + d.left = r6(d.left - take); carried = r6(carried + take); d.paid = (d.paid || []).concat([{ day, pol: take, ref }]).slice(-20); + } + M.deferred[game] = q.filter(d => d.left > 0); + if (carried) { D.total = r6(D.total + carried); D.carried = r6(D.carried + carried); tier.allowed = r6(tier.allowed + carried); totalRem = Math.max(0, r6(totalRem - carried)); } + // the new grant + let allowed = pol, deferred = 0, dropped = 0, capHit = null; + const wouldAllowed = kind === 'daily' ? Math.min(pol, dailyRem, totalRem) : Math.min(pol, totalRem); + const wouldHit = wouldAllowed < pol ? (kind === 'daily' && dailyRem <= totalRem ? 'daily' : 'total') : null; + if (enforced) { + allowed = r6(wouldAllowed); capHit = wouldHit; + if (kind === 'daily') { dropped = r6(pol - allowed); if (dropped) D.dropped = r6(D.dropped + dropped); } + else { deferred = r6(pol - allowed); if (deferred) { q.push({ ref, pol, left: deferred, ts: t, day }); M.deferred[game] = q; D.deferredOut = r6(D.deferredOut + deferred); } } + if (capHit) { D.hits[capHit] += 1; tier[capHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1; } + } else if (wouldHit) { // before capsStartDate: everything is allowed, but Admin sees what the caps would have done + D.would[kind === 'daily' ? 'dropped' : 'deferred'] = r6(D.would[kind === 'daily' ? 'dropped' : 'deferred'] + (pol - wouldAllowed)); + D.would[wouldHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1; + } + if (kind === 'daily') D.daily = r6(D.daily + allowed); + D.total = r6(D.total + allowed); tier.allowed = r6(tier.allowed + allowed); D.grants += 1; + // tournament activity: one point per reported grant (progress and daily weigh the same) + if (pol > 0) { const wk = weekKey(t); M.weeks[wk] = M.weeks[wk] || {}; M.weeks[wk][game] = (M.weeks[wk][game] || 0) + 1; } + if (capHit) { const p = passes.get(e) || { until: 0, bought: [] }; passes.set(e, Object.assign({}, p, { lastCapHit: { ts: t, day, game, kind: capHit, pass } })); } + const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed }; + L.refs[key] = out; touch(); + return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false }; +} + +// POST /api/partner/polgrant/void: the game decided not to pay after all. Reverses this ref's own share (the carry it triggered +// belongs to earlier refs and stays). The ref stays answered, as voided, so a replay is still idempotent. +function voidGrant(o) { + const game = String(o.game || '').toLowerCase(); const ref = String(o.ref || '').slice(0, 120); const key = game + ':' + ref; + const prev = L.refs[key]; if (!prev) return { ok: true, unknown: true }; + if (prev.voided) return { ok: true, voided: true, repeat: true }; + const M = member(prev.email); const D = dayRow(M, prev.day); + const own = r6(prev.own || 0); + D.total = Math.max(0, r6(D.total - own)); if (prev.kind === 'daily') D.daily = Math.max(0, r6(D.daily - own)); + const tier = D.tier[prev.pass ? 'pass' : 'free']; tier.allowed = Math.max(0, r6(tier.allowed - own)); + let removed = 0; const q = M.deferred[game] || []; for (const d of q) if (d.ref === ref) { removed = r6(removed + d.left); d.left = 0; } M.deferred[game] = q.filter(d => d.left > 0); + if (removed) D.deferredOut = Math.max(0, r6(D.deferredOut - removed)); + const wk = weekKey(prev.ts || Date.now()); if (M.weeks[wk] && M.weeks[wk][game]) M.weeks[wk][game] -= 1; + Object.assign(prev, { voided: true, allowed: 0, deferred: 0, carried: 0, voidedAt: Date.now(), reversed: { allowed: own, deferred: removed } }); touch(); + return { ok: true, voided: true, reversed: { allowed: own, deferred: removed } }; +} + +// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ---- +function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; } +function holdersIn(start, end) { + const out = []; + for (const [e, p] of passes) { if (!p || !(p.until > 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 +function salesIn(start, end) { 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) { 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); 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} Game Pass Tournament · ' + 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, '

You finished #' + w.place + ' in the Game Pass Tournament for the ' + row.label + ' with ' + w.score + ' plays across the games. Your prize of ' + w.pol.toFixed(2) + ' POL is paid to the wallet on your InstantAdPay account by the games this week.

'); } 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).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 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 ((p.until || 0) > t) active += 1; for (const b of p.bought || []) { if (!isSale(b)) { comped += 1; continue; } soldTotal += 1; usdTotal += Number(b.usd) || 0; if (b.ts >= ws) { soldWeek += 1; usdWeek += Number(b.usd) || 0; } } } + for (const [, o] of orders) if (o.status === 'waiting') waiting += 1; + const wk = { pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, carried: 0, dropped: 0, deferredOut: 0, grants: 0, would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 }, players: 0 }; + const today = { allowed: 0, grants: 0, players: 0 }; + let qEntries = 0, qPol = 0, qMembers = 0; const byGame = {}; + for (const [e, M] of Object.entries(L.members)) { + let inWeek = false; + for (const [d, D] of Object.entries(M.days)) { + if (d < wkFrom) continue; inWeek = true; + for (const k of ['pass', 'free']) { wk[k].allowed = r6(wk[k].allowed + D.tier[k].allowed); wk[k].hitsDaily += D.tier[k].hitsDaily; wk[k].hitsTotal += D.tier[k].hitsTotal; } + wk.carried = r6(wk.carried + D.carried); wk.dropped = r6(wk.dropped + D.dropped); wk.deferredOut = r6(wk.deferredOut + D.deferredOut); wk.grants += D.grants; + for (const k of ['dropped', 'deferred']) wk.would[k] = r6(wk.would[k] + D.would[k]); wk.would.hitsDaily += D.would.hitsDaily; wk.would.hitsTotal += D.would.hitsTotal; + if (d === day) { today.allowed = r6(today.allowed + D.total); today.grants += D.grants; today.players += 1; } + } + if (inWeek) wk.players += 1; + let mine = 0; for (const [g, q] of Object.entries(M.deferred)) for (const x of q) { qEntries += 1; qPol = r6(qPol + x.left); mine += 1; byGame[g] = r6((byGame[g] || 0) + x.left); } + if (mine) qMembers += 1; + const W = M.weeks[wkFrom] || {}; for (const [g, n] of Object.entries(W)) { byGame['plays:' + g] = (byGame['plays:' + g] || 0) + n; } + void e; + } + const rows = [...prizes.values()].sort((a, b) => a.week < b.week ? 1 : -1); + return { enabled: c.enabled, settings: { price: c.price, days: c.days, 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 }, + passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting }, + pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today }, + capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would }, + deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame }, + tournament: { lastRun: rows[0] ? rows[0].ranAt : null, last: rows[0] || null, next: nextTournamentAt(t), pending: pending().length, history: rows.slice(0, 8) } }; +} + +// ---- housekeeping: answered refs and day rows older than KEEP_DAYS, week tallies older than 10 weeks ---- +function prune(now) { + const t = now || Date.now(); const cut = t - KEEP_DAYS * 86400000; const cutDay = dayKey(cut); const cutWeek = dayKey(weekStart(t - 70 * 86400000)); let n = 0; + for (const [k, r] of Object.entries(L.refs)) if ((r.ts || 0) < cut) { delete L.refs[k]; n++; } + for (const [e, M] of Object.entries(L.members)) { + for (const d of Object.keys(M.days)) if (d < cutDay) { delete M.days[d]; n++; } + for (const w of Object.keys(M.weeks)) if (w < cutWeek) { delete M.weeks[w]; n++; } + if (!Object.keys(M.days).length && !Object.keys(M.weeks).length && !Object.values(M.deferred).some(q => q.length)) delete L.members[e]; + } + for (const [k, o] of orders) if (o.status === 'waiting' && t - o.ts > 30 * 86400000) orders.delete(k); // a pass order nobody paid for in a month is forgotten + if (n) touch(); + return n; +} + +module.exports = { init, cfg, GAMES, NAMES, flag, view, buy, comp, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey, + _ledger: () => L }; diff --git a/public/admin.html b/public/admin.html index 450749a..a220c67 100644 --- a/public/admin.html +++ b/public/admin.html @@ -101,6 +101,7 @@ + + +