Documentation comes from this release commit, without inheriting newer content. Commit: 63ea8c2b3d.
Hub Integration: Magic Piano × @leapgame/app-sdk
The hub (@leapgame/app-sdk) is a dependency-injection container: it defines port interfaces for subscriptions, ads, auth tokens, and tracking, but imports zero native SDKs itself. Magic Piano's src/core/sdk/hub.ts bootstraps the hub by injecting the real native implementations — react-native-purchases (via createPurchasesAdapter), AppsFlyer (via createAppsFlyerAdapter), and Firebase Auth's getIdToken callback (ads do not go through the hub: they live behind @core/ads on Google AdMob — see admob-integration.md) — at app startup. A second singleton, src/core/sdk/instance.ts, manages the @piano/sdk (game engine + analytics), injecting Firebase Analytics adapters and an MMKV-backed player-data store. The two singletons share the same Firebase anonymous uid but are otherwise independent; the hub handles money and identity while the game SDK handles gameplay, MIDI, and event tracking.
1. RevenueCat — IAP & Subscription
Status: ✅ Fully integrated
What it does: Manages subscription purchases (weekly / yearly, with 50%-off discount variant), the one-off "remove ads" IAP, individual song unlocks, restore purchases, and entitlement syncing into the local Zustand store.
How it's wired:
- Hub port:
hub.subscription(typeSubscriptionServicefrom@leapgame/app-sdk), enabled whenpurchasesSdkis injected intocreateHub. - Adapter:
createPurchasesAdapteratsrc/core/sdk/adapters/purchases-adapter.ts— thin pass-through wrappingreact-native-purchases'Purchasesstatic class into the hub'sPurchasesSdkinterface. - Bootstrap:
getHub()insrc/core/sdk/hub.ts— dynamically importsreact-native-purchases, wraps it, and passes it aspurchasesSdktocreateHub. RevenueCat is configured by the hub withEXPO_PUBLIC_REVENUECAT_IOS_API_KEY/EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEYand the entitlement id"VIP". - appUserId: After anon sign-in, the Firebase uid is read and passed as
appUserIdso RevenueCat links the subscriber record to the Firebase identity. - Entitlement sync call path:
- At startup:
getCustomerInfo()→resolveEntitlements()→syncEntitlementsFromRC(). - On purchase:
PaywallHostcallshub.subscription.purchase(pkg)→ result carriescustomerInfo→syncEntitlementsFromRC(). - On restore:
hub.subscription.restore()→ samesyncEntitlementsFromRC()path. - On guest re-login (sign out → sign in again):
refreshEntitlements()atsrc/features/monetization/refresh-entitlements.tsre-pullsPurchases.getCustomerInfo()to restore a returning subscriber's flags without a full relaunch.
- At startup:
- Entitlement resolution:
src/features/monetization/resolve-entitlements.ts— checksinfo.entitlements.active["VIP"]?.isActiveforisPremium; checksallPurchasedProductIdentifiersforcom.piano.noadspackforisNoAds. - Entitlement storage: MMKV-persisted Zustand store at
src/features/songs/entitlements-store.tsholdsisPremiumandadsRemoved.setPremiumEntitlement()inentitlements-actions.tsalso callslibrary.setSubscription()andsdk.player.setVip()to propagate the flag into the game engine.
Key code:
Product catalog (src/features/monetization/catalog.ts):
com.piano.weekly/com.piano.yearly(RC offeringdefault)com.piano.weekly50/com.piano.yearly50(RC offeringdiscount— the 50%-off variant)com.piano.noadspack(RC offeringiap_noads)- Per-song IAP:
com.piano.songdeal1(Rush E),com.piano.songdeal2(Passo Bem Solto)
Gaps / TODOs:
storeIds: {}is an empty object — if the hub uses this field for store product id validation, no ids are registered (no functional impact observed yet, but worth confirming with the hub's internals).androidad unit ids are absent from theadsconfig block (onlyioskeys are set); no Android build is currently targeted so this is latent.isPremiumCachedis a module-level boolean only set on firstgetCustomerInfo()— it is not refreshed after a mid-session restore (the entitlements store gets updated, but the ad-gate flag in hub.ts does not re-read it until the next app launch). Low risk while iOS-only.- The
no_adsentitlement is checked viaallPurchasedProductIdentifiers(product id match), not via an RC entitlement name — a future RC dashboard restructuring could break this check.
2. AppsFlyer
Status: 🟡 Partial — adapter and event schema fully designed; SDK not yet installed or wired
What it does (design intent): Sends custom conversion events (af_inters_displayed, af_rewarded_displayed, af_song_click) to AppsFlyer for attribution and ROAS measurement. Auto-SDK events (af_ad_revenue, af_purchase, first_open, session_start) are expected to be emitted by the AppsFlyer SDK itself.
How it's wired (design):
- Adapter:
AppsFlyerAnalyticsAdapteratpackages/analytics/src/adapters/appsflyer.ts— implementsIAnalyticsAdapter, accepts an injectedAppsFlyerClientinterface (avoids importingreact-native-appsflyerat package scope so the analytics package stays test-friendly). - Event routing:
packages/analytics/src/event-routing.tsdefineseventProviders—af_inters_displayedandaf_rewarded_displayedroute to["appsflyer"]only;song_clickroutes to["firebase"]with a name override{ appsflyer: "af_song_click" }. - Auto-SDK guard:
AUTO_SDK_EVENTSset excludesaf_ad_revenue,af_purchase,first_open,session_startfrom the dispatcher so they are never double-counted. - What is NOT yet done:
react-native-appsflyeris not inpackage.jsonand not innode_modules.AppsFlyerAnalyticsAdapteris not instantiated anywhere insrc/core/sdk/instance.ts'sbuildAnalyticsAdapters()— only Firebase and console adapters are active.- No AppsFlyer SDK init call (no app key, no
appsFlyer.initSdk()) exists anywhere in the app source.
Key code (design layer — not yet wired):
Gaps / TODOs:
- Install
react-native-appsflyerand run a native rebuild. - In
src/core/sdk/instance.tsbuildAnalyticsAdapters(), wrap the RN AppsFlyer SDK in anAppsFlyerClientshim and pushnew AppsFlyerAnalyticsAdapter(shim)into the adapters array. - Add AppsFlyer SDK init (app key, dev key) — likely in
hub.tsorapp/_layout.tsx. - The
appsflyeridparam defined inad_impression/ad_impression_amaevent schemas (packages/analytics/src/event-schemas.ts) has nowhere to be populated until the SDK is live and returns the AppsFlyer ID.
3. Events / Analytics
Status: ✅ Fully integrated (Firebase sink); 🟡 AppsFlyer sink pending (see Feature 2)
What it does: All in-app behavioural events flow through a typed AnalyticsDispatcher in @piano/analytics, which validates params via valibot schemas, applies per-provider name overrides, and fans out to one or more adapters. Currently the live sink is Firebase Analytics only.
How it's wired:
- Package:
packages/analytics/— containsAnalyticsDispatcher,FirebaseAnalyticsAdapter,AppsFlyerAnalyticsAdapter,ConsoleAnalyticsAdapter,DebugBridgeAnalyticsAdapter, and Valibot event schemas. - Adapter injection:
buildAnalyticsAdapters()insrc/core/sdk/instance.tscreatesFirebaseAnalyticsAdapter(injecting the RNFB modularlogEvent/setUserPropertycalls so the analytics package never imports React Native), plusConsoleAnalyticsAdapterin dev, plus an optional WebSocket debug bridge for the analytics visualizer. - SDK wiring:
createPianoSdk({ analytics: buildAnalyticsAdapters() })passes the adapter array to the game SDK, which wraps them inAnalyticsDispatcherand exposessdk.analytics.track(event, params). trackEvent()call path:src/core/sdk/analytics.tsexposes the app-widetrackEvent<E>(event, params)helper. It callsgetSdkSync()for synchronous dispatch when the SDK is already resolved, or falls back togetSdk().then(s => s.analytics.track(...))for pre-init events (which the dispatcher queues untilinitAll()completes).- Hub tracking sink:
hub.tracking.addSink({ name: "firebase", log: logEvent(...) })inhub.ts— a separate Firebase sink for hub-internal events (e.g. subscription lifecycle). This is distinct fromsdk.analytics(game events) — the hub does not use the@piano/analyticsdispatcher. - Event schemas: ~79 events defined as Valibot schemas in
packages/analytics/src/event-schemas.ts; types derive viav.InferOutput. The full human-readable tracking sheet lives atdocs/analytics/Piano-Tracking-Events.xlsx. - Event categories:
- FTUE / onboarding:
fn_loading_start,fn_after_splash_screen,fn_intro_*,fn_training_*,fn_tutorial_* - Song funnel:
song_impression→song_click→song_load→song_start→me_start→song_end→song_result - Ads:
fullads_*,videoads_*,bannerads_*,openads_*,ad_impression - Subscription:
sub_offer_show,sub_offer_click,sub_offer_close,sub_offer_cancel,user_subscription - IAP:
iap_offer_show,iap_offer_click,iap_offer_success,iap_offer_fail,iap_offer_reward - Navigation:
screen_view(fired automatically byuseScreenViewTrackinghook)
- FTUE / onboarding:
Key code:
Gaps / TODOs:
- The
af_inters_displayedandaf_rewarded_displayedevents are routed to theappsflyerprovider inevent-routing.ts, but will silently be a no-op untilAppsFlyerAnalyticsAdapteris added tobuildAnalyticsAdapters(). ad_impression_amaroutes tofirebase_only_ama— a provider type declared in the type union but not mapped to any concrete adapter; it will currently be swallowed by the dispatcher (no adapter with name"firebase_only_ama"exists). Needs clarification on whether it should route to the same Firebase adapter under a different event name.- Song-session correlation (
song_session_id) is maintained in a module-level singleton insrc/core/sdk/analytics.ts— it is not persisted and resets on app restart orresetSdk().
4. Auth
Status: 🟡 Partial — Firebase anonymous auth fully integrated; named account auth (email/password) gated off pending Firebase linkWithCredential implementation
What it does: Signs in anonymously via Firebase Auth on first launch, producing an uid that is reused as the RevenueCat App User ID, the player-data storage key, and the guest session identity. Real email/password sign-in routes are declared but intentionally suspended.
How it's wired:
firebase-auth.ts:ensureAnonUid()atsrc/core/sdk/firebase-auth.ts— callssignInAnonymously(getAuth(getApp())), which is idempotent (RNFB reuses the cached anon user from the iOS Keychain across launches). Returns theuid, ornullif offline with no cached user.- Hub seam:
makeFirebaseGetIdToken()insrc/core/sdk/hub.ts— signs in anonymously, then returns a() => Promise<string | null>closure that callsuser.getIdToken()on demand. This closure is passed asgetIdTokentocreateHub, and the hub calls it before every authenticated backend request. appUserId: AftermakeFirebaseGetIdToken()resolves,getAuth().currentUser?.uidis read and passed asappUserIdtocreateHub— linking RevenueCat to the same Firebase identity.- Guest session:
ensureGuestSession()atsrc/features/auth/guest.tscallsgetGuestIdentity()(which awaitsgetHub()to guarantee anon sign-in is complete), then writes aSessionobject intouseAuthStorewith the Firebase uid asuser.id. On every guest login it also callsrefreshEntitlements()to restore a returning subscriber's flags. AUTH_ENABLEDflag:app/_layout.tsxline 29 —const AUTH_ENABLED = false. The(auth)route group (Stack.Protected guard={AUTH_ENABLED && hasCompleted}) is permanently blocked.src/features/auth/api.tsadditionally rejects all sign-in / sign-up calls with an explicit error message directing to11.FIRESTORE-INTEGRATION.md §11.- Sign-out:
performSignOut()atsrc/features/auth/signOut.ts— wipesuseAuthStore,useEntitlementsStore,useTracksStore,usePianoUiStore,useOnboardingStore,queryClient, and callswipePlayerDataForUid(uid)+wipeLibraryForUser(uid)so a fresh guest session starts clean. - SDK init:
getSdk()ininstance.tsawaitsensureAnonUid()before creatingcreatePianoSdk, scoping the MMKVMmkvPlayerDataStorageto the uid.
Key code:
Gaps / TODOs:
- Named account auth (email / password +
linkWithCredential) is fully suspended. Re-enabling requires wiring real Firebase Auth sign-in and linking the anonymous credential to a named account before surfacing the(auth)routes. GUEST_CLOUD_SYNCflag inguest.ts(defaults to the value exported from@core/services/library) gates whether the anon uid partition is synced tousers/{uid}/libraryon Firestore — check the current value to confirm if cloud library sync is live.- Token TTL in
guest.ts(GUEST_TOKEN_TTL_MS = 1h) reflects Firebase ID token lifetime. There is no automatic refresh loop in the guest session; expired tokens are only refreshed when the hub re-callsgetIdToken()on a new backend request (RNFB handles refresh under the hood viagetIdToken()).