DeFi Primitives
Advanced
1-2 weeks

График Склада и Добыча ликвидности

Time-based rewards distribution to LP stakers from a single vault

GitHub

Problem

You want to incentivize liquidity provision by distributing reward tokens to LP stakers over time.

Solution

A rewards vault holds reward tokens and distributes them proportionally to stakers based on their stake amount and duration. Uses accumulator pattern for gas efficiency.

How It Works

  1. 1Protocol deposits reward tokens into vault with emission schedule
  2. 2Users stake LP tokens to receive proportional rewards
  3. 3Reward rate = totalRewards / emissionPeriod
  4. 4Each staker earns: (theirStake / totalStake) * rewardRate * timeStaked
  5. 5Accumulator pattern tracks rewards without iterating all stakers
  6. 6Users can claim rewards and unstake at any time

Code Examples

{
  // Rewards Vault with accumulator pattern
  // R4: Reward per token accumulated (scaled by 1e18)
  // R5: Last update height
  // R6: Reward rate per block
  // R7: Total staked amount
  
  val vaultNFT = SELF.tokens(0)._1
  val rewardToken = SELF.tokens(1)._1
  val rewardBalance = SELF.tokens(1)._2
  
  val rewardPerToken = SELF.R4[Long].get
  val lastUpdate = SELF.R5[Int].get
  val rewardRate = SELF.R6[Long].get
  val totalStaked = SELF.R7[Long].get
  
  // Calculate new accumulated rewards
  val blocksPassed = HEIGHT - lastUpdate
  val newRewards = if (totalStaked > 0) {
    blocksPassed * rewardRate * 1000000000000000000L / totalStaked
  } else 0L
  val newRewardPerToken = rewardPerToken + newRewards
  
  // Vault continues with updated state
  val vaultContinues = {
    val newVault = OUTPUTS(0)
    newVault.tokens(0)._1 == vaultNFT &&
    newVault.R4[Long].get == newRewardPerToken &&
    newVault.R5[Int].get == HEIGHT
  }
  
  // Validate stake/unstake/claim operations
  val validOperation = {
    // Check stake boxes in data inputs for reward calculation
    // Implementation depends on staking box structure
    true
  }
  
  vaultContinues && validOperation
}

Rewards vault using accumulator pattern. Tracks rewardPerToken to calculate individual rewards without iterating all stakers.

Use Cases

  • Liquidity mining programs
  • Protocol token distribution
  • Staking rewards
  • Yield farming incentives
  • Governance token distribution

Security Considerations

  • !Use accumulator pattern to avoid iteration gas costs
  • !Protect against reward manipulation via flash stakes
  • !Consider minimum stake duration
  • !Audit precision and rounding
  • !Plan for reward token exhaustion

Real-World Implementations

Spectrum Finance

LP staking rewards

Level Up Your ErgoScript Skills

Get notified about new patterns, tutorials, and developer resources.

Follow for daily updates