Document Version: 1.0.0
Priority: P0 — Critical Architecture
Status: Canonical Reference Specification
The Mind Block backend powers an interactive, personalized Web3 cognitive training and puzzle-solving platform. As the system scales with new gameplay modes, blockchain reward mechanisms, analytics, and social competition features, the core domain concepts must be clearly delineated to prevent tight coupling and technical debt.
- Separation of Concerns: Authentication/Identity (
User), Player Customization (PlayerProfile), Gameplay Context (GameSession), Content Inventory (Challenge), and Execution Ledger (ChallengeAttempt) are independent domain models with distinct lifecycles. - Authoritative Backend Execution: All challenge selection, scoring, verification, and reward eligibility are calculated and verified authoritatively on the backend.
- Event-Driven & Decoupled Side Effects: Progress updates, streak evaluations, achievement unlocks, and blockchain minting are triggered via domain events rather than monolithic transaction scripts.
- Single Source of Truth: No duplicate entities or overlapping responsibilities.
erDiagram
User ||--|| PlayerProfile : "has 1:1"
User ||--o{ GameSession : "initiates"
User ||--o{ ChallengeAttempt : "executes"
User ||--o{ PlayerProgress : "accumulates"
User ||--|| PlayerStats : "maintains"
User ||--o{ UserAchievement : "earns"
User ||--o{ UserReward : "claims"
User ||--o{ LeaderboardEntry : "ranks in"
GameSession ||--o{ ChallengeAttempt : "contains"
Challenge ||--o{ ChallengeAttempt : "attempted in"
Challenge ||--o{ PlayerProgress : "tracks mastery of"
Category ||--o{ Challenge : "classifies"
Achievement ||--o{ UserAchievement : "unlocked by"
Reward ||--o{ UserReward : "distributed via"
- Purpose: Serves as the core authentication, security, and account ownership boundary.
- Responsible Service:
UsersService,AuthService(UsersModule,AuthModule) - Ownership: Root aggregate entity. Deleting a user cascades or archives downstream records per privacy/GDPR compliance.
- Fields:
Field Type Required Description idUUIDYes Unique immutable user identifier (Primary Key) emailstringNo (Unique) User email address (unique when present) passwordHashstringNo Bcrypt password hash (null for OAuth users) googleIdstringNo (Unique) Federated Google OAuth subject identifier stellarWalletstringNo (Unique) Public Stellar blockchain public key ( G...)roleUserRoleYes USER,ADMIN,CREATOR,SUPERADMINstatusUserStatusYes ACTIVE,SUSPENDED,DELETEDemailVerifiedbooleanYes Whether email ownership was confirmed lastLoginAtTimestampNo Timestamp of most recent successful authentication createdAtTimestampYes Account creation timestamp updatedAtTimestampYes Account modification timestamp
- Purpose: Holds player settings, avatar, demographic information, learning objectives, and gameplay preferences. Decoupled from core authentication.
- Responsible Service:
PlayerProfileService(ProfileModule) - Ownership: Owned 1:1 by
User. - Fields:
Field Type Required Description idUUIDYes Primary Key userIdUUIDYes (Unique) Foreign key to User.idusernamestringYes (Unique) Public player handle (e.g. @cryptomind)displayNamestringYes Display name avatarUrlstringNo URL to avatar image or NFT avatar biostringNo Player bio / motto countrystringNo ISO country code or country name timezonestringYes IANA timezone (e.g. 'America/New_York')defaultDifficultyDifficultyYes Preferred initial difficulty ( BEGINNER, etc.)preferredCategoriesUUID[]No Array of Category IDs of interest ageGroupstringNo Demographic age group (for analytics) occupationstringNo Occupation / professional field goalsstring[]No Target goals (e.g. ['Speed', 'Logic'])availableHoursstring[]No Preferred daily training hours createdAtTimestampYes Creation timestamp updatedAtTimestampYes Update timestamp
- Purpose: Represents an active or completed gameplay session (e.g., Daily Quest run, Practice Session, Skill Assessment, Multiplayer Match, Speedrun). Manages session-level state, rules, duration, and challenge sequence.
- Responsible Service:
GameSessionService(GameSessionModule/QuestsModule) - Ownership: Owned by
User. Contains multipleChallengeAttemptinstances. - Lifecycle:
INITIALIZED→IN_PROGRESS→COMPLETED|ABANDONED|EXPIRED - Fields:
Field Type Required Description idUUIDYes Primary Key userIdUUIDYes Foreign key to User.idgameModeGameModeYes DAILY_QUEST,PRACTICE,ASSESSMENT,SPEEDRUN,MULTIPLAYERstatusSessionStatusYes INITIALIZED,IN_PROGRESS,COMPLETED,ABANDONED,EXPIREDtargetChallengeCountintYes Number of challenges planned for this session completedChallengeCountintYes Number of challenges completed so far totalScoreintYes Total score accumulated in this session totalTimeSpentintYes Seconds spent actively solving metadataJSONNo Session-specific context (e.g. quest date, lobby ID) startedAtTimestampYes Session start timestamp endedAtTimestampNo Session conclusion timestamp expiresAtTimestampNo Expiration deadline for time-bound sessions
- Purpose: The canonical definition of a playable puzzle, problem, or quiz item. (Mapped from legacy
Puzzle). - Responsible Service:
ChallengesService(ChallengesModule/PuzzlesModule) - Ownership: Content entity owned by system/creators; referenced by attempts and progress.
- Fields:
Field Type Required Description idUUIDYes Primary Key categoryIdUUIDYes Foreign key to Category.iddifficultyDifficultyYes BEGINNER,INTERMEDIATE,ADVANCED,EXPERTtitlestringNo Optional challenge title questionstringYes Question prompt / problem markdown optionsstring[]Yes Selectable answer choices correctAnswerstringYes Canonical answer key (Authoritative/Private) explanationstringNo Educational explanation after completion hintsstring[]No Progressive hint strings pointsintYes Base XP / point value timeLimitintYes Time limit in seconds isActivebooleanYes Whether available for active selection tagsstring[]No Content tags (e.g. ['algorithms', 'math'])createdAtTimestampYes Creation timestamp updatedAtTimestampYes Last edit timestamp
- Purpose: Records a player's real-time interaction with a specific
Challenge. Authoritatively tracks the submitted answer, timing, hints consumed, and outcome. - Responsible Service:
ChallengeAttemptService(ChallengeAttemptModule) - Ownership: Owned by
User; optionally belongs toGameSession; referencesChallenge. - Lifecycle:
STARTED→SUBMITTED→CORRECT|INCORRECT|EXPIRED - Fields:
Field Type Required Description idUUIDYes Primary Key userIdUUIDYes Foreign key to User.idchallengeIdUUIDYes Foreign key to Challenge.idsessionIdUUIDNo Optional foreign key to GameSession.idstatusAttemptStatusYes STARTED,SUBMITTED,CORRECT,INCORRECT,EXPIREDuserAnswerstringNo Player's submitted answer (null while STARTED) scoreintYes Score awarded (calculated authoritatively) timeSpentintYes Time elapsed in seconds hintsUsedintYes Number of hints consumed solutionRevealedbooleanYes If player forfeited to view answer startedAtTimestampYes When attempt was initiated submittedAtTimestampNo When attempt was submitted / finalized
- Purpose: Permanent historical record of player learning outcomes, category mastery, and overall challenge completion history. Used by the selection engine to avoid repeat challenges.
- Responsible Service:
ProgressService(ProgressModule) - Ownership: Owned by
User; referencesChallengeandCategory. - Fields:
Field Type Required Description idUUIDYes Primary Key userIdUUIDYes Foreign key to User.idchallengeIdUUIDYes Foreign key to Challenge.idcategoryIdUUIDYes Foreign key to Category.idattemptIdUUIDNo Foreign key to qualifying ChallengeAttempt.idisMasteredbooleanYes Whether solved correctly without hints totalAttemptsintYes Number of attempts made by user on this challenge bestScoreintYes Highest score achieved on this challenge firstCompletedAtTimestampYes Initial successful completion lastAttemptedAtTimestampYes Most recent attempt date
- Purpose: Fast-read materialized view / aggregate of player metrics (XP, level, current streak, longest streak, accuracy, total challenges completed). Eliminates expensive on-the-fly table scans.
- Responsible Service:
PlayerStatsService/XpLevelService(UsersModule/StreakModule) - Ownership: 1:1 with
User. - Fields:
Field Type Required Description idUUIDYes Primary Key userIdUUIDYes (Unique) Foreign key to User.idtotalXpintYes Total accumulated XP currentLevelintYes Current computed player level challengesSolvedintYes Total distinct challenges solved accuracyRatefloatYes Overall accuracy percentage (0.0 - 100.0) currentStreakintYes Current active daily streak longestStreakintYes All-time highest streak achieved lastActiveDateDateNo Last active date (YYYY-MM-DD) for streak check averageSolveTimeintYes Average seconds per solve tokensBalanceintYes In-game token balance updatedAtTimestampYes Last recalculation timestamp
-
Purpose: Defines achievements/badges and tracks individual player unlocks and claim status.
-
Responsible Service:
AchievementsService(AchievementsModule) -
Ownership:
Achievementis a master catalog entity;UserAchievementis a join entity owned byUser. -
Fields (
Achievement):Field Type Required Description idUUIDYes Primary Key slugstringYes (Unique) Identifier (e.g. 'streak-7-days','math-master')titlestringYes Achievement title descriptionstringYes Criteria description badgeIconUrlstringYes Badge visual asset categorystringYes STREAK,MASTERY,SPEED,SPECIALxpRewardintYes Bonus XP on unlock tokenRewardintYes Bonus tokens on unlock isActivebooleanYes Availability toggle -
Fields (
UserAchievement):Field Type Required Description idUUIDYes Primary Key userIdUUIDYes Foreign key to User.idachievementIdUUIDYes Foreign key to Achievement.idunlockedAtTimestampYes When criteria were fulfilled isClaimedbooleanYes Whether rewards have been claimed
-
Purpose: Manages the economic reward catalog (off-chain tokens, NFT badges, Stellar Soroban contract disbursements) and individual reward claims.
-
Responsible Service:
RewardsService,BlockchainService(RewardsModule,BlockchainModule) -
Ownership:
UserRewardis owned byUser. -
Fields (
Reward):Field Type Required Description idUUIDYes Primary Key typeRewardTypeYes TOKEN,STELLAR_NFT,BADGE,STREAK_FREEZEamountnumericYes Amount or token value assetCodestringNo Stellar asset code or NFT metadata URI namestringYes Reward name descriptionstringNo Description of reward -
Fields (
UserReward):Field Type Required Description idUUIDYes Primary Key userIdUUIDYes Foreign key to User.idrewardIdUUIDYes Foreign key to Reward.idstatusRewardStatusYes PENDING,CLAIMED,MINTED,FAILEDtxHashstringNo Stellar transaction hash if on-chain claimedAtTimestampNo Claim timestamp
- Purpose: High-performance ranking entity holding competitive scores across daily, weekly, and all-time intervals and specific categories.
- Responsible Service:
LeaderboardService(LeaderboardModule) - Ownership: Maintained by system; points to
User. - Fields:
Field Type Required Description idUUIDYes Primary Key userIdUUIDYes Foreign key to User.idtimeframeTimeframeYes DAILY,WEEKLY,ALL_TIME,SEASONALperiodKeystringYes Period identifier (e.g. '2026-W34','2026-08-19')categoryIdUUIDNo Null for global leaderboard; UUID for category-specific scoreintYes Ranking score / XP in this period rankintYes Computed ordinal rank challengesCompletedintYes Count of challenges completed in period updatedAtTimestampYes Timestamp of score snapshot
| Existing Code Entity | Canonical Domain Entity | Discrepancies & Harmonization Plan |
|---|---|---|
users/user.entity.ts (User) |
User + PlayerProfile + PlayerStats |
Currently, User contains authentication, profile (bio, interests, country), and stats (xp, level, tokens). As a progressive refactor, User remains backward-compatible while new features interact via PlayerProfile and PlayerStats abstractions. |
puzzles/entities/puzzle.entity.ts (Puzzle) |
Challenge |
Puzzle is the concrete table representation of Challenge. Canonical contracts alias Puzzle as Challenge. |
challenge-attempt/entities/challenge-attempt.entity.ts |
ChallengeAttempt |
Fully aligns with the canonical model. Supports sessionId, timing, hints, and lifecycle states. |
progress/entities/progress.entity.ts (UserProgress) |
PlayerProgress |
Standard progress record tracking user-challenge outcomes and daily quests. |
progress/entities/user-progress.entity.ts (Duplicate) |
Deprecated / Redundant | Found duplicate UserProgress definition. Standardized to progress.entity.ts (UserProgress). |
quests/entities/daily-quest.entity.ts (DailyQuest) |
GameSession (Specialized) |
DailyQuest functions as a specialized GameSession with gameMode: DAILY_QUEST. Future sessions leverage generalized GameSession. |
streak/entities/streak.entity.ts (Streak) |
PlayerStats (Streak Component) |
Holds currentStreak, longestStreak, and lastActiveDate. Forms part of PlayerStats. |
categories/entities/category.entity.ts (Category) |
Category |
Standard taxonomy entity classifying challenges. |
- Relational Integrity & Foreign Keys:
- Soft-delete or cascaded deletions ensure audit logs and blockchain transaction histories (
UserReward) remain immutable even if a user account is removed.
- Soft-delete or cascaded deletions ensure audit logs and blockchain transaction histories (
- Indexing Strategy:
- Composite Index
(userId, challengeId)onchallenge_attemptsanduser_progressfor instant history checks during challenge selection. - Index on
(categoryId, difficulty, isActive)onpuzzlesfor sub-millisecond candidate filtering. - Index on
(timeframe, periodKey, score DESC)onleaderboard_entriesfor fast pagination.
- Composite Index
- Partitioning High-Volume Tables:
challenge_attemptsandanalytics_eventsshould be range-partitioned bystarted_at/created_at(monthly partitions) as query volume grows.
- Caching & Redis Layer:
- Active user session state and current challenge candidate pools are cached in Redis (
REDIS_CLIENT) with 1-hour TTLs to prevent heavy PostgreSQL queries during active gameplay.
- Active user session state and current challenge candidate pools are cached in Redis (