> ## Documentation Index
> Fetch the complete documentation index at: https://docs.learnway.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Smart Contracts Suite

> Complete Lisk L2 smart contract architecture (learnway_onchain_infrastructure/): LearnWayAdmin, LearnWayManager, LearnwayXPGemsContract (XP & Gems state engines), Badges NFT, and Certificates.

# Smart Contracts Suite (`learnway_onchain_infrastructure/`)

LearnWay deploys an interconnected suite of Solidity smart contracts on **Lisk L2** (OP Stack rollup). The contracts operate under a unified Role-Based Access Control (RBAC) governance layer managed by **`LearnWayAdmin.sol`**.

Unlike typical token projects, **`XPContract` and `GemContract` are custom UUPS-upgradeable gamification state and leaderboard engines** (not standard ERC-20 tokens). They maintain verifiable on-chain player progression, transaction ledgers, activity cooldowns, and contest leaderboards directly on Lisk L2.

***

## Inter-Contract Relationship & Hierarchy

```mermaid theme={null}
graph TD
    subgraph Governance["🏛️ Access Control & Emergency System"]
        Admin["LearnWayAdmin.sol<br/>• DEFAULT_ADMIN_ROLE (Multi-sig)<br/>• MANAGER_ROLE<br/>• MINTER_ROLE / BURNER_ROLE<br/>• EMERGENCY_ROLE (Pausable)"]
    end

    subgraph Coordinator["⚡ Operational Coordinator"]
        Manager["LearnWayManager.sol<br/>(Has MANAGER_ROLE)<br/>• completeLesson()<br/>• completeBattle()<br/>• addAchievement()<br/>• mintCertificate()"]
    end

    subgraph GamificationState["🎮 On-Chain Gamification & Accounting Engines"]
        XP["XPContract.sol<br/>• Custom Gamification Engine<br/>• Level Tracking & Leaderboards<br/>• Battle & Contest Scoring"]
        Gems["GemContract.sol<br/>• In-Game Utility Accounting<br/>• Reward Events & Tx Ledger<br/>• Batch Updates & Stakes"]
    end

    subgraph NFTCredentials["🏆 Credentials & Milestone NFTs"]
        Badges["BadgesNFT.sol<br/>• ERC-721 Badges<br/>• Milestone Achievements"]
        Certs["LearnWayCertificate.sol<br/>• ERC-1155 Credentials<br/>• Course Completion Certs"]
    end

    Admin -.->|Enforces Access Control & Pause State| Manager
    Admin -.->|Enforces Access Control & Pause State| XP
    Admin -.->|Enforces Access Control & Pause State| Gems
    Admin -.->|Enforces Access Control & Pause State| Badges
    Admin -.->|Enforces Access Control & Pause State| Certs

    Manager -->|Award XP & Update Levels| XP
    Manager -->|Reward Gems & Settle Wagers| Gems
    Manager -->|Mint Milestone Badges| Badges
    Manager -->|Mint Course Certificates| Certs

    Relayer["Transaction Relayer (learnway-transaction-processor)"] -->|Submits Admin Transactions| Manager
```

***

## Contract Deep Dive

### 1. `LearnWayAdmin.sol` (RBAC & Emergency Circuit Breaker)

* **Standard**: OpenZeppelin `AccessControlDefaultAdminRules` and `Pausable`.
* **Central Source of Truth**: All other contracts query `LearnWayAdmin` to check caller permissions.
* **Roles**:
  * `DEFAULT_ADMIN_ROLE`: High-security multi-sig treasury key for role assignments and contract upgrades.
  * `MANAGER_ROLE`: Granted strictly to `LearnWayManager.sol` so it can trigger state changes across all domain contracts.
  * `MINTER_ROLE` / `BURNER_ROLE`: Granular roles for authorized token minting/burning.
  * `EMERGENCY_ROLE`: Circuit breaker capable of instantly pausing all state changes across the entire suite during security events.

### 2. `LearnWayManager.sol` (Business Orchestrator)

* **Purpose**: Master coordinator called by the backend relayer (`learnway-transaction-processor`).
* **Core Functions**:
  * `completeLesson(address student, uint256 lessonId, uint256 xpEarned, uint256 gemsEarned)`: Atomically updates XP level progression, records gem rewards, and checks milestone criteria.
  * `completeBattle(address winner, address loser, uint256 stakeAmount)`: Validates PvP quiz battle outcomes and transfers wagered gems to the winner.
  * `addAchievement(...)` & `unlockAchievement(address user, uint256 achievementId)`: Registers achievements and triggers NFT badge mints.
  * `mintCertificate(address student, uint256 courseId, string metadataUri)`: Issues a verifiable ERC-1155 completion certificate.

### 3. `XPContract.sol` (Custom On-Chain XP & Leaderboard Engine)

* **Architecture**: UUPS-upgradeable state contract (not ERC-20).
* **On-Chain Accounting & Scoring Rules**:
  * **Point Allocations**: Configurable constants for `battleWinXP`, `battleLossXP`, `contestParticipationXP`, `correctAnswerXP`, and `incorrectAnswerXP`.
  * **Player Level Progression**: Tracks `totalXP`, `currentLevel`, `xpInCurrentLevel`, `xpRequiredForNextLevel`, and emits `LevelUpEvent`.
  * **Contest Leaderboards**: Computes and stores on-chain contest rankings via `getContestLeaderboard(contestId)` and `getTopUsers(count)`.
  * **Seasonal Resets**: Supports periodic leaderboard season rollover via `SeasonResetEvent`.
  * **Batch Processing**: Exposes `batchUpdateXP` for high-throughput multi-user reward distribution.

### 4. `GemContract.sol` (In-Game Gems Accounting & Transaction Ledger)

* **Architecture**: UUPS-upgradeable utility accounting contract (not ERC-20).
* **On-Chain Ledger & Balances**:
  * **Balance Management**: Tracks player gem balances, spending cooldown periods (`COOLDOWN_PERIOD`), and emits `GemsRewardedEvent`.
  * **Verifiable Transaction Ledger**: Emits indexed `TransactionRecorded` events (`txIndex`, `txType`, `gems`, `xp`, `timestamp`) for immutable on-chain audit trails.
  * **High-Volume Updates**: Exposes `batchUpdateGems` for multi-user reward distribution and contest payouts.
  * **Access Controlled**: Only authorized managers (with `MANAGER_ROLE` verified by `LearnWayAdmin`) can mint or deduct gems.

### 5. `BadgesNFT.sol` (Achievement NFTs)

* **Standard**: ERC-721 with soulbound attribute support.
* **Behavior**: Mints unique badge tokens for milestones (7-Day Streak, Solidity Master, Contest Champion) pointing to verifiable IPFS/ImageKit metadata.

### 6. `LearnWayCertificate.sol` (Course Completion Credentials)

* **Standard**: ERC-1155 Multi-Token.
* **Behavior**: Issues cryptographically verifiable course credentials containing student name, completion timestamp, instructor credential signature, and course ID.

### 7. `VerifyingPaymaster.sol` (Client Gas Sponsorship)

* **Standard**: ERC-4337 Paymaster contract.
* **Behavior**: Subsidizes gas exclusively for mobile client `UserOperation`s executed through `/alto`. Validates server signatures generated by `PaymasterSignerService`.
