@smartico/public-api 0.0.380 → 0.0.381

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CLAUDE.md +103 -0
  2. package/README.md +32 -10
  3. package/dist/Base/ClassId.d.ts +2 -0
  4. package/dist/Jackpots/JackpotDetails.d.ts +14 -15
  5. package/dist/Jackpots/JackpotPot.d.ts +10 -6
  6. package/dist/Raffle/GetRaffleWonPrizesRequest.d.ts +9 -0
  7. package/dist/Raffle/GetRaffleWonPrizesResponse.d.ts +52 -0
  8. package/dist/Raffle/index.d.ts +2 -0
  9. package/dist/SmarticoAPI.d.ts +6 -1
  10. package/dist/SmarticoLib/index.d.ts +5 -1
  11. package/dist/WSAPI/WSAPIAvatars.d.ts +267 -49
  12. package/dist/WSAPI/WSAPIBonuses.d.ts +224 -10
  13. package/dist/WSAPI/WSAPIGamePick.d.ts +538 -253
  14. package/dist/WSAPI/WSAPIGeneral.d.ts +156 -14
  15. package/dist/WSAPI/WSAPIInbox.d.ts +547 -58
  16. package/dist/WSAPI/WSAPIJackpots.d.ts +292 -57
  17. package/dist/WSAPI/WSAPILeaderBoard.d.ts +127 -13
  18. package/dist/WSAPI/WSAPIMiniGames.d.ts +465 -49
  19. package/dist/WSAPI/WSAPIRaffles.d.ts +576 -52
  20. package/dist/WSAPI/WSAPITournaments.d.ts +3 -3
  21. package/dist/WSAPI/WSAPITypes.d.ts +243 -132
  22. package/dist/WSAPI/WSAPIUser.d.ts +193 -43
  23. package/dist/index.js +3409 -615
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.modern.mjs +3391 -608
  26. package/dist/index.modern.mjs.map +1 -1
  27. package/docs/Callbacks.md +162 -0
  28. package/docs/SmarticoObject.md +445 -0
  29. package/docs/Transforms.md +99 -0
  30. package/docs/api/README.md +26 -0
  31. package/docs/api/classes/WSAPIAvatars.md +282 -54
  32. package/docs/api/classes/WSAPIBonuses.md +233 -12
  33. package/docs/api/classes/WSAPIClans.md +380 -10
  34. package/docs/api/classes/WSAPIGamePick.md +555 -26
  35. package/docs/api/classes/WSAPIGeneral.md +165 -16
  36. package/docs/api/classes/WSAPIInbox.md +588 -64
  37. package/docs/api/classes/WSAPIJackpots.md +320 -66
  38. package/docs/api/classes/WSAPILeaderBoard.md +133 -15
  39. package/docs/api/classes/WSAPIMiniGames.md +501 -64
  40. package/docs/api/classes/WSAPIMissions.md +58 -79
  41. package/docs/api/classes/WSAPIRaffles.md +647 -69
  42. package/docs/api/classes/WSAPIStore.md +83 -108
  43. package/docs/api/classes/WSAPITournaments.md +495 -28
  44. package/docs/api/classes/WSAPIUser.md +520 -83
  45. package/docs/api/documents/Callbacks.md +162 -0
  46. package/docs/api/documents/SmarticoObject.md +445 -0
  47. package/docs/api/documents/Transforms.md +99 -0
  48. package/docs/api/enumerations/BonusStatus-1.md +11 -6
  49. package/docs/api/enumerations/JoinClanErrorCode.md +81 -0
  50. package/docs/api/enumerations/TournamentRegistrationError.md +12 -0
  51. package/docs/api/functions/clanTournamentPlayersTransform.md +13 -0
  52. package/docs/api/interfaces/AvatarCustomized.md +25 -0
  53. package/docs/api/interfaces/AvatarDefinition.md +94 -0
  54. package/docs/api/interfaces/AvatarPrompt.md +45 -0
  55. package/docs/api/interfaces/BonusMetaMap-1.md +4 -1
  56. package/docs/api/interfaces/BonusTemplateMetaMap-1.md +9 -4
  57. package/docs/api/interfaces/Clan.md +4 -0
  58. package/docs/api/interfaces/ClanInfo.md +109 -0
  59. package/docs/api/interfaces/ClanMember.md +53 -0
  60. package/docs/api/interfaces/ClanTournamentPlayerRaw.md +67 -0
  61. package/docs/api/interfaces/GemsDiamondsLog.md +43 -0
  62. package/docs/api/interfaces/GetClanInfoResponse.md +61 -0
  63. package/docs/api/interfaces/GetClanTournamentPlayersResponse.md +81 -0
  64. package/docs/api/interfaces/GetRaffleWonPrizesRequest.md +59 -0
  65. package/docs/api/interfaces/GetRaffleWonPrizesResponse.md +95 -0
  66. package/docs/api/interfaces/InboxMarkMessageAction.md +10 -2
  67. package/docs/api/interfaces/JackpotDetails.md +14 -15
  68. package/docs/api/interfaces/JackpotPot.md +9 -6
  69. package/docs/api/interfaces/LeaderBoardDetailsT.md +14 -8
  70. package/docs/api/interfaces/LeaderBoardUserT.md +8 -5
  71. package/docs/api/interfaces/LeaderBoardsRewardsT.md +7 -0
  72. package/docs/api/interfaces/PointsLog.md +43 -0
  73. package/docs/api/interfaces/RaffleWonPrize.md +59 -0
  74. package/docs/api/interfaces/RaffleWonPrizePublicMeta.md +27 -0
  75. package/docs/api/interfaces/RaffleWonPrizeUser.md +43 -0
  76. package/docs/api/interfaces/TAchCategory.md +2 -7
  77. package/docs/api/interfaces/TAvatarCustomized.md +4 -4
  78. package/docs/api/interfaces/TAvatarDefinition.md +13 -14
  79. package/docs/api/interfaces/TAvatarPrompt.md +6 -6
  80. package/docs/api/interfaces/TBonus.md +16 -8
  81. package/docs/api/interfaces/TBuyStoreItemResult.md +4 -29
  82. package/docs/api/interfaces/TClaimBonusResult.md +5 -5
  83. package/docs/api/interfaces/TClan.md +8 -4
  84. package/docs/api/interfaces/TClanInfo.md +47 -0
  85. package/docs/api/interfaces/TClanJoinResult.md +11 -1
  86. package/docs/api/interfaces/TClanTournamentPlayer.md +55 -0
  87. package/docs/api/interfaces/TClanTournamentPlayersResult.md +27 -0
  88. package/docs/api/interfaces/TClans.md +3 -1
  89. package/docs/api/interfaces/TGetTranslations.md +4 -0
  90. package/docs/api/interfaces/TInboxMessage.md +14 -6
  91. package/docs/api/interfaces/TInboxMessageBody.md +18 -12
  92. package/docs/api/interfaces/TLevel.md +17 -20
  93. package/docs/api/interfaces/TLevelCurrent.md +19 -18
  94. package/docs/api/interfaces/TMiniGamePlayBatchResult.md +14 -6
  95. package/docs/api/interfaces/TMiniGamePlayResult.md +9 -4
  96. package/docs/api/interfaces/TMissionClaimRewardResult.md +1 -9
  97. package/docs/api/interfaces/TMissionOptInResult.md +1 -5
  98. package/docs/api/interfaces/TMissionOrBadge.md +4 -7
  99. package/docs/api/interfaces/TRaffleOptinResponse.md +4 -2
  100. package/docs/api/interfaces/TSegmentCheckResult.md +10 -0
  101. package/docs/api/interfaces/TSetAvatarResult.md +3 -3
  102. package/docs/api/interfaces/TStoreItem.md +3 -13
  103. package/docs/api/interfaces/TTournament.md +1 -1
  104. package/docs/api/interfaces/TTournamentDetailed.md +1 -1
  105. package/docs/api/interfaces/TTournamentRegistrationResult.md +4 -2
  106. package/docs/api/interfaces/TUICustomSection.md +23 -19
  107. package/docs/api/interfaces/TUserProfile.md +18 -16
  108. package/docs/api/interfaces/TransformedRaffleClaimPrizeResponse.md +6 -2
  109. package/docs/api/interfaces/UserLevelExtraCountersT.md +9 -2
  110. package/docs/api/type-aliases/ActivityLogEntry.md +3 -0
  111. package/docs/native/ADDING_METHODS.md +7 -2
  112. package/docs/native/PROTOCOL.md +337 -0
  113. package/docs/ui/avatars/UIGuide_getAvatarPrompts.md +100 -0
  114. package/docs/ui/avatars/UIGuide_getAvatarsCustomized.md +90 -0
  115. package/docs/ui/avatars/UIGuide_getAvatarsList.md +105 -0
  116. package/docs/ui/avatars/UIGuide_setAvatar.md +118 -0
  117. package/docs/ui/bonuses/UIGuide_claimBonus.md +144 -0
  118. package/docs/ui/bonuses/UIGuide_getBonuses.md +176 -0
  119. package/docs/ui/gamepick/UIGuide_gamePickGetActiveRound.md +99 -0
  120. package/docs/ui/gamepick/UIGuide_gamePickGetActiveRounds.md +76 -0
  121. package/docs/ui/gamepick/UIGuide_gamePickGetBoard.md +81 -0
  122. package/docs/ui/gamepick/UIGuide_gamePickGetGameInfo.md +78 -0
  123. package/docs/ui/gamepick/UIGuide_gamePickGetHistory.md +55 -0
  124. package/docs/ui/gamepick/UIGuide_gamePickGetRoundInfoForUser.md +71 -0
  125. package/docs/ui/gamepick/UIGuide_gamePickGetUserInfo.md +64 -0
  126. package/docs/ui/gamepick/UIGuide_gamePickSubmitSelection.md +103 -0
  127. package/docs/ui/gamepick/UIGuide_gamePickSubmitSelectionQuiz.md +67 -0
  128. package/docs/ui/general/UIGuide_getCustomSections.md +137 -0
  129. package/docs/ui/general/UIGuide_getRelatedItemsForGame.md +140 -0
  130. package/docs/ui/inbox/UIGuide_deleteInboxMessage.md +135 -0
  131. package/docs/ui/inbox/UIGuide_getInboxMessageBody.md +133 -0
  132. package/docs/ui/inbox/UIGuide_getInboxMessages.md +186 -0
  133. package/docs/ui/inbox/UIGuide_markInboxMessageAsRead.md +122 -0
  134. package/docs/ui/inbox/UIGuide_markUnmarkInboxMessageAsFavorite.md +84 -0
  135. package/docs/ui/jackpots/UIGuide_getJackpotEligibleGames.md +73 -0
  136. package/docs/ui/jackpots/UIGuide_getJackpotWinners.md +83 -0
  137. package/docs/ui/jackpots/UIGuide_jackpotGet.md +138 -0
  138. package/docs/ui/jackpots/UIGuide_jackpotOptIn.md +85 -0
  139. package/docs/ui/jackpots/UIGuide_jackpotOptOut.md +65 -0
  140. package/docs/ui/leaderboard/UIGuide_getLeaderBoard.md +166 -0
  141. package/docs/ui/minigames/UIGuide_getMiniGames.md +153 -0
  142. package/docs/ui/minigames/UIGuide_getMiniGamesHistory.md +90 -0
  143. package/docs/ui/minigames/UIGuide_playMiniGame.md +150 -0
  144. package/docs/ui/minigames/UIGuide_playMiniGameBatch.md +128 -0
  145. package/docs/ui/raffles/UIGuide_claimRafflePrize.md +99 -0
  146. package/docs/ui/raffles/UIGuide_getRaffleDrawRun.md +117 -0
  147. package/docs/ui/raffles/UIGuide_getRaffleDrawRunsHistory.md +92 -0
  148. package/docs/ui/raffles/UIGuide_getRaffleWonPrizes.md +120 -0
  149. package/docs/ui/raffles/UIGuide_getRaffles.md +175 -0
  150. package/docs/ui/raffles/UIGuide_requestRaffleOptin.md +114 -0
  151. package/docs/ui/user/UIGuide_getActivityLog.md +130 -0
  152. package/docs/ui/user/UIGuide_getLevels.md +47 -42
  153. package/package.json +1 -1
  154. package/src/Base/ClassId.ts +2 -0
  155. package/src/Jackpots/JackpotDetails.ts +14 -15
  156. package/src/Jackpots/JackpotPot.ts +10 -6
  157. package/src/Raffle/GetRaffleWonPrizesRequest.ts +12 -0
  158. package/src/Raffle/GetRaffleWonPrizesResponse.ts +56 -0
  159. package/src/Raffle/index.ts +3 -1
  160. package/src/SmarticoAPI.ts +14 -1
  161. package/src/SmarticoLib/index.ts +4 -0
  162. package/src/WSAPI/WSAPIAvatars.ts +267 -49
  163. package/src/WSAPI/WSAPIBonuses.ts +224 -10
  164. package/src/WSAPI/WSAPIGamePick.ts +538 -253
  165. package/src/WSAPI/WSAPIGeneral.ts +156 -14
  166. package/src/WSAPI/WSAPIInbox.ts +545 -56
  167. package/src/WSAPI/WSAPIJackpots.ts +297 -61
  168. package/src/WSAPI/WSAPILeaderBoard.ts +127 -13
  169. package/src/WSAPI/WSAPIMiniGames.ts +465 -49
  170. package/src/WSAPI/WSAPIRaffles.ts +592 -64
  171. package/src/WSAPI/WSAPITournaments.ts +3 -3
  172. package/src/WSAPI/WSAPITypes.ts +243 -132
  173. package/src/WSAPI/WSAPIUser.ts +193 -43
  174. package/tsconfig.json +9 -1
@@ -153,6 +153,8 @@ var ClassId;
153
153
  ClassId[ClassId["RAF_CLAIM_PRIZE_RESPONSE"] = 909] = "RAF_CLAIM_PRIZE_RESPONSE";
154
154
  ClassId[ClassId["RAF_OPTIN_REQUEST"] = 916] = "RAF_OPTIN_REQUEST";
155
155
  ClassId[ClassId["RAF_OPTIN_RESPONSE"] = 917] = "RAF_OPTIN_RESPONSE";
156
+ ClassId[ClassId["RAF_GET_WON_PRIZES_REQUEST"] = 920] = "RAF_GET_WON_PRIZES_REQUEST";
157
+ ClassId[ClassId["RAF_GET_WON_PRIZES_RESPONSE"] = 921] = "RAF_GET_WON_PRIZES_RESPONSE";
156
158
  /*
157
159
  RAF_GET_TICKETS_REQUEST = 902,
158
160
  RAF_GET_TICKETS_RESPONSE = 903,
@@ -2436,7 +2438,7 @@ class WSAPIUser extends WSAPIBase {
2436
2438
  *
2437
2439
  * **Inbox unread count** — `core_inbox_unread_count` on this profile
2438
2440
  * is push-updated in real time (under 1 second). For an inbox badge,
2439
- * prefer this field over {@link getInboxUnreadCount} (which is cached
2441
+ * prefer this field over `getInboxUnreadCount` (which is cached
2440
2442
  * for 30 s) — same value, fresher signal.
2441
2443
  *
2442
2444
  * **Language**: `core_user_language` reflects the server's stored
@@ -2506,15 +2508,75 @@ class WSAPIUser extends WSAPIBase {
2506
2508
  throw new Error('Tracker is not initialized, cannot getUserProfile');
2507
2509
  }
2508
2510
  }
2509
- /** Check if user belongs to specific segments
2510
- * **Example**:
2511
- * ```
2512
- * _smartico.api.checkSegmentMatch(1).then((result) => {
2513
- * console.log(result);
2511
+ /**
2512
+ * Checks whether the current user matches a single segment, returning
2513
+ * `true` / `false` directly. Use this as a decision primitive to gate
2514
+ * UI surfaces (e.g. show a "VIP lounge" tab only when the user is in
2515
+ * the VIP segment), or to drive segment-specific CTA copy.
2516
+ *
2517
+ * Every call is a server round-trip — there is no SDK-side cache. For
2518
+ * checking multiple segments in one round-trip, use
2519
+ * {@link checkSegmentListMatch} instead.
2520
+ *
2521
+ * @remarks
2522
+ * **Refresh model**
2523
+ * - **No client cache.** Every call sends a request; the SDK does not
2524
+ * memoize results.
2525
+ * - **No push event** notifies the consumer when segment membership
2526
+ * flips (the user crosses a qualification threshold, or the
2527
+ * operator changes the segment definition). Membership changes
2528
+ * become visible only on the next `checkSegmentMatch` call.
2529
+ * - **Behavioral segments (configured against BigQuery) have batch
2530
+ * lag** — even if the user's activity has changed (deposit, wager,
2531
+ * etc.), the segment-membership result may not reflect that change
2532
+ * until the next batch evaluation run (typically up to several
2533
+ * hours).
2534
+ *
2535
+ * **Rate limit** (important)
2536
+ * The server caps `checkSegment*` calls at **10 requests per
2537
+ * 60-second window**, with a minimum gap of **~5 seconds between
2538
+ * consecutive calls**. Avoid calling on every render — cache the
2539
+ * result client-side for the session, or until you have a reason to
2540
+ * believe the user's state changed (e.g. after a deposit completes,
2541
+ * a level changes via {@link getUserProfile}'s `props_change`, or a
2542
+ * specific custom event fires).
2543
+ *
2544
+ * **`is_matching: false` is ambiguous on the server** — both "the
2545
+ * segment doesn't exist for this label" and "the user doesn't
2546
+ * qualify" return `false` with no distinguishing signal. Pass IDs
2547
+ * you've verified are valid for your label.
2548
+ *
2549
+ * **Idempotency**: safe. Read-only. No side effects (no analytics
2550
+ * events, no DB writes).
2551
+ *
2552
+ * **Visitor mode**: not supported.
2553
+ *
2554
+ * @param segment_id The segment ID. Segment IDs are label-scoped;
2555
+ * the same numeric ID can refer to different
2556
+ * segments under different labels. Use the IDs
2557
+ * configured for your label.
2558
+ * @returns `true` if the user currently matches the
2559
+ * segment, `false` otherwise. `false` also covers
2560
+ * the "segment doesn't exist for this label"
2561
+ * case — these are not distinguishable.
2562
+ *
2563
+ * @example
2564
+ * ```ts
2565
+ * const isVip = await window._smartico.api.checkSegmentMatch(vipSegmentId);
2566
+ * if (isVip) {
2567
+ * console.log('[smartico] user is in VIP segment — render the VIP-only widget surface');
2568
+ * } else {
2569
+ * console.log('[smartico] user not in VIP segment (or segment id misconfigured) — hide the VIP surface');
2570
+ * }
2571
+ *
2572
+ * // Cache the result for the session; re-check after material user-state changes.
2573
+ * window._smartico.on('props_change', async (changed) => {
2574
+ * if ('ach_points_ever' in changed || 'ach_level_current_id' in changed) {
2575
+ * const fresh = await window._smartico.api.checkSegmentMatch(vipSegmentId);
2576
+ * console.log('[smartico] user state changed — VIP membership now:', fresh);
2577
+ * }
2514
2578
  * });
2515
2579
  * ```
2516
- *
2517
- * **Visitor mode: not supported**
2518
2580
  */
2519
2581
  async checkSegmentMatch(segment_id) {
2520
2582
  const r = await this.api.coreCheckSegments(this.userExtId, [segment_id]);
@@ -2524,14 +2586,67 @@ class WSAPIUser extends WSAPIBase {
2524
2586
  return false;
2525
2587
  }
2526
2588
  }
2527
- /** Check if user belongs to specific list of segments
2528
- * **Example**:
2529
- * ```
2530
- * _smartico.api.checkSegmentListMatch([1, 2, 3]).then((result) => {
2531
- * console.log(result);
2532
- * });
2589
+ /**
2590
+ * Checks the current user's membership in multiple segments in a
2591
+ * single server round-trip — returns a `TSegmentCheckResult[]` with
2592
+ * one entry per *unique* segment ID. Use this instead of looping
2593
+ * {@link checkSegmentMatch} when you need to evaluate several
2594
+ * segments at once (e.g. multi-segment composite gating, A/B-style
2595
+ * cohort detection).
2596
+ *
2597
+ * @remarks
2598
+ * **Response order is NOT guaranteed**
2599
+ * The server returns results in an unspecified order — different
2600
+ * from the input array. Always correlate by the `segment_id` field on
2601
+ * each `TSegmentCheckResult` rather than by array position. The
2602
+ * returned array length may also be smaller than the input array
2603
+ * (duplicate IDs are silently de-duplicated server-side).
2604
+ *
2605
+ * **Single round-trip**
2606
+ * The entire `segment_ids` array is sent in one request. Two segments
2607
+ * cost the same as one in terms of network latency and rate-limit
2608
+ * consumption (one call = one rate-limit slot, regardless of how many
2609
+ * segments).
2610
+ *
2611
+ * **Shared semantics with `checkSegmentMatch`**
2612
+ * Both methods wrap the same underlying server endpoint and share
2613
+ * the same caching, refresh, rate-limit, and ambiguity behavior. See
2614
+ * {@link checkSegmentMatch} for: no client cache · no push event for
2615
+ * membership changes · behavioral segments have batch lag · rate
2616
+ * limit (10 requests / 60 s, ~5 s minimum gap between calls) ·
2617
+ * `is_matching: false` doesn't distinguish "not in segment" from
2618
+ * "segment doesn't exist for this label".
2619
+ *
2620
+ * **Idempotency**: safe. Read-only. No side effects.
2621
+ *
2622
+ * **Visitor mode**: not supported.
2623
+ *
2624
+ * @param segment_ids Array of segment IDs to check. Duplicates are
2625
+ * silently de-duplicated server-side. Segment IDs
2626
+ * are label-scoped — use the IDs configured for
2627
+ * your label.
2628
+ * @returns Array of `{ segment_id, is_matching }` results.
2629
+ * Order is NOT guaranteed; correlate by
2630
+ * `segment_id`. Length may be less than the input
2631
+ * when duplicate IDs were sent.
2632
+ *
2633
+ * @example
2634
+ * ```ts
2635
+ * const segmentIds = [vipSegmentId, newPlayerSegmentId, freeRollSegmentId];
2636
+ * const results = await window._smartico.api.checkSegmentListMatch(segmentIds);
2637
+ *
2638
+ * // Always correlate by segment_id — the response order is unspecified.
2639
+ * const byId = new Map(results.map(r => [r.segment_id, r.is_matching]));
2640
+ *
2641
+ * if (byId.get(vipSegmentId)) {
2642
+ * console.log('[smartico] user is in VIP segment — render VIP surface');
2643
+ * }
2644
+ * if (byId.get(newPlayerSegmentId) && byId.get(freeRollSegmentId)) {
2645
+ * console.log('[smartico] new player AND eligible for free roll — show the welcome promo');
2646
+ * }
2647
+ *
2648
+ * // Cache the result map for the session; refresh on material state changes.
2533
2649
  * ```
2534
- * **Visitor mode: not supported**
2535
2650
  */
2536
2651
  async checkSegmentListMatch(segment_ids) {
2537
2652
  return await this.api.coreCheckSegments(this.userExtId, Array.isArray(segment_ids) ? segment_ids : [segment_ids]);
@@ -2689,7 +2804,7 @@ class WSAPIUser extends WSAPIBase {
2689
2804
  * The SDK exposes raw numeric values; the meaning of each counter
2690
2805
  * (deposit amount, wager amount, lifetime spend, etc.) is fully
2691
2806
  * operator-defined per label. Resolve labels for display via
2692
- * {@link getTranslations} — the operator's display strings are
2807
+ * `getTranslations` — the operator's display strings are
2693
2808
  * stored under the translation keys `levelsCounter1Name` and
2694
2809
  * `levelsCounter2Name`.
2695
2810
  *
@@ -2747,36 +2862,68 @@ class WSAPIUser extends WSAPIBase {
2747
2862
  return OCache.use(onUpdateContextKey.LevelExtraCounters, ECacheContext.WSAPI, () => this.api.getUserGamificationInfoT(this.userExtId), CACHE_DATA_SEC);
2748
2863
  }
2749
2864
  /**
2750
- * Returns the activity log for a user within a specified time range.
2751
- * The response includes both points changes and gems/diamonds changes.
2752
- * Each log entry contains information about the change amount, balance, and source.
2753
- * The returned list is cached for 30 seconds.
2754
- * You can pass the onUpdate callback as a parameter, it will be called every time the activity log is updated and will provide the updated list of activity logs for the last 10 minutes.
2865
+ * Returns the user's unified balance-change history — every points, gems, and
2866
+ * diamonds transaction within the requested time window, ordered newest-first.
2867
+ * Use to power an "Activity" / "History" tab showing wins, claims, purchases,
2868
+ * level-up rewards, and operator adjustments.
2755
2869
  *
2756
- * **Example**:
2757
- * ```
2758
- * const startTime = Math.floor(Date.now() / 1000) - 86400 * 30; // 30 days ago
2759
- * const endTime = Math.floor(Date.now() / 1000); // now
2760
- *
2761
- * _smartico.api.getActivityLog({
2762
- * startTimeSeconds: startTime,
2763
- * endTimeSeconds: endTime,
2764
- * from: 0,
2765
- * to: 50,
2766
- * onUpdate: (data) => console.log('Updated:', data)
2767
- * }).then((result) => {
2768
- * console.log(result);
2769
- * });
2770
- * ```
2870
+ * The returned shape is the same regardless of currency type — `type` (see
2871
+ * {@link UserBalanceType}) distinguishes points / gems / diamonds and
2872
+ * `source_type_id` (see {@link PointChangeSourceType}) names the originating
2873
+ * event.
2771
2874
  *
2772
- * **Visitor mode: not supported**
2875
+ * @remarks
2876
+ * **Preconditions**
2877
+ * - User must be authenticated. Visitor mode is not guarded at the SDK level
2878
+ * but is not meaningful — activity is per-user.
2879
+ *
2880
+ * **Pagination — `from` / `to` are offset + ceiling, not timestamps**
2881
+ * The SDK derives `offset = from`, `limit = min(to - from, 50)` — the server
2882
+ * hard-caps a single response at 50 entries. For infinite scroll, advance
2883
+ * `from` by 50 between calls. Both `startTimeSeconds` and `endTimeSeconds`
2884
+ * are epoch seconds bounding the window the server scans.
2885
+ *
2886
+ * **Subscription model (`onUpdate`)**
2887
+ * The callback fires when the user's `ach_points_balance`,
2888
+ * `ach_gems_balance`, or `ach_diamonds_balance` changes (i.e. whenever a
2889
+ * wallet event lands). The pushed payload is a FIXED re-fetch of the
2890
+ * **last 10 minutes / first 50 entries** — it does NOT honor the original
2891
+ * call's `startTimeSeconds` / `endTimeSeconds` / `from` / `to`. Consumers
2892
+ * maintaining a long historical view must re-call `getActivityLog` with
2893
+ * their own params after receiving an `onUpdate` notification.
2894
+ *
2895
+ * **Refresh**
2896
+ * - The SDK caches results for 30 seconds.
2897
+ * - Push triggers fire only on balance changes; transactions that don't
2898
+ * alter a balance (theoretical zero-amount entries) won't refresh.
2899
+ *
2900
+ * **Visitor mode**: not meaningful (no per-user history available).
2901
+ *
2902
+ * **UI guidance**: see [UI Guide — `getActivityLog`](../../docs/ui/user/UIGuide_getActivityLog.md).
2773
2903
  *
2774
- * @param params - Activity log parameters
2775
- * @param params.startTimeSeconds - Start time in seconds (epoch timestamp)
2776
- * @param params.endTimeSeconds - End time in seconds (epoch timestamp)
2777
- * @param params.from - Start index of records to return
2778
- * @param params.to - End index of records to return
2779
- * @param params.onUpdate - Optional callback function that will be called when the activity log is updated
2904
+ * @returns Array of {@link TActivityLog} ordered newest-first.
2905
+ *
2906
+ * @example
2907
+ * ```ts
2908
+ * const now = Math.floor(Date.now() / 1000);
2909
+ * const start = now - 86400 * 30; // 30 days
2910
+ *
2911
+ * const log = await window._smartico.api.getActivityLog({
2912
+ * startTimeSeconds: start,
2913
+ * endTimeSeconds: now,
2914
+ * from: 0,
2915
+ * to: 50,
2916
+ * onUpdate: (refreshed) => {
2917
+ * console.log('[smartico] wallet changed — refreshed payload is last 10 min / 50 entries:', refreshed.length, 'rows');
2918
+ * // If the consumer is showing a full 30-day view, re-call getActivityLog with the original params here.
2919
+ * },
2920
+ * });
2921
+ *
2922
+ * for (const row of log) {
2923
+ * const sign = row.amount >= 0 ? '+' : '';
2924
+ * console.log('[smartico] activity row — render with', row.type === 0 ? 'points' : row.type === 1 ? 'gems' : 'diamonds', 'icon, color by sign:', sign + row.amount, 'balance after:', row.balance, 'source:', row.source_type_id);
2925
+ * }
2926
+ * ```
2780
2927
  */
2781
2928
  async getActivityLog({
2782
2929
  startTimeSeconds,
@@ -2800,11 +2947,114 @@ class WSAPIUser extends WSAPIBase {
2800
2947
 
2801
2948
  /** @group General */
2802
2949
  class WSAPIGeneral extends WSAPIUser {
2950
+ /**
2951
+ * Returns the operator-configured "custom sections" the current user is eligible
2952
+ * to see. Custom sections are nav-level entries the operator builds in the BO —
2953
+ * HTML pages, themed mission grids, store / raffle / tournament category pages,
2954
+ * lootbox calendars, redirect links, and Liquid-templated dashboards — each
2955
+ * surfaced with its own icon and label.
2956
+ *
2957
+ * Use the response to build the side menu / bottom-bar / nav grid of a
2958
+ * gamification widget. Each section's `section_type_id` (see
2959
+ * {@link AchCustomSectionType}) tells the consumer which page component to mount
2960
+ * when the user opens the section.
2961
+ *
2962
+ * @remarks
2963
+ * **Preconditions**
2964
+ * - No prerequisite calls. Typically fetched once at app boot to build the
2965
+ * navigation skeleton.
2966
+ *
2967
+ * **Server-side eligibility filtering**
2968
+ * Sections are filtered server-side by the user's segments / level / brand and
2969
+ * the section's `active_from_date` / `active_till_date` window. Sections the
2970
+ * user is ineligible for are omitted from the response entirely — there is no
2971
+ * "locked" state to render.
2972
+ *
2973
+ * **Ordering**
2974
+ * Response is server-ordered. Render in the order received; do NOT re-sort
2975
+ * client-side (the operator's order is the intended nav order).
2976
+ *
2977
+ * **Refresh**
2978
+ * - The SDK caches results for 30 seconds.
2979
+ * - No push subscription. Re-call after a segment / level change might
2980
+ * make new sections eligible, or just rely on the 30 s cache turnover.
2981
+ *
2982
+ * **Visitor mode**: supported.
2983
+ *
2984
+ * **UI guidance**: see [UI Guide — `getCustomSections`](../../docs/ui/general/UIGuide_getCustomSections.md).
2985
+ *
2986
+ * @returns Array of {@link TUICustomSection} — empty if the label has no
2987
+ * active custom sections or the user is ineligible for all of them.
2988
+ *
2989
+ * @example
2990
+ * ```ts
2991
+ * const sections = await window._smartico.api.getCustomSections();
2992
+ *
2993
+ * for (const s of sections) {
2994
+ * console.log('[smartico] nav entry', s.menu_name, 'type', s.section_type_id, '→ mount the matching page component');
2995
+ * // Render s.menu_img (64x64) as the nav icon and s.menu_name as the label.
2996
+ * // For section_type_id === AchCustomSectionType.REDIRECT_LINK, do NOT mount a page —
2997
+ * // resolve s.url_or_dp on click (DP string or external URL).
2998
+ * }
2999
+ * ```
3000
+ */
2803
3001
  async getCustomSections() {
2804
3002
  return OCache.use(onUpdateContextKey.CustomSections, ECacheContext.WSAPI, () => this.api.customSectionsGetT(this.userExtId), CACHE_DATA_SEC);
2805
3003
  }
2806
3004
  /**
2807
- * Requests translations for the given language. Returns the object including translation key/translation value pairs. All possible translation keys defined in the back office.
3005
+ * Returns the full set of operator-defined translation key/value pairs for the
3006
+ * label, merged across the requested language and the English baseline.
3007
+ *
3008
+ * Translation keys are free-form strings defined by the operator in the BO. The
3009
+ * SDK consumer treats the result as a flat dictionary: `translations[key]`. If
3010
+ * the key is missing entirely, do NOT trust `undefined` semantics — defensively
3011
+ * fall back to the key string itself or a hardcoded literal.
3012
+ *
3013
+ * @remarks
3014
+ * **Preconditions**
3015
+ * - No prerequisite calls.
3016
+ * - `lang_code` is the ISO language code the operator uses in the BO
3017
+ * (e.g. `"EN"`, `"FR"`, `"ES"`). Case is not normalised — match what the
3018
+ * operator configured.
3019
+ *
3020
+ * **EN fallback**
3021
+ * The SDK issues an English-baseline fetch first, then overlays the
3022
+ * `lang_code` translations on top. Any key the operator has only defined in
3023
+ * English (i.e. missing in the requested language) is returned with the
3024
+ * English value. Keys missing in both are absent from the map — the consumer
3025
+ * must handle missing keys (the default Smartico UI returns the key string
3026
+ * itself as the fallback text).
3027
+ *
3028
+ * **What's included**
3029
+ * The SDK passes an empty `areas` filter to the server, which returns ALL
3030
+ * translation namespaces configured for the label (Gamification, Casino,
3031
+ * Trading, Affiliation, etc. — whichever are populated). For a Gamification-
3032
+ * only widget, the consumer can ignore unused namespaces — keys are flat
3033
+ * strings, not nested.
3034
+ *
3035
+ * **Refresh**
3036
+ * - Cached internally per `(lang_code, label, brand)` for ~30 seconds.
3037
+ * - No push subscription. Operators editing translations in the BO will see
3038
+ * the change after the cache window expires.
3039
+ *
3040
+ * **Visitor mode**: supported. Translations are label-scoped, not user-
3041
+ * scoped — `lang_code` is the sole language selector and is independent of
3042
+ * the `vapi(lang)` argument used elsewhere.
3043
+ *
3044
+ * @param lang_code ISO language code (e.g. `"EN"`, `"FR"`). Defaults to
3045
+ * `"EN"` server-side if empty.
3046
+ * @returns {@link TGetTranslations} — `{ translations: { [key]: string } }`.
3047
+ *
3048
+ * @example
3049
+ * ```ts
3050
+ * const r = await window._smartico.api.getTranslations('FR');
3051
+ *
3052
+ * // Defensive lookup: fall back to the key itself if the operator hasn't
3053
+ * // defined the string.
3054
+ * const t = (k: string) => r.translations[k] ?? k;
3055
+ *
3056
+ * console.log('[smartico] localized label "missions_title" →', t('missions_title'));
3057
+ * ```
2808
3058
  */
2809
3059
  async getTranslations(lang_code) {
2810
3060
  const r = await this.api.getTranslationsT(this.userExtId, lang_code, []);
@@ -2813,21 +3063,60 @@ class WSAPIGeneral extends WSAPIUser {
2813
3063
  };
2814
3064
  }
2815
3065
  /**
2816
- * Returns all the related tournaments and missions for the provided game id for the current user
2817
- * The provided Game ID should correspond to the ID from the Games Catalog - https://help.smartico.ai/welcome/technical-guides/games-catalog-api
3066
+ * Returns the missions and tournaments associated with a casino / sportsbook
3067
+ * game in the operator's games catalog — the reverse of "given this mission,
3068
+ * which games count for it" — so you can surface "play this game to progress
3069
+ * mission X" / "tournament Y features this game" badges on game tiles or
3070
+ * detail screens.
2818
3071
  *
2819
- * **Example**:
2820
- * ```
2821
- * _smartico.api.getRelatedItemsForGame('gold-slot2').then((result) => {
2822
- * console.log(result);
2823
- * });
2824
- * ```
3072
+ * The shape mirrors `getMissions` (`UserAchievement[]`) and `getTournamentsList`
3073
+ * (`Tournament[]`) — same wire types, no reduced subset.
2825
3074
  *
2826
- * **Example in the Visitor mode**:
2827
- * ```
2828
- * _smartico.vapi('EN').getRelatedItemsForGame('gold-slot2').then((result) => {
2829
- * console.log(result);
2830
- * });
3075
+ * @remarks
3076
+ * **Preconditions**
3077
+ * - `related_game_id` must be a Games Catalog ID (the same external string the
3078
+ * operator uses in the catalog at
3079
+ * {@link https://help.smartico.ai/welcome/technical-guides/games-catalog-api}).
3080
+ *
3081
+ * **Server-side eligibility filtering**
3082
+ * Missions and tournaments are filtered by the user's segments / level / brand
3083
+ * before being returned. A user who is ineligible for a mission segment will
3084
+ * NOT see that mission in the result even if it lists the game. The same
3085
+ * filtering applies to tournaments. Treat the response as "what this user
3086
+ * should see" — no client-side eligibility pass needed.
3087
+ *
3088
+ * **No cache**
3089
+ * Every call is a live server round-trip. Missions/tournaments are operator-
3090
+ * mutated state (opt-in, completion, expiry) that changes during a session;
3091
+ * caching staler than the user's last action would mis-render eligibility.
3092
+ * Avoid building a consumer-side cache for UI-critical paths.
3093
+ *
3094
+ * **Refresh**
3095
+ * - Re-call when the user navigates to a new game tile / detail surface.
3096
+ * - Re-call after the user opts into / completes a related mission to refresh
3097
+ * the "play this game" badge.
3098
+ *
3099
+ * **Visitor mode**: supported via `_smartico.vapi(lang).getRelatedItemsForGame(...)`.
3100
+ *
3101
+ * **UI guidance**: see [UI Guide — `getRelatedItemsForGame`](../../docs/ui/general/UIGuide_getRelatedItemsForGame.md).
3102
+ *
3103
+ * @param related_game_id External Games Catalog ID of the game (e.g. `"gold-slot2"`).
3104
+ * @returns {@link GetRelatedAchTourResponse} — `{ achievements, tournaments? }`.
3105
+ * `tournaments` may be `undefined` (treat as empty); both arrays may be empty
3106
+ * when no eligible entities reference the game.
3107
+ *
3108
+ * @example
3109
+ * ```ts
3110
+ * const r = await window._smartico.api.getRelatedItemsForGame('gold-slot2');
3111
+ *
3112
+ * const missions = r.achievements ?? [];
3113
+ * const tournaments = r.tournaments ?? [];
3114
+ *
3115
+ * if (missions.length === 0 && tournaments.length === 0) {
3116
+ * console.log('[smartico] no related missions / tournaments — hide the related badge on the game tile');
3117
+ * } else {
3118
+ * console.log('[smartico] related entities:', missions.length, 'missions /', tournaments.length, 'tournaments — show a "X missions / Y tournaments" badge');
3119
+ * }
2831
3120
  * ```
2832
3121
  */
2833
3122
  async getRelatedItemsForGame(related_game_id) {
@@ -3381,12 +3670,125 @@ class WSAPIMissions extends WSAPIGeneral {
3381
3670
  /** @group Bonuses */
3382
3671
  class WSAPIBonuses extends WSAPIMissions {
3383
3672
  /**
3384
- * Returns all the bonuses for the current user
3385
- * The returned bonuses are cached for 30 seconds. But you can pass the onUpdate callback as a parameter.
3386
- * Note that each time you call getBonuses with a new onUpdate callback, the old one will be overwritten by the new one.
3387
- * The onUpdate callback will be called on bonus claimed and the updated bonuses will be passed to it.
3673
+ * Returns the bonuses awarded to the current user — both pending
3674
+ * (player-claim required) and already-redeemed. Each bonus carries
3675
+ * a `bonus_status_id` ({@link BonusStatus}) describing its lifecycle
3676
+ * stage and an `is_redeemable` flag that signals whether the
3677
+ * consumer must trigger a manual {@link claimBonus} call.
3678
+ *
3679
+ * Bonuses originate from many sources (CRM rules, mission/tournament
3680
+ * rewards, store redemptions, mini-game prizes, manual operator
3681
+ * awards) and all surface through this single list. The consumer
3682
+ * cannot distinguish the source server-side without operator
3683
+ * coordination.
3388
3684
  *
3389
- * **Visitor mode: not supported**
3685
+ * @remarks
3686
+ * **Subscription model (`onUpdate`)**
3687
+ * The callback receives the FULL refreshed bonuses list (never a
3688
+ * diff/patch). Each subsequent call to `getBonuses({ onUpdate })`
3689
+ * REPLACES the prior callback. Pass `onUpdate: undefined` (or omit
3690
+ * it) to keep the prior callback in place; the callback is never
3691
+ * auto-cleared.
3692
+ *
3693
+ * **Update triggers** — the callback fires after every
3694
+ * {@link claimBonus} call resolves on this connection (success OR
3695
+ * failure). This is the ONLY trigger.
3696
+ *
3697
+ * Does NOT fire when: a new bonus is awarded server-side
3698
+ * (CRM rule, mission completion, store purchase, etc.), a bonus
3699
+ * expires, or an operator manually issues / cancels a bonus. Those
3700
+ * changes surface only on the next cache miss (after the 30 s TTL).
3701
+ * Re-call `getBonuses()` manually if your UI needs near-live state
3702
+ * for server-driven awards.
3703
+ *
3704
+ * **Reading state from the returned bonus**
3705
+ * Drive UI bucketing from `bonus_status_id` (enum {@link BonusStatus}):
3706
+ *
3707
+ * - `COUPON_ISSUED` (2) — actionable; player must claim. Pair with
3708
+ * `is_redeemable === true` to gate the Claim button.
3709
+ * - `REDEEM_FAILED` (4) — also actionable; the previous claim
3710
+ * attempt failed but the bonus is still valid. Surface a retry CTA
3711
+ * — the default Smartico UI treats this identically to
3712
+ * `COUPON_ISSUED` from the player's perspective.
3713
+ * - `REDEEMED` (3) — historical; show in a "claimed" tab.
3714
+ * - `New` (1), `COUPON_ISSUE_FAILED` (5), `EXPIRED` (6) — these
3715
+ * should not normally reach the client and are typically filtered
3716
+ * out by operator-side widget configuration; if they do appear,
3717
+ * they have no player-actionable state.
3718
+ *
3719
+ * `is_redeemable` is the authoritative gate for showing the Claim
3720
+ * button — it's `true` only when the bonus is in a claimable status
3721
+ * AND the operator's integration uses a coupon model (where the
3722
+ * player must explicitly trigger delivery). Auto-redeemed bonuses
3723
+ * arrive already in `REDEEMED` state with `is_redeemable: false`.
3724
+ *
3725
+ * **Field hierarchy — display amount**
3726
+ * Bonuses carry both template-level (`label_bonus_template_meta_map.description`)
3727
+ * and instance-level (`bonus_meta_map.uiAmount`) display strings.
3728
+ * Prefer `bonus_meta_map.uiAmount` when present — it's the dynamic
3729
+ * amount computed at issuance time (e.g. from a dynamic-bonus
3730
+ * formula). Fall back to `label_bonus_template_meta_map.description`
3731
+ * (which can include HTML; sanitize before injecting).
3732
+ *
3733
+ * **Date format**
3734
+ * `create_date` and `redeem_date` are ISO 8601 UTC strings WITHOUT
3735
+ * a timezone suffix (`"YYYY-MM-DDTHH:MM:SS"`). Parse as UTC and
3736
+ * display in the user's local timezone. `redeem_date` is absent
3737
+ * until the bonus reaches `REDEEMED` status.
3738
+ *
3739
+ * **Cache TTL**: the SDK caches the response for 30 seconds. Cache
3740
+ * is fully cleared on login / logout.
3741
+ *
3742
+ * **Idempotency / Side effects**: safe. Read-only.
3743
+ *
3744
+ * **UI guidance**: see [UI Guide — `getBonuses`](../../docs/ui/bonuses/UIGuide_getBonuses.md).
3745
+ *
3746
+ * **Visitor mode**: not supported.
3747
+ *
3748
+ * @param params Optional. Omit to fetch without subscribing.
3749
+ * @param params.onUpdate Callback invoked with the full refreshed
3750
+ * bonuses list after every
3751
+ * {@link claimBonus} resolves. Each call
3752
+ * to `getBonuses` overwrites the prior
3753
+ * callback.
3754
+ * @returns Promise resolving to the bonuses list.
3755
+ * Empty array if no bonuses are visible.
3756
+ *
3757
+ * @example
3758
+ * ```ts
3759
+ * const bonuses = await window._smartico.api.getBonuses({
3760
+ * onUpdate: (refreshed) => {
3761
+ * console.log('[smartico] bonuses refreshed (after claimBonus) — re-render the bonuses UI from this array:', refreshed);
3762
+ * },
3763
+ * });
3764
+ *
3765
+ * // Bucket into pending vs redeemed tabs. The default Smartico UI groups
3766
+ * // COUPON_ISSUED + REDEEM_FAILED into the same "Pending" tab.
3767
+ * const pending = bonuses.filter(b =>
3768
+ * b.bonus_status_id === 2 || b.bonus_status_id === 4 // COUPON_ISSUED or REDEEM_FAILED
3769
+ * );
3770
+ * const redeemed = bonuses.filter(b => b.bonus_status_id === 3); // REDEEMED
3771
+ *
3772
+ * console.log('[smartico] render bonus tabs: pending=', pending.length, 'redeemed=', redeemed.length);
3773
+ *
3774
+ * // Render each pending bonus card; show Claim button only when redeemable.
3775
+ * for (const b of pending) {
3776
+ * const amount = b.bonus_meta_map?.uiAmount || b.label_bonus_template_meta_map?.description;
3777
+ * if (b.is_redeemable) {
3778
+ * console.log('[smartico] render Claim button for bonus', b.bonus_id, '— amount:', amount);
3779
+ * } else {
3780
+ * console.log('[smartico] render bonus as informational (no Claim button) — amount:', amount);
3781
+ * }
3782
+ * }
3783
+ *
3784
+ * // Server-awarded bonuses (e.g. from a CRM campaign) do NOT push;
3785
+ * // poll if you need near-live awareness.
3786
+ * setInterval(async () => {
3787
+ * const fresh = await window._smartico.api.getBonuses();
3788
+ * const newCount = fresh.filter(b => b.bonus_status_id === 2 || b.bonus_status_id === 4).length;
3789
+ * console.log('[smartico] poll tick — pending bonuses now:', newCount);
3790
+ * }, 30_000);
3791
+ * ```
3390
3792
  */
3391
3793
  async getBonuses({
3392
3794
  onUpdate
@@ -3397,12 +3799,113 @@ class WSAPIBonuses extends WSAPIMissions {
3397
3799
  return OCache.use(onUpdateContextKey.Bonuses, ECacheContext.WSAPI, () => this.api.bonusesGetItemsT(this.userExtId), CACHE_DATA_SEC);
3398
3800
  }
3399
3801
  /**
3400
- * Claim the bonus by bonus_id. Returns the err_code in case of success or error.
3401
- * Note that this method can be used only on integrations where originally failed bonus can be claimed again.
3402
- * For example, user won a bonus in the mini-game, but Operator rejected this bonus.
3403
- * This bonus will be available for the user to claim again.
3802
+ * Triggers manual redemption of a coupon-model bonus the user has
3803
+ * been awarded. For bonuses with `is_redeemable === true` returned
3804
+ * by {@link getBonuses}, this is the call that asks the operator's
3805
+ * integration to actually credit the bonus to the player's account.
3806
+ * Bonuses on integrations that auto-redeem arrive already in
3807
+ * `REDEEMED` state and do not require this call.
3404
3808
  *
3405
- * **Visitor mode: not supported**
3809
+ * Use this for `bonus_status_id` of `COUPON_ISSUED` (2) as the
3810
+ * first-time claim, and for `REDEEM_FAILED` (4) as a retry after a
3811
+ * prior unsuccessful attempt.
3812
+ *
3813
+ * @remarks
3814
+ * **Preconditions**
3815
+ * Read the candidate bonus from {@link getBonuses} and gate the
3816
+ * call on `is_redeemable === true`. The SDK forwards the request
3817
+ * unconditionally — calling on a non-claimable bonus returns
3818
+ * `err_code = -1`.
3819
+ *
3820
+ * **Error codes** (in `err_code`)
3821
+ *
3822
+ * The SDK currently types `err_code` as {@link SAWSpinErrorCode} for
3823
+ * historical reasons, but the values returned by this method come
3824
+ * from the server's general error space and are NOT mini-game codes.
3825
+ * Branch on the numeric values:
3826
+ *
3827
+ * - `0` — success; the bonus has been redeemed and the operator's
3828
+ * integration has credited the player's account.
3829
+ * - `-1` — bonus not claimable: not found, already claimed by
3830
+ * another session, or its status is no longer `COUPON_ISSUED` /
3831
+ * `REDEEM_FAILED`. Treat as idempotent — refresh
3832
+ * {@link getBonuses} and reconcile.
3833
+ * - `1` — generic server error. Transient; allow retry after a brief
3834
+ * delay.
3835
+ * - `9999` — uncaught server exception. Treat as a transient failure;
3836
+ * surface a generic error and allow retry.
3837
+ * - other non-zero — generic server error. Surface `err_message` if
3838
+ * any.
3839
+ *
3840
+ * **`success` field is unreliable**: the wire response does not
3841
+ * carry a `success` boolean — the field on `TClaimBonusResult` will
3842
+ * be `undefined` in practice. Always branch on `err_code === 0`
3843
+ * for the success check.
3844
+ *
3845
+ * **Refresh after success (and after failure)**
3846
+ * The SDK automatically refreshes the bonuses cache on every
3847
+ * response (success OR failure) and fires any `onUpdate` callback
3848
+ * registered via {@link getBonuses}'s `onUpdate`. After
3849
+ * `err_code === 0`, the redeemed bonus shifts from
3850
+ * `COUPON_ISSUED` / `REDEEM_FAILED` to `REDEEMED` on the refreshed
3851
+ * array, with `redeem_date` populated. After a failure, the bonus
3852
+ * typically lands in `REDEEM_FAILED` and remains claimable for a
3853
+ * retry.
3854
+ *
3855
+ * **Idempotency**: NOT idempotent at the SDK level. A second call
3856
+ * returns `err_code = -1` once the first has succeeded — treat that
3857
+ * as success in the UI rather than as a real error. Guard the call
3858
+ * site against double-clicks (set a local "claiming" flag on click,
3859
+ * clear it on response).
3860
+ *
3861
+ * **Side effects** (on `err_code === 0`)
3862
+ * - Bonus status transitions to `REDEEMED`; `redeem_date` is set.
3863
+ * - The operator's integration credits the player's account
3864
+ * externally. The SDK does not observe that credit directly —
3865
+ * balance updates flow over the user-properties channel from the
3866
+ * operator's side, not from this response.
3867
+ * - Server-side analytics events fire downstream (not directly
3868
+ * observable from the SDK).
3869
+ *
3870
+ * **UI guidance**: see [UI Guide — `claimBonus`](../../docs/ui/bonuses/UIGuide_claimBonus.md).
3871
+ *
3872
+ * **Visitor mode**: not supported.
3873
+ *
3874
+ * @param bonus_id The `bonus_id` from a `TBonus` returned by
3875
+ * {@link getBonuses}.
3876
+ * @returns `{ err_code, err_message, success? }`; success when
3877
+ * `err_code === 0` (or `err_code === -1` when treated as
3878
+ * idempotent no-op). The `success` field is unreliable —
3879
+ * ignore it.
3880
+ *
3881
+ * @example
3882
+ * ```ts
3883
+ * const bonuses = await window._smartico.api.getBonuses({
3884
+ * onUpdate: (refreshed) => console.log('[smartico] bonuses refreshed — re-render from this array', refreshed),
3885
+ * });
3886
+ * const bonus = bonuses.find(b => b.bonus_id === bonusId);
3887
+ *
3888
+ * if (!bonus) {
3889
+ * console.log('[smartico] bonus no longer visible — refresh list and hide CTA');
3890
+ * return;
3891
+ * }
3892
+ * if (!bonus.is_redeemable) {
3893
+ * console.log('[smartico] bonus is not claimable (auto-redeemed or already finalised) — keep CTA hidden');
3894
+ * return;
3895
+ * }
3896
+ *
3897
+ * console.log('[smartico] claim starting — set in-flight flag, show loading dots on the Claim button, keep the modal open');
3898
+ * const r = await window._smartico.api.claimBonus(bonus.bonus_id);
3899
+ * console.log('[smartico] claim response received — clear in-flight flag');
3900
+ *
3901
+ * if (r.err_code === 0 || r.err_code === -1) {
3902
+ * console.log('[smartico] claim succeeded (or was already done) — show a success toast; the getBonuses onUpdate above will fire with the refreshed list');
3903
+ * } else if (r.err_code === 9999) {
3904
+ * console.error('[smartico] uncaught server exception — show a generic error toast and allow retry');
3905
+ * } else {
3906
+ * console.error('[smartico] claim failed — surface this error message to the user; the bonus will move to REDEEM_FAILED state and remain claimable for a retry:', r.err_message);
3907
+ * }
3908
+ * ```
3406
3909
  */
3407
3910
  async claimBonus(bonus_id) {
3408
3911
  const r = await this.api.bonusClaimItem(this.userExtId, bonus_id);
@@ -4481,7 +4984,7 @@ class WSAPITournaments extends WSAPIStore {
4481
4984
  *
4482
4985
  * For clan tournaments (`is_clan_based === true`), the user must
4483
4986
  * already belong to a clan before calling. If they don't, prompt them
4484
- * to pick a clan first via {@link joinClan}, then call
4987
+ * to pick a clan first via `joinClan`, then call
4485
4988
  * `registerInTournament` after the clan-join resolves. See "Error
4486
4989
  * codes" `1010` below for the server-side safety net.
4487
4990
  *
@@ -4490,8 +4993,8 @@ class WSAPITournaments extends WSAPIStore {
4490
4993
  * tournament lobby refresh fires.
4491
4994
  * - `1010` — `TOURNAMENT_USER_CANNOT_JOIN_WITHOUT_CLAN`: clan-based
4492
4995
  * tournament and the user has no clan. Surface the clan-pick flow
4493
- * (e.g. open a clan-pick modal driven by {@link getClans} +
4494
- * {@link joinClan}), then retry registration.
4996
+ * (e.g. open a clan-pick modal driven by `getClans` +
4997
+ * `joinClan`), then retry registration.
4495
4998
  * - `30001` — `TOURNAMENT_INSTANCE_NOT_FOUND`: instance ID is invalid
4496
4999
  * or the tournament was deleted. Refresh the lobby via
4497
5000
  * `getTournamentsList()` and hide the entry from the UI.
@@ -5049,23 +5552,81 @@ class WSAPIJackpots extends WSAPIClans {
5049
5552
  OCache.clear(ECacheContext.WSAPI, onUpdateContextKey.Pots);
5050
5553
  OCache.clear(ECacheContext.WSAPI, onUpdateContextKey.JackpotWinners);
5051
5554
  }
5052
- /** Returns list of Jackpots that are active in the system and matching to the filter definition.
5053
- * If filter is not provided, all active jackpots will be returned.
5054
- * Filter can be used to get jackpots related to specific game or specific jackpot template.
5055
- * You can call this method every second in order to get up to date information about current value of the jackpot(s) and present them to the end-users
5555
+ /**
5556
+ * Returns the user-eligible jackpots active for the label, fused with their live
5557
+ * pot values. Each entry carries the static template (name, description, opt-in
5558
+ * state, eligible games, currency) plus a freshly-fetched `pot` snapshot.
5056
5559
  *
5057
- * **Example**:
5058
- * ```
5059
- * _smartico.api.jackpotGet({ related_game_id: 'wooko-slot' }).then((result) => {
5060
- * console.log(result);
5061
- * });
5062
- * ```
5560
+ * Designed to be polled at high frequency (every 1 second is fine) — the SDK
5561
+ * splits the response into a 30-second template cache and a 1-second pot-value
5562
+ * cache so consumers can render a live-counting pot amount without hammering
5563
+ * the server for the static template data.
5063
5564
  *
5064
- * **Example in the Visitor mode**:
5065
- * ```
5066
- * _smartico.vapi('EN').jackpotGet({ related_game_id: 'wooko-slot' }).then((result) => {
5067
- * console.log(result);
5068
- * });
5565
+ * @remarks
5566
+ * **Preconditions**
5567
+ * - No prerequisite calls.
5568
+ * - Visitor mode supported via `_smartico.vapi(lang).jackpotGet(...)`.
5569
+ *
5570
+ * **Server-side eligibility filtering**
5571
+ * Jackpots are filtered server-side by the user's segments before being
5572
+ * returned. Templates the user is ineligible for never appear in this
5573
+ * response — there is no "locked" state to render. An empty result for a
5574
+ * known-good user typically means none of the configured templates match
5575
+ * the user's segments / level / brand.
5576
+ *
5577
+ * **Filter behavior**
5578
+ * Passing `related_game_id` returns only jackpots linked to that game (from
5579
+ * the operator's games catalog). Passing `jp_template_id` returns just that
5580
+ * single template. With no filter, all active templates the user is
5581
+ * eligible for are returned. Changing the filter between calls flushes both
5582
+ * the template cache and the pot cache.
5583
+ *
5584
+ * **Two-tier cache**
5585
+ * - Template definitions: 30 s cache. Re-fetched on filter change or when
5586
+ * opt-in / opt-out / a jackpot-win push lands.
5587
+ * - Pot values: 1 s cache. Re-fetched on every call past the 1-second
5588
+ * window so a 1 Hz poll renders a smoothly counting pot.
5589
+ *
5590
+ * **`jp_public_meta.custom_data`**
5591
+ * Server returns this as a JSON-encoded string; the SDK parses it inline so
5592
+ * consumers always receive either a parsed object or the raw string.
5593
+ *
5594
+ * **Personal vs MultiUser jackpots** (see {@link JackpotType})
5595
+ * - `MultiUser` (1) — shared pot; `registration_count` reflects real opted-in
5596
+ * user count; temperature transitions fire push events.
5597
+ * - `Personal` (2) — independent per-user pot; `registration_count` is
5598
+ * always 1; temperature push events are suppressed.
5599
+ *
5600
+ * **Refresh**
5601
+ * - `jp_status_id`, segment changes, and operator template edits surface
5602
+ * after the 30 s template cache TTL.
5603
+ * - Opt-in / opt-out / jackpot-win push events all clear the template and
5604
+ * pot caches — the next call re-fetches.
5605
+ *
5606
+ * **Visitor mode**: supported.
5607
+ *
5608
+ * **UI guidance**: see [UI Guide — `jackpotGet`](../../docs/ui/jackpots/UIGuide_jackpotGet.md).
5609
+ *
5610
+ * @param filter Optional filter narrowing the result set.
5611
+ * @param filter.related_game_id Limit to jackpots linked to this game ID
5612
+ * (from the operator's games catalog).
5613
+ * @param filter.jp_template_id Limit to a single template.
5614
+ * @returns Array of {@link JackpotDetails} — empty if the user is eligible
5615
+ * for no active jackpots.
5616
+ *
5617
+ * @example
5618
+ * ```ts
5619
+ * // Poll every second for live pot counter
5620
+ * setInterval(async () => {
5621
+ * const jackpots = await window._smartico.api.jackpotGet();
5622
+ * for (const jp of jackpots) {
5623
+ * console.log('[smartico] update pot widget for', jp.jp_public_meta.name, '— amount:', jp.pot.current_pot_amount_user_currency, jp.user_currency, '— temperature:', jp.pot.current_pot_temperature);
5624
+ * }
5625
+ * }, 1000);
5626
+ *
5627
+ * // Filtered fetch for a specific game tile
5628
+ * const linked = await window._smartico.api.jackpotGet({ related_game_id: 'gold-slot2' });
5629
+ * console.log('[smartico] linked jackpots for game:', linked.length);
5069
5630
  * ```
5070
5631
  */
5071
5632
  async jackpotGet(filter) {
@@ -5102,18 +5663,68 @@ class WSAPIJackpots extends WSAPIClans {
5102
5663
  });
5103
5664
  }
5104
5665
  /**
5105
- * Opt-in currently logged in user to the jackpot with the specified jp_template_id.
5106
- * You may call jackpotGet method after doing optin to see that user is opted in to the jackpot.
5666
+ * Opts the authenticated user into a jackpot. From this point on, the user
5667
+ * contributes to the pot (per the template's `contribution_type` and
5668
+ * `contribution_value`) and is eligible to win when the pot explodes.
5107
5669
  *
5108
- * **Example**:
5109
- * ```
5110
- * _smartico.api.jackpotOptIn({ jp_template_id: 123 }).then((result) => {
5111
- * console.log('Opted in to the jackpot');
5112
- * });
5113
- * ```
5670
+ * On success the SDK clears the jackpot caches — the next
5671
+ * {@link jackpotGet} call returns the updated `is_opted_in: true` and an
5672
+ * incremented `registration_count`.
5114
5673
  *
5115
- * **Visitor mode: not supported**
5674
+ * @remarks
5675
+ * **Preconditions**
5676
+ * - User must be authenticated. Visitor mode not supported.
5677
+ * - `jp_template_id` is mandatory — the SDK throws synchronously if missing.
5678
+ * - The jackpot must currently be active and the user must be in its
5679
+ * eligibility segment. Ineligible jackpots are filtered out of
5680
+ * {@link jackpotGet} entirely, so a card the user sees is opt-in-able.
5681
+ *
5682
+ * **Error handling**
5683
+ * The server returns a non-zero `errCode` with a human-readable `errMsg`
5684
+ * for any failure. Common causes:
5685
+ * - User is in a control group.
5686
+ * - Jackpot template is not active (status changed since the user opened
5687
+ * the card).
5688
+ * - User is already opted in (the SDK has no client-side guard against a
5689
+ * double-tap; the server enforces).
5690
+ * - DB race / generic server error.
5691
+ *
5692
+ * The SDK does NOT enumerate distinct numeric codes for each cause — branch
5693
+ * on `errCode === 0` for success and surface `errMsg` as-is for failures.
5694
+ *
5695
+ * **Idempotency / re-opt-in semantics**
5696
+ * - **Already opted in** → returns non-zero `errCode` ("User already opted in").
5697
+ * - **Previously opted in then opted out** → succeeds silently; the server
5698
+ * re-activates the registration. This is not an error path — a user can
5699
+ * freely cycle opt-in / opt-out.
5700
+ *
5701
+ * **Refresh after success**
5702
+ * - The SDK clears the template, pot, and winners caches.
5703
+ * - The next {@link jackpotGet} call returns `is_opted_in: true` for this
5704
+ * template.
5705
+ *
5706
+ * **Side effects**
5707
+ * Fires a `JACKPOT_OPT_IN` engagement event (visible to operator-side
5708
+ * automation rules). Does NOT immediately move points / gems — contributions
5709
+ * happen per-bet via the user's gameplay, not on opt-in.
5710
+ *
5711
+ * **Visitor mode**: not supported.
5712
+ *
5713
+ * **UI guidance**: see [UI Guide — `jackpotOptIn`](../../docs/ui/jackpots/UIGuide_jackpotOptIn.md).
5116
5714
  *
5715
+ * @param filter.jp_template_id ID of the jackpot template to join.
5716
+ * @returns {@link JackpotsOptinResponse} — `errCode === 0` on success.
5717
+ *
5718
+ * @example
5719
+ * ```ts
5720
+ * const r = await window._smartico.api.jackpotOptIn({ jp_template_id: 42 });
5721
+ *
5722
+ * if (r.errCode === 0) {
5723
+ * console.log('[smartico] opted in — refresh jackpot card to show opt-out CTA');
5724
+ * } else {
5725
+ * console.error('[smartico] opt-in failed — show this message in an error toast:', r.errMsg);
5726
+ * }
5727
+ * ```
5117
5728
  */
5118
5729
  async jackpotOptIn(filter) {
5119
5730
  if (!filter.jp_template_id) {
@@ -5123,18 +5734,63 @@ class WSAPIJackpots extends WSAPIClans {
5123
5734
  return result;
5124
5735
  }
5125
5736
  /**
5126
- * Opt-out currently logged in user from the jackpot with the specified jp_template_id.
5127
- * You may call jackpotGet method after doing optout to see that user is not opted in to the jackpot.
5737
+ * Opts the authenticated user out of a jackpot. From this point on the user
5738
+ * no longer contributes to the pot and is not eligible to win.
5128
5739
  *
5129
- * **Example**:
5130
- * ```
5131
- * _smartico.api.jackpotOptOut({ jp_template_id: 123 }).then((result) => {
5132
- * console.log('Opted out from the jackpot');
5133
- * });
5134
- * ```
5740
+ * The user can re-join later via {@link jackpotOptIn} — opt-out is not
5741
+ * permanent.
5135
5742
  *
5136
- * **Visitor mode: not supported**
5743
+ * @remarks
5744
+ * **Preconditions**
5745
+ * - User must be authenticated. Visitor mode not supported.
5746
+ * - `jp_template_id` is mandatory — the SDK throws synchronously if missing.
5747
+ *
5748
+ * **Error handling**
5749
+ * The server returns a non-zero `errCode` with a human-readable `errMsg` for
5750
+ * any failure. Common causes:
5751
+ * - User has never opted in OR is already opted out — server returns
5752
+ * non-zero `errCode` for the "already opted out" case. Calling opt-out
5753
+ * on a jackpot the user has never registered for typically returns
5754
+ * success (the server finds no registration row to update).
5755
+ * - DB race / generic server error.
5756
+ *
5757
+ * Unlike {@link jackpotOptIn}, opt-out does NOT check the template's status
5758
+ * — the user can opt out of a jackpot that has been deactivated by the
5759
+ * operator.
5760
+ *
5761
+ * **Idempotency**
5762
+ * - First opt-out → success.
5763
+ * - Second opt-out → non-zero `errCode` ("Already opted out").
5764
+ * - Opt-out of a never-joined jackpot → typically succeeds silently
5765
+ * (no registration row to act on).
5766
+ *
5767
+ * **Refresh after success**
5768
+ * - The SDK clears the template, pot, and winners caches.
5769
+ * - The next {@link jackpotGet} call returns `is_opted_in: false` for this
5770
+ * template and a decremented `registration_count`.
5137
5771
  *
5772
+ * **Side effects**
5773
+ * Fires a `JACKPOT_OPT_OUT` engagement event for operator-side automation
5774
+ * rules. The user's existing contributions to the current pot remain in
5775
+ * place — opt-out stops future contributions but does not refund past ones.
5776
+ *
5777
+ * **Visitor mode**: not supported.
5778
+ *
5779
+ * **UI guidance**: see [UI Guide — `jackpotOptOut`](../../docs/ui/jackpots/UIGuide_jackpotOptOut.md).
5780
+ *
5781
+ * @param filter.jp_template_id ID of the jackpot template to leave.
5782
+ * @returns {@link JackpotsOptoutResponse} — `errCode === 0` on success.
5783
+ *
5784
+ * @example
5785
+ * ```ts
5786
+ * const r = await window._smartico.api.jackpotOptOut({ jp_template_id: 42 });
5787
+ *
5788
+ * if (r.errCode === 0) {
5789
+ * console.log('[smartico] opted out — refresh jackpot card to show join CTA');
5790
+ * } else {
5791
+ * console.error('[smartico] opt-out failed — show this message in an error toast:', r.errMsg);
5792
+ * }
5793
+ * ```
5138
5794
  */
5139
5795
  async jackpotOptOut(filter) {
5140
5796
  if (!filter.jp_template_id) {
@@ -5144,25 +5800,64 @@ class WSAPIJackpots extends WSAPIClans {
5144
5800
  return result;
5145
5801
  }
5146
5802
  /**
5147
- * Returns jackpot winners for the given `jp_template_id` (paginated on the server).
5148
- * Default page size on the wire is 20; use `limit`, `offset`, and repeated calls to load more.
5149
- * The full protocol response also includes `has_more`; this method returns only the `winners` array.
5803
+ * Returns past winners of a specific jackpot template, paginated. Use to
5804
+ * power a "Recent winners" panel inside the jackpot detail modal.
5150
5805
  *
5151
- * **Example**:
5152
- * ```
5153
- * _smartico.api.getJackpotWinners({
5154
- * jp_template_id: 123,
5155
- * }).then((result) => {
5156
- * console.log(result);
5157
- * });
5158
- * ```
5806
+ * **Important**: respect the `expose_winners_over_api` flag on the jackpot's
5807
+ * {@link JackpotDetails} before calling this method. The server-side handler
5808
+ * does NOT enforce that flag — it is a UI-only gate. Custom UIs that ignore
5809
+ * the flag will display winners the operator intended to keep private.
5159
5810
  *
5160
- * **Visitor mode: not supported**
5811
+ * @remarks
5812
+ * **Preconditions**
5813
+ * - User must be authenticated. Visitor mode not supported.
5814
+ * - `jp_template_id` is mandatory — the SDK throws synchronously if missing.
5815
+ * - The consumer SHOULD check
5816
+ * {@link JackpotDetails.expose_winners_over_api} before calling, since
5817
+ * the server does not enforce it.
5818
+ *
5819
+ * **Pagination**
5820
+ * Server default page size is 20. Pass `limit` and `offset` to paginate
5821
+ * (e.g. infinite-scroll). The wire response carries a `has_more` flag, but
5822
+ * this SDK method returns only the `winners` array — detect end-of-list by
5823
+ * a returned array shorter than `limit`.
5824
+ *
5825
+ * **Currency caveat**
5826
+ * Winner amounts in the response (`winner.winning_amount_jp_currency`) are
5827
+ * in the jackpot's NATIVE currency, NOT the user's wallet currency. If a
5828
+ * user-currency display is needed, the consumer must convert client-side.
5829
+ *
5830
+ * **Refresh**
5831
+ * - The SDK caches per `jp_template_id` for 30 seconds.
5832
+ * - Caches clear on jackpot-win push events and on opt-in / opt-out.
5833
+ *
5834
+ * **Error handling**
5835
+ * Non-zero `errCode` on control-group users or generic server errors. The
5836
+ * SDK does NOT enumerate distinct codes — branch on `errCode === 0` and
5837
+ * surface `errMsg` on failure.
5838
+ *
5839
+ * **Visitor mode**: not supported.
5840
+ *
5841
+ * **UI guidance**: see [UI Guide — `getJackpotWinners`](../../docs/ui/jackpots/UIGuide_getJackpotWinners.md).
5842
+ *
5843
+ * @returns Array of {@link JackpotWinnerHistory} entries newest-first.
5844
+ *
5845
+ * @example
5846
+ * ```ts
5847
+ * const [jp] = await window._smartico.api.jackpotGet({ jp_template_id: 42 });
5848
+ *
5849
+ * if (!jp || !jp.expose_winners_over_api) {
5850
+ * console.log('[smartico] winners hidden by operator config — hide the winners tab');
5851
+ * return;
5852
+ * }
5161
5853
  *
5162
- * @param params - Jackpot winners parameters
5163
- * @param params.jp_template_id - Jackpot template id (required; throws if missing)
5164
- * @param params.limit - Page size (server default 20 when omitted)
5165
- * @param params.offset - Offset into the winner list
5854
+ * const winners = await window._smartico.api.getJackpotWinners({
5855
+ * jp_template_id: 42,
5856
+ * limit: 20,
5857
+ * offset: 0,
5858
+ * });
5859
+ * console.log('[smartico] render', winners.length, 'recent winner rows (amounts in', jp.jp_currency + ')');
5860
+ * ```
5166
5861
  */
5167
5862
  async getJackpotWinners({
5168
5863
  limit,
@@ -5172,29 +5867,67 @@ class WSAPIJackpots extends WSAPIClans {
5172
5867
  return OCache.use(onUpdateContextKey.JackpotWinners + jp_template_id, ECacheContext.WSAPI, () => this.api.getJackpotWinnersT(this.userExtId, limit, offset, jp_template_id), JACKPOT_WINNERS_CACHE_SEC);
5173
5868
  }
5174
5869
  /**
5175
- * Returns the eligible games for the jackpot with the specified jp_template_id.
5870
+ * Returns the casino games eligible to contribute to a specific jackpot —
5871
+ * the catalog the user must play to grow the pot. Use to power an
5872
+ * "Eligible games" carousel inside the jackpot detail modal.
5176
5873
  *
5177
- * **Example**:
5178
- * ```
5179
- * _smartico.api.getJackpotEligibleGames({ jp_template_id: 123 }).then((result) => {
5180
- * console.log(result);
5181
- * });
5182
- * ```
5874
+ * **Shortcut**: when the jackpot's
5875
+ * {@link JackpotDetails.ach_related_game_allow_all} flag is `true`, every
5876
+ * game in the operator catalog contributes — there's no point calling this
5877
+ * method (the result would be the full catalog). The default Smartico UI
5878
+ * hides the Eligible Games tab entirely in that case.
5183
5879
  *
5184
- * **Visitor mode: not supported**
5880
+ * @remarks
5881
+ * **Preconditions**
5882
+ * - User must be authenticated. Visitor mode not supported.
5883
+ * - `jp_template_id` is mandatory.
5185
5884
  *
5186
- */
5187
- async getJackpotEligibleGames({
5188
- jp_template_id,
5189
- onUpdate
5190
- }) {
5191
- if (onUpdate) {
5192
- this.onUpdateCallback.set(onUpdateContextKey.JackpotEligibleGames, onUpdate);
5193
- }
5194
- return OCache.use(onUpdateContextKey.JackpotEligibleGames + jp_template_id, ECacheContext.WSAPI, () => this.api.getJackpotEligibleGamesT(this.userExtId, {
5195
- jp_template_id
5196
- }), JACKPOT_ELIGIBLE_GAMES_CACHE_SEC);
5197
- }
5885
+ * **`onUpdate` caveat**
5886
+ * The `onUpdate` callback is accepted to match the SDK's subscription
5887
+ * contract but is NOT auto-invoked by any current server push. It will only
5888
+ * fire if a consumer (or a future SDK version) explicitly pushes an update.
5889
+ * Treat it as a no-op for now.
5890
+ *
5891
+ * **Refresh**
5892
+ * - The SDK caches per `jp_template_id` for 30 seconds.
5893
+ * - Cache does NOT clear on opt-in / opt-out / jackpot-win — eligible-game
5894
+ * lists rarely change during a session. Wait for the 30 s TTL.
5895
+ *
5896
+ * **Error handling**
5897
+ * Non-zero `errCode` on control-group users or generic server errors.
5898
+ * Branch on `errCode === 0` and surface `errMsg` on failure.
5899
+ *
5900
+ * **Visitor mode**: not supported.
5901
+ *
5902
+ * **UI guidance**: see [UI Guide — `getJackpotEligibleGames`](../../docs/ui/jackpots/UIGuide_getJackpotEligibleGames.md).
5903
+ *
5904
+ * @returns {@link TGetJackpotEligibleGamesResponse} —
5905
+ * `{ eligible_games: JackpotEligibleGame[] }`.
5906
+ *
5907
+ * @example
5908
+ * ```ts
5909
+ * const [jp] = await window._smartico.api.jackpotGet({ jp_template_id: 42 });
5910
+ *
5911
+ * if (jp?.ach_related_game_allow_all) {
5912
+ * console.log('[smartico] all games eligible — hide the eligible-games tab');
5913
+ * return;
5914
+ * }
5915
+ *
5916
+ * const r = await window._smartico.api.getJackpotEligibleGames({ jp_template_id: 42 });
5917
+ * console.log('[smartico] render', r.eligible_games.length, 'eligible game tiles');
5918
+ * ```
5919
+ */
5920
+ async getJackpotEligibleGames({
5921
+ jp_template_id,
5922
+ onUpdate
5923
+ }) {
5924
+ if (onUpdate) {
5925
+ this.onUpdateCallback.set(onUpdateContextKey.JackpotEligibleGames, onUpdate);
5926
+ }
5927
+ return OCache.use(onUpdateContextKey.JackpotEligibleGames + jp_template_id, ECacheContext.WSAPI, () => this.api.getJackpotEligibleGamesT(this.userExtId, {
5928
+ jp_template_id
5929
+ }), JACKPOT_ELIGIBLE_GAMES_CACHE_SEC);
5930
+ }
5198
5931
  }
5199
5932
 
5200
5933
  /** @group Raffles */
@@ -5204,26 +5937,112 @@ class WSAPIRaffles extends WSAPIJackpots {
5204
5937
  this.updateEntity(onUpdateContextKey.Raffles, payload);
5205
5938
  }
5206
5939
  /**
5207
- * Returns the list of Raffles available for user
5208
- * The returned list of Raffles is cached for 30 seconds. But you can pass the onUpdate callback as a parameter. Note that each time you call getRaffles with a new onUpdate callback, the old one will be overwritten by the new one.
5209
- * The onUpdate callback will be called on claiming prize. Updated Raffles will be passed to onUpdate callback.
5940
+ * Returns all raffles visible to the current user, each carrying an
5941
+ * embedded `draws[]` array with per-draw state (current state, ticket
5942
+ * counts, opt-in status, prize structure). Use this to power a
5943
+ * raffles lobby screen and to drive per-draw CTAs (opt-in, view
5944
+ * winners, claim).
5945
+ *
5946
+ * The embedded `draws[i]` objects are sufficient for rendering all
5947
+ * draw cards — winner details with usernames / avatars require a
5948
+ * follow-up {@link getRaffleDrawRun} call (the embedded form carries
5949
+ * only `winners_total` / `winners_limit` / `winners_offset` metadata,
5950
+ * not individual winner rows).
5210
5951
  *
5211
- * **Example**:
5952
+ * @remarks
5953
+ * **Subscription model (`onUpdate`)**
5954
+ * The callback receives the FULL refreshed raffle list (never a
5955
+ * diff/patch). Each subsequent call to `getRaffles({ onUpdate })`
5956
+ * REPLACES the prior callback. Pass `onUpdate: undefined` (or omit
5957
+ * it) to keep the prior callback in place; the callback is never
5958
+ * auto-cleared.
5212
5959
  *
5213
- * ```
5214
- * _smartico.api.getRaffles().then((result) => {
5215
- * console.log(result);
5216
- * });
5217
- * ```
5960
+ * **Update triggers** — the callback fires when:
5218
5961
  *
5219
- * **Example in the Visitor mode**:
5962
+ * 1. {@link claimRafflePrize} resolves on this connection (any
5963
+ * response code) — the refreshed list reflects the new
5964
+ * `has_unclaimed_prize` / `claimed_date` state.
5965
+ * 2. {@link requestRaffleOptin} resolves on this connection (any
5966
+ * response code) — the refreshed list reflects the new
5967
+ * `user_opted_in` state on the affected draw.
5968
+ *
5969
+ * Does NOT fire for: server-side draw executions, ticket increments
5970
+ * (other users earning tickets), or operator-side raffle/draw config
5971
+ * changes. Those changes surface only on the next cache miss (after
5972
+ * the 30 s TTL) — poll manually if your UI needs sub-30s freshness
5973
+ * during an in-progress draw.
5974
+ *
5975
+ * **Reading state from the returned raffle**
5976
+ * - `current_tickets_count` vs `max_tickets_count` drives the
5977
+ * `ticket_cap_visualization` banner (enum
5978
+ * {@link RaffleTicketCapVisualization}: `Empty` = no banner,
5979
+ * `Counter` = show "X tickets remaining", `Message` = show
5980
+ * sold-out message).
5981
+ * - Within each draw, `current_state`
5982
+ * ({@link RaffleDrawInstanceState}) buckets the draw into Open
5983
+ * (accepting tickets), WinnerSelection (currently drawing), or
5984
+ * Executed (winners selected).
5985
+ * - `execution_type` ({@link RaffleDrawTypeExecution}) distinguishes
5986
+ * one-shot (`ExecDate`), repeating (`Recurring`), or special
5987
+ * one-shot (`Grand`) draws. Recurring draws share a stable
5988
+ * `draws[i].id` (the schedule definition) across runs — `run_id`
5989
+ * is the per-execution instance.
5220
5990
  *
5221
- * ```
5222
- * _smartico.vapi('EN').getRaffles().then((result) => {
5223
- * console.log(result);
5991
+ * **Cache TTL**: the SDK caches the response for 30 seconds. Cache
5992
+ * is fully cleared on login / logout. The server also invalidates
5993
+ * the SDK cache when a draw executes on the server side.
5994
+ *
5995
+ * **Idempotency / Side effects**: safe. Read-only.
5996
+ *
5997
+ * **UI guidance**: see [UI Guide — `getRaffles`](../../docs/ui/raffles/UIGuide_getRaffles.md).
5998
+ *
5999
+ * **Visitor mode**: supported. The same shape is returned, scoped
6000
+ * to the brand's public raffles. Per-user fields (`my_tickets_count`,
6001
+ * `my_last_tickets`, `user_opted_in`) are not meaningful for
6002
+ * visitors. The `onUpdate` callback is accepted but never fires
6003
+ * because the mutation methods that trigger it
6004
+ * ({@link claimRafflePrize}, {@link requestRaffleOptin}) are not
6005
+ * available / not effective in visitor mode.
6006
+ *
6007
+ * @param params Optional. Omit to fetch without subscribing.
6008
+ * @param params.onUpdate Callback invoked with the full refreshed
6009
+ * raffles list after every
6010
+ * {@link claimRafflePrize} or
6011
+ * {@link requestRaffleOptin} round-trip
6012
+ * on this connection.
6013
+ * @returns Promise resolving to the raffles list.
6014
+ *
6015
+ * @example
6016
+ * ```ts
6017
+ * const raffles = await window._smartico.api.getRaffles({
6018
+ * onUpdate: (refreshed) => {
6019
+ * console.log('[smartico] raffles refreshed (after claim/optin) — re-render from this array:', refreshed);
6020
+ * },
5224
6021
  * });
5225
- * ```
5226
6022
  *
6023
+ * for (const raffle of raffles) {
6024
+ * console.log('[smartico] render raffle', raffle.id, '—', raffle.name, ':', raffle.draws.length, 'draws');
6025
+ *
6026
+ * // Bucket draws: active/upcoming first (sorted by execution_ts ASC), then executed last.
6027
+ * const sorted = [...raffle.draws].sort((a, b) => {
6028
+ * const aDone = a.current_state === 3; // Executed
6029
+ * const bDone = b.current_state === 3;
6030
+ * if (aDone !== bDone) return aDone ? 1 : -1; // executed sink to the bottom
6031
+ * return a.execution_ts - b.execution_ts;
6032
+ * });
6033
+ *
6034
+ * for (const d of sorted) {
6035
+ * if (d.requires_optin && !d.user_opted_in && d.is_active && d.current_state !== 3) {
6036
+ * console.log('[smartico] draw', d.run_id, '— show OPT IN CTA (requires_optin + not yet opted in + still active)');
6037
+ * }
6038
+ * if (d.current_state === 3) {
6039
+ * console.log('[smartico] draw', d.run_id, 'executed — fetch winner details via getRaffleDrawRun');
6040
+ * }
6041
+ * }
6042
+ * }
6043
+ *
6044
+ * // For winner detail on an executed draw, call getRaffleDrawRun separately.
6045
+ * ```
5227
6046
  */
5228
6047
  async getRaffles({
5229
6048
  onUpdate
@@ -5234,27 +6053,106 @@ class WSAPIRaffles extends WSAPIJackpots {
5234
6053
  return OCache.use(onUpdateContextKey.Raffles, ECacheContext.WSAPI, () => this.api.getRafflesT(this.userExtId), CACHE_DATA_SEC);
5235
6054
  }
5236
6055
  /**
5237
- * Returns draw run for provided raffle_id and run_id.
5238
- * You can pass winners_from and winners_to parameters to get a specific range of winners. Default is 0-20.
6056
+ * Returns the full detail of a single raffle draw run — same shape
6057
+ * as the embedded `TRaffleDraw` in {@link getRaffles}, but populated
6058
+ * with paginated `prizes[].winners[]` rows including usernames and
6059
+ * avatars. Use this to render a draw detail / winners screen, or to
6060
+ * page through the winner list of an executed draw.
5239
6061
  *
6062
+ * Each call is a fresh server round-trip — there is no client cache.
6063
+ * Re-call to refresh.
5240
6064
  *
5241
- * **Example**:
6065
+ * @remarks
6066
+ * **Preconditions**
6067
+ * Pass `raffle_id` (the parent raffle's `id`) and `run_id` (the
6068
+ * specific run instance — `TRaffleDraw.run_id` from
6069
+ * {@link getRaffles}'s embedded draws). Note that
6070
+ * `TRaffleDraw.id` is the *schedule_id* (stable across runs of a
6071
+ * recurring draw) — that's NOT what this method takes; it takes the
6072
+ * per-instance `run_id`.
5242
6073
  *
5243
- * ```javascript
5244
- * _smartico.api.getRaffleDrawRun({raffle_id: 156, run_id: 145}).then((result) => {
5245
- * console.log(result);
5246
- * });
5247
- * ```
6074
+ * **Refresh model**
6075
+ * - **No subscription.** One-shot promise.
6076
+ * - **No client cache.** Every call sends a network request.
6077
+ * - **No push event** refreshes the response. Live winner-list
6078
+ * updates require a fresh call.
6079
+ * - The default Smartico UI polls this method on a variable cadence
6080
+ * while a draw is in flight: every 3 s during `WinnerSelection`,
6081
+ * every 10 s when the countdown is under 5 minutes, every 30 s
6082
+ * otherwise.
6083
+ *
6084
+ * **Winner pagination**
6085
+ * `winners_from` / `winners_to` define a half-open range of winner
6086
+ * indices. The default window is `0–20` (20 winners). The server
6087
+ * caps the window at 50 rows per call — passing a larger range
6088
+ * silently truncates. For "load more" pagination, advance
6089
+ * `winners_from` by the prior page size and pass the same
6090
+ * `winners_to` offset. `winners_total` on the returned
6091
+ * `TRaffleDraw` is the authoritative total count for pagination.
6092
+ *
6093
+ * The current user's own winning rows (if any) are server-sorted
6094
+ * to the top of the result.
6095
+ *
6096
+ * **Throws**
6097
+ * Both `raffle_id` and `run_id` are required — the SDK throws
6098
+ * synchronously when either is missing or falsy.
6099
+ *
6100
+ * **Idempotency / Side effects**: safe. Read-only.
6101
+ *
6102
+ * **UI guidance**: see [UI Guide — `getRaffleDrawRun`](../../docs/ui/raffles/UIGuide_getRaffleDrawRun.md).
6103
+ *
6104
+ * **Visitor mode**: supported.
6105
+ *
6106
+ * @param props.raffle_id The parent raffle's `id` (from `TRaffle.id`).
6107
+ * @param props.run_id The draw run instance ID (from
6108
+ * `TRaffleDraw.run_id`, not `TRaffleDraw.id`).
6109
+ * @param props.winners_from First winner index to return (0-based).
6110
+ * Defaults to `0`.
6111
+ * @param props.winners_to Last winner index (exclusive).
6112
+ * Defaults to `20`. Server caps the
6113
+ * window at 50 rows per call.
6114
+ * @returns Promise resolving to `TRaffleDraw`
6115
+ * with `prizes[].winners[]` populated
6116
+ * and `winners_total` set.
5248
6117
  *
5249
- * **Example in the Visitor mode**:
6118
+ * @example
6119
+ * ```ts
6120
+ * const raffles = await window._smartico.api.getRaffles();
6121
+ * const raffle = raffles[0];
6122
+ * const draw = raffle.draws.find(d => d.current_state === 3); // Executed
5250
6123
  *
6124
+ * if (!draw) {
6125
+ * console.log('[smartico] no executed draw — skip detail view');
6126
+ * return;
6127
+ * }
5251
6128
  *
5252
- * ```javascript
5253
- * _smartico.vapi('EN').getRaffleDrawRun({ raffle_id: 156, run_id: 145 }).then((result) => {
5254
- * console.log(result);
6129
+ * // First page of winners.
6130
+ * const detail = await window._smartico.api.getRaffleDrawRun({
6131
+ * raffle_id: raffle.id,
6132
+ * run_id: draw.run_id, // NOTE: run_id, NOT draw.id
6133
+ * winners_from: 0,
6134
+ * winners_to: 20,
5255
6135
  * });
5256
- * ```
5257
6136
  *
6137
+ * for (const prize of detail.prizes) {
6138
+ * console.log('[smartico] prize', prize.name, '— winners on this page:', prize.winners.length);
6139
+ * const myWin = prize.winners.find(w => w.username === currentUsername); // or another match
6140
+ * if (myWin) {
6141
+ * console.log('[smartico] current user won this prize — surface a Claim CTA if not yet claimed');
6142
+ * }
6143
+ * }
6144
+ *
6145
+ * // Load more — pagination via winners_from / winners_to.
6146
+ * if ((detail.winners_total ?? 0) > 20) {
6147
+ * const next = await window._smartico.api.getRaffleDrawRun({
6148
+ * raffle_id: raffle.id,
6149
+ * run_id: draw.run_id,
6150
+ * winners_from: 20,
6151
+ * winners_to: 40,
6152
+ * });
6153
+ * console.log('[smartico] page 2 loaded — append', next.prizes.flatMap(p => p.winners).length, 'winners');
6154
+ * }
6155
+ * ```
5258
6156
  */
5259
6157
  async getRaffleDrawRun(props) {
5260
6158
  if (!props.raffle_id || !props.run_id) {
@@ -5263,25 +6161,76 @@ class WSAPIRaffles extends WSAPIJackpots {
5263
6161
  return await this.api.getRaffleDrawRunT(this.userExtId, props.raffle_id, props.run_id, props.winners_from, props.winners_to);
5264
6162
  }
5265
6163
  /**
5266
- * Returns history of draw runs for the provided raffle_id and draw_id, if the draw_id is not provided will return history of all the draws for the provided raffle_id
6164
+ * Returns the history of past-executed draw runs for a raffle —
6165
+ * optionally scoped to a single recurring draw schedule. Each row
6166
+ * is a previously-executed run with its scheduled and
6167
+ * actual-execution timestamps, the user's win status, and an
6168
+ * unclaimed-prize flag for surfacing a Claim CTA on history rows.
6169
+ *
6170
+ * @remarks
6171
+ * **Preconditions**
6172
+ * `raffle_id` is required. `draw_id` is optional — when omitted,
6173
+ * the response includes history for ALL draws of the raffle; when
6174
+ * supplied, it scopes to that one draw's recurring history. The
6175
+ * `draw_id` to pass is `TRaffleDraw.id` (the schedule_id, stable
6176
+ * across runs), not `run_id`.
5267
6177
  *
6178
+ * **Server-side filtering**
6179
+ * Draws configured by the operator to hide their history are
6180
+ * excluded from the response automatically. Cancelled runs are
6181
+ * also excluded.
6182
+ *
6183
+ * **Sort order**
6184
+ * Server returns rows by scheduled `execution_ts` descending
6185
+ * (newest first). No client-side sort required.
6186
+ *
6187
+ * **Refresh model**
6188
+ * - **No subscription.** One-shot promise.
6189
+ * - **No client cache.** Every call hits the server.
6190
+ * - **No push event** refreshes the response. Re-call manually to
6191
+ * pick up newly-executed runs or `has_unclaimed_prize` flips
6192
+ * after a {@link claimRafflePrize} call.
5268
6193
  *
5269
- * **Example**:
6194
+ * **Idempotency / Side effects**: safe. Read-only.
5270
6195
  *
5271
- * ```javascript
5272
- * _smartico.api.getRaffleDrawRunsHistory({ raffle_id: 156, draw_id: 432 }).then((result) => {
5273
- * console.log(result);
6196
+ * **UI guidance**: see [UI Guide — `getRaffleDrawRunsHistory`](../../docs/ui/raffles/UIGuide_getRaffleDrawRunsHistory.md).
6197
+ *
6198
+ * **Visitor mode**: supported. The same shape is returned with
6199
+ * `is_winner` and `has_unclaimed_prize` always `false` for visitors.
6200
+ *
6201
+ * @param props.raffle_id The parent raffle's `id` (from `TRaffle.id`).
6202
+ * Required.
6203
+ * @param props.draw_id Optional — the draw's schedule_id
6204
+ * (`TRaffleDraw.id`). When set, scopes the
6205
+ * history to that one draw's runs. When
6206
+ * omitted, includes all draws of the raffle.
6207
+ * @returns Promise resolving to a `TRaffleDrawRun[]`
6208
+ * ordered newest-first. Empty if no executed
6209
+ * runs exist.
6210
+ *
6211
+ * @example
6212
+ * ```ts
6213
+ * const raffles = await window._smartico.api.getRaffles();
6214
+ * const raffle = raffles[0];
6215
+ *
6216
+ * // History across all draws of the raffle.
6217
+ * const allHistory = await window._smartico.api.getRaffleDrawRunsHistory({
6218
+ * raffle_id: raffle.id,
5274
6219
  * });
5275
- * ```
5276
6220
  *
5277
- * **Example in the Visitor mode**:
6221
+ * // Highlight rows where the user has an unclaimed prize.
6222
+ * const unclaimed = allHistory.filter(r => r.has_unclaimed_prize);
6223
+ * if (unclaimed.length > 0) {
6224
+ * console.log('[smartico] surface a "Claim" CTA on these', unclaimed.length, 'history rows:', unclaimed.map(r => r.run_id));
6225
+ * }
5278
6226
  *
5279
- * ```javascript
5280
- * _smartico.vapi('EN').getRaffleDrawRunsHistory({ raffle_id: 156, draw_id: 432 }).then((result) => {
5281
- * console.log(result);
6227
+ * // Scoped history of one recurring draw (use draw.id, the schedule_id).
6228
+ * const oneDrawHistory = await window._smartico.api.getRaffleDrawRunsHistory({
6229
+ * raffle_id: raffle.id,
6230
+ * draw_id: raffle.draws[0].id, // schedule_id (stable across recurring runs)
5282
6231
  * });
6232
+ * console.log('[smartico] render history rows for the daily draw — newest first:', oneDrawHistory.length, 'rows');
5283
6233
  * ```
5284
- *
5285
6234
  */
5286
6235
  async getRaffleDrawRunsHistory(props) {
5287
6236
  const res = await this.api.getRaffleDrawRunsHistory(this.userExtId, props);
@@ -5291,25 +6240,113 @@ class WSAPIRaffles extends WSAPIJackpots {
5291
6240
  return drawRunHistoryTransform(res);
5292
6241
  }
5293
6242
  /**
5294
- * Returns `err_code` and `err_message` after the call; `err_code` 0 means the request succeeded.
6243
+ * Claims a raffle prize the user has won. Call this when the user
6244
+ * has a winning row with `should_claim === true` and an unclaimed
6245
+ * `won_id` (read from a `TRafflePrizeWinner` on a
6246
+ * {@link getRaffleDrawRun} result, or surfaced by `has_unclaimed_prize`
6247
+ * on a {@link getRaffleDrawRunsHistory} row that the consumer drills
6248
+ * into).
5295
6249
  *
6250
+ * On success (`errorCode === 0`), the server records the claim and
6251
+ * triggers prize delivery through the operator's integration —
6252
+ * delivery is server-side, not part of this response.
5296
6253
  *
5297
- * **Example**:
6254
+ * @remarks
6255
+ * **Result shape note**: this method returns
6256
+ * `TransformedRaffleClaimPrizeResponse` with `errorCode` /
6257
+ * `errorMessage` (camelCase full-word) — different from most other
6258
+ * SDK result types which use `err_code` / `err_message` (snake_case
6259
+ * short-word). Branch on the camelCase keys when reading this
6260
+ * method's result.
5298
6261
  *
5299
- * ```javascript
5300
- * _smartico.api.claimRafflePrize({won_id:251}).then((result) => {
5301
- * console.log(result);
5302
- * });
5303
- * ```
6262
+ * **Preconditions**
6263
+ * Pass a `won_id` that identifies an unclaimed winning row for the
6264
+ * current user. The `won_id` comes from
6265
+ * `TRafflePrizeWinner.raf_won_id` returned by
6266
+ * {@link getRaffleDrawRun}.
6267
+ *
6268
+ * **Error codes** (in `errorCode`)
6269
+ * - `0` — success; the claim is recorded and prize delivery is
6270
+ * queued server-side.
6271
+ * - `1` — generic claim failure. The `errorMessage` distinguishes
6272
+ * the specific cause (the server uses one error code for several
6273
+ * distinct conditions): the prize has already been claimed, the
6274
+ * `won_id` doesn't match a winning row for this user, or the user
6275
+ * is in a control group for this raffle. Treat `1` as a retryable
6276
+ * error if the message suggests a transient condition; treat as
6277
+ * idempotent success if the message indicates already-claimed
6278
+ * (the underlying state is what the consumer wants either way —
6279
+ * the prize is claimed).
6280
+ * - other non-zero — generic server error. Surface `errorMessage`
6281
+ * if any.
6282
+ *
6283
+ * **Claim window**
6284
+ * There is no server-enforced claim deadline. Won prizes remain
6285
+ * claimable indefinitely until the operator archives them.
6286
+ *
6287
+ * **Idempotency**: NOT idempotent. A second call on the same
6288
+ * `won_id` returns `errorCode === 1` with `errorMessage` indicating
6289
+ * the prize has already been claimed. The SDK does NOT enforce an
6290
+ * in-flight lock. Guard the call site against double-clicks (set
6291
+ * a local "claiming" flag on click, clear it on response).
5304
6292
  *
5305
- * **Example in the Visitor mode**:
6293
+ * **Refresh after success (and after failure)**
6294
+ * The SDK automatically refreshes the raffles cache on every
6295
+ * response — both success and failure paths fire the `onUpdate`
6296
+ * callback registered via {@link getRaffles}. After `errorCode === 0`,
6297
+ * the affected `TRaffleDrawRun.has_unclaimed_prize` (in history)
6298
+ * and the winner row's `claimed_date` reflect the claim on the next
6299
+ * refresh.
6300
+ *
6301
+ * **Side effects** (on `errorCode === 0`)
6302
+ * - The winner row's `claimed_date` is set server-side.
6303
+ * - Prize delivery is queued for the operator's integration to
6304
+ * process. Balance / bonus / inbox updates that result from the
6305
+ * delivery arrive through their own channels — not in this
6306
+ * response.
6307
+ *
6308
+ * **Throws**
6309
+ * `won_id` is required — the SDK throws synchronously when missing
6310
+ * or falsy.
6311
+ *
6312
+ * **UI guidance**: see [UI Guide — `claimRafflePrize`](../../docs/ui/raffles/UIGuide_claimRafflePrize.md).
6313
+ *
6314
+ * **Visitor mode**: not meaningfully supported. The SDK does not
6315
+ * block the call, but visitor sessions have no win history and the
6316
+ * server will reject it.
6317
+ *
6318
+ * @param props.won_id The winning row's `raf_won_id` (from
6319
+ * `TRafflePrizeWinner` returned by
6320
+ * {@link getRaffleDrawRun}).
6321
+ * @returns `{ errorCode, errorMessage? }`; success when
6322
+ * `errorCode === 0`. Note camelCase keys (see "Result
6323
+ * shape note" above).
5306
6324
  *
5307
- * ```javascript
5308
- * _smartico.vapi('EN').claimRafflePrize({ won_id: 251 }).then((result) => {
5309
- * console.log(result);
6325
+ * @example
6326
+ * ```ts
6327
+ * const detail = await window._smartico.api.getRaffleDrawRun({
6328
+ * raffle_id: raffleId,
6329
+ * run_id: runId,
5310
6330
  * });
5311
- * ```
6331
+ * const myWin = detail.prizes.flatMap(p => p.winners).find(w => /* user match here *\/ true);
6332
+ *
6333
+ * if (!myWin || !myWin.raf_won_id || myWin.claimed_date) {
6334
+ * console.log('[smartico] nothing to claim — keep CTA hidden');
6335
+ * return;
6336
+ * }
6337
+ *
6338
+ * console.log('[smartico] claim starting — set in-flight flag, show loading dots on the Claim button, keep the modal open');
6339
+ * const r = await window._smartico.api.claimRafflePrize({ won_id: myWin.raf_won_id });
6340
+ * console.log('[smartico] claim response received — clear in-flight flag');
5312
6341
  *
6342
+ * if (r.errorCode === 0) {
6343
+ * console.log('[smartico] claim succeeded — show a success toast; getRaffles onUpdate above will fire with refreshed state; prize delivery happens server-side');
6344
+ * } else if (r.errorCode === 1 && r.errorMessage?.toLowerCase().includes('already claimed')) {
6345
+ * console.log('[smartico] prize was already claimed (perhaps from another tab) — treat as success, hide the Claim CTA');
6346
+ * } else {
6347
+ * console.error('[smartico] claim failed — surface this error message to the user and allow retry:', r.errorMessage);
6348
+ * }
6349
+ * ```
5313
6350
  */
5314
6351
  async claimRafflePrize(props) {
5315
6352
  if (!props.won_id) {
@@ -5321,9 +6358,104 @@ class WSAPIRaffles extends WSAPIJackpots {
5321
6358
  return raffleClaimPrizeResponseTransform(res);
5322
6359
  }
5323
6360
  /**
5324
- * Requests an opt-in for the specified raffle. Returns the err_code.
6361
+ * Opts the current user into a specific raffle draw run. Required
6362
+ * for draws where `TRaffleDraw.requires_optin === true` — without
6363
+ * opt-in, the user's tickets do NOT participate in that run, even
6364
+ * if they hold tickets for the raffle.
5325
6365
  *
5326
- * **Visitor mode: not supported**
6366
+ * Opt-in is per-run: a recurring draw's next run requires a fresh
6367
+ * opt-in. The user's `TRaffleDraw.user_opted_in` flag reflects the
6368
+ * current state for the current run only.
6369
+ *
6370
+ * @remarks
6371
+ * **Preconditions**
6372
+ * Read the candidate draw from {@link getRaffles}'s embedded
6373
+ * `draws[]` and gate the call on
6374
+ * `requires_optin === true && !user_opted_in && is_active &&
6375
+ * current_state !== Executed`. Calling without these guards may
6376
+ * return a non-zero `err_code`.
6377
+ *
6378
+ * **Argument mapping** — the three IDs come from different fields:
6379
+ * - `raffle_id` — the parent raffle's `TRaffle.id`
6380
+ * - `draw_id` — `TRaffleDraw.id` (schedule_id, stable across runs)
6381
+ * - `raffle_run_id` — `TRaffleDraw.run_id` (instance ID for this
6382
+ * specific run)
6383
+ *
6384
+ * **Error codes** (in `err_code`)
6385
+ * - `0` — success; the user is opted into this run. Tickets
6386
+ * collected after the run's `ticket_start_ts` will participate.
6387
+ * - `1` — generic opt-in failure. The `err_message` distinguishes
6388
+ * the specific cause: the draw doesn't require opt-in
6389
+ * (`requires_optin === false`), `raffle_id` doesn't match the
6390
+ * `draw_id`, the user is already opted in (or the draw has
6391
+ * completed), or the user is in a control group for this raffle.
6392
+ * - other non-zero — generic server error. Surface `err_message`.
6393
+ *
6394
+ * **Idempotency**: NOT idempotent. A second call on the same
6395
+ * `raffle_run_id` returns `err_code === 1` with `err_message`
6396
+ * indicating the user is already opted in. Treat as success in
6397
+ * the UI — the underlying state is what the consumer wants.
6398
+ * Guard the call site against double-clicks.
6399
+ *
6400
+ * **Refresh after success (and after failure)**
6401
+ * The SDK automatically refreshes the raffles cache on every
6402
+ * response and fires the `onUpdate` callback registered via
6403
+ * {@link getRaffles}. After `err_code === 0`, the affected draw's
6404
+ * `user_opted_in` flips to `true` on the refreshed list.
6405
+ *
6406
+ * **Side effects** (on `err_code === 0`)
6407
+ * - The user is registered for this run. Tickets earned within
6408
+ * the run's eligibility window will participate in the draw.
6409
+ * - No balance change. No CRM-side rewards. Opt-in is a metadata
6410
+ * operation only.
6411
+ *
6412
+ * **Throws**
6413
+ * `raffle_id`, `draw_id`, and `raffle_run_id` are all required —
6414
+ * the SDK throws synchronously when any is missing or falsy.
6415
+ *
6416
+ * **UI guidance**: see [UI Guide — `requestRaffleOptin`](../../docs/ui/raffles/UIGuide_requestRaffleOptin.md).
6417
+ *
6418
+ * **Visitor mode**: not supported.
6419
+ *
6420
+ * @param props.raffle_id The parent raffle's `id`.
6421
+ * @param props.draw_id The draw's schedule_id (`TRaffleDraw.id`).
6422
+ * @param props.raffle_run_id The run instance ID (`TRaffleDraw.run_id`).
6423
+ * @returns `{ err_code, err_message? }`; success
6424
+ * when `err_code === 0` (treat
6425
+ * "already opted in" as idempotent
6426
+ * success).
6427
+ *
6428
+ * @example
6429
+ * ```ts
6430
+ * const raffles = await window._smartico.api.getRaffles({
6431
+ * onUpdate: (refreshed) => console.log('[smartico] raffles refreshed — re-render', refreshed),
6432
+ * });
6433
+ * const raffle = raffles[0];
6434
+ * const draw = raffle.draws.find(d =>
6435
+ * d.requires_optin && !d.user_opted_in && d.is_active && d.current_state !== 3
6436
+ * );
6437
+ *
6438
+ * if (!draw) {
6439
+ * console.log('[smartico] no opt-in-required draw available — keep CTA hidden');
6440
+ * return;
6441
+ * }
6442
+ *
6443
+ * console.log('[smartico] opt-in starting — set in-flight flag, show loading dots on the Opt-in button');
6444
+ * const r = await window._smartico.api.requestRaffleOptin({
6445
+ * raffle_id: raffle.id,
6446
+ * draw_id: draw.id, // schedule_id, NOT run_id
6447
+ * raffle_run_id: draw.run_id,
6448
+ * });
6449
+ * console.log('[smartico] opt-in response received — clear in-flight flag');
6450
+ *
6451
+ * if (r.err_code === 0) {
6452
+ * console.log('[smartico] opted in successfully — show "Fully opted in" state on the draw card; onUpdate above will fire with user_opted_in: true');
6453
+ * } else if (r.err_code === 1 && r.err_message?.toLowerCase().includes('already opted in')) {
6454
+ * console.log('[smartico] already opted in (perhaps from another tab) — treat as success, show "Fully opted in"');
6455
+ * } else {
6456
+ * console.error('[smartico] opt-in failed — surface this error to the user:', r.err_message);
6457
+ * }
6458
+ * ```
5327
6459
  */
5328
6460
  async requestRaffleOptin(props) {
5329
6461
  if (!props.raffle_id) {
@@ -5341,29 +6473,233 @@ class WSAPIRaffles extends WSAPIJackpots {
5341
6473
  err_message: r.errMsg
5342
6474
  };
5343
6475
  }
6476
+ /**
6477
+ * Returns every prize the current user has won within a single raffle —
6478
+ * across ALL of that raffle's draws, newest-won first — in one paginated
6479
+ * call. Use this to power a "my prizes" screen for a raffle (prize name,
6480
+ * prize image, the user's name/avatar) without walking
6481
+ * {@link getRaffleDrawRunsHistory} and then paging
6482
+ * {@link getRaffleDrawRun}'s per-draw winner lists.
6483
+ *
6484
+ * Each row carries its own `raf_won_id`, which IS the `won_id` to pass to
6485
+ * {@link claimRafflePrize}: a row with `requires_claim === true` and no
6486
+ * `claimed_date` is directly claimable.
6487
+ *
6488
+ * @remarks
6489
+ * **Authentication required**
6490
+ * Works only for an identified (logged-in) user. Visitor / anonymous
6491
+ * sessions are rejected — call this only after identify.
6492
+ *
6493
+ * **Preconditions**
6494
+ * `raffle_id` is required — the SDK throws synchronously when it is
6495
+ * missing or falsy.
6496
+ *
6497
+ * **Coverage & sort order**
6498
+ * Includes the user's wins from every draw of the raffle — recurring,
6499
+ * one-shot, and grand draws, across all historical runs. Rows are ordered
6500
+ * newest-win first; there is no "unclaimed first" ordering, so sort
6501
+ * client-side if you want claimable prizes at the top.
6502
+ *
6503
+ * **Pagination**
6504
+ * `offset` / `limit` page the `won_prizes[]` rows (the SDK defaults to
6505
+ * `0` / `20`). `total` is the authoritative full count of the user's wins
6506
+ * for this raffle across all draws — drive "load more" from it
6507
+ * (`offset + won_prizes.length < total`). An `offset` past the end returns
6508
+ * an empty `won_prizes[]` with the real `total` and `errCode 0` — not an
6509
+ * error. The server does NOT clamp `limit`, so always pass an explicit,
6510
+ * sane page size.
6511
+ *
6512
+ * **Rate limit**
6513
+ * The server caps this at roughly 30 calls per minute with a ~5-second
6514
+ * minimum gap between calls. Fetch on screen open and on explicit "load
6515
+ * more" — don't poll it on a timer.
6516
+ *
6517
+ * **Error codes** (in `errCode`)
6518
+ * - `0` — success. Also returned with an empty `won_prizes[]` and
6519
+ * `total 0` when the user has no wins, or is not eligible to see this
6520
+ * raffle.
6521
+ * - `1` — generic server error; surface `errMsg` if present.
6522
+ *
6523
+ * There are no granular codes — an unknown raffle, an ineligible user,
6524
+ * and "no wins" all surface as `errCode 0` with an empty list.
6525
+ *
6526
+ * **Reading the result**
6527
+ * - Null-check `user` before reading it — it is `null` whenever
6528
+ * `won_prizes` is empty.
6529
+ * - For the avatar, use `user.avatar_id` (already a full URL for a system
6530
+ * avatar, otherwise an avatar token to resolve against the widget's
6531
+ * avatar domain); `user.avatar_url` is always `null`.
6532
+ * - Render `public_username` as-is (it is server-masked for privacy, e.g.
6533
+ * `"32:r*****"`) and substitute a "You" label for the current user.
6534
+ * - Treat `claimed_date` as the claim flag: `null` until claimed, then
6535
+ * epoch ms.
6536
+ *
6537
+ * **Idempotency / Side effects**: safe and read-only — one-shot promise,
6538
+ * no client cache, no subscription. The server caches the response
6539
+ * briefly; a successful {@link claimRafflePrize} invalidates that cache,
6540
+ * so a follow-up call reflects the new `claimed_date`. This method does
6541
+ * NOT refresh the {@link getRaffles} list or fire its `onUpdate` — re-call
6542
+ * manually to pick up newly-won prizes or a `claimed_date` flip.
6543
+ *
6544
+ * **UI guidance**: see [UI Guide — `getRaffleWonPrizes`](../../docs/ui/raffles/UIGuide_getRaffleWonPrizes.md).
6545
+ *
6546
+ * **Visitor mode**: not supported (see "Authentication required").
6547
+ *
6548
+ * @param props.raffle_id The parent raffle's `id` (from `TRaffle.id`). Required.
6549
+ * @param props.offset Zero-based index of the first row to return. Defaults to `0`.
6550
+ * @param props.limit Page size. Defaults to `20`.
6551
+ * @returns Promise resolving to {@link GetRaffleWonPrizesResponse}
6552
+ * (`user`, this page of `won_prizes`, and `total`;
6553
+ * `errCode 0` on success).
6554
+ *
6555
+ * @example
6556
+ * ```ts
6557
+ * const raffles = await window._smartico.api.getRaffles();
6558
+ * const raffle = raffles[0];
6559
+ *
6560
+ * // First page of the user's won prizes for this raffle.
6561
+ * const page = await window._smartico.api.getRaffleWonPrizes({
6562
+ * raffle_id: raffle.id,
6563
+ * offset: 0,
6564
+ * limit: 20,
6565
+ * });
6566
+ *
6567
+ * if (page.errCode !== 0) {
6568
+ * console.error('[smartico] could not load won prizes — show a retry state:', page.errMsg);
6569
+ * return;
6570
+ * }
6571
+ * if (page.won_prizes.length === 0) {
6572
+ * console.log('[smartico] no wins in this raffle (or not eligible) — render the empty state');
6573
+ * return;
6574
+ * }
6575
+ *
6576
+ * console.log('[smartico]', page.user?.public_username, 'won', page.total, 'prizes total');
6577
+ * for (const prize of page.won_prizes) {
6578
+ * console.log('[smartico] render prize card —', prize.public_meta.name, prize.public_meta.image_url);
6579
+ * if (prize.requires_claim && !prize.claimed_date) {
6580
+ * console.log('[smartico] show a Claim CTA — on click call claimRafflePrize({ won_id:', prize.raf_won_id, '})');
6581
+ * }
6582
+ * }
6583
+ *
6584
+ * // Load more.
6585
+ * if (page.offset + page.won_prizes.length < page.total) {
6586
+ * const next = await window._smartico.api.getRaffleWonPrizes({
6587
+ * raffle_id: raffle.id,
6588
+ * offset: page.offset + page.limit,
6589
+ * limit: 20,
6590
+ * });
6591
+ * console.log('[smartico] appended', next.won_prizes.length, 'more prizes');
6592
+ * }
6593
+ * ```
6594
+ */
6595
+ async getRaffleWonPrizes(props) {
6596
+ var _props$offset, _props$limit;
6597
+ if (!props.raffle_id) {
6598
+ throw new Error('raffle_id is required');
6599
+ }
6600
+ return await this.api.getRaffleWonPrizes(this.userExtId, {
6601
+ raffle_id: props.raffle_id,
6602
+ offset: (_props$offset = props.offset) != null ? _props$offset : 0,
6603
+ limit: (_props$limit = props.limit) != null ? _props$limit : 20
6604
+ });
6605
+ }
5344
6606
  }
5345
6607
 
5346
6608
  /** @group MiniGames */
5347
6609
  class WSAPIMiniGames extends WSAPIRaffles {
5348
6610
  /**
5349
- * Returns the list of mini-games configured for the current user (not filtered by spin availability or Widget visibility).
5350
- * The returned list of mini-games is cached for 30 seconds. But you can pass the onUpdate callback as a parameter. Note that each time you call getMiniGames with a new onUpdate callback, the old one will be overwritten by the new one.
5351
- * The onUpdate callback will be called on available spin count change, if mini-game has increasing jackpot per spin or won prize is spin/jackpot and if max count of the available user spins equals one, also if the spins were issued to the user manually in the BO. Updated templates will be passed to onUpdate callback.
6611
+ * Returns all mini-game templates ("SAW" = Spin And Win — the
6612
+ * umbrella term for wheel-spin, scratch-card, lootbox, gift-box,
6613
+ * treasure-hunt, plinko, coin-flip, quiz, and several other formats)
6614
+ * configured for the label. Optionally subscribes to live updates
6615
+ * via `onUpdate`: the callback fires whenever the user's
6616
+ * `spin_count` changes, jackpot grows, a manual spin is issued, or
6617
+ * a spin response lands.
6618
+ *
6619
+ * The list is NOT filtered by spin availability — every configured
6620
+ * template is returned, including ones the user cannot currently
6621
+ * play. The `visibile_when_can_spin` flag on each template hints
6622
+ * which to hide in a default lobby view (consumer-side filter).
5352
6623
  *
5353
- * **Example**:
5354
- * ```
5355
- * _smartico.api.getMiniGames().then((result) => {
5356
- * console.log(result);
5357
- * });
5358
- * ```
6624
+ * @remarks
6625
+ * **Subscription model (`onUpdate`)**
6626
+ * The callback receives the FULL refreshed template list (never a
6627
+ * diff/patch). Each subsequent call to `getMiniGames({ onUpdate })`
6628
+ * REPLACES the prior callback. Pass `onUpdate: undefined` (or omit
6629
+ * it) to keep the prior callback in place; the callback is never
6630
+ * auto-cleared.
5359
6631
  *
5360
- * **Example in the Visitor mode**:
5361
- * ```
5362
- * _smartico.vapi('EN').getMiniGames().then((result) => {
5363
- * console.log(result);
6632
+ * **Update triggers** — the callback fires when:
6633
+ *
6634
+ * 1. The server pushes a `spin_count` change (campaign award,
6635
+ * store purchase, BO manual issuance, mission reward).
6636
+ * 2. Any {@link playMiniGame} or {@link playMiniGameBatch}
6637
+ * resolves on this connection — the cached array refreshes
6638
+ * with updated `spin_count`, `jackpot_current`, and any new
6639
+ * `next_available_spin_ts`.
6640
+ * 3. Acknowledge responses land (via auto-acknowledge or
6641
+ * {@link miniGameWinAcknowledgeRequest}).
6642
+ *
6643
+ * Jackpot growth is observable on the refreshed `jackpot_current`
6644
+ * field — the SDK inlines the live value into template `name` /
6645
+ * `promo_text` / prize `name` via a `{{jackpot}}` template
6646
+ * substitution at fetch time.
6647
+ *
6648
+ * **Game-type variants**
6649
+ * All twelve `SAWGameType` values (`SpinAWheel`, `ScratchCard`,
6650
+ * `MatchX`, `GiftBox`, `PrizeDrop`, `Quiz`, `LootboxWeekdays`,
6651
+ * `LootboxCalendarDays`, `TreasureHunt`, `Voyager`, `Plinko`,
6652
+ * `CoinFlip`) surface through the same template shape. Most are
6653
+ * played via {@link playMiniGame}; the exceptions are:
6654
+ * - `PrizeDrop` — server-push only; the consumer does NOT call
6655
+ * `playMiniGame`. Prizes arrive via the prize-drop push channel.
6656
+ * - `MatchX` / `Quiz` — predictions are submitted via a separate
6657
+ * games server (not this SDK); the SAW spin is fired
6658
+ * server-internally to deduct the buy-in.
6659
+ *
6660
+ * **Cache TTL**: the SDK caches the response for 30 seconds. Cache
6661
+ * is fully cleared on login / logout.
6662
+ *
6663
+ * **Idempotency / Side effects**: safe. Read-only.
6664
+ *
6665
+ * **UI guidance**: see [UI Guide — `getMiniGames`](../../docs/ui/minigames/UIGuide_getMiniGames.md).
6666
+ *
6667
+ * **Visitor mode**: supported. Only templates configured with
6668
+ * `is_visitor_mode = true` in the BO are returned for anonymous
6669
+ * sessions. Spins from these templates may also be played (visitor
6670
+ * mode is the one mini-game flow that does support play — see
6671
+ * {@link playMiniGame} for the visitor-stop semantics).
6672
+ *
6673
+ * @param params Optional. Omit to fetch without subscribing.
6674
+ * @param params.onUpdate Callback invoked with the full refreshed
6675
+ * template array after any spin-count
6676
+ * change, spin response, or acknowledge
6677
+ * response on this connection.
6678
+ * @returns Promise resolving to the template
6679
+ * array. Empty if no templates are
6680
+ * visible to the user.
6681
+ *
6682
+ * @example
6683
+ * ```ts
6684
+ * const games = await window._smartico.api.getMiniGames({
6685
+ * onUpdate: (refreshed) => {
6686
+ * console.log('[smartico] mini-game templates refreshed — re-render lobby from this array:', refreshed);
6687
+ * },
5364
6688
  * });
5365
- * ```
5366
6689
  *
6690
+ * // Filter the lobby view per the visibility flag.
6691
+ * const visible = games.filter(g =>
6692
+ * !g.visibile_when_can_spin || (g.spin_count && g.spin_count > 0)
6693
+ * );
6694
+ *
6695
+ * for (const g of visible) {
6696
+ * console.log('[smartico] render game card', g.id, '—', g.name,
6697
+ * '— type:', g.saw_game_type,
6698
+ * '— buy-in:', g.saw_buyin_type,
6699
+ * '— spins available:', g.spin_count ?? 0,
6700
+ * '— jackpot:', g.jackpot_current, g.jackpot_symbol);
6701
+ * }
6702
+ * ```
5367
6703
  */
5368
6704
  async getMiniGames({
5369
6705
  onUpdate
@@ -5374,19 +6710,73 @@ class WSAPIMiniGames extends WSAPIRaffles {
5374
6710
  return OCache.use(onUpdateContextKey.Saw, ECacheContext.WSAPI, () => this.api.sawGetTemplatesT(this.userExtId), CACHE_DATA_SEC);
5375
6711
  }
5376
6712
  /**
5377
- * Returns the list of mini-games based on the provided parameters. "Limit" and "offset" indicate the range of items to be fetched.
5378
- * The maximum number of items per request is limited to 20.
5379
- * You can leave this params empty and by default it will return list of mini-games ranging from 0 to 20.
5380
- * The returned list of mini-games history is cached for 30 seconds.
6713
+ * Returns a paginated, newest-first list of the user's past
6714
+ * mini-game spins — each row carries the won prize ID, the
6715
+ * client-side `request_id` used for the spin, and a
6716
+ * server-recorded `is_claimed` flag (`true` if the spin has been
6717
+ * acknowledged). Optionally filter to a single template via
6718
+ * `saw_template_id`.
6719
+ *
6720
+ * Use this to power a "My prizes" / win-history surface, or to
6721
+ * recover unacknowledged spins (rows with `is_claimed === false`
6722
+ * carry a `client_request_id` you can pass to
6723
+ * {@link miniGameWinAcknowledgeRequest}).
5381
6724
  *
5382
- * **Example**:
5383
- * ```
5384
- * _smartico.api.getMiniGamesHistory().then((result) => {
5385
- * console.log(result);
5386
- * });
5387
- * ```
6725
+ * @remarks
6726
+ * **Pagination**
6727
+ * `limit` defaults to 20, `offset` defaults to 0. Sort order is
6728
+ * `create_date` DESC (newest first) — no client-side re-sort
6729
+ * required. For "load more" pagination, advance `offset` by the
6730
+ * page size on each subsequent call.
6731
+ *
6732
+ * The underlying protocol carries a `hasMore` boolean on the
6733
+ * response, but the SDK strips it from the public surface —
6734
+ * detect end of list when the returned array length is less than
6735
+ * `limit`.
6736
+ *
6737
+ * **`is_claimed` semantics**
6738
+ * Maps directly to the server's "acknowledge_date is non-null"
6739
+ * state. A spin where the auto-acknowledge fire-and-forget
6740
+ * succeeded shows `is_claimed: true`; a spin where the
6741
+ * acknowledge was lost (network drop) or where the user is on an
6742
+ * explicit-acknowledge flow shows `is_claimed: false` with a
6743
+ * usable `client_request_id`. A server-side fallback job
6744
+ * auto-acknowledges stale rows every ~60 seconds — so even
6745
+ * "lost" prizes are eventually delivered without consumer action.
6746
+ *
6747
+ * **Cache TTL**: the SDK caches the response for 30 seconds.
6748
+ * Cache is invalidated implicitly when a new spin or acknowledge
6749
+ * response lands.
6750
+ *
6751
+ * **Idempotency / Side effects**: safe. Read-only.
6752
+ *
6753
+ * **UI guidance**: see [UI Guide — `getMiniGamesHistory`](../../docs/ui/minigames/UIGuide_getMiniGamesHistory.md).
5388
6754
  *
5389
- * **Visitor mode: not supported**
6755
+ * **Visitor mode**: not supported.
6756
+ *
6757
+ * @param params Optional pagination + filter bag.
6758
+ * @param params.limit Page size. Defaults to 20.
6759
+ * @param params.offset Number of rows to skip. Defaults to 0.
6760
+ * @param params.saw_template_id When set, scopes the history to
6761
+ * a single template's spins.
6762
+ *
6763
+ * @returns Promise resolving to `TSawHistory[]` in newest-first
6764
+ * order. Empty when the user has no history.
6765
+ *
6766
+ * @example
6767
+ * ```ts
6768
+ * const history = await window._smartico.api.getMiniGamesHistory({ limit: 20 });
6769
+ *
6770
+ * // Show unacknowledged spins with a Claim CTA.
6771
+ * const unacknowledged = history.filter(h => !h.is_claimed);
6772
+ * console.log('[smartico] surface a "Claim" CTA on these', unacknowledged.length, 'history rows:',
6773
+ * unacknowledged.map(h => h.client_request_id));
6774
+ *
6775
+ * // Load-more pagination — advance offset by the prior page size.
6776
+ * const page2 = await window._smartico.api.getMiniGamesHistory({ limit: 20, offset: 20 });
6777
+ * console.log('[smartico] page 2 loaded —', page2.length, 'more rows;',
6778
+ * page2.length < 20 ? 'end of list reached, hide "Load more"' : 'keep "Load more" visible');
6779
+ * ```
5390
6780
  */
5391
6781
  async getMiniGamesHistory({
5392
6782
  limit,
@@ -5396,18 +6786,164 @@ class WSAPIMiniGames extends WSAPIRaffles {
5396
6786
  return OCache.use(onUpdateContextKey.SAWHistory, ECacheContext.WSAPI, () => this.api.getSawWinningHistoryT(this.userExtId, limit, offset, saw_template_id), CACHE_DATA_SEC);
5397
6787
  }
5398
6788
  /**
5399
- * Plays the specified by template_id mini-game on behalf of user and returns prize_id or err_code
5400
- * After playMiniGame is called, you can call getMiniGames to get the list of mini-games.The returned list of mini-games is cached for 30 seconds. But you can pass the onUpdate callback as a parameter. Note that each time you call playMiniGame with a new onUpdate callback, the old one will be overwritten by the new one.
5401
- * The onUpdate callback will be called on available spin count change, if mini-game has increasing jackpot per spin or won prize is spin/jackpot and if max count of the available user spins equals one, also if the spins were issued to the user manually in the BO. Updated templates will be passed to onUpdate callback.
6789
+ * Plays one round of a mini-game template — runs the server's
6790
+ * randomised prize selection, deducts the buy-in cost (if any),
6791
+ * and returns the won `prize_id`. After the play resolves, the SDK
6792
+ * automatically fires a server-side acknowledgement on a
6793
+ * fire-and-forget basis, marking the spin as "delivered" so the
6794
+ * prize takes effect.
6795
+ *
6796
+ * Works for all `SAWGameType` values EXCEPT:
6797
+ * - `PrizeDrop` — prizes arrive server-pushed; do NOT call
6798
+ * `playMiniGame` for this type.
6799
+ * - `MatchX` / `Quiz` — prediction submission goes through a
6800
+ * separate games server; `playMiniGame` is not the entry point.
5402
6801
  *
5403
- * **Example**:
5404
- * ```
5405
- * _smartico.api.playMiniGame(55).then((result) => {
5406
- * console.log(result);
6802
+ * @remarks
6803
+ * **Preconditions**
6804
+ * Read the candidate template from {@link getMiniGames} and check:
6805
+ * - `spin_count > 0` for spin-based templates
6806
+ * (`saw_buyin_type === 'spins'`).
6807
+ * - Sufficient balance for paid templates — points / gems /
6808
+ * diamonds from {@link getUserProfile} against
6809
+ * `buyin_cost_points` / `_gems` / `_diamonds`.
6810
+ * - `next_available_spin_ts` is in the past (or unset) — the
6811
+ * server enforces a per-period max-attempts cap.
6812
+ * - Template is currently in its active period
6813
+ * (operator-configured `activeFromDate` / `activeTillDate`).
6814
+ *
6815
+ * **Error codes** (in `err_code`, typed as {@link SAWSpinErrorCode})
6816
+ * - `0` (`SAW_OK`) — success; `prize_id` identifies the won prize
6817
+ * in `template.prizes`.
6818
+ * - `40001` (`SAW_NO_SPINS`) — user has no spin attempts for a
6819
+ * spin-based template.
6820
+ * - `40002` (`SAW_PRIZE_POOL_EMPTY`) — all prize slots in the
6821
+ * template are depleted.
6822
+ * - `40003` (`SAW_NOT_ENOUGH_POINTS`) — insufficient points for a
6823
+ * points-cost template.
6824
+ * - `40004` (`SAW_FAILED_MAX_SPINS_REACHED`) — per-period
6825
+ * max-attempts cap reached. The server's
6826
+ * `first_spin_in_period` value (exposed in
6827
+ * {@link TMiniGamePlayBatchResult}; not surfaced in the single
6828
+ * `TMiniGamePlayResult`) marks the period start.
6829
+ * - `40007` (`SAW_TEMPLATE_NOT_ACTIVE`) — template outside its
6830
+ * active time window.
6831
+ * - `40009` (`SAW_NOT_IN_SEGMENT`) — user fails the template's
6832
+ * visibility segment check, OR (for lootbox variants) the day's
6833
+ * prize pool is empty.
6834
+ * - `40011` (`SAW_NO_BALANCE_GEMS`) — insufficient gems.
6835
+ * - `40012` (`SAW_NO_BALANCE_DIAMONDS`) — insufficient diamonds.
6836
+ * - `-40001` (`SAW_VISITOR_STOP_SPIN_REQUEST`) — visitor session
6837
+ * tried to play a non-visitor-mode template. The default UI
6838
+ * silently stops the game; no prize awarded.
6839
+ * - other non-zero — generic server error. Surface `err_message`.
6840
+ *
6841
+ * **Prize handling**
6842
+ * On `err_code === 0`, `prize_id` matches an entry in
6843
+ * `template.prizes`. Look up the prize's `prize_type`
6844
+ * ({@link MiniGamePrizeTypeName}) to decide UI treatment:
6845
+ * - `'no-prize'` — the user spun but won nothing (an operator-
6846
+ * configured "loss" slot). Buy-in is still deducted.
6847
+ * - `'points'` / `'gems-and-diamonds'` / `'spin'` — value
6848
+ * credited to the user's profile / spin balance; visible on
6849
+ * the next refresh.
6850
+ * - `'bonus'` — surfaces via {@link getBonuses}.
6851
+ * - `'jackpot'` — drains the template's `jackpot_current` to the
6852
+ * user; resets the accumulator.
6853
+ * - `'raffle-ticket'` — adds tickets to the relevant raffle.
6854
+ * - `'mission'` / `'change-level'` — visible via the
6855
+ * corresponding domain methods.
6856
+ * - `'manual'` — operator delivers offline.
6857
+ *
6858
+ * **Auto-acknowledge**
6859
+ * The SDK calls the server's acknowledge endpoint immediately
6860
+ * after the spin response, on a fire-and-forget basis (not
6861
+ * awaited). This marks the spin as "delivered" so prize effects
6862
+ * take hold. If the auto-acknowledge fails (network drop), the
6863
+ * spin appears as `is_claimed: false` in
6864
+ * {@link getMiniGamesHistory}; the consumer can recover it by
6865
+ * passing the `client_request_id` to
6866
+ * {@link miniGameWinAcknowledgeRequest}. A server-side fallback
6867
+ * job auto-acknowledges stale spins every ~60 seconds, so prizes
6868
+ * are eventually delivered even without consumer action.
6869
+ *
6870
+ * **Idempotency**: NOT idempotent. A double-click sends two
6871
+ * spins and deducts the buy-in twice. The SDK does NOT guard
6872
+ * against rapid clicks at the public API level — guard the call
6873
+ * site with an in-flight flag. The server enforces a per-user
6874
+ * per-template lock that serialises concurrent requests, so two
6875
+ * simultaneous calls won't be processed in parallel, but they
6876
+ * will both be processed sequentially (i.e. both deduct).
6877
+ *
6878
+ * **Refresh after success (and after failure)**
6879
+ * The SDK automatically refreshes the templates cache on every
6880
+ * spin response and fires any `onUpdate` callback registered via
6881
+ * {@link getMiniGames} or this method. After `err_code === 0`, the
6882
+ * affected template's `spin_count` / `jackpot_current` /
6883
+ * `next_available_spin_ts` reflect the new state on the
6884
+ * refreshed array.
6885
+ *
6886
+ * **Side effects** (on `err_code === 0`)
6887
+ * - Buy-in deducted from the user's balance (points / gems /
6888
+ * diamonds / spin tickets — depending on `saw_buyin_type`).
6889
+ * Balance updates flow via the user-properties channel
6890
+ * (subscribe to {@link getUserProfile} `props_change` to
6891
+ * observe).
6892
+ * - Prize value credited per the prize's type (see "Prize
6893
+ * handling" above).
6894
+ * - A `minigame_attempt` analytics event fires server-side with
6895
+ * the result status.
6896
+ *
6897
+ * **UI guidance**: see [UI Guide — `playMiniGame`](../../docs/ui/minigames/UIGuide_playMiniGame.md).
6898
+ *
6899
+ * **Visitor mode**: not supported. Visitor sessions trying to
6900
+ * spin receive `SAW_VISITOR_STOP_SPIN_REQUEST (-40001)`.
6901
+ *
6902
+ * @param template_id The mini-game template ID (from
6903
+ * `TMiniGameTemplate.id`).
6904
+ * @param params Optional. Pass an `onUpdate` callback to
6905
+ * subscribe to subsequent template refreshes.
6906
+ * @returns `{ err_code, err_message, prize_id }` — success when
6907
+ * `err_code === 0`. `prize_id` is always populated; look
6908
+ * it up in `template.prizes` to interpret the prize.
6909
+ *
6910
+ * @example
6911
+ * ```ts
6912
+ * const games = await window._smartico.api.getMiniGames({
6913
+ * onUpdate: (refreshed) => console.log('[smartico] templates refreshed — re-render lobby', refreshed),
5407
6914
  * });
5408
- * ```
6915
+ * const game = games.find(g => g.id === templateId);
5409
6916
  *
5410
- * **Visitor mode: not supported**
6917
+ * if (!game) {
6918
+ * console.log('[smartico] template not in current list — refresh getMiniGames');
6919
+ * return;
6920
+ * }
6921
+ * if (game.saw_buyin_type === 'spins' && (game.spin_count ?? 0) === 0) {
6922
+ * console.log('[smartico] no spins available — disable Play button, show "No spins" message');
6923
+ * return;
6924
+ * }
6925
+ *
6926
+ * console.log('[smartico] play starting — set in-flight flag, start game animation (wheel spin / scratch / lootbox open / etc.)');
6927
+ * const r = await window._smartico.api.playMiniGame(game.id);
6928
+ * console.log('[smartico] play response received');
6929
+ *
6930
+ * if (r.err_code === 0) {
6931
+ * const prize = game.prizes.find(p => p.id === r.prize_id);
6932
+ * if (prize?.prize_type === 'no-prize') {
6933
+ * console.log('[smartico] user lost — animate to the no-prize slot and show "Better luck next time" modal');
6934
+ * } else {
6935
+ * console.log('[smartico] user won — animate to prize', prize?.name,
6936
+ * '— show acknowledge modal per template.acknowledge_type;',
6937
+ * 'getMiniGames onUpdate fires shortly with refreshed spin_count / jackpot');
6938
+ * }
6939
+ * } else if (r.err_code === 40004) {
6940
+ * console.error('[smartico] max spins reached — show countdown to next available spin (use playMiniGameBatch for first_spin_in_period if needed)');
6941
+ * } else if (r.err_code === -40001) {
6942
+ * console.log('[smartico] visitor stopped — silently end the game, no prize modal');
6943
+ * } else {
6944
+ * console.error('[smartico] play failed — show generic error with this message:', r.err_message);
6945
+ * }
6946
+ * ```
5411
6947
  */
5412
6948
  async playMiniGame(template_id, {
5413
6949
  onUpdate
@@ -5425,29 +6961,171 @@ class WSAPIMiniGames extends WSAPIRaffles {
5425
6961
  return o;
5426
6962
  }
5427
6963
  /**
5428
- * Sends the acknowledge request with specific client_request_id from minigame history in order to claim prize
5429
- * **Example**:
5430
- * ```
5431
- * _smartico.api.miniGameWinAcknowledgeRequest('2a189322-31bb-4119-b943-bx7868ff8dc3').then((result) => {
5432
- * console.log(result);
5433
- * });
6964
+ * Manually acknowledges a mini-game spin — marks the spin as
6965
+ * "delivered" so the prize takes effect server-side. Most consumers
6966
+ * do NOT need to call this method directly; {@link playMiniGame}
6967
+ * and {@link playMiniGameBatch} auto-acknowledge on success. Use
6968
+ * this only for recovery scenarios.
6969
+ *
6970
+ * @remarks
6971
+ * **When to call**
6972
+ * - **Lost auto-acknowledge** — when the WebSocket dropped between
6973
+ * the spin response and the auto-acknowledge fire-and-forget,
6974
+ * the spin shows `is_claimed: false` in
6975
+ * {@link getMiniGamesHistory}. Pass that row's
6976
+ * `client_request_id` here to deliver the prize.
6977
+ * - **Explicit-acknowledge UI** — for templates configured with
6978
+ * the `ExplicitAcknowledge` acknowledge type (operator
6979
+ * decision), the consumer's UI shows a "Claim" CTA after the
6980
+ * prize animation. Click handler calls this method with the
6981
+ * spin's `client_request_id` rather than auto-acknowledging.
6982
+ *
6983
+ * **No-op on already-acknowledged spins**
6984
+ * The server's acknowledge SQL matches on `acknowledge_date IS
6985
+ * NULL` — a duplicate call returns successfully with no effect.
6986
+ *
6987
+ * **Server-side fallback**
6988
+ * Even without ever calling this method, a server-side job
6989
+ * auto-acknowledges stale spins every ~60 seconds — so prizes are
6990
+ * eventually delivered. The `is_claimed` flag flips on the next
6991
+ * `getMiniGamesHistory` call after the job runs.
6992
+ *
6993
+ * **Idempotency**: safe. Repeated calls have no effect after the
6994
+ * first.
6995
+ *
6996
+ * **Side effects** (on first successful call for an unacknowledged
6997
+ * spin)
6998
+ * - Prize value credited per the prize's type (see
6999
+ * {@link playMiniGame} "Prize handling").
7000
+ * - The spin's `is_claimed` flag flips to `true` on the next
7001
+ * {@link getMiniGamesHistory} call.
7002
+ *
7003
+ * **Visitor mode**: not supported.
7004
+ *
7005
+ * @param request_id The `client_request_id` from a `TSawHistory`
7006
+ * row returned by {@link getMiniGamesHistory}.
7007
+ *
7008
+ * @example
7009
+ * ```ts
7010
+ * const history = await window._smartico.api.getMiniGamesHistory({ limit: 20 });
7011
+ * const unacknowledged = history.filter(h => !h.is_claimed);
7012
+ *
7013
+ * for (const row of unacknowledged) {
7014
+ * console.log('[smartico] re-acknowledging stale spin', row.client_request_id);
7015
+ * await window._smartico.api.miniGameWinAcknowledgeRequest(row.client_request_id);
7016
+ * }
7017
+ *
7018
+ * // Re-fetch history to see the updated is_claimed flags.
7019
+ * const fresh = await window._smartico.api.getMiniGamesHistory({ limit: 20 });
7020
+ * console.log('[smartico] history after recovery —', fresh.filter(h => !h.is_claimed).length, 'still unacknowledged');
5434
7021
  * ```
5435
7022
  */
5436
7023
  async miniGameWinAcknowledgeRequest(request_id) {
5437
7024
  return this.api.doAcknowledgeRequest(this.userExtId, request_id);
5438
7025
  }
5439
7026
  /**
5440
- * Plays the specified by template_id mini-game on behalf of user spin_count times and returns array of the prizes
5441
- * After playMiniGameBatch is called, you can call getMiniGames to get the list of mini-games. The returned list of mini-games is cached for 30 seconds. But you can pass the onUpdate callback as a parameter. Note that each time you call playMiniGameBatch with a new onUpdate callback, the old one will be overwritten by the new one.
5442
- * The onUpdate callback will be called on available spin count change, if mini-game has increasing jackpot per spin or won prize is spin/jackpot and if max count of the available user spins equals one, also if the spins were issued to the user manually in the BO. Updated templates will be passed to onUpdate callback.
7027
+ * Plays a mini-game template `spin_count` times in one round-trip.
7028
+ * Returns an array of per-spin results — each independent, each
7029
+ * with its own error code. Like {@link playMiniGame}, the SDK
7030
+ * auto-acknowledges every result on a fire-and-forget basis.
5443
7031
  *
5444
- * **Example**:
5445
- * ```
5446
- * _smartico.api.playMiniGameBatch(55, 10).then((result) => {
5447
- * console.log(result);
5448
- * });
7032
+ * Use this when a UI offers "spin N times" affordances
7033
+ * (multi-spin buttons, lootbox open-N flows). The server processes
7034
+ * each spin independently — there is no atomicity / rollback if
7035
+ * one fails.
7036
+ *
7037
+ * @remarks
7038
+ * **Result shape note** — `TMiniGamePlayBatchResult` uses
7039
+ * `errCode` / `errMessage` (camelCase) — DIFFERENT from
7040
+ * {@link TMiniGamePlayResult} which uses `err_code` / `err_message`
7041
+ * (snake_case). Branch on the camelCase keys when reading batch
7042
+ * results.
7043
+ *
7044
+ * **Per-spin independence**
7045
+ * The server iterates the requested spins and calls the prize
7046
+ * engine once per entry. If spin #2 fails with `SAW_NO_SPINS`,
7047
+ * spin #3 is still attempted — the server does NOT stop on first
7048
+ * error and does NOT roll back successful spins. Each
7049
+ * `results[i].errCode` is independent.
7050
+ *
7051
+ * Practical implication: if the user has 3 spins available and
7052
+ * requests 5, expect results 0-2 with `errCode === 0` and results
7053
+ * 3-4 with `errCode === SAW_NO_SPINS`.
7054
+ *
7055
+ * **Error codes**
7056
+ * Per-result `errCode` is from {@link SAWSpinErrorCode}. See
7057
+ * {@link playMiniGame} for the full table; the same codes apply
7058
+ * per spin.
7059
+ *
7060
+ * **`first_spin_in_period` field**
7061
+ * Populated on results where `errCode === SAW_FAILED_MAX_SPINS_REACHED`
7062
+ * (40004). The value is the epoch-ms timestamp of the user's
7063
+ * first spin in the current cooldown period. Compute the
7064
+ * countdown as:
7065
+ * `template.max_spins_period_ms - (Date.now() - first_spin_in_period)`.
7066
+ *
7067
+ * **`jackpot_amount` field**
7068
+ * Populated on results where the won prize is a jackpot
7069
+ * (`prize_type === 'jackpot'`). The amount the user just claimed
7070
+ * from the template's jackpot accumulator.
7071
+ *
7072
+ * **Auto-acknowledge**
7073
+ * The SDK fires a batch-acknowledge for all `request_id`s after
7074
+ * the batch response lands — fire-and-forget. Same recovery
7075
+ * semantics as {@link playMiniGame}: lost acknowledgements
7076
+ * become recoverable via {@link miniGameWinAcknowledgeRequest}
7077
+ * per row, and a server-side fallback job auto-acknowledges
7078
+ * stale spins every ~60 seconds.
7079
+ *
7080
+ * **Idempotency**: NOT idempotent. A double-click sends two
7081
+ * batches. Guard the call site with an in-flight flag.
7082
+ *
7083
+ * **Refresh after success (and after failure)**
7084
+ * Same as {@link playMiniGame} — the templates cache refreshes
7085
+ * and any `onUpdate` callback registered via {@link getMiniGames}
7086
+ * fires with the updated `spin_count` / `jackpot_current`.
7087
+ *
7088
+ * **Side effects** (per-spin, on `errCode === 0`)
7089
+ * Same as {@link playMiniGame} — buy-in deducted, prize value
7090
+ * credited per prize type.
7091
+ *
7092
+ * **UI guidance**: see [UI Guide — `playMiniGameBatch`](../../docs/ui/minigames/UIGuide_playMiniGameBatch.md).
7093
+ *
7094
+ * **Visitor mode**: not supported.
7095
+ *
7096
+ * @param template_id The mini-game template ID.
7097
+ * @param spin_count Number of spins to play. The server attempts
7098
+ * all `spin_count` spins — partial successes
7099
+ * are normal when the user runs out of
7100
+ * balance / spins mid-batch.
7101
+ * @param params Optional. Pass an `onUpdate` callback to
7102
+ * subscribe to subsequent template refreshes.
7103
+ * @returns `TMiniGamePlayBatchResult[]` — one entry per requested
7104
+ * spin, in request order. Note the camelCase `errCode` /
7105
+ * `errMessage` keys (see "Result shape note" above).
7106
+ *
7107
+ * @example
7108
+ * ```ts
7109
+ * const game = (await window._smartico.api.getMiniGames()).find(g => g.id === templateId);
7110
+ * if (!game) return;
7111
+ *
7112
+ * console.log('[smartico] batch play starting — set in-flight flag, animate the chosen N spins sequentially in UI');
7113
+ * const results = await window._smartico.api.playMiniGameBatch(game.id, 5);
7114
+ * console.log('[smartico] batch response received — clear in-flight flag');
7115
+ *
7116
+ * for (const [i, r] of results.entries()) {
7117
+ * if (r.errCode === 0) {
7118
+ * const prize = game.prizes.find(p => p.id === r.saw_prize_id);
7119
+ * console.log('[smartico] spin', i, 'won:', prize?.name,
7120
+ * r.jackpot_amount ? '(jackpot: ' + r.jackpot_amount + ')' : '');
7121
+ * } else if (r.errCode === 40004) {
7122
+ * const msTillNext = game.max_spins_period_ms! - (Date.now() - (r.first_spin_in_period ?? 0));
7123
+ * console.log('[smartico] spin', i, 'capped — ' + Math.ceil(msTillNext / 1000) + ' s until next allowed');
7124
+ * } else {
7125
+ * console.error('[smartico] spin', i, 'failed —', r.errCode, r.errMessage);
7126
+ * }
7127
+ * }
5449
7128
  * ```
5450
- * **Visitor mode: not supported**
5451
7129
  */
5452
7130
  async playMiniGameBatch(template_id, spin_count, {
5453
7131
  onUpdate
@@ -5482,79 +7160,297 @@ class WSAPIMiniGames extends WSAPIRaffles {
5482
7160
  /** @group Avatars */
5483
7161
  class WSAPIAvatars extends WSAPIMiniGames {
5484
7162
  /**
5485
- * Returns the list of avatars available in the catalog for the current user.
5486
- * The response includes both free avatars and earned/purchased ones.
5487
- * Avatars with `hide_until_achieved = true` and `is_given = false` should be hidden from the user.
5488
- * The result is cached for 30 seconds.
7163
+ * Returns the avatar catalog available to the current user — every pre-defined
7164
+ * avatar configured for the label, with per-user unlock flags (`is_given`, `is_in_use`)
7165
+ * applied server-side.
5489
7166
  *
5490
- * **Example**:
5491
- * ```
5492
- * _smartico.api.getAvatarsList().then((result) => {
5493
- * console.log(result);
5494
- * });
5495
- * ```
7167
+ * The returned `avatar_url` is the absolute CDN URL (the SDK prefixes relative paths
7168
+ * with the configured avatar domain). AI-customized variants are NOT returned here —
7169
+ * those live in {@link getAvatarsCustomized}.
5496
7170
  *
5497
- * **Visitor mode: not supported**
7171
+ * @remarks
7172
+ * **Preconditions**
7173
+ * - User must be authenticated. Visitor mode is not supported.
7174
+ * - No other prerequisite calls.
7175
+ *
7176
+ * **Visibility filter** (consumer-applied)
7177
+ * Avatars with `hide_until_achieved === true && is_given === false` should be filtered
7178
+ * out of the grid — they represent surprise unlocks that should remain hidden until
7179
+ * the user earns them. The default Smartico UI drops these before rendering.
7180
+ *
7181
+ * **Lock state** (consumer-applied)
7182
+ * Lock condition: `!is_given && avatar_source_type_id !== 0`. Free avatars
7183
+ * (`avatar_source_type_id === 0`) are always selectable; non-free avatars are locked
7184
+ * until `is_given` flips to true (operator grants via campaign, mission reward, store
7185
+ * purchase, etc.).
7186
+ *
7187
+ * **Sort order**
7188
+ * Server does NOT pre-sort. Caller must sort by `priority` ascending (lower = first).
7189
+ *
7190
+ * **Refresh**
7191
+ * - The SDK caches results for 30 seconds.
7192
+ * - {@link setAvatar} clears this cache on completion; the next call re-fetches.
7193
+ * - No push subscription — there is no `onUpdate` callback for avatar methods.
7194
+ * - When `is_given` flips server-side (e.g. the user earns a new avatar), the change
7195
+ * surfaces only on the next call after the 30-second cache window expires.
7196
+ *
7197
+ * **Visitor mode**: not supported.
7198
+ *
7199
+ * **UI guidance**: see [UI Guide — `getAvatarsList`](../../docs/ui/avatars/UIGuide_getAvatarsList.md).
7200
+ *
7201
+ * @returns Array of {@link TAvatarDefinition} — empty array if the feature is disabled
7202
+ * on the label.
7203
+ *
7204
+ * @example
7205
+ * ```ts
7206
+ * const avatars = await window._smartico.api.getAvatarsList();
7207
+ *
7208
+ * // Apply the standard visibility filter and sort.
7209
+ * const visible = avatars
7210
+ * .filter((a) => !a.hide_until_achieved || a.is_given)
7211
+ * .sort((a, b) => a.priority - b.priority);
7212
+ *
7213
+ * console.log('[smartico] visible avatars:', visible.length, '— render as a grid');
7214
+ *
7215
+ * const active = visible.find((a) => a.is_in_use);
7216
+ * if (active) {
7217
+ * console.log('[smartico] currently in use — overlay a checkmark on this card:', active.avatar_real_id);
7218
+ * }
7219
+ * ```
5498
7220
  */
5499
7221
  async getAvatarsList() {
5500
7222
  return OCache.use(onUpdateContextKey.AvatarsList, ECacheContext.WSAPI, () => this.api.avatarsGetListT(this.userExtId), CACHE_DATA_SEC);
5501
7223
  }
5502
7224
  /**
5503
- * Returns the list of AI-customized avatars for the current user.
5504
- * Each entry represents a previously generated AI customization for a specific base avatar.
5505
- * The result is cached for 30 seconds.
7225
+ * Returns the user's previously generated AI-customized avatar variants.
5506
7226
  *
5507
- * **Example**:
5508
- * ```
5509
- * _smartico.api.getAvatarsCustomized().then((result) => {
5510
- * console.log(result);
5511
- * });
5512
- * ```
7227
+ * Each entry is one AI-generated image derived from a base avatar in the catalog
7228
+ * (the base is identified by `avatar_real_id` and was originally a
7229
+ * {@link TAvatarDefinition} from {@link getAvatarsList}). These variants are stored
7230
+ * server-side under the user record and persist across sessions.
5513
7231
  *
5514
- * **Visitor mode: not supported**
7232
+ * @remarks
7233
+ * **Preconditions**
7234
+ * - User must be authenticated. Visitor mode is not supported.
7235
+ * - Has meaning only after at least one successful AI customization run (see below).
7236
+ * New users get an empty array.
7237
+ *
7238
+ * **Where customized avatars come from**
7239
+ * AI customization is **not** a WebSocket method on this SDK. It is a separate HTTP
7240
+ * POST to the operator-configured `avatar-customize` endpoint that takes a base avatar
7241
+ * plus a style prompt from {@link getAvatarPrompts} and returns a generated CDN URL.
7242
+ * Once that POST resolves successfully, the new variant is persisted and surfaces in
7243
+ * the next `getAvatarsCustomized()` call. The variant URL can then be passed to
7244
+ * {@link setAvatar} to activate it.
7245
+ *
7246
+ * **Relation to `getAvatarsList`**
7247
+ * AI variants do NOT appear in {@link getAvatarsList}. Catalog and variants are two
7248
+ * separate collections — combine them client-side if the UI needs a unified view per
7249
+ * base avatar.
7250
+ *
7251
+ * **Sort order**
7252
+ * Server does NOT pre-sort. Caller typically sorts by `dt_created` descending to show
7253
+ * the newest variant first.
7254
+ *
7255
+ * **Refresh**
7256
+ * - The SDK caches results for 30 seconds.
7257
+ * - {@link setAvatar} clears this cache on completion.
7258
+ * - After a successful AI customization POST, the consumer should re-call to surface
7259
+ * the new variant — the customization endpoint is outside the SDK so the SDK cannot
7260
+ * auto-invalidate.
7261
+ * - No push subscription.
7262
+ *
7263
+ * **Visitor mode**: not supported.
7264
+ *
7265
+ * **UI guidance**: see [UI Guide — `getAvatarsCustomized`](../../docs/ui/avatars/UIGuide_getAvatarsCustomized.md).
7266
+ *
7267
+ * @returns Array of {@link TAvatarCustomized} — empty if the user has never run AI
7268
+ * customization, or if the feature is disabled on the label.
7269
+ *
7270
+ * @example
7271
+ * ```ts
7272
+ * const variants = await window._smartico.api.getAvatarsCustomized();
7273
+ *
7274
+ * // Group by the base avatar so the UI can show "this base has 3 AI variants".
7275
+ * const byBase = new Map<number, typeof variants>();
7276
+ * for (const v of variants) {
7277
+ * const list = byBase.get(v.avatar_real_id) ?? [];
7278
+ * list.push(v);
7279
+ * byBase.set(v.avatar_real_id, list);
7280
+ * }
7281
+ *
7282
+ * // Newest-first within each base.
7283
+ * for (const list of byBase.values()) {
7284
+ * list.sort((a, b) => b.dt_created.localeCompare(a.dt_created));
7285
+ * }
7286
+ *
7287
+ * console.log('[smartico] AI variants by base avatar — render as a carousel under each base');
7288
+ * ```
5515
7289
  */
5516
7290
  async getAvatarsCustomized() {
5517
7291
  return OCache.use(onUpdateContextKey.AvatarsCustomized, ECacheContext.WSAPI, () => this.api.avatarsGetCustomizedT(this.userExtId), CACHE_DATA_SEC);
5518
7292
  }
5519
7293
  /**
5520
- * Returns the list of AI customization prompts (styles) available for avatar customization.
5521
- * Each prompt represents a visual style that can be applied to a base avatar.
5522
- * The result is cached for 30 seconds.
7294
+ * Returns the catalog of AI style prompts available for avatar customization.
5523
7295
  *
5524
- * **Example**:
5525
- * ```
5526
- * _smartico.api.getAvatarPrompts().then((result) => {
5527
- * console.log(result);
5528
- * });
5529
- * ```
7296
+ * Each entry is a "style" the user can apply to a base avatar (e.g. "Cartoon",
7297
+ * "Watercolor", "Cyberpunk"). Prompts carry a cost expressed in points, gems, or
7298
+ * diamonds — applying a prompt deducts the cost server-side as part of the AI
7299
+ * generation request.
5530
7300
  *
5531
- * **Visitor mode: not supported**
7301
+ * @remarks
7302
+ * **Preconditions**
7303
+ * - User must be authenticated. Visitor mode is not supported.
7304
+ * - No other prerequisite calls. The customization UI typically calls this on demand
7305
+ * when the user opens the style picker, not on app boot.
7306
+ *
7307
+ * **Cost handling**
7308
+ * Each prompt declares `cost_currency_type_id` (0 = points, 1 = gems, 2 = diamonds)
7309
+ * and `cost_value` (amount). The deduction happens server-side inside the
7310
+ * `avatar-customize` HTTP POST (the AI generation request, which is NOT part of this
7311
+ * SDK). The client should compare `cost_value` against the live balance from
7312
+ * {@link getUserProfile} to disable prompts the user cannot afford, but the server is
7313
+ * the source of truth and will reject under-funded requests authoritatively.
7314
+ *
7315
+ * **Refresh**
7316
+ * - The SDK caches results for 30 seconds.
7317
+ * - Not invalidated by {@link setAvatar} (prompts are catalog metadata, independent
7318
+ * of the user's active avatar).
7319
+ * - No push subscription.
7320
+ *
7321
+ * **Visitor mode**: not supported.
7322
+ *
7323
+ * **UI guidance**: see [UI Guide — `getAvatarPrompts`](../../docs/ui/avatars/UIGuide_getAvatarPrompts.md).
7324
+ *
7325
+ * @returns Array of {@link TAvatarPrompt} — empty if the AI customization feature is
7326
+ * disabled on the label.
7327
+ *
7328
+ * @example
7329
+ * ```ts
7330
+ * const [prompts, profile] = await Promise.all([
7331
+ * window._smartico.api.getAvatarPrompts(),
7332
+ * window._smartico.api.getUserProfile(),
7333
+ * ]);
7334
+ *
7335
+ * for (const p of prompts) {
7336
+ * // The consumer reads the matching balance from profile based on
7337
+ * // p.cost_currency_type_id (0=points, 1=gems, 2=diamonds).
7338
+ * console.log('[smartico] prompt', p.name, '— cost', p.cost_value, 'currency_type', p.cost_currency_type_id);
7339
+ * }
7340
+ * ```
5532
7341
  */
5533
7342
  async getAvatarPrompts() {
5534
7343
  return OCache.use(onUpdateContextKey.AvatarPrompts, ECacheContext.WSAPI, () => this.api.avatarsGetPromptsT(this.userExtId), CACHE_DATA_SEC);
5535
7344
  }
5536
7345
  /**
5537
- * Sets the specified avatar as the active avatar for the current user.
5538
- * Pass `avatar_url` (the `TAvatarDefinition.url` path or a CDN URL for AI-customized avatars)
5539
- * and `avatar_real_id` from the avatar catalog.
5540
- * After a successful call, the avatar list cache is cleared so the next `getAvatarsList()` call reflects `is_in_use`.
7346
+ * Activates the specified avatar for the current user. The chosen image becomes the
7347
+ * profile avatar — any subsequent {@link getUserProfile} call will reflect the new
7348
+ * `avatar_url`.
5541
7349
  *
5542
- * **Example**:
5543
- * ```
5544
- * _smartico.api.getAvatarsList().then((avatars) => {
5545
- * const avatar = avatars.find((a) => !a.hide_until_achieved || a.is_given);
5546
- * if (avatar) {
5547
- * _smartico.api.setAvatar({
5548
- * avatar_url: avatar.url,
5549
- * avatar_real_id: avatar.avatar_real_id,
5550
- * }).then((result) => {
5551
- * console.log(result);
5552
- * });
5553
- * }
7350
+ * Pass `avatar_url` (a {@link TAvatarDefinition.url} from the catalog or a
7351
+ * {@link TAvatarCustomized.url} from the AI-variant list) plus `avatar_real_id` of the
7352
+ * base avatar. The server validates ownership before applying — locked avatars are
7353
+ * rejected.
7354
+ *
7355
+ * @remarks
7356
+ * **Preconditions**
7357
+ * - User must be authenticated. Visitor mode is not supported.
7358
+ * - `avatar_url` must be non-empty and `avatar_real_id` must be truthy — the SDK
7359
+ * throws synchronously otherwise (the request never reaches the server).
7360
+ * - The avatar must exist in the catalog from {@link getAvatarsList} (or be an AI
7361
+ * variant of a base avatar the user already owns). Free avatars
7362
+ * (`avatar_source_type_id === 0`) and the user's currently active avatar bypass the
7363
+ * ownership check; all others require `is_given === true`.
7364
+ *
7365
+ * **Error codes** (in `err_code`)
7366
+ * - `0` — success; cache is cleared and the profile avatar updates immediately.
7367
+ * - `1` — avatar not found in the catalog. The `avatar_real_id` doesn't exist for
7368
+ * this label.
7369
+ * - `2` — avatar inactive (deactivated by the operator).
7370
+ * - `3` — outside the avatar's active time window
7371
+ * (`active_from_date` / `active_till_date`).
7372
+ * - `4` — user does not own this avatar (it isn't in their `is_given` set and isn't
7373
+ * a free / default avatar).
7374
+ * - other non-zero — generic server error; surface `err_message` if present.
7375
+ *
7376
+ * The default Smartico UI shows a hardcoded "Failed to apply avatar" toast on any
7377
+ * non-zero `err_code` and does not surface `err_message`. Custom UIs SHOULD branch
7378
+ * on the code and prefer `err_message` when present (it is the localized server
7379
+ * string).
7380
+ *
7381
+ * **Refresh after success**
7382
+ * - The SDK clears both the `getAvatarsList` and `getAvatarsCustomized` caches —
7383
+ * the next call to either returns fresh data with the new `is_in_use` flag set on
7384
+ * the chosen avatar.
7385
+ * - The server persists the new avatar URL on the user record; {@link getUserProfile}
7386
+ * reflects it on the next read in this session.
7387
+ * - **No push to other open sessions.** A second device / tab the user is logged in
7388
+ * on will not see the new avatar until it next calls {@link getUserProfile} or
7389
+ * re-identifies. Plan UI accordingly.
7390
+ *
7391
+ * **Idempotency**: safe to retry. Re-applying the same `avatar_real_id` returns
7392
+ * `err_code: 0` and produces no double side effects (no double-deduction — this
7393
+ * method does not charge any currency — and no duplicate log entries).
7394
+ *
7395
+ * **Side effects**: updates the user's stored `avatar_id` / `avatar_real_id`. Does
7396
+ * NOT cost points, gems, or diamonds — the cost lives on the separate AI
7397
+ * customization HTTP flow ({@link getAvatarPrompts}). Does NOT write a user-visible
7398
+ * entry to {@link getActivityLog}.
7399
+ *
7400
+ * **UI guidance**: see [UI Guide — `setAvatar`](../../docs/ui/avatars/UIGuide_setAvatar.md).
7401
+ *
7402
+ * **Visitor mode**: not supported.
7403
+ *
7404
+ * @param props.avatar_url Absolute CDN URL of the avatar image. Read from
7405
+ * {@link TAvatarDefinition.url} for catalog avatars or
7406
+ * {@link TAvatarCustomized.url} for AI variants.
7407
+ * @param props.avatar_real_id Numeric ID of the base avatar from
7408
+ * {@link TAvatarDefinition.avatar_real_id}. For AI
7409
+ * variants, this is the `avatar_real_id` of the base
7410
+ * they were derived from.
7411
+ * @returns {@link TSetAvatarResult} — check `err_code === 0` for success.
7412
+ *
7413
+ * @example
7414
+ * ```ts
7415
+ * const avatars = await window._smartico.api.getAvatarsList();
7416
+ * const target = avatars.find((a) => a.avatar_real_id === 7);
7417
+ *
7418
+ * if (!target) {
7419
+ * console.error('[smartico] avatar 7 not in catalog — hide the picker entry');
7420
+ * return;
7421
+ * }
7422
+ *
7423
+ * const isLocked = !target.is_given && target.avatar_source_type_id !== 0;
7424
+ * if (isLocked) {
7425
+ * console.log('[smartico] avatar is locked — show "earn this first" prompt instead of calling setAvatar');
7426
+ * return;
7427
+ * }
7428
+ *
7429
+ * const r = await window._smartico.api.setAvatar({
7430
+ * avatar_url: target.avatar_url,
7431
+ * avatar_real_id: target.avatar_real_id,
5554
7432
  * });
5555
- * ```
5556
7433
  *
5557
- * **Visitor mode: not supported**
7434
+ * switch (r.err_code) {
7435
+ * case 0:
7436
+ * console.log('[smartico] avatar applied — close picker, refresh header avatar');
7437
+ * break;
7438
+ * case 1:
7439
+ * console.error('[smartico] avatar not in catalog — refresh catalog and show error');
7440
+ * break;
7441
+ * case 2:
7442
+ * console.error('[smartico] avatar inactive — operator disabled it; hide from picker');
7443
+ * break;
7444
+ * case 3:
7445
+ * console.error('[smartico] outside time window — show "available on X" message');
7446
+ * break;
7447
+ * case 4:
7448
+ * console.error('[smartico] not owned — show unlock requirements');
7449
+ * break;
7450
+ * default:
7451
+ * console.error('[smartico] avatar apply failed — show generic error toast:', r.err_message);
7452
+ * }
7453
+ * ```
5558
7454
  */
5559
7455
  async setAvatar(props) {
5560
7456
  var _r$errCode;
@@ -5577,37 +7473,65 @@ class WSAPIAvatars extends WSAPIMiniGames {
5577
7473
  /** @group GamePick */
5578
7474
  class WSAPIGamePick extends WSAPIAvatars {
5579
7475
  /**
5580
- * Returns the active rounds for the specified MatchX or Quiz game.
5581
- * Each round includes its events (matches/questions) along with the current user's selections and scores.
5582
- *
5583
- * @param props.saw_template_id - The ID of the MatchX or Quiz game template
5584
- *
5585
- * **Response** `GamesApiResponse<GamePickRound[]>`:
5586
- * - `errCode` - 0 on success
5587
- * - `data` - Array of rounds, each containing:
5588
- * - `round_id`, `round_name` - Round identifier and display name
5589
- * - `open_date`, `last_bet_date` - Timestamps (ms) for round open and betting deadline
5590
- * - `is_active_now`, `is_resolved` - Round state flags
5591
- * - `round_status_id` - Round status: -1 (active), 2 (no more bets), 3 (all events resolved), 4 (round resolved)
5592
- * - `score_full_win`, `score_part_win`, `score_lost` - Scoring rules per prediction outcome
5593
- * - `user_score` - Current user's total score in this round
5594
- * - `user_placed_bet` - Whether the user has submitted predictions
5595
- * - `has_open_for_bet_events` - Whether there are events still open for betting
5596
- * - `events[]` - Array of events with `gp_event_id`, `market_type_id`, `event_meta` (team names, images, sport), `match_date`, `is_open_for_bets`, `odds_details`, and user selection fields
5597
- *
5598
- * **Example**:
5599
- * ```
5600
- * _smartico.api.gamePickGetActiveRounds({
5601
- * saw_template_id: 1083,
5602
- * }).then((result) => {
5603
- * console.log(result.data); // GamePickRound[]
5604
- * result.data.forEach(round => {
5605
- * console.log(round.round_name, round.events.length);
5606
- * });
5607
- * });
5608
- * ```
7476
+ * Returns every open round for a MatchX or Quiz game template, with the full
7477
+ * event list (matches / questions) and the current user's selections per event.
5609
7478
  *
5610
- * **Visitor mode: not supported**
7479
+ * Use to power the rounds-lobby screen — typically a list of round cards a user
7480
+ * can tap into to make predictions. For a single round, use
7481
+ * {@link gamePickGetActiveRound} (lighter payload when only one round is shown).
7482
+ *
7483
+ * @remarks
7484
+ * **Preconditions**
7485
+ * - User must be authenticated.
7486
+ * - `saw_template_id` must reference a MatchX or Quiz game template. The SDK
7487
+ * throws synchronously if it's missing.
7488
+ *
7489
+ * **Transport**
7490
+ * Game Pick methods are HTTP REST calls to a separate Game Pick games server
7491
+ * (not the main WebSocket). One consequence: there is no SDK cache and no push
7492
+ * subscription — every call is a fresh server roundtrip.
7493
+ *
7494
+ * **Round status**
7495
+ * Each round's `round_status_id` is a {@link GPRoundStatus} value. Rounds with
7496
+ * status `NoEventsDefined` (1) are filtered out server-side and never appear
7497
+ * here. Other values: `Other` (-1, normally open), `NoMoreBetsAllowed` (2),
7498
+ * `AllEventsResolved_ButNotRound` (3), `RoundResolved` (4 — appears here only
7499
+ * briefly during transition; use {@link gamePickGetHistory} for resolved rounds).
7500
+ *
7501
+ * **Error codes** (in `errCode`)
7502
+ * - `0` — success.
7503
+ * - `100002` — template not found (the `saw_template_id` doesn't reference a
7504
+ * MatchX/Quiz game).
7505
+ * - `100003` — no open rounds available for this template right now.
7506
+ * - `100000` — auth hash invalid; SDK session needs re-initialization.
7507
+ * - `100004` — generic server error.
7508
+ *
7509
+ * **Refresh**
7510
+ * - No cache; every call is live.
7511
+ * - No push subscription. Poll while the user is on the screen if you need
7512
+ * live round-status changes (typically every 30–60 s is enough).
7513
+ *
7514
+ * **Visitor mode**: not supported. The SDK throws synchronously on visitor
7515
+ * sessions.
7516
+ *
7517
+ * **UI guidance**: see [UI Guide — `gamePickGetActiveRounds`](../../docs/ui/gamepick/UIGuide_gamePickGetActiveRounds.md).
7518
+ *
7519
+ * @param props.saw_template_id ID of the MatchX or Quiz game template.
7520
+ * @returns Wrapped {@link GamesApiResponse} of {@link GamePickRound} array.
7521
+ *
7522
+ * @example
7523
+ * ```ts
7524
+ * const r = await window._smartico.api.gamePickGetActiveRounds({ saw_template_id: 1083 });
7525
+ *
7526
+ * if (r.errCode !== 0) {
7527
+ * console.error('[smartico] active rounds fetch failed — show empty rounds lobby:', r.errMessage);
7528
+ * return;
7529
+ * }
7530
+ *
7531
+ * for (const round of r.data ?? []) {
7532
+ * console.log('[smartico] render a round card:', round.round_name, '— events:', round.events.length, 'user has placed bet:', round.user_placed_bet);
7533
+ * }
7534
+ * ```
5611
7535
  */
5612
7536
  async gamePickGetActiveRounds(props) {
5613
7537
  if (!props.saw_template_id) {
@@ -5616,29 +7540,56 @@ class WSAPIGamePick extends WSAPIAvatars {
5616
7540
  return this.api.gpGetActiveRounds(props.saw_template_id);
5617
7541
  }
5618
7542
  /**
5619
- * Returns a single active round for the specified MatchX or Quiz game.
5620
- * The round includes full event details with the current user's selections.
7543
+ * Returns a single round (events, user selections, scoring rules) for a
7544
+ * MatchX or Quiz game. Use to power the round-detail / prediction-input
7545
+ * screen the user lands on after picking a round from the lobby.
5621
7546
  *
5622
- * @param props.saw_template_id - The ID of the MatchX or Quiz game template
5623
- * @param props.round_id - The specific round to retrieve
7547
+ * Same shape as one entry of {@link gamePickGetActiveRounds}; cheaper when the
7548
+ * UI only shows one round at a time.
5624
7549
  *
5625
- * **Response** `GamesApiResponse<GamePickRound>`:
5626
- * - `errCode` - 0 on success
5627
- * - `data` - Single round object with the same structure as in `gamePickGetActiveRounds`,
5628
- * including `events[]` with full event details, user selections, and resolution info
7550
+ * @remarks
7551
+ * **Preconditions**
7552
+ * - User must be authenticated. Visitor mode not supported.
7553
+ * - `saw_template_id` and `round_id` are mandatory — the SDK throws if either
7554
+ * is missing.
7555
+ *
7556
+ * **Error codes** (in `errCode`)
7557
+ * - `0` — success.
7558
+ * - `4` — round / event not found (e.g. round resolved after the last
7559
+ * `gamePickGetActiveRounds` poll); non-fatal — retry after a fresh active-
7560
+ * rounds fetch.
7561
+ * - `100002` — template not found.
7562
+ * - `100000` — auth hash invalid.
7563
+ * - `100004` — generic server error.
7564
+ *
7565
+ * **Refresh**
7566
+ * - No cache; every call is live.
7567
+ * - Re-call after {@link gamePickSubmitSelection} or
7568
+ * {@link gamePickSubmitSelectionQuiz} to surface the persisted predictions.
7569
+ * - Poll while the user is on the prediction screen if event resolution
7570
+ * updates are needed (typically every 30–60 s).
5629
7571
  *
5630
- * **Example**:
5631
- * ```
5632
- * _smartico.api.gamePickGetActiveRound({
5633
- * saw_template_id: 1083,
5634
- * round_id: 31652,
5635
- * }).then((result) => {
5636
- * console.log(result.data.round_name, result.data.events.length);
5637
- * console.log(result.data.user_score, result.data.user_placed_bet);
7572
+ * **Visitor mode**: not supported.
7573
+ *
7574
+ * **UI guidance**: see [UI Guide — `gamePickGetActiveRound`](../../docs/ui/gamepick/UIGuide_gamePickGetActiveRound.md).
7575
+ *
7576
+ * @param props.saw_template_id ID of the MatchX or Quiz game template.
7577
+ * @param props.round_id ID of the round to fetch.
7578
+ * @returns Wrapped {@link GamesApiResponse} of a single {@link GamePickRound}.
7579
+ *
7580
+ * @example
7581
+ * ```ts
7582
+ * const r = await window._smartico.api.gamePickGetActiveRound({
7583
+ * saw_template_id: 1083,
7584
+ * round_id: 31652,
5638
7585
  * });
5639
- * ```
5640
7586
  *
5641
- * **Visitor mode: not supported**
7587
+ * if (r.errCode === 0 && r.data) {
7588
+ * console.log('[smartico] render round detail page —', r.data.round_name, '— user has placed bet:', r.data.user_placed_bet, 'score so far:', r.data.user_score);
7589
+ * } else {
7590
+ * console.error('[smartico] round fetch failed — bounce back to the lobby and refresh:', r.errMessage);
7591
+ * }
7592
+ * ```
5642
7593
  */
5643
7594
  async gamePickGetActiveRound(props) {
5644
7595
  if (!props.saw_template_id) {
@@ -5650,29 +7601,52 @@ class WSAPIGamePick extends WSAPIAvatars {
5650
7601
  return this.api.gpGetActiveRound(props.saw_template_id, props.round_id);
5651
7602
  }
5652
7603
  /**
5653
- * Returns the history of all rounds (including resolved ones) for the specified MatchX or Quiz game.
5654
- * Each round contains full event details with results and the current user's predictions.
7604
+ * Returns the full round history (active + resolved) for a MatchX or Quiz game
7605
+ * template, newest-first. Each round carries the user's predictions plus the
7606
+ * server-resolved outcome on each event.
5655
7607
  *
5656
- * @param props.saw_template_id - The ID of the MatchX or Quiz game template
7608
+ * Use to power a "Past predictions" / history tab. For just the open rounds,
7609
+ * use {@link gamePickGetActiveRounds} (faster — skips resolved data).
5657
7610
  *
5658
- * **Response** `GamesApiResponse<GamePickRound[]>`:
5659
- * - `errCode` - 0 on success
5660
- * - `data` - Array of rounds ordered by `round_row_id` descending (newest first).
5661
- * Each round has the same structure as in `gamePickGetActiveRounds`, including resolved events
5662
- * with `resolution_type_id` (0=None, 2=Lost, 3=PartialWin, 4=FullWin) and `resolution_score`
7611
+ * @remarks
7612
+ * **Preconditions**
7613
+ * - User must be authenticated. Visitor mode not supported.
5663
7614
  *
5664
- * **Example**:
5665
- * ```
5666
- * _smartico.api.gamePickGetHistory({
5667
- * saw_template_id: 1083,
5668
- * }).then((result) => {
5669
- * result.data.forEach(round => {
5670
- * console.log(round.round_name, 'Score:', round.user_score, 'Resolved:', round.is_resolved);
5671
- * });
5672
- * });
5673
- * ```
7615
+ * **Sort order**
7616
+ * Server returns rounds newest-first. No client-side sort needed.
5674
7617
  *
5675
- * **Visitor mode: not supported**
7618
+ * **Per-event resolution**
7619
+ * Each event in the rounds carries `resolution_type_id` — values are from
7620
+ * {@link GamePickResolutionType}: `None` (0, not yet resolved), `Lost` (2),
7621
+ * `PartialWin` (3), `FullWin` (4). Use these to render result badges on
7622
+ * each event row.
7623
+ *
7624
+ * **Error codes** (in `errCode`)
7625
+ * - `0` — success.
7626
+ * - `100002` — template not found.
7627
+ * - `100000` — auth hash invalid.
7628
+ * - `100004` — generic server error.
7629
+ *
7630
+ * **Refresh**
7631
+ * - No cache.
7632
+ * - No push subscription. Re-call when the user opens the history tab.
7633
+ *
7634
+ * **Visitor mode**: not supported.
7635
+ *
7636
+ * **UI guidance**: see [UI Guide — `gamePickGetHistory`](../../docs/ui/gamepick/UIGuide_gamePickGetHistory.md).
7637
+ *
7638
+ * @param props.saw_template_id ID of the MatchX or Quiz game template.
7639
+ * @returns Wrapped {@link GamesApiResponse} of {@link GamePickRound} array,
7640
+ * newest-first.
7641
+ *
7642
+ * @example
7643
+ * ```ts
7644
+ * const r = await window._smartico.api.gamePickGetHistory({ saw_template_id: 1083 });
7645
+ *
7646
+ * for (const round of r.data ?? []) {
7647
+ * console.log('[smartico] history row —', round.round_name, 'score:', round.user_score, 'resolved:', round.is_resolved);
7648
+ * }
7649
+ * ```
5676
7650
  */
5677
7651
  async gamePickGetHistory(props) {
5678
7652
  if (!props.saw_template_id) {
@@ -5681,36 +7655,66 @@ class WSAPIGamePick extends WSAPIAvatars {
5681
7655
  return this.api.gpGetGamesHistory(props.saw_template_id);
5682
7656
  }
5683
7657
  /**
5684
- * Returns the leaderboard for a specific round within a MatchX or Quiz game.
5685
- * Use `round_id = -1` (AllRoundsGameBoardID) to get the season/overall leaderboard across all rounds.
5686
- *
5687
- * @param props.saw_template_id - The ID of the MatchX or Quiz game template
5688
- * @param props.round_id - The round to get the leaderboard for. Use -1 for overall/seasonal leaderboard
5689
- *
5690
- * **Response** `GamesApiResponse<GamePickRoundBoard>`:
5691
- * - `errCode` - 0 on success
5692
- * - `data` - Leaderboard object containing:
5693
- * - Round base fields (`round_id`, `round_name`, `open_date`, `last_bet_date`, etc.)
5694
- * - `users[]` - Ranked list of players, each with:
5695
- * - `ext_user_id`, `int_user_id` - User identifiers
5696
- * - `public_username`, `avatar_url` - Display info (usernames may be masked based on label settings)
5697
- * - `gp_position` - Leaderboard rank (null if not yet ranked)
5698
- * - `resolution_score` - Total score in this round
5699
- * - `full_wins_count`, `part_wins_count`, `lost_count` - Prediction outcome counts
5700
- * - `my_user` - Current user's entry (same fields as above), or null if user hasn't participated
5701
- *
5702
- * **Example**:
5703
- * ```
5704
- * _smartico.api.gamePickGetBoard({
5705
- * saw_template_id: 1083,
5706
- * round_id: 31652,
5707
- * }).then((result) => {
5708
- * console.log('Top players:', result.data.users);
5709
- * console.log('My position:', result.data.my_user?.gp_position);
7658
+ * Returns the leaderboard for a MatchX or Quiz game round — ranked list of
7659
+ * players plus the current user's entry (`my_user`). Pass `round_id: -1` for
7660
+ * the season / overall leaderboard across every round in the template.
7661
+ *
7662
+ * @remarks
7663
+ * **Preconditions**
7664
+ * - User must be authenticated. Visitor mode not supported.
7665
+ *
7666
+ * **`round_id` semantics**
7667
+ * - Positive `round_id` — per-round leaderboard scoped to that round's events.
7668
+ * - `-1` — season / overall leaderboard aggregating scores across every round
7669
+ * of the template.
7670
+ *
7671
+ * **`my_user`**
7672
+ * The current user's entry is returned separately from the `users[]` array
7673
+ * — `my_user` may be `null` if the user has never made a prediction on this
7674
+ * round / template. Use it to render the user's rank in a sticky footer or
7675
+ * "you are here" highlight regardless of pagination.
7676
+ *
7677
+ * **Username masking**
7678
+ * `public_username` on other players may be masked / anonymized by operator
7679
+ * label settings. Always pair with `avatar_url` so the user can recognize
7680
+ * themselves in the ranking by avatar even when usernames are hidden.
7681
+ *
7682
+ * **Error codes** (in `errCode`)
7683
+ * - `0` — success.
7684
+ * - `100002` — template not found.
7685
+ * - `100000` — auth hash invalid.
7686
+ * - `100004` — generic server error.
7687
+ *
7688
+ * **Refresh**
7689
+ * - No cache.
7690
+ * - No push subscription. Poll while the leaderboard is visible
7691
+ * (every 30–60 s) if you want live rank updates after match
7692
+ * resolution.
7693
+ *
7694
+ * **Visitor mode**: not supported.
7695
+ *
7696
+ * **UI guidance**: see [UI Guide — `gamePickGetBoard`](../../docs/ui/gamepick/UIGuide_gamePickGetBoard.md).
7697
+ *
7698
+ * @param props.saw_template_id ID of the MatchX or Quiz game template.
7699
+ * @param props.round_id Round ID, or `-1` for the season leaderboard.
7700
+ * @returns Wrapped {@link GamesApiResponse} of {@link GamePickRoundBoard}.
7701
+ *
7702
+ * @example
7703
+ * ```ts
7704
+ * const r = await window._smartico.api.gamePickGetBoard({
7705
+ * saw_template_id: 1083,
7706
+ * round_id: -1, // season leaderboard
5710
7707
  * });
5711
- * ```
5712
7708
  *
5713
- * **Visitor mode: not supported**
7709
+ * if (r.errCode === 0 && r.data) {
7710
+ * console.log('[smartico] render leaderboard rows for top', r.data.users.length, 'players');
7711
+ * if (r.data.my_user) {
7712
+ * console.log('[smartico] pin "you are rank #' + r.data.my_user.gp_position + '" footer to bottom');
7713
+ * } else {
7714
+ * console.log('[smartico] user not ranked — render "Play a round to join the leaderboard" CTA');
7715
+ * }
7716
+ * }
7717
+ * ```
5714
7718
  */
5715
7719
  async gamePickGetBoard(props) {
5716
7720
  if (!props.saw_template_id) {
@@ -5722,43 +7726,107 @@ class WSAPIGamePick extends WSAPIAvatars {
5722
7726
  return this.api.gpGetGameBoard(props.saw_template_id, props.round_id);
5723
7727
  }
5724
7728
  /**
5725
- * Submits score predictions for a round in a MatchX game.
5726
- * Sends the round object with user selections for all events at once.
5727
- * Each event must include `team1_user_selection` and `team2_user_selection` representing predicted scores.
5728
- * If the user hasn't placed bets before, one game attempt (spin) will be consumed.
5729
- * Predictions can be edited until each match starts (if `allow_edit_answers` is enabled on the round).
5730
- *
5731
- * @param props.saw_template_id - The ID of the MatchX game template
5732
- * @param props.round - Round object containing `round_id` and `events[]`. Typically obtained from `gamePickGetActiveRound`
5733
- * and modified with user predictions. Each event needs: `gp_event_id`, `team1_user_selection`, `team2_user_selection`
5734
- *
5735
- * **Response** `GamesApiResponse<GamePickRound>`:
5736
- * - `errCode` - 0 on success. Non-zero codes indicate errors (e.g. not enough points/attempts)
5737
- * - `data` - Updated round with all events reflecting the submitted selections.
5738
- * `user_placed_bet` will be `true`, `has_not_submitted_changes` will be `false`
5739
- *
5740
- * **Example**:
5741
- * ```
5742
- * _smartico.api.gamePickGetActiveRound({
5743
- * saw_template_id: 1190,
5744
- * round_id: 38665,
5745
- * }).then((roundData) => {
5746
- * const round = roundData.data;
5747
- * round.events = round.events.map(e => ({
5748
- * gp_event_id: e.gp_event_id,
5749
- * team1_user_selection: 1,
5750
- * team2_user_selection: 0,
5751
- * }));
5752
- * _smartico.api.gamePickSubmitSelection({
5753
- * saw_template_id: 1190,
5754
- * round: round,
5755
- * }).then((result) => {
5756
- * console.log(result.data.user_placed_bet); // true
5757
- * });
7729
+ * Submits all score predictions for a round in a MatchX game in one shot.
7730
+ * Each event in the round must carry `team1_user_selection` and
7731
+ * `team2_user_selection` (the predicted scores).
7732
+ *
7733
+ * On the user's FIRST submit for a round, the server charges one buy-in (one
7734
+ * "spin" / one currency deduction based on the template's `saw_buyin_type_id`).
7735
+ * Subsequent edits within the same round are free and only persist changed
7736
+ * selections.
7737
+ *
7738
+ * @remarks
7739
+ * **Preconditions**
7740
+ * - User must be authenticated. Visitor mode not supported.
7741
+ * - `saw_template_id` and `props.round.round_id` are mandatory — SDK throws if
7742
+ * either is missing.
7743
+ * - Each event passed must include `gp_event_id` and the two
7744
+ * `team{1,2}_user_selection` fields. Missing events default to "no change".
7745
+ *
7746
+ * **Error codes** (in `errCode`)
7747
+ * - `0` — success; the response `data` is the updated round with
7748
+ * `user_placed_bet === true` and `has_not_submitted_changes === false`.
7749
+ * - `3` (`NoBetsUpdatedOnSubmit`) — submit produced no changes, OR every event
7750
+ * is past its `last_bet_date` deadline. The buy-in is NOT consumed; the
7751
+ * current round is still returned in `data`.
7752
+ * - `4` — round / event not found; refresh state and retry.
7753
+ * - `100002` — template not found.
7754
+ * - `100000` — auth hash invalid.
7755
+ * - `100004` — generic server error.
7756
+ *
7757
+ * Buy-in failures pass through the {@link SAWSpinErrorCode} values on first
7758
+ * submit:
7759
+ * - `40001` — no spins left (when `saw_buyin_type_id` is Spins).
7760
+ * - `40003` — insufficient points.
7761
+ * - `40004` — global max-spins cap hit.
7762
+ * - `40007` — template outside its active date window.
7763
+ * - `40009` — user excluded by segment rule.
7764
+ * - `40011` — insufficient gems.
7765
+ * - `40012` — insufficient diamonds.
7766
+ *
7767
+ * **Idempotency**
7768
+ * Re-submitting identical selections returns `errCode: 3` (no changes); the
7769
+ * buy-in is consumed exactly once per round-per-user. Re-submitting after
7770
+ * `last_bet_date` also returns `errCode: 3` without consuming the buy-in.
7771
+ *
7772
+ * **Side effects**
7773
+ * - First successful submit deducts the buy-in (Points / Gems / Diamonds /
7774
+ * one Spin) per `saw_buyin_type_id`.
7775
+ * - Reports a `minigame_matchx_prediction` event to the operator's event log.
7776
+ * - Updates the round's participant counter (`users_cnt`) and per-event
7777
+ * counters (`num_users`).
7778
+ * - Score is awarded after the operator resolves the round
7779
+ * ({@link GPRoundStatus} = `RoundResolved`).
7780
+ *
7781
+ * **Visitor mode**: not supported.
7782
+ *
7783
+ * **UI guidance**: see [UI Guide — `gamePickSubmitSelection`](../../docs/ui/gamepick/UIGuide_gamePickSubmitSelection.md).
7784
+ *
7785
+ * @param props.saw_template_id ID of the MatchX game template.
7786
+ * @param props.round Round object with `round_id` + `events[]`
7787
+ * carrying the user's score predictions.
7788
+ * @returns Wrapped {@link GamesApiResponse} with the updated round.
7789
+ *
7790
+ * @example
7791
+ * ```ts
7792
+ * const ar = await window._smartico.api.gamePickGetActiveRound({
7793
+ * saw_template_id: 1190,
7794
+ * round_id: 38665,
5758
7795
  * });
5759
- * ```
7796
+ * if (ar.errCode !== 0 || !ar.data) {
7797
+ * console.error('[smartico] could not fetch round to submit — show error and bounce back');
7798
+ * return;
7799
+ * }
5760
7800
  *
5761
- * **Visitor mode: not supported**
7801
+ * const round = ar.data;
7802
+ * round.events = round.events.map(e => ({
7803
+ * gp_event_id: e.gp_event_id,
7804
+ * team1_user_selection: 1,
7805
+ * team2_user_selection: 0,
7806
+ * }));
7807
+ *
7808
+ * const r = await window._smartico.api.gamePickSubmitSelection({
7809
+ * saw_template_id: 1190,
7810
+ * round,
7811
+ * });
7812
+ *
7813
+ * switch (r.errCode) {
7814
+ * case 0:
7815
+ * console.log('[smartico] predictions saved — show confirmation, refresh leaderboard');
7816
+ * break;
7817
+ * case 3:
7818
+ * console.log('[smartico] nothing changed (or all events closed) — silent no-op');
7819
+ * break;
7820
+ * case 40001:
7821
+ * case 40003:
7822
+ * case 40011:
7823
+ * case 40012:
7824
+ * console.error('[smartico] insufficient balance / spins — show top-up CTA:', r.errMessage);
7825
+ * break;
7826
+ * default:
7827
+ * console.error('[smartico] submit failed — show generic error toast:', r.errMessage);
7828
+ * }
7829
+ * ```
5762
7830
  */
5763
7831
  async gamePickSubmitSelection(props) {
5764
7832
  var _props$round;
@@ -5771,42 +7839,83 @@ class WSAPIGamePick extends WSAPIAvatars {
5771
7839
  return this.api.gpSubmitSelection(props.saw_template_id, props.round, false);
5772
7840
  }
5773
7841
  /**
5774
- * Submits answers for a round in a Quiz game.
5775
- * Sends the round object with user answers for all events at once.
5776
- * Each event must include `user_selection` with the answer value (e.g. '1', '2', 'x', 'yes', 'no' — depending on the market type).
5777
- * If the user hasn't placed bets before, one game attempt (spin) will be consumed.
5778
- * Answers can be edited until each match starts (if `allow_edit_answers` is enabled on the round).
5779
- *
5780
- * @param props.saw_template_id - The ID of the Quiz game template
5781
- * @param props.round - Round object containing `round_id` and `events[]`. Typically obtained from `gamePickGetActiveRound`
5782
- * and modified with user answers. Each event needs: `gp_event_id`, `user_selection`
5783
- *
5784
- * **Response** `GamesApiResponse<GamePickRound>`:
5785
- * - `errCode` - 0 on success. Non-zero codes indicate errors (e.g. not enough points/attempts)
5786
- * - `data` - Updated round with all events reflecting the submitted answers.
5787
- * `user_placed_bet` will be `true`, `has_not_submitted_changes` will be `false`
5788
- *
5789
- * **Example**:
5790
- * ```
5791
- * _smartico.api.gamePickGetActiveRound({
5792
- * saw_template_id: 1183,
5793
- * round_id: 37974,
5794
- * }).then((roundData) => {
5795
- * const round = roundData.data;
5796
- * round.events = round.events.map(e => ({
5797
- * gp_event_id: e.gp_event_id,
5798
- * user_selection: 'x',
5799
- * }));
5800
- * _smartico.api.gamePickSubmitSelectionQuiz({
5801
- * saw_template_id: 1183,
5802
- * round: round,
5803
- * }).then((result) => {
5804
- * console.log(result.data.user_placed_bet); // true
5805
- * });
7842
+ * Submits all quiz answers for a round in one shot. Each event in the round
7843
+ * must carry `user_selection` (the answer value — typically `"1"` / `"2"` /
7844
+ * `"x"` for 1×2 markets, `"yes"` / `"no"` for binary markets, or any
7845
+ * operator-defined string for custom markets).
7846
+ *
7847
+ * Same first-submit buy-in behavior as {@link gamePickSubmitSelection} — one
7848
+ * buy-in is charged on the first successful submit; subsequent edits within
7849
+ * the same round are free.
7850
+ *
7851
+ * @remarks
7852
+ * **Preconditions**
7853
+ * - User must be authenticated. Visitor mode not supported.
7854
+ * - `saw_template_id` and `props.round.round_id` are mandatory — SDK throws if
7855
+ * either is missing.
7856
+ * - Each event must include `gp_event_id` and `user_selection`. Missing
7857
+ * events default to "no change".
7858
+ *
7859
+ * **Error codes** (in `errCode`)
7860
+ * - `0` — success.
7861
+ * - `3` (`NoBetsUpdatedOnSubmit`) — no changes, OR every event past
7862
+ * `last_bet_date`. Buy-in NOT consumed; current round returned in `data`.
7863
+ * - `4` — round / event not found.
7864
+ * - `100002` — template not found.
7865
+ * - `100000` — auth hash invalid.
7866
+ * - `100004` — generic server error.
7867
+ *
7868
+ * Buy-in failures use the same {@link SAWSpinErrorCode} pass-through values
7869
+ * as {@link gamePickSubmitSelection} — see that method's TSDoc for the
7870
+ * `40001` / `40003` / `40004` / `40007` / `40009` / `40011` / `40012`
7871
+ * semantics.
7872
+ *
7873
+ * **Idempotency**: identical to {@link gamePickSubmitSelection} — re-submit
7874
+ * returns `errCode: 3` and never double-charges the buy-in.
7875
+ *
7876
+ * **Side effects**: identical to {@link gamePickSubmitSelection}, with the
7877
+ * reported event being `minigame_quiz_prediction` instead of
7878
+ * `minigame_matchx_prediction`.
7879
+ *
7880
+ * **Visitor mode**: not supported.
7881
+ *
7882
+ * **UI guidance**: see [UI Guide — `gamePickSubmitSelectionQuiz`](../../docs/ui/gamepick/UIGuide_gamePickSubmitSelectionQuiz.md).
7883
+ *
7884
+ * @param props.saw_template_id ID of the Quiz game template.
7885
+ * @param props.round Round object with `round_id` + `events[]`
7886
+ * carrying the user's answer selections.
7887
+ * @returns Wrapped {@link GamesApiResponse} with the updated round.
7888
+ *
7889
+ * @example
7890
+ * ```ts
7891
+ * const ar = await window._smartico.api.gamePickGetActiveRound({
7892
+ * saw_template_id: 1183,
7893
+ * round_id: 37974,
7894
+ * });
7895
+ * if (ar.errCode !== 0 || !ar.data) {
7896
+ * console.error('[smartico] could not fetch round to submit answers — show error');
7897
+ * return;
7898
+ * }
7899
+ *
7900
+ * const round = ar.data;
7901
+ * round.events = round.events.map(e => ({
7902
+ * gp_event_id: e.gp_event_id,
7903
+ * user_selection: 'x',
7904
+ * }));
7905
+ *
7906
+ * const r = await window._smartico.api.gamePickSubmitSelectionQuiz({
7907
+ * saw_template_id: 1183,
7908
+ * round,
5806
7909
  * });
5807
- * ```
5808
7910
  *
5809
- * **Visitor mode: not supported**
7911
+ * if (r.errCode === 0) {
7912
+ * console.log('[smartico] quiz answers saved — show confirmation');
7913
+ * } else if (r.errCode === 3) {
7914
+ * console.log('[smartico] nothing changed — silent no-op');
7915
+ * } else {
7916
+ * console.error('[smartico] quiz submit failed:', r.errMessage);
7917
+ * }
7918
+ * ```
5810
7919
  */
5811
7920
  async gamePickSubmitSelectionQuiz(props) {
5812
7921
  var _props$round2;
@@ -5819,35 +7928,51 @@ class WSAPIGamePick extends WSAPIAvatars {
5819
7928
  return this.api.gpSubmitSelection(props.saw_template_id, props.round, true);
5820
7929
  }
5821
7930
  /**
5822
- * Returns the current user's profile information within the specified MatchX or Quiz game.
5823
- * The user record is synced from the Smartico platform into the games DB (synced every 1 minute).
5824
- * If the user doesn't exist in the games DB yet, it will be created automatically on first call.
5825
- *
5826
- * @param props.saw_template_id - The ID of the MatchX or Quiz game template
5827
- *
5828
- * **Response** `GamesApiResponse<GamePickUserInfo>`:
5829
- * - `errCode` - 0 on success
5830
- * - `data`:
5831
- * - `ext_user_id` - External user ID (Smartico internal numeric ID)
5832
- * - `int_user_id` - Internal user ID within the games system
5833
- * - `public_username` - Display name
5834
- * - `avatar_url` - User's avatar image URL
5835
- * - `last_wallet_sync_time` - Last time the user's balance was synced from Smartico
5836
- * - `ach_points_balance` - User's current points balance
5837
- * - `ach_gems_balance` - User's current gems balance
5838
- * - `ach_diamonds_balance` - User's current diamonds balance
5839
- * - `pubic_username_set` - Whether the user has set a custom username
5840
- *
5841
- * **Example**:
5842
- * ```
5843
- * _smartico.api.gamePickGetUserInfo({
5844
- * saw_template_id: 1083,
5845
- * }).then((result) => {
5846
- * console.log(result.data.public_username, result.data.ach_points_balance);
5847
- * });
5848
- * ```
7931
+ * Returns the current user's profile within the Game Pick system — display
7932
+ * name, avatar, balances, and last wallet-sync timestamp. The Game Pick server
7933
+ * maintains its own user record that mirrors the user's Smartico balances; the
7934
+ * mirror is updated at most once per minute, so `last_wallet_sync_time` tells
7935
+ * the consumer how stale the balances on the response are.
5849
7936
  *
5850
- * **Visitor mode: not supported**
7937
+ * On the user's first call for a given game, the Game Pick server lazily
7938
+ * provisions a user record — so this method doubles as a "register the user
7939
+ * with this game" call.
7940
+ *
7941
+ * @remarks
7942
+ * **Preconditions**
7943
+ * - User must be authenticated. Visitor mode not supported.
7944
+ *
7945
+ * **Balance freshness**
7946
+ * The balances returned here are the cached mirror — at most ~1 minute stale.
7947
+ * For an up-to-the-second view of Points / Gems / Diamonds, read from
7948
+ * {@link getUserProfile} instead. Use this method's balances only for
7949
+ * in-Game-Pick display.
7950
+ *
7951
+ * **Error codes** (in `errCode`)
7952
+ * - `0` — success.
7953
+ * - `100002` — template not found.
7954
+ * - `100000` — auth hash invalid.
7955
+ * - `100004` — generic server error.
7956
+ *
7957
+ * **Refresh**
7958
+ * - No cache. Server-side mirror refreshes at most every 60 s.
7959
+ * - No push subscription.
7960
+ *
7961
+ * **Visitor mode**: not supported.
7962
+ *
7963
+ * **UI guidance**: see [UI Guide — `gamePickGetUserInfo`](../../docs/ui/gamepick/UIGuide_gamePickGetUserInfo.md).
7964
+ *
7965
+ * @param props.saw_template_id ID of the MatchX or Quiz game template.
7966
+ * @returns Wrapped {@link GamesApiResponse} of {@link GamePickUserInfo}.
7967
+ *
7968
+ * @example
7969
+ * ```ts
7970
+ * const r = await window._smartico.api.gamePickGetUserInfo({ saw_template_id: 1083 });
7971
+ *
7972
+ * if (r.errCode === 0 && r.data) {
7973
+ * console.log('[smartico] render Game Pick header — name:', r.data.public_username, '— points:', r.data.ach_points_balance, '— synced:', r.data.last_wallet_sync_time);
7974
+ * }
7975
+ * ```
5851
7976
  */
5852
7977
  async gamePickGetUserInfo(props) {
5853
7978
  if (!props.saw_template_id) {
@@ -5856,38 +7981,56 @@ class WSAPIGamePick extends WSAPIAvatars {
5856
7981
  return this.api.gpGetUserInfo(props.saw_template_id);
5857
7982
  }
5858
7983
  /**
5859
- * Returns the game configuration and the list of all rounds for the specified MatchX or Quiz game.
5860
- * Includes the SAW template definition, label settings, and round metadata (without events).
5861
- *
5862
- * @param props.saw_template_id - The ID of the MatchX or Quiz game template
5863
- *
5864
- * **Response** `GamesApiResponse<GamePickGameInfo>`:
5865
- * - `errCode` - 0 on success
5866
- * - `data`:
5867
- * - `sawTemplate` - Game template configuration including:
5868
- * - `saw_template_id`, `saw_game_type_id` (6 = MatchX/Quiz)
5869
- * - `saw_template_ui_definition` - UI settings (name, ranking options, ask_for_username, etc.)
5870
- * - `saw_buyin_type_id` - Cost type (1=Free, 2=Points, 3=Gems, 4=Diamonds, 5=Spins)
5871
- * - `buyin_cost_points` - Cost per attempt
5872
- * - `spin_count` - Available attempts for the current user
5873
- * - `allRounds[]` - List of all rounds (metadata only, no events), each with:
5874
- * - `round_id`, `round_name`, `round_description`
5875
- * - `open_date`, `last_bet_date` - Timestamps (ms)
5876
- * - `is_active_now`, `is_resolved`, `round_status_id`
5877
- * - `labelInfo` - Label/brand configuration and settings
5878
- *
5879
- * **Example**:
5880
- * ```
5881
- * _smartico.api.gamePickGetGameInfo({
5882
- * saw_template_id: 1189,
5883
- * }).then((result) => {
5884
- * console.log(result.data.sawTemplate.saw_template_ui_definition.name);
5885
- * console.log('Rounds:', result.data.allRounds.length);
5886
- * console.log('Buy-in type:', result.data.sawTemplate.saw_buyin_type_id);
5887
- * });
5888
- * ```
7984
+ * Returns the game template configuration plus a metadata listing of every
7985
+ * round (without events). Use to power the game's welcome / lobby screen —
7986
+ * shows the template name, buy-in cost, the user's remaining attempts, and
7987
+ * the full round list.
5889
7988
  *
5890
- * **Visitor mode: not supported**
7989
+ * The `allRounds[]` here is a lightweight metadata-only view — to render
7990
+ * predictions or leaderboards, call {@link gamePickGetActiveRound} /
7991
+ * {@link gamePickGetActiveRounds} / {@link gamePickGetBoard} for the rounds
7992
+ * the user actually opens.
7993
+ *
7994
+ * @remarks
7995
+ * **Preconditions**
7996
+ * - User must be authenticated. Visitor mode not supported.
7997
+ *
7998
+ * **Buy-in semantics**
7999
+ * The `sawTemplate.saw_buyin_type_id` value determines which currency is
8000
+ * deducted on the user's first prediction in any round:
8001
+ * - Free — no deduction.
8002
+ * - Points — `buyin_cost_points` deducted from the user's points balance.
8003
+ * - Gems — deducted from the user's gems balance.
8004
+ * - Diamonds — deducted from the user's diamonds balance.
8005
+ * - Spins — one spin counted from `spin_count`.
8006
+ *
8007
+ * **Error codes** (in `errCode`)
8008
+ * - `0` — success.
8009
+ * - `100002` — template not found.
8010
+ * - `100000` — auth hash invalid.
8011
+ * - `100004` — generic server error.
8012
+ *
8013
+ * **Refresh**
8014
+ * - No cache.
8015
+ * - No push subscription. Re-call after a successful
8016
+ * {@link gamePickSubmitSelection} to refresh `spin_count`.
8017
+ *
8018
+ * **Visitor mode**: not supported.
8019
+ *
8020
+ * **UI guidance**: see [UI Guide — `gamePickGetGameInfo`](../../docs/ui/gamepick/UIGuide_gamePickGetGameInfo.md).
8021
+ *
8022
+ * @param props.saw_template_id ID of the MatchX or Quiz game template.
8023
+ * @returns Wrapped {@link GamesApiResponse} of {@link GamePickGameInfo}.
8024
+ *
8025
+ * @example
8026
+ * ```ts
8027
+ * const r = await window._smartico.api.gamePickGetGameInfo({ saw_template_id: 1189 });
8028
+ *
8029
+ * if (r.errCode === 0 && r.data) {
8030
+ * console.log('[smartico] render Game Pick lobby — title:', r.data.sawTemplate.saw_template_ui_definition.name);
8031
+ * console.log('[smartico] rounds available:', r.data.allRounds.length, '— buy-in type:', r.data.sawTemplate.saw_buyin_type_id, 'cost:', r.data.sawTemplate.buyin_cost_points);
8032
+ * }
8033
+ * ```
5891
8034
  */
5892
8035
  async gamePickGetGameInfo(props) {
5893
8036
  if (!props.saw_template_id) {
@@ -5896,35 +8039,73 @@ class WSAPIGamePick extends WSAPIAvatars {
5896
8039
  return this.api.gpGetGameInfo(props.saw_template_id);
5897
8040
  }
5898
8041
  /**
5899
- * Returns round data with events and picks for a specific user (identified by their internal user ID).
5900
- * Useful for viewing another user's predictions from the leaderboard.
5901
- * The `int_user_id` can be obtained from the `gamePickGetBoard` response (`users[].int_user_id`).
5902
- *
5903
- * @param props.saw_template_id - The ID of the MatchX or Quiz game template
5904
- * @param props.round_id - The round to get info for
5905
- * @param props.int_user_id - Internal user ID of the player whose predictions to view (from leaderboard data)
5906
- *
5907
- * **Response** `GamesApiResponse<GamePickRound>`:
5908
- * - `errCode` - 0 on success
5909
- * - `data` - Round object with the target user's selections.
5910
- * Same structure as `gamePickGetActiveRound`, but `user_selection`/`team1_user_selection`/`team2_user_selection`
5911
- * fields on events reflect the specified user's picks instead of the current user's.
5912
- * Events also include `resolution_type_id` (0=None, 2=Lost, 3=PartialWin, 4=FullWin) showing how each prediction was scored
5913
- *
5914
- * **Example**:
5915
- * ```
5916
- * _smartico.api.gamePickGetRoundInfoForUser({
5917
- * saw_template_id: 1083,
5918
- * round_id: 31652,
5919
- * int_user_id: 65653810,
5920
- * }).then((result) => {
5921
- * result.data.events.forEach(e => {
5922
- * console.log(e.event_meta.team1_name, 'vs', e.event_meta.team2_name, '→', e.user_selection);
5923
- * });
8042
+ * Returns a round with another player's predictions instead of the current
8043
+ * user's. The target player is identified by `int_user_id` (the Game Pick
8044
+ * system's internal user ID, obtained from {@link gamePickGetBoard}'s
8045
+ * `users[].int_user_id`).
8046
+ *
8047
+ * Use to power "view this player's picks" affordances opened from leaderboard
8048
+ * rows — community / social inspection of how a top-ranked user predicted.
8049
+ *
8050
+ * @remarks
8051
+ * **Preconditions**
8052
+ * - User must be authenticated. Visitor mode not supported.
8053
+ * - `saw_template_id`, `round_id`, and `int_user_id` are all mandatory — SDK
8054
+ * throws synchronously if any is missing.
8055
+ * - `int_user_id` must come from a leaderboard fetch in the same game
8056
+ * template; it is stable within a template but not portable across
8057
+ * templates.
8058
+ *
8059
+ * **Shape vs `gamePickGetActiveRound`**
8060
+ * Same {@link GamePickRound} structure, but `user_selection` /
8061
+ * `team1_user_selection` / `team2_user_selection` reflect the TARGET user's
8062
+ * predictions instead of the caller's. Each event still carries its own
8063
+ * `resolution_type_id` (see {@link GamePickResolutionType}) so the UI can
8064
+ * render result badges per pick.
8065
+ *
8066
+ * **Error codes** (in `errCode`)
8067
+ * - `0` — success.
8068
+ * - `4` — round / event / user not found.
8069
+ * - `100002` — template not found.
8070
+ * - `100000` — auth hash invalid.
8071
+ * - `100004` — generic server error.
8072
+ *
8073
+ * **Refresh**
8074
+ * - No cache. Re-call when opening a different leaderboard row's
8075
+ * "view picks" modal.
8076
+ * - No push subscription.
8077
+ *
8078
+ * **Visitor mode**: not supported.
8079
+ *
8080
+ * **UI guidance**: see [UI Guide — `gamePickGetRoundInfoForUser`](../../docs/ui/gamepick/UIGuide_gamePickGetRoundInfoForUser.md).
8081
+ *
8082
+ * @param props.saw_template_id ID of the MatchX or Quiz game template.
8083
+ * @param props.round_id ID of the round to inspect.
8084
+ * @param props.int_user_id Internal user ID from
8085
+ * `gamePickGetBoard.users[].int_user_id`.
8086
+ * @returns Wrapped {@link GamesApiResponse} with the target user's
8087
+ * {@link GamePickRound}.
8088
+ *
8089
+ * @example
8090
+ * ```ts
8091
+ * const board = await window._smartico.api.gamePickGetBoard({
8092
+ * saw_template_id: 1083, round_id: 31652,
5924
8093
  * });
5925
- * ```
8094
+ * const topPlayer = board.data?.users?.[0];
8095
+ * if (!topPlayer) return;
5926
8096
  *
5927
- * **Visitor mode: not supported**
8097
+ * const r = await window._smartico.api.gamePickGetRoundInfoForUser({
8098
+ * saw_template_id: 1083,
8099
+ * round_id: 31652,
8100
+ * int_user_id: topPlayer.int_user_id,
8101
+ * });
8102
+ *
8103
+ * if (r.errCode === 0 && r.data) {
8104
+ * for (const ev of r.data.events) {
8105
+ * console.log('[smartico] render row —', ev.event_meta.team1_name, 'vs', ev.event_meta.team2_name, '— picked:', ev.user_selection, '— resolution:', ev.resolution_type_id);
8106
+ * }
8107
+ * }
8108
+ * ```
5928
8109
  */
5929
8110
  async gamePickGetRoundInfoForUser(props) {
5930
8111
  if (!props.saw_template_id) {
@@ -5943,21 +8124,135 @@ class WSAPIGamePick extends WSAPIAvatars {
5943
8124
  /** @group LeaderBoard */
5944
8125
  class WSAPILeaderBoard extends WSAPIGamePick {
5945
8126
  /**
5946
- * Returns the leaderboard for the current type (default is Daily). If getPreviousPeriod is passed as true, a leaderboard for the previous period for the current type will be returned.
5947
- * For example, if the type is Weekly and getPreviousPeriod is true, a leaderboard for the previous week will be returned.
8127
+ * Returns the operator-configured standalone leaderboard for the
8128
+ * given period type — top-20 ranked entries, the current user's
8129
+ * own entry (when authenticated), and the configured prize table.
8130
+ * Use this to power a leaderboard page with daily / weekly /
8131
+ * monthly tabs.
5948
8132
  *
5949
- * **Example**:
5950
- * ```
5951
- * _smartico.api.getLeaderBoard(1).then((result) => {
5952
- * console.log(result);
5953
- * });
5954
- * ```
8133
+ * The leaderboard for each period type is configured separately by
8134
+ * the operator. A label may have any combination of DAILY, WEEKLY,
8135
+ * and MONTHLY boards configured (or none).
5955
8136
  *
5956
- * **Example in the Visitor mode**:
5957
- * ```
5958
- * _smartico.vapi('EN').getLeaderBoard(1).then((result) => {
5959
- * console.log(result);
5960
- * });
8137
+ * @remarks
8138
+ * **Return value note** — the runtime may return `undefined` if no
8139
+ * board is configured for the requested `periodType`, despite the
8140
+ * static return type being `Promise<LeaderBoardDetailsT>`. Defend
8141
+ * against that case in consumer code.
8142
+ *
8143
+ * **Preconditions**
8144
+ * Pass a `periodType` from {@link LeaderBoardPeriodType}
8145
+ * (`DAILY = 1`, `WEEKLY = 2`, `MONTHLY = 3`). Pass
8146
+ * `getPreviousPeriod: true` to fetch the most-recently-ended
8147
+ * period's snapshot (yesterday's results, last week's results,
8148
+ * last month's results) instead of the current live period. The
8149
+ * SDK only exposes one period back — older snapshots are not
8150
+ * reachable through this method.
8151
+ *
8152
+ * **Top-20 cap**
8153
+ * The server hard-caps `users[]` at 20 entries, ordered by
8154
+ * `position` ASC. Position values are server-computed (DENSE_RANK
8155
+ * over all participants); the truncation at 20 is for transport
8156
+ * size only — `position` may exceed 20 elsewhere.
8157
+ *
8158
+ * **The `me` field**
8159
+ * Always populated for authenticated users (even when they have
8160
+ * zero points in the period). `me.position === -1` is the signal
8161
+ * that the user is active but ranked outside the top 20 (or has no
8162
+ * activity yet). `me` is `undefined` for visitor-mode sessions.
8163
+ *
8164
+ * **Rewards are points only**
8165
+ * `rewards[].points` are gamification points credited to the user's
8166
+ * balance when the period finalizes. The leaderboard never awards
8167
+ * gems, diamonds, store items, or bonuses. The first element of
8168
+ * the array is the prize for place 1, the second for place 2, and
8169
+ * so on. The array length is the number of paid places.
8170
+ *
8171
+ * **Cache TTL — single shared key (known limitation)**
8172
+ * The SDK caches the response for 30 seconds under a SINGLE shared
8173
+ * key — calling `getLeaderBoard(DAILY)` followed by
8174
+ * `getLeaderBoard(WEEKLY)` within the same 30 s window returns the
8175
+ * cached DAILY result for the WEEKLY call. Same applies to
8176
+ * switching `getPreviousPeriod`. To force a fresh fetch when
8177
+ * switching periods or current/previous, call
8178
+ * `_smartico.api.clearCaches()` before the second call, or simply
8179
+ * wait out the TTL.
8180
+ *
8181
+ * **Period boundaries**
8182
+ * The server finalizes each period on a server-configurable
8183
+ * schedule: DAILY at midnight + operator-defined offset; WEEKLY
8184
+ * at the start of Monday; MONTHLY on the 1st of each month. At
8185
+ * finalization, the server distributes the configured `rewards[]`
8186
+ * points to the top placeholders and resets the live board. After
8187
+ * finalization, `getLeaderBoard(periodType, false)` returns the
8188
+ * NEW (empty) period's board; call with
8189
+ * `getPreviousPeriod: true` to see the just-ended standings.
8190
+ *
8191
+ * **Refresh model**
8192
+ * - One-shot fetch (no subscription).
8193
+ * - No push event refreshes the cache; finalization at the period
8194
+ * boundary is NOT pushed to the client.
8195
+ * - Poll manually if the consumer needs near-live state during an
8196
+ * in-progress period.
8197
+ *
8198
+ * **Idempotency / Side effects**: safe. Read-only.
8199
+ *
8200
+ * **UI guidance**: see [UI Guide — `getLeaderBoard`](../../docs/ui/leaderboard/UIGuide_getLeaderBoard.md).
8201
+ *
8202
+ * **Visitor mode**: supported. The same shape is returned, scoped
8203
+ * to the brand's public leaderboard. `me` is `undefined` for
8204
+ * visitors.
8205
+ *
8206
+ * @param periodType The board's period type
8207
+ * ({@link LeaderBoardPeriodType}).
8208
+ * Selects which pre-configured board to
8209
+ * fetch; the board itself is bound to one
8210
+ * period by the operator.
8211
+ * @param getPreviousPeriod When `true`, returns the most recent
8212
+ * finalized snapshot for that period type
8213
+ * (e.g. last week's results). Defaults to
8214
+ * `false` (current in-progress period).
8215
+ * @returns Promise resolving to `LeaderBoardDetailsT`.
8216
+ * **At runtime, may resolve to `undefined`**
8217
+ * when no board is configured for the
8218
+ * requested period type — guard against it.
8219
+ *
8220
+ * @example
8221
+ * ```ts
8222
+ * import { LeaderBoardPeriodType } from '@smartico/public-api';
8223
+ *
8224
+ * const board = await window._smartico.api.getLeaderBoard(LeaderBoardPeriodType.WEEKLY);
8225
+ *
8226
+ * if (!board) {
8227
+ * console.log('[smartico] no weekly board configured for this label — hide the leaderboard surface');
8228
+ * return;
8229
+ * }
8230
+ *
8231
+ * console.log('[smartico] render leaderboard tab —', board.name, '—', board.users.length, 'ranked entries (top 20 max)');
8232
+ *
8233
+ * // Render prize table.
8234
+ * for (const reward of board.rewards) {
8235
+ * console.log('[smartico] prize row — place', reward.place, '→', reward.points, 'points');
8236
+ * }
8237
+ *
8238
+ * // "Me" panel — sticky row showing the current user's rank.
8239
+ * if (board.me) {
8240
+ * if (board.me.position === -1) {
8241
+ * console.log('[smartico] user is unranked — show "You are unranked, earn points to enter the leaderboard"');
8242
+ * } else if (board.me.position > 20) {
8243
+ * console.log('[smartico] user is ranked', board.me.position, 'but outside the visible top-20 — show sticky "me" row with', board.me.points, 'points');
8244
+ * } else {
8245
+ * console.log('[smartico] user is in the top 20 at position', board.me.position, '— highlight their row in the main list');
8246
+ * }
8247
+ * }
8248
+ *
8249
+ * // Switch to previous period view — but bust the cache first to avoid the shared-key collision.
8250
+ * await window._smartico.api.clearCaches();
8251
+ * const prev = await window._smartico.api.getLeaderBoard(LeaderBoardPeriodType.WEEKLY, true);
8252
+ * console.log('[smartico] previous-week standings — render with greyed-out "ended" treatment:', prev?.users.length, 'finalists');
8253
+ *
8254
+ * // Visitor-mode equivalent — me is always undefined.
8255
+ * // const visitorBoard = await window._smartico.vapi('EN').getLeaderBoard(LeaderBoardPeriodType.DAILY);
5961
8256
  * ```
5962
8257
  */
5963
8258
  async getLeaderBoard(periodType, getPreviousPeriod) {
@@ -5968,23 +8263,49 @@ class WSAPILeaderBoard extends WSAPIGamePick {
5968
8263
  /** @group Inbox */
5969
8264
  class WSAPIInbox extends WSAPILeaderBoard {
5970
8265
  /**
5971
- * Reports an impression event for an engagement (when engagement content is displayed to the user).
5972
- * Use this method to track when users view engagement content such as inbox messages, popups.
5973
- * When using for Inbox cases, you need to use message guid as engagement_uid, and pass 31 as activityType.
8266
+ * Records that an engagement (inbox message, popup) was displayed to
8267
+ * the user. Use this to drive engagement analytics — every visible
8268
+ * inbox message should fire one impression event per render
8269
+ * occurrence, and every popup display should fire one.
5974
8270
  *
5975
- * **Example**:
5976
- * ```
5977
- * _smartico.api.reportImpressionEvent({
5978
- * engagement_uid: 'abc123-def456',
5979
- * activityType: 31 // Inbox
5980
- * });
5981
- * ```
8271
+ * **Fire-and-forget**: the call is asynchronous and one-way — there
8272
+ * is no response promise to await and no error reporting. The SDK
8273
+ * swallows transport failures silently. Returns `void`.
5982
8274
  *
5983
- * **Visitor mode: not supported**
8275
+ * @remarks
8276
+ * **When to call**
8277
+ * - Inbox: when a message becomes visible (the user opens / scrolls
8278
+ * it into view). The default Smartico UI fires this when the
8279
+ * message detail expands, alongside
8280
+ * {@link markInboxMessageAsRead}.
8281
+ * - Popup: when the popup content is shown to the user.
8282
+ *
8283
+ * **Activity types**
8284
+ * Pass {@link ActivityTypeLimited.Inbox} (`31`) for inbox messages,
8285
+ * {@link ActivityTypeLimited.Popup} (`30`) for popups. Other values
8286
+ * are not used by the engagement-impression channel.
8287
+ *
8288
+ * **Idempotency**: the server records every impression event —
8289
+ * repeated calls add to the impression count. Don't fire it on
8290
+ * every re-render; fire it once per logical "display" event
8291
+ * (modal open, list-row scroll-into-view, popup show).
8292
+ *
8293
+ * **Side effects**: server-side increments the engagement's
8294
+ * `impression_count` and updates `last_impression_date`. The
8295
+ * counter is observable via operator analytics; the SDK consumer
8296
+ * receives no signal back.
8297
+ *
8298
+ * **Visitor mode**: not supported.
5984
8299
  *
5985
- * @param params - Event parameters
5986
- * @param params.engagement_uid - Unique identifier for the engagement
5987
- * @param params.activityType - Type of engagement activity (Popup=30, Inbox=31)
8300
+ * @example
8301
+ * ```ts
8302
+ * // When the user opens an inbox message in the detail view.
8303
+ * window._smartico.api.reportImpressionEvent({
8304
+ * engagement_uid: message.message_guid,
8305
+ * activityType: 31, // ActivityTypeLimited.Inbox
8306
+ * });
8307
+ * console.log('[smartico] inbox impression reported for', message.message_guid, '— no response to await, fire-and-forget');
8308
+ * ```
5988
8309
  */
5989
8310
  reportImpressionEvent({
5990
8311
  engagement_uid,
@@ -5993,25 +8314,54 @@ class WSAPIInbox extends WSAPILeaderBoard {
5993
8314
  this.api.reportEngagementImpression(this.userExtId, engagement_uid, activityType);
5994
8315
  }
5995
8316
  /**
5996
- * Reports a click/action event for an engagement (when user interacts with engagement content).
5997
- * Use this method to track when users click on or interact with engagement content such as inbox messages, popups.
5998
- * When using for Inbox cases, you need to use message guid as engagement_uid, and pass 31 as activityType, and pass the action/deeplink that was triggered by the user interaction as action.
8317
+ * Records that the user interacted with an engagement — typically
8318
+ * tapping a CTA button, following a deep-link, or clicking a popup
8319
+ * action. Use this to drive engagement analytics on what users
8320
+ * actually act on (vs what they merely see —
8321
+ * {@link reportImpressionEvent}).
5999
8322
  *
6000
- * **Example**:
6001
- * ```
6002
- * _smartico.api.reportClickEvent({
6003
- * engagement_uid: 'abc123-def456',
6004
- * activityType: 31 // Inbox
6005
- * action: 'dp:gf_missions'
6006
- * });
6007
- * ```
8323
+ * **Fire-and-forget**: the call is asynchronous and one-way — there
8324
+ * is no response promise to await and no error reporting. The SDK
8325
+ * swallows transport failures silently. Returns `void`.
6008
8326
  *
6009
- * **Visitor mode: not supported**
8327
+ * @remarks
8328
+ * **When to call**
8329
+ * - Inbox: when the user taps a CTA button on a message or follows
8330
+ * a deep-link inside the message body. Pass the deep-link or URL
8331
+ * as `action`.
8332
+ * - Popup: when the user clicks a popup action button.
8333
+ *
8334
+ * **Activity types**
8335
+ * Pass {@link ActivityTypeLimited.Inbox} (`31`) for inbox,
8336
+ * {@link ActivityTypeLimited.Popup} (`30`) for popups.
8337
+ *
8338
+ * **`action` payload**
8339
+ * Pass the deep-link or URL that the user triggered (e.g.
8340
+ * `'dp:gf_missions'`, `'https://example.com/promo'`). The SDK
8341
+ * forwards the string to the server for analytics — it does not
8342
+ * execute the deep-link. To execute deep-links safely, call
8343
+ * `_smartico.dp(action)` separately.
8344
+ *
8345
+ * **Idempotency**: the server records every click event —
8346
+ * repeated calls add to the count. Fire once per logical user
8347
+ * action.
8348
+ *
8349
+ * **Side effects**: server-side updates the engagement's
8350
+ * `last_action` field; observable via operator analytics. The SDK
8351
+ * consumer receives no signal back.
6010
8352
  *
6011
- * @param params - Event parameters
6012
- * @param params.engagement_uid - Unique identifier for the engagement
6013
- * @param params.activityType - Type of engagement activity (Popup=30, Inbox=31)
6014
- * @param params.action - Optional action/deeplink that was triggered by the user interaction
8353
+ * **Visitor mode**: not supported.
8354
+ *
8355
+ * @example
8356
+ * ```ts
8357
+ * // When the user taps a CTA button in an inbox message.
8358
+ * window._smartico.api.reportClickEvent({
8359
+ * engagement_uid: message.message_guid,
8360
+ * activityType: 31, // ActivityTypeLimited.Inbox
8361
+ * action: 'dp:gf_missions',
8362
+ * });
8363
+ * window._smartico.dp('dp:gf_missions'); // separately execute the deep-link
8364
+ * ```
6015
8365
  */
6016
8366
  reportClickEvent({
6017
8367
  engagement_uid,
@@ -6020,19 +8370,118 @@ class WSAPIInbox extends WSAPILeaderBoard {
6020
8370
  }) {
6021
8371
  this.api.reportEngagementAction(this.userExtId, engagement_uid, activityType, action);
6022
8372
  }
6023
- /** Returns inbox messages based on the provided parameters. "From" and "to" indicate the range of messages to be fetched.
6024
- * The maximum number of messages per request is limited to 20.
6025
- * An indicator "onlyFavorite" can be passed to get only messages marked as favorites.
6026
- * An indicator "read_status" can be passed to get only messages marked as read or unread.
6027
- * You can leave this params empty and by default it will return list of messages ranging from 0 to 20.
6028
- * This function returns a list of messages without the body of each message.
6029
- * To get the body of the message you need to call getInboxMessageBody function and pass the message guid contained in each message of this request.
6030
- * All other action like mark as read, favorite, delete, etc. can be done using this message GUID.
6031
- * The "onUpdate" callback will be triggered when the user receives a new message. It will provide an updated list of messages, ranging from 0 to 20, to the onUpdate callback function.
8373
+ /**
8374
+ * Returns the user's inbox messages — newest first — with optional
8375
+ * filtering by category, favorite status, and read state. Each
8376
+ * `TInboxMessage` is a lightweight envelope (`message_guid`,
8377
+ * `sent_date`, `read`, `favorite`, `category_id`, `expire_on_dt`);
8378
+ * fetch the rich body (title, preview, icon, html_body, buttons)
8379
+ * separately via {@link getInboxMessageBody}.
6032
8380
  *
6033
- * **Visitor mode: not supported**
8381
+ * Use this to power an inbox list screen. Subscribe via `onUpdate`
8382
+ * to react to newly-arrived messages pushed by the server (from
8383
+ * campaigns, automation rules, manual operator sends).
8384
+ *
8385
+ * @remarks
8386
+ * **Subscription model (`onUpdate`)**
8387
+ * The callback receives the FULL refreshed message list (never a
8388
+ * diff/patch). Each subsequent call to `getInboxMessages({ onUpdate })`
8389
+ * REPLACES the prior callback. Pass `onUpdate: undefined` (or omit
8390
+ * it) to keep the prior callback in place; the callback is never
8391
+ * auto-cleared.
8392
+ *
8393
+ * **Update triggers** — the callback fires ONLY when:
8394
+ *
8395
+ * 1. A new message is pushed by the server (campaign / automation /
8396
+ * operator send). The refreshed list includes the new message
8397
+ * at the top.
8398
+ *
8399
+ * Does NOT fire for: `markInboxMessageAsRead`,
8400
+ * `markAllInboxMessagesAsRead`,
8401
+ * `markUnmarkInboxMessageAsFavorite`, `deleteInboxMessage`,
8402
+ * `deleteAllInboxMessages`. After a mutation, re-call
8403
+ * `getInboxMessages` manually if your UI needs the refreshed list
8404
+ * — or maintain optimistic state locally.
8405
+ *
8406
+ * **Pagination**
8407
+ * `from` (defaults to `0`) and `to` (defaults to `20`) define a
8408
+ * half-open range of message indices. The server caps the page at
8409
+ * **20 messages per request** — passing `to - from > 20` silently
8410
+ * truncates to 20. For "load more" pagination, advance `from` by
8411
+ * the prior page size on each subsequent call.
8412
+ *
8413
+ * **Filters**
8414
+ * All filters are ANDed server-side. Omitting a filter means "no
8415
+ * constraint" on that dimension:
8416
+ * - `categoryId` ({@link InboxCategories}): `General` (0),
8417
+ * `Platform` (1), `Personal` (2). Omit to get all categories.
8418
+ * - `onlyFavorite: true` returns only starred messages.
8419
+ * Omit / `false` returns all (starred and not).
8420
+ * - `read_status` ({@link InboxReadStatus}): `UnreadOnly` (1) or
8421
+ * `ReadOnly` (2). Omit to get both.
8422
+ *
8423
+ * **Server-side filtering** (always applied)
8424
+ * Expired messages (`expire_on_dt` in the past) and
8425
+ * soft-deleted messages are excluded server-side. Consumers do not
8426
+ * need to filter for these.
8427
+ *
8428
+ * **No client cache**: every call sends a fresh server round-trip.
8429
+ * To avoid redundant fetches in your UI, hold the result in
8430
+ * application state and re-fetch on `onUpdate` fires or explicit
8431
+ * user-driven refresh.
8432
+ *
8433
+ * **Idempotency / Side effects**: safe. Read-only.
8434
+ *
8435
+ * **UI guidance**: see [UI Guide — `getInboxMessages`](../../docs/ui/inbox/UIGuide_getInboxMessages.md).
8436
+ *
8437
+ * **Visitor mode**: not supported.
8438
+ *
8439
+ * @param params Optional filters + subscription.
8440
+ * @param params.from First message index (0-based). Defaults
8441
+ * to `0`.
8442
+ * @param params.to Last message index (exclusive).
8443
+ * Defaults to `20`. Server caps the page
8444
+ * at 20.
8445
+ * @param params.onlyFavorite When `true`, returns only favorite
8446
+ * (starred) messages.
8447
+ * @param params.categoryId When set, returns only messages in this
8448
+ * category ({@link InboxCategories}).
8449
+ * @param params.read_status When set, scopes to read or unread
8450
+ * only ({@link InboxReadStatus}).
8451
+ * @param params.onUpdate Callback invoked with the full
8452
+ * refreshed list when a new message
8453
+ * arrives.
8454
+ *
8455
+ * @returns Promise resolving to up to 20 `TInboxMessage` envelopes.
8456
+ * Empty array when the user has no messages matching the
8457
+ * filter.
8458
+ *
8459
+ * @example
8460
+ * ```ts
8461
+ * const messages = await window._smartico.api.getInboxMessages({
8462
+ * onUpdate: (refreshed) => {
8463
+ * console.log('[smartico] new inbox message arrived — re-render the list from this array, new message is at index 0:', refreshed);
8464
+ * },
8465
+ * });
6034
8466
  *
6035
- * @param params
8467
+ * // For each message, fetch its body for the list view (title, preview, icon).
8468
+ * for (const msg of messages) {
8469
+ * const body = await window._smartico.api.getInboxMessageBody(msg.message_guid);
8470
+ * console.log('[smartico] render message', msg.message_guid,
8471
+ * '— title:', body.title,
8472
+ * '— preview:', body.preview_body,
8473
+ * '— read:', msg.read,
8474
+ * '— favorite:', msg.favorite);
8475
+ * }
8476
+ *
8477
+ * // "Load more" pagination — advance from by the prior page size.
8478
+ * const page2 = await window._smartico.api.getInboxMessages({ from: 20, to: 40 });
8479
+ * console.log('[smartico] page 2:', page2.length, 'messages');
8480
+ *
8481
+ * // Filter examples.
8482
+ * const onlyStarred = await window._smartico.api.getInboxMessages({ onlyFavorite: true });
8483
+ * const onlyUnread = await window._smartico.api.getInboxMessages({ read_status: 1 }); // InboxReadStatus.UnreadOnly
8484
+ * ```
6036
8485
  */
6037
8486
  async getInboxMessages({
6038
8487
  from,
@@ -6048,10 +8497,53 @@ class WSAPIInbox extends WSAPILeaderBoard {
6048
8497
  return await this.api.getInboxMessagesT(this.userExtId, from, to, onlyFavorite, categoryId, read_status);
6049
8498
  }
6050
8499
  /**
6051
- * Returns inbox unread count.
8500
+ * Returns the user's current unread inbox message count — a single
8501
+ * integer suitable for driving a header badge. Optionally subscribe
8502
+ * to live updates via `onUpdate`.
6052
8503
  *
6053
- * **Visitor mode: not supported**
6054
- * @param params
8504
+ * For most UIs, prefer `core_inbox_unread_count` from
8505
+ * {@link getUserProfile} instead: it carries the same value, is
8506
+ * push-updated in real time via the user-properties channel, and
8507
+ * doesn't require a separate cache. This method is useful when you
8508
+ * want a dedicated subscription tied to the inbox surface rather
8509
+ * than the broader user-properties channel.
8510
+ *
8511
+ * @remarks
8512
+ * **Subscription model**
8513
+ * `onUpdate` fires whenever the cached value changes — either on a
8514
+ * push from the user-properties channel (new message arrival,
8515
+ * mark-as-read, delete) or after an inbox-list fetch that returns
8516
+ * a fresh count.
8517
+ *
8518
+ * **Cache TTL**: 30 seconds. The cached value is patched in place
8519
+ * by push events (no full re-fetch on every push), so the
8520
+ * `onUpdate` callback reflects server state with sub-second latency
8521
+ * regardless of the TTL.
8522
+ *
8523
+ * **Idempotency / Side effects**: safe. Read-only.
8524
+ *
8525
+ * **Visitor mode**: not supported.
8526
+ *
8527
+ * @param params Optional subscription bag.
8528
+ * @param params.onUpdate Callback invoked with the new unread
8529
+ * count whenever it changes (push-driven).
8530
+ * @returns Promise resolving to the current unread
8531
+ * count (integer, includes `0`).
8532
+ *
8533
+ * @example
8534
+ * ```ts
8535
+ * // Static read for an initial badge render.
8536
+ * const count = await window._smartico.api.getInboxUnreadCount();
8537
+ * console.log('[smartico] inbox badge initial count:', count);
8538
+ *
8539
+ * // Live subscription for badge updates.
8540
+ * await window._smartico.api.getInboxUnreadCount({
8541
+ * onUpdate: (newCount) => {
8542
+ * console.log('[smartico] inbox count changed — update the badge to:', newCount,
8543
+ * '— hide badge entirely when 0, show raw integer otherwise (no "99+" cap in the default UI)');
8544
+ * },
8545
+ * });
8546
+ * ```
6055
8547
  */
6056
8548
  async getInboxUnreadCount({
6057
8549
  onUpdate
@@ -6062,17 +8554,113 @@ class WSAPIInbox extends WSAPILeaderBoard {
6062
8554
  return OCache.use(onUpdateContextKey.InboxUnreadCount, ECacheContext.WSAPI, () => this.api.getInboxUnreadCountT(this.userExtId), CACHE_DATA_SEC);
6063
8555
  }
6064
8556
  /**
6065
- * Returns the message body of the specified message guid.
8557
+ * Returns the rich body of a single inbox message — title, preview
8558
+ * text, icon, click action, optional rich HTML body, and optional
8559
+ * buttons. Call this after fetching the envelope list via
8560
+ * {@link getInboxMessages} to render either a list-item preview or
8561
+ * a full detail view.
8562
+ *
8563
+ * The message body is served from a CDN — not over the WebSocket —
8564
+ * so latency depends on CDN proximity rather than WS round-trip
8565
+ * time. There is NO client-side cache; every call is a fresh
8566
+ * HTTP fetch. Browser HTTP caching applies (Cache-Control headers
8567
+ * from the CDN), but the SDK does not memoize the result.
6066
8568
  *
6067
- * **Visitor mode: not supported**
8569
+ * @remarks
8570
+ * **Rich vs simple messages**
8571
+ * The shape of the returned body branches on the `action` field:
8572
+ * - When `action === 'dp:inbox'`, the message has a rich HTML body
8573
+ * (`html_body`) and may have up to 2 action `buttons`. Use these
8574
+ * for a full-detail rendering.
8575
+ * - For any other `action` (deep-link like `'dp:deposit'` or a URL),
8576
+ * the message is a simple notification — `html_body` and
8577
+ * `buttons` will be `undefined` regardless of what's in the
8578
+ * underlying CDN payload. Render `title` + `preview_body` + a
8579
+ * single CTA driving the `action`.
8580
+ *
8581
+ * **The `action` field**
8582
+ * For both shapes, `action` carries either a deep-link
8583
+ * (`'dp:gf_missions'`) or a plain URL. Pass it to `_smartico.dp()`
8584
+ * for safe execution — that helper handles URL vs deep-link
8585
+ * routing.
8586
+ *
8587
+ * **Idempotency / Side effects**: safe. Read-only HTTP fetch.
8588
+ *
8589
+ * **UI guidance**: see [UI Guide — `getInboxMessageBody`](../../docs/ui/inbox/UIGuide_getInboxMessageBody.md).
8590
+ *
8591
+ * **Visitor mode**: not supported.
8592
+ *
8593
+ * @param messageGuid The `message_guid` from a `TInboxMessage`
8594
+ * returned by {@link getInboxMessages}.
8595
+ * @returns Promise resolving to `TInboxMessageBody`.
8596
+ *
8597
+ * @example
8598
+ * ```ts
8599
+ * const body = await window._smartico.api.getInboxMessageBody(messageGuid);
8600
+ *
8601
+ * console.log('[smartico] render message — title:', body.title,
8602
+ * '— preview:', body.preview_body,
8603
+ * '— icon:', body.icon);
8604
+ *
8605
+ * if (body.action === 'dp:inbox' && body.html_body) {
8606
+ * console.log('[smartico] rich message — render the html_body in a sandboxed iframe; render up to 2 action buttons:',
8607
+ * body.buttons?.length ?? 0);
8608
+ * } else {
8609
+ * console.log('[smartico] simple message — show preview_body + single CTA wired to:', body.action,
8610
+ * '— execute via _smartico.dp(body.action)');
8611
+ * }
8612
+ * ```
6068
8613
  */
6069
8614
  async getInboxMessageBody(messageGuid) {
6070
8615
  return await this.api.getInboxMessageBodyT(messageGuid);
6071
8616
  }
6072
8617
  /**
6073
- * Requests to mark inbox message with specified guid as read
8618
+ * Marks a single inbox message as read. Server-side this flips the
8619
+ * message's `is_read` flag and decrements the user's unread count
8620
+ * (the change propagates back via the user-properties channel —
8621
+ * subscribers to {@link getInboxUnreadCount}'s `onUpdate` and
8622
+ * {@link getUserProfile}'s `core_inbox_unread_count` see it within
8623
+ * ~1 second).
6074
8624
  *
6075
- * **Visitor mode: not supported**
8625
+ * @remarks
8626
+ * **Error codes** (in `err_code`)
8627
+ * - `0` — success; the message is now marked read. Idempotent — a
8628
+ * second call on the same `messageGuid` also returns `0`.
8629
+ * - other non-zero — server error. Surface `err_message` if any.
8630
+ *
8631
+ * **Refresh after success**
8632
+ * The SDK does NOT auto-refresh {@link getInboxMessages} (no
8633
+ * `onUpdate` callback fires after this mutation). The unread-count
8634
+ * channel ({@link getInboxUnreadCount}, `core_inbox_unread_count`)
8635
+ * DOES auto-update — subscribers to it see the new count
8636
+ * automatically. If your inbox list UI shows the `read` field, you
8637
+ * have two options: re-call `getInboxMessages` after the mutation,
8638
+ * or update the local copy optimistically.
8639
+ *
8640
+ * **Idempotency**: safe. Repeated calls return `err_code === 0`.
8641
+ *
8642
+ * **Side effects** (on success)
8643
+ * - Server-side `is_read` flag set to true.
8644
+ * - Server-side `core_inbox_unread_count` decremented (if the
8645
+ * message was previously unread).
8646
+ *
8647
+ * **UI guidance**: see [UI Guide — `markInboxMessageAsRead`](../../docs/ui/inbox/UIGuide_markInboxMessageAsRead.md).
8648
+ *
8649
+ * **Visitor mode**: not supported.
8650
+ *
8651
+ * @param messageGuid The `message_guid` from a `TInboxMessage`.
8652
+ * @returns `{ err_code, err_message }`; success when
8653
+ * `err_code === 0`.
8654
+ *
8655
+ * @example
8656
+ * ```ts
8657
+ * const r = await window._smartico.api.markInboxMessageAsRead(message.message_guid);
8658
+ * if (r.err_code === 0) {
8659
+ * console.log('[smartico] marked as read — optimistically flip the local read indicator; the inbox badge auto-decrements via the user-properties channel');
8660
+ * } else {
8661
+ * console.error('[smartico] mark-as-read failed — keep the local state as-is and show a non-blocking error if appropriate:', r.err_message);
8662
+ * }
8663
+ * ```
6076
8664
  */
6077
8665
  async markInboxMessageAsRead(messageGuid) {
6078
8666
  const r = await this.api.markInboxMessageRead(this.userExtId, messageGuid);
@@ -6082,9 +8670,57 @@ class WSAPIInbox extends WSAPILeaderBoard {
6082
8670
  };
6083
8671
  }
6084
8672
  /**
6085
- * Requests to mark all inbox messages as read
8673
+ * Marks ALL of the user's inbox messages as read in one server
8674
+ * round-trip — typically wired to a "Mark all as read" CTA in the
8675
+ * inbox header.
6086
8676
  *
6087
- * **Visitor mode: not supported**
8677
+ * The operation is global to the user — NOT filtered by the
8678
+ * current view (active category tab, favorite filter, etc.). Every
8679
+ * unread message in the user's inbox flips to read.
8680
+ *
8681
+ * @remarks
8682
+ * **Error codes** (in `err_code`)
8683
+ * - `0` — success; all currently-unread messages flipped to read.
8684
+ * - other non-zero — server error. Surface `err_message` if any.
8685
+ *
8686
+ * **Race condition note**: a new message arriving server-side
8687
+ * between the call and its processing remains unread (the
8688
+ * server's mark-all operation is a snapshot in time). Subsequent
8689
+ * `getInboxMessages` calls show the new message as unread.
8690
+ *
8691
+ * **Refresh after success**
8692
+ * Same as {@link markInboxMessageAsRead} — `getInboxMessages`
8693
+ * `onUpdate` does NOT fire automatically, but the unread-count
8694
+ * channel does (the badge will drop to 0, or to the count of any
8695
+ * new messages that arrived during processing).
8696
+ *
8697
+ * **Idempotency**: safe. A second call on an already-all-read
8698
+ * inbox returns `err_code === 0` with no-op effect.
8699
+ *
8700
+ * **Side effects** (on success)
8701
+ * - Every unread message flipped to read.
8702
+ * - `core_inbox_unread_count` drops to 0 (or near 0 if races).
8703
+ *
8704
+ * **UI guidance**: included in the
8705
+ * [UI Guide — `markInboxMessageAsRead`](../../docs/ui/inbox/UIGuide_markInboxMessageAsRead.md)
8706
+ * (Bulk variant section).
8707
+ *
8708
+ * **Visitor mode**: not supported.
8709
+ *
8710
+ * @returns `{ err_code, err_message }`; success when
8711
+ * `err_code === 0`.
8712
+ *
8713
+ * @example
8714
+ * ```ts
8715
+ * console.log('[smartico] mark-all-read starting — set in-flight flag on the "Mark all read" button, show loading dots');
8716
+ * const r = await window._smartico.api.markAllInboxMessagesAsRead();
8717
+ * console.log('[smartico] mark-all-read response — clear in-flight flag');
8718
+ * if (r.err_code === 0) {
8719
+ * console.log('[smartico] all messages marked read — optimistically flip every local read indicator; badge auto-drops via user-properties channel');
8720
+ * } else {
8721
+ * console.error('[smartico] mark-all failed — surface a non-blocking error:', r.err_message);
8722
+ * }
8723
+ * ```
6088
8724
  */
6089
8725
  async markAllInboxMessagesAsRead() {
6090
8726
  const r = await this.api.markAllInboxMessageRead(this.userExtId);
@@ -6094,9 +8730,57 @@ class WSAPIInbox extends WSAPILeaderBoard {
6094
8730
  };
6095
8731
  }
6096
8732
  /**
6097
- * Requests to mark inbox message with specified guid as favorite. Pass mark true to add message to favorite and false to remove.
8733
+ * Toggles a message's favorite (starred) state — pass `mark: true`
8734
+ * to favorite, `mark: false` to unfavorite. Use to power a star
8735
+ * icon click handler on the inbox list.
6098
8736
  *
6099
- * **Visitor mode: not supported**
8737
+ * @remarks
8738
+ * **Error codes** (in `err_code`)
8739
+ * - `0` — success; the message's favorite state flipped to the
8740
+ * requested value.
8741
+ * - other non-zero — server error. Surface `err_message` if any.
8742
+ *
8743
+ * **Refresh after success**
8744
+ * The SDK does NOT auto-refresh {@link getInboxMessages}. To
8745
+ * reflect the new state in the UI, update the local copy of the
8746
+ * affected `TInboxMessage` (set `favorite` to the new value) or
8747
+ * re-call `getInboxMessages`.
8748
+ *
8749
+ * **Idempotency**: safe. `mark: true` on an already-favorite
8750
+ * message returns `err_code === 0` (no-op). Same for `mark: false`
8751
+ * on a non-favorite.
8752
+ *
8753
+ * **Side effects** (on success)
8754
+ * - Server-side `is_starred` flag set to the requested value.
8755
+ * - No effect on read state, unread count, or other fields.
8756
+ *
8757
+ * **UI guidance**: see [UI Guide — `markUnmarkInboxMessageAsFavorite`](../../docs/ui/inbox/UIGuide_markUnmarkInboxMessageAsFavorite.md).
8758
+ *
8759
+ * **Visitor mode**: not supported.
8760
+ *
8761
+ * @param messageGuid The `message_guid` from a `TInboxMessage`.
8762
+ * @param mark `true` to favorite, `false` to unfavorite.
8763
+ * @returns `{ err_code, err_message }`; success when
8764
+ * `err_code === 0`.
8765
+ *
8766
+ * @example
8767
+ * ```ts
8768
+ * // Toggle handler — flip the local state optimistically, then
8769
+ * // call the server, and revert if the call fails.
8770
+ * const target = !message.favorite;
8771
+ * console.log('[smartico] optimistically flip the star to', target, '— it will revert if the server rejects');
8772
+ *
8773
+ * const r = await window._smartico.api.markUnmarkInboxMessageAsFavorite(
8774
+ * message.message_guid,
8775
+ * target,
8776
+ * );
8777
+ *
8778
+ * if (r.err_code === 0) {
8779
+ * console.log('[smartico] favorite toggled — keep the local state and show a brief "Added to favorites" / "Removed from favorites" toast');
8780
+ * } else {
8781
+ * console.error('[smartico] favorite toggle failed — revert the local state and show an error toast:', r.err_message);
8782
+ * }
8783
+ * ```
6100
8784
  */
6101
8785
  async markUnmarkInboxMessageAsFavorite(messageGuid, mark) {
6102
8786
  const r = await this.api.markUnmarkInboxMessageAsFavorite(this.userExtId, messageGuid, mark);
@@ -6106,9 +8790,52 @@ class WSAPIInbox extends WSAPILeaderBoard {
6106
8790
  };
6107
8791
  }
6108
8792
  /**
6109
- * Requests to delete inbox message
8793
+ * Soft-deletes a single inbox message. After deletion, the message
8794
+ * is excluded from future {@link getInboxMessages} responses
8795
+ * server-side, but its row is retained for analytics — there is no
8796
+ * "undelete" path via the SDK.
6110
8797
  *
6111
- * **Visitor mode: not supported**
8798
+ * @remarks
8799
+ * **Error codes** (in `err_code`)
8800
+ * - `0` — success; the message is now deleted from the user's
8801
+ * view.
8802
+ * - other non-zero — server error. Surface `err_message` if any.
8803
+ *
8804
+ * **Refresh after success**
8805
+ * The SDK does NOT auto-refresh {@link getInboxMessages}. Drop the
8806
+ * deleted message from your local list, or re-call
8807
+ * `getInboxMessages` to reload. If the deleted message was unread,
8808
+ * the unread count drops automatically via the user-properties
8809
+ * channel.
8810
+ *
8811
+ * **Idempotency**: safe. A second call on an already-deleted
8812
+ * `messageGuid` returns `err_code === 0` (server treats it as a
8813
+ * no-op — already-deleted messages are filtered out).
8814
+ *
8815
+ * **Side effects** (on success)
8816
+ * - Server-side `is_deleted` flag set to true.
8817
+ * - If the message was unread, `core_inbox_unread_count`
8818
+ * decrements via the user-properties channel.
8819
+ *
8820
+ * **UI guidance**: see [UI Guide — `deleteInboxMessage`](../../docs/ui/inbox/UIGuide_deleteInboxMessage.md).
8821
+ *
8822
+ * **Visitor mode**: not supported.
8823
+ *
8824
+ * @param messageGuid The `message_guid` from a `TInboxMessage`.
8825
+ * @returns `{ err_code, err_message }`; success when
8826
+ * `err_code === 0`.
8827
+ *
8828
+ * @example
8829
+ * ```ts
8830
+ * // Swipe-to-delete on mobile; trash-icon click on desktop.
8831
+ * console.log('[smartico] delete starting — animate the row out of the list (slide left/right by 100%)');
8832
+ * const r = await window._smartico.api.deleteInboxMessage(message.message_guid);
8833
+ * if (r.err_code === 0) {
8834
+ * console.log('[smartico] deleted — drop the message from the local list, fire a brief "Message deleted" toast (no undo affordance — there is no undelete via the SDK)');
8835
+ * } else {
8836
+ * console.error('[smartico] delete failed — animate the row back into place and show a non-blocking error:', r.err_message);
8837
+ * }
8838
+ * ```
6112
8839
  */
6113
8840
  async deleteInboxMessage(messageGuid) {
6114
8841
  const r = await this.api.deleteInboxMessage(this.userExtId, messageGuid);
@@ -6118,9 +8845,61 @@ class WSAPIInbox extends WSAPILeaderBoard {
6118
8845
  };
6119
8846
  }
6120
8847
  /**
6121
- * Requests to delete all inbox messages
8848
+ * Soft-deletes ALL of the user's inbox messages in one server
8849
+ * round-trip — typically wired to a "Delete all" CTA in the inbox
8850
+ * header (usually behind a confirm dialog given the destructive
8851
+ * nature).
6122
8852
  *
6123
- * **Visitor mode: not supported**
8853
+ * The operation is global to the user — NOT filtered by the
8854
+ * current view (active category tab, favorite filter, etc.). Every
8855
+ * non-deleted message in the user's inbox flips to deleted.
8856
+ *
8857
+ * @remarks
8858
+ * **Error codes** (in `err_code`)
8859
+ * - `0` — success; the entire inbox is now empty from the user's
8860
+ * view.
8861
+ * - other non-zero — server error. Surface `err_message` if any.
8862
+ *
8863
+ * **Race condition note**: a new message arriving server-side
8864
+ * between the call and its processing is NOT deleted (the
8865
+ * server's delete-all operation is a snapshot in time). Subsequent
8866
+ * `getInboxMessages` calls show the new message.
8867
+ *
8868
+ * **Refresh after success**
8869
+ * Same as {@link deleteInboxMessage} — `getInboxMessages` `onUpdate`
8870
+ * does not fire automatically. Replace the local list with `[]`
8871
+ * (or re-call `getInboxMessages`). The unread count drops to 0
8872
+ * (or near-0 if races) via the user-properties channel.
8873
+ *
8874
+ * **Idempotency**: safe. A second call on an already-empty inbox
8875
+ * returns `err_code === 0` with no-op effect.
8876
+ *
8877
+ * **Side effects** (on success)
8878
+ * - Every message flipped to deleted server-side.
8879
+ * - `core_inbox_unread_count` drops to 0.
8880
+ * - There is no SDK undelete path — recovery requires operator
8881
+ * intervention.
8882
+ *
8883
+ * **UI guidance**: included in the
8884
+ * [UI Guide — `deleteInboxMessage`](../../docs/ui/inbox/UIGuide_deleteInboxMessage.md)
8885
+ * (Bulk variant section).
8886
+ *
8887
+ * **Visitor mode**: not supported.
8888
+ *
8889
+ * @returns `{ err_code, err_message }`; success when
8890
+ * `err_code === 0`.
8891
+ *
8892
+ * @example
8893
+ * ```ts
8894
+ * // After a confirm dialog "Are you sure you want to delete all messages?"
8895
+ * console.log('[smartico] delete-all confirmed — show loading state on the "Delete all" button');
8896
+ * const r = await window._smartico.api.deleteAllInboxMessages();
8897
+ * if (r.err_code === 0) {
8898
+ * console.log('[smartico] inbox cleared — replace the local list with [], fire a "All messages deleted" toast, badge auto-drops to 0');
8899
+ * } else {
8900
+ * console.error('[smartico] delete-all failed — show a non-blocking error toast:', r.err_message);
8901
+ * }
8902
+ * ```
6124
8903
  */
6125
8904
  async deleteAllInboxMessages() {
6126
8905
  const r = await this.api.deleteAllInboxMessages(this.userExtId);
@@ -7468,6 +10247,10 @@ class SmarticoAPI {
7468
10247
  const message = this.buildMessage(user_ext_id, ClassId.RAF_OPTIN_REQUEST, props);
7469
10248
  return await this.send(message, ClassId.RAF_OPTIN_RESPONSE);
7470
10249
  }
10250
+ async getRaffleWonPrizes(user_ext_id, props) {
10251
+ const message = this.buildMessage(user_ext_id, ClassId.RAF_GET_WON_PRIZES_REQUEST, props);
10252
+ return await this.send(message, ClassId.RAF_GET_WON_PRIZES_RESPONSE);
10253
+ }
7471
10254
  async getActivityLog(user_ext_id, startTimeSeconds, endTimeSeconds, limit, offset) {
7472
10255
  const message = this.buildMessage(user_ext_id, ClassId.GET_POINT_HISTORY_REQUEST, {
7473
10256
  startTimeSeconds: Math.floor(startTimeSeconds),