The Mining feature allows users to purchase "Virtual Miners" (Plans) that generate tokens passively over time.
- Users buy plans to acquire "Hashrate".
- Formula:
Reward = Hashrate * RatePerHashPerSecond * SecondsElapsed. - The exact
RatePerHashPerSecondis determined by thedailyRewardPerHashconfig (default: 1 hash = X tokens/day).
To serve thousands of users efficiently, the system does not update balances every second. Instead, it uses a Lazy Checkpoint system:
- State: Stored in
user_mining_state(Total Hashrate, Last Claimed Time, Pending Rewards). - Calculation: When a user visits the page, buys a miner, or claims:
- Calculating
(Now - LastClaimedTime). - Accruing new rewards to
pendingRewards. - Updating
LastClaimedTimetoNow.
- Calculating
- Standard Plans: Pre-configured by admins (Price, Hashrate, Duration).
- Custom Plans: Users define investment amount and duration. The system dynamically calculates the Hashrate to achieve a target APY (Configurable).
-
Atomic Transactions:
- Purchases use database transactions to deduct tokens and grant miners simultaneously.
- Uses
FOR UPDATErow locking to prevent negative balance exploits.
-
Validation:
- Checks plan availability (isActive, Sale End Date).
- Enforces "Max Supply" and "Max Per User" limits.
-
Claim Limits:
- Minimum Claim: Users must accumulate a minimum amount (e.g., 10 tokens) to claim.
- Cooldown: Optional cooldown between claims (e.g., 1 hour) to reduce DB write load.
- Service:
lib/services/mining.ts - Config:
lib/services/mining-config.ts(Stored in DBsettings). - Models:
user_miners,user_mining_state,mining_plans.
