Skip to main content
Developer & Creator Documentation

Monetization, Rewarded Ad-Gate & Consent Mode v2 Architecture

YourPlayground.games keeps 100% of game browsing and instant arcade play free of subscription paywalls by aligning ad formats with high-intent value moments across web and native mobile

Open AI Studio Direct-Answer FAQ Hub Machine-Readable Corpus (/llms-full.txt)

Monetization, Rewarded Ad-Gate & Consent Mode v2 Architecture

Document ID: YPG-MON-007 | Index: docs/README.md

Scope: Google AdSense, Google IMA HTML5 SDK VAST 4.2 Rewarded Video, Single-Use HMAC adGrantToken State Machine, Play-Credit Loop, AdMob Mobile/Tablet Placements, Google Consent Mode v2 (ypg_consent_v2), and Telemetry (window.ypgTrack)

Primary Modules: src/services/adGateService.mjs, src/routes/apiAdsRouter.mjs, public/assets/js/adGateModal.mjs, src/views/layout.mjs, public/assets/js/authModal.mjs


1. Hybrid Web & Mobile Monetization Strategy

YourPlayground.games keeps 100% of game browsing and instant arcade play free of subscription paywalls by aligning ad formats with high-intent value moments across web and native mobile/tablet surfaces:

  1. Web Studio Watch-Ad-to-Generate Gate (Google AdSense + Google IMA HTML5 SDK VAST 4.2): Generating a brand-new AI game (which consumes live Google Cloud Vertex AI compute) requires completing a short sponsored ad session (15–30 s VAST rewarded video or AdSense slot in production; 5 s deterministic local test preview on :9033).
  2. Extended Play-Credit Ticket Loop (Play More, Keep Creating!): Highlighted in the canonical ticket banner (Watch a short ad (15–30 sec) -> Earn play credits (or extra generation) -> Continue playing and creating for free), rewarded completions grant creator generation credits without interrupting active mid-frame gameplay.
  3. Non-Intrusive Showcase Display Slots (ADSENSE_DISPLAY_SLOT_ID): Optional responsive display inventory strictly outside #ypg-stage-viewport so zero accidental clicks ("fat-finger" policy violations) ever occur near arcade controls.
  4. Native iOS & Android AdMob Placements: Google AdMob Rewarded Video (for AI synthesis unlocks), Rewarded Interstitial (between multi-game arcade marathons), and Adaptive Anchored Banners on Showcase/Leaderboard tabs (never overlapping the game WebView).

2. Google AdSense & IMA HTML5 SDK VAST 4.2 Architecture

2.1 Environment-Driven Live vs. Local Test Mode (src/config/env.mjs)

Zero code edits are required to transition between local deterministic E2E testing and live Google monetization:

Environment VariableFormat / ExampleRuntime Behavior
ADSENSE_PUBLISHER_ID (alias ADSENSE_CLIENT_ID)ca-pub-1234567890123456 or pub-...Normalized via normalizeAdsensePublisherId(); injects <meta name="google-adsense-account">, <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-...">, and /ads.txt DIRECT, f08c47fec0942fa0 record.
ADSENSE_SLOT_ID (alias ADSENSE_REWARD_SLOT_ID)9876543210Hydrates <ins class="adsbygoogle"> inside #ypg-ad-gate-modal and sets adsenseMode = 'live' when paired with ADSENSE_PUBLISHER_ID.
ADSENSE_DISPLAY_SLOT_ID (alias ADSENSE_BANNER_SLOT)1122334455Exposes optional non-stage display banner slot ID in GET /api/config and #ypg-bootstrap.
VAST_REWARD_TAG_URLhttps://pubads.g.doubleclick.net/gampad/ads?...Configures IAB VAST 4.2 / Google Ad Manager H5 Games Ads video tag URL (adsense.vastConfigured: true in /api/config).
AD_WATCH_DURATION_SECONDS5 (dev) / 15–30 (prod)Server-enforced watch duration (0 ≤ T ≤ 300 s) before POST /api/ads/sessions/:id/complete issues an adGrantToken.

2.2 Google IMA HTML5 SDK VAST 4.2 Integration Contract

When vastRewardTagUrl is configured alongside live AdSense/GAM inventory, the ad-gate container mounts a dedicated video element + google.ima.AdDisplayContainer overlay inside #ypg-ad-gate-modal:

  1. User click on Watch Ad & Generate Game provides the synchronous user-activation gesture required by adDisplayContainer.initialize().
  2. AdsLoader.requestAds(adsRequest) fetches the VAST 4.2 XML manifest (linear skippable/non-skippable rewarded creative).
  3. IMA lifecycle events map deterministically onto the server session endpoints:
  • AdEvent.Type.STARTED → visual countdown & progress track active (ad_gate_open).
  • AdEvent.Type.COMPLETE (and server elapsed threshold satisfied) → unlocks #ypg-ad-complete-btn → POST /api/ads/sessions/:sessionId/complete.
  • AdEvent.Type.SKIPPED / user Cancel / Escape → POST /api/ads/sessions/:sessionId/cancel (ad_gate_cancel), cleanly aborting synthesis without charge.
  • AdErrorEvent (no-fill / ad-blocker fallback) → falls back cleanly to the timed house/AdSense sponsorship slot so legitimate creators are never deadlocked by regional VAST no-fill.

3. Single-Use HMAC adGrantToken Cryptographic State Machine

Implemented in src/services/adGateService.mjs, the ad gate enforces server-authoritative timing, actor binding, and atomic single-use token burn.

stateDiagram-v2
    [*] --> Watching: POST /api/ads/sessions<br/>(ads_<32-hex>, status='watching')
    Watching --> Watching: Early POST .../complete (elapsed < requiredMs - 250ms)<br/>Returns 400 AD_INCOMPLETE (session stays open)
    Watching --> Cancelled: POST .../cancel or User Escape<br/>(status='cancelled')
    Watching --> Expired: nowMs > expiresAtMs<br/>(status='expired', 400 AD_EXPIRED)
    Watching --> GrantIssued: POST .../complete (elapsed >= requiredMs - 250ms)<br/>Mints HMAC-SHA256 adGrantToken (jti=adg_<32-hex>, TTL=300s)
    Cancelled --> [*]: Blocks future /complete (400 AD_CANCELLED)
    Expired --> [*]
    GrantIssued --> GrantVerified: POST /api/games/generate Step 1 (verifyGrantToken)<br/>Validates payload + actor without burning token
    GrantVerified --> GrantIssued: Step 2 Input Invalid (400 INVALID_INPUT)<br/>Token preserved so creator can fix prompt typo!
    GrantVerified --> Consumed: Step 3 Input Valid (consumeGrantToken)<br/>grant.consumed = true (Single-Use Burn)
    Consumed --> [*]: Replay attempts rejected with 402 AD_REQUIRED

3.1 Token Payload & Actor Provenance Upgrade

When completeSession() succeeds, signGrantPayload() signs the following JSON structure using HMAC-SHA256 with AD_HMAC_SECRET (defaulting to SESSION_SECRET):

{
  "v": 1,
  "jti": "adg_9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c",
  "sid": "ads_1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d",
  "act": "vis_a1b2c3d4e5f60718293a4b5c6d7e8f90",
  "vid": "vis_a1b2c3d4e5f60718293a4b5c6d7e8f90",
  "uid": null,
  "est": true,
  "iat": 1795284000000,
  "exp": 1795284300000
}

Actor Matching Invariant (actorsMatch(owner, caller)):

  1. If both owner.userId and caller.userId are present, they must be strictly equal (usr_... === usr_...), preventing cross-account token theft.
  2. If both share the same signed ypg_vid browser cookie (owner.visitorId === caller.visitorId), access is granted—smoothly handling first-visit cookie establishment (Set-Cookie on startSession echoed back on completeSession and generate) as well as mid-flow sign-in/sign-out transitions.
  3. Periodic in-memory garbage collection (pruneExpiredRecords()) evicts expired sessions and grants after a 15-minute grace window so memory usage stays bounded O(A_active).

4. Google AdMob Mobile & Tablet Monetization Architecture

On universal iOS and Android applications (see docs/mobile/MOBILE_AND_TABLET_ARCHITECTURE.md), Google Mobile Ads SDK (AdMob) mirrors the web ad-gate state machine using Server-Side Verification (SSV):

Placement SurfaceAdMob FormatTrigger ConditionUX & Store Policy Safeguard
Studio Generate GateRewardedAdTapping Create Your Game — Free when play/generation credits = 0AdMob SSV callback (custom_data = sessionId) signs ECDSA reward confirmation verified by backend before minting adGrantToken.
Play More Credit RefillRewardedAdTapping Play More, Keep Creating! ticket bannerGrants +3 play/remix credits cached in Firestore user/device wallet.
Post-Game Loop TransitionRewardedInterstitialAdOptional opt-in prompt after every N = 4 completed YPG_GAME_OVER roundsNever triggered mid-gameplay; explicit 15s pre-prompt with instant cancel option.
Explore / Leaderboard FooterAnchoredAdaptiveBannerDocked strictly on /showcase and /categories native tabsAutomatically hidden (GONE / removed) whenever the Studio or Playable Game WebView stage is active.

5. Google Consent Mode v2 (ypg_consent_v2) & Privacy Engineering

Compliance with GDPR, ePrivacy Directive, DMA, UK PECR, and KVKK is engineered directly into <head> in src/views/layout.mjs (lines 334–368) and hydrated by initConsentBanner() in public/assets/js/authModal.mjs (lines 222–329).

5.1 Default-Denied Synchronous <head> Initialization

Before any external Google Analytics (gtag.js), Google Tag Manager (gtm.js), Microsoft Clarity (clarity.ms), or Google AdSense (adsbygoogle.js) script tag is parsed by the browser:

  1. gtag('consent', 'default', { ad_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied', analytics_storage: 'denied', wait_for_update: 500 }) executes synchronously.
  2. If returning user preferences exist in window.localStorage.getItem('ypg_consent_v2'), <head> immediately parses and dispatches gtag('consent', 'update', window.__ypgConsentState) prior to tag firing.
  3. First-time visitors see the compact, non-blocking <aside id="ypg-consent-banner"> (Accept All, Essential Only, Customize with granular Analytics & Telemetry and Personalized Ads checkboxes). Users can reopen preferences at any time via the footer Cookie Settings button (data-testid="cookie-settings-btn").

5.2 Stored ypg_consent_v2 Schema

{
  "version": 2,
  "analytics": true,
  "ads": true,
  "ad_storage": "granted",
  "ad_user_data": "granted",
  "ad_personalization": "granted",
  "analytics_storage": "granted",
  "updatedAt": "2026-11-21T18:00:00.000Z"
}

6. Client Telemetry Taxonomy (window.ypgTrack)

window.ypgTrack(eventName, params) (layout.mjs lines 371–389) pushes structured event envelopes into a bounded 200-event ring buffer (window.ypgEventBuffer / window.__ypgEvents) for deterministic inspection and forwards events to window.gtag('event', eventName, safeParams) strictly when GA_MEASUREMENT_ID is configured AND window.__ypgConsentState.analytics_storage === 'granted':

Event NameSource ModulePayload Parameters (params)Funnel Stage Measured
prompt_submitstudioClient.mjs{ engine, model, thinkingLevel, isRemix }Top-of-funnel Studio intent & model selection distribution
ad_gate_openadGateModal.mjs{ sessionId, mode, requiredSeconds }Rewarded ad modal impression start
ad_gate_completeadGateModal.mjs{ sessionId, mode }Rewarded ad completion & adGrantToken issuance
ad_gate_canceladGateModal.mjs{ sessionId, mode }Early ad dismissal / drop-off rate
game_generatedstudioClient.mjs{ slug, engine, model, thinkingLevel }Successful Vertex AI synthesis & stage hot-swap
game_stage_playplayerStage.mjs{ slug }Interactive OOPIF stage load & active gameplay session
game_remixstudioClient.mjs / authModal.mjs`{ slug, source: 'studio_url' \'remix_link' }`
auth_sign_inauthModal.mjs`{ mode: 'google_oauth' \'test', provider }`