Vyper theorytheory 0/50 · 0%
Web3 integration · hard

45. Building a simple staking contract

Deposits, rewards accrual and withdrawals.

A staking contract tracks each user's deposited amount and the time (or block) since their last update, then computes rewards proportionally when they claim or withdraw.

staked: public(HashMap[address, uint256])
reward_rate: public(uint256)          # reward units per second per token
last_update: public(HashMap[address, uint256])

@external
def stake(amount: uint256):
    self._update_rewards(msg.sender)
    self.staked[msg.sender] += amount
    ERC20(self.token).transferFrom(msg.sender, self, amount)

@internal
def _update_rewards(user: address):
    elapsed: uint256 = block.timestamp - self.last_update[user]
    self.rewards[user] += self.staked[user] * self.reward_rate * elapsed
    self.last_update[user] = block.timestamp

Always update rewards *before* changing a user's staked balance, otherwise you'll compute rewards using the wrong principal amount for part of the elapsed period.

Check your understanding

  1. 1. Why update rewards before changing the staked balance?

  2. 2. What two pieces of state does a basic staking contract need per user?

  3. 3. Which external call moves tokens into the staking contract?