DeFi Primitives
Advanced
1-2 weeksRewards Vault & Liquidity Mining Pattern
Time-based rewards distribution to LP stakers from a single vault
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
- 1Protocol deposits reward tokens into vault with emission schedule
- 2Users stake LP tokens to receive proportional rewards
- 3Reward rate = totalRewards / emissionPeriod
- 4Each staker earns: (theirStake / totalStake) * rewardRate * timeStaked
- 5Accumulator pattern tracks rewards without iterating all stakers
- 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
Resources
Fee Considerations
Claiming rewards requires transaction. Consider batching claims or minimum claim amounts.