0Pricing
Blockchain Smart Contracts with Solidity · Lesson

Yield Farming and Staking Rewards

Understand how DeFi yield farming and staking reward contracts distribute tokens over time, including the reward-per-token accounting pattern used by major protocols.

Yield Farming and Staking Rewards is a free Blockchain Smart Contracts with Solidity lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Blockchain Smart Contracts with Solidity learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Yield Farming?

Yield farming means depositing tokens into a protocol to earn additional token rewards. Users stake an asset, and the protocol distributes a reward token continuously over time to incentivize participation.

The Core Challenge

The hard part is fairly splitting rewards among many stakers who deposit and withdraw at different times, without looping over every user (which would be too gas-expensive).

The solution is the reward-per-token accumulator pattern.

Reward Per Token Idea

Track a single global accumulator: the total reward earned per staked token since the contract started. Each user stores a snapshot of this accumulator at their last interaction.

Their owed reward = stake amount times (current accumulator minus their snapshot).

State Variables

Set up the bookkeeping variables that drive the accounting.

uint256 public rewardRate;            // reward tokens per second
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public totalStaked;

mapping(address => uint256) public balances;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;

Computing Reward Per Token

The accumulator grows by the reward emitted since the last update, divided by the total staked.

function rewardPerToken() public view returns (uint256) {
    if (totalStaked == 0) return rewardPerTokenStored;
    uint256 elapsed = block.timestamp - lastUpdateTime;
    return rewardPerTokenStored + (elapsed * rewardRate * 1e18) / totalStaked;
}

Calculating Earned Rewards

A user's earned amount is their balance times the difference between the current accumulator and their last paid snapshot, plus anything already credited.

function earned(address account) public view returns (uint256) {
    uint256 diff = rewardPerToken() - userRewardPerTokenPaid[account];
    return (balances[account] * diff) / 1e18 + rewards[account];
}

The Update Modifier

Before any state-changing action, settle the user's pending rewards and refresh the global accumulator. A modifier keeps this consistent.

modifier updateReward(address account) {
    rewardPerTokenStored = rewardPerToken();
    lastUpdateTime = block.timestamp;
    if (account != address(0)) {
        rewards[account] = earned(account);
        userRewardPerTokenPaid[account] = rewardPerTokenStored;
    }
    _;
}

Staking Tokens

Staking pulls tokens from the user and increases their balance and the total. The modifier settles rewards first.

function stake(uint256 amount) external updateReward(msg.sender) {
    require(amount > 0, 'zero amount');
    totalStaked += amount;
    balances[msg.sender] += amount;
    stakingToken.transferFrom(msg.sender, address(this), amount);
}

Withdrawing Stake

Withdrawal mirrors staking: settle rewards, decrease balances, then return the staked tokens.

function withdraw(uint256 amount) external updateReward(msg.sender) {
    require(balances[msg.sender] >= amount, 'too much');
    totalStaked -= amount;
    balances[msg.sender] -= amount;
    stakingToken.transfer(msg.sender, amount);
}

Claiming Rewards

Claiming sends accrued reward tokens to the user and resets their pending balance to zero.

function getReward() external updateReward(msg.sender) {
    uint256 reward = rewards[msg.sender];
    if (reward > 0) {
        rewards[msg.sender] = 0;
        rewardsToken.transfer(msg.sender, reward);
    }
}

Risks to Watch

Yield farming carries risks: impermanent loss when staking LP tokens, reward token inflation, and contract exploits. Always ensure the contract holds enough reward tokens to cover emissions and audit the math carefully.

Quick Check

Test your understanding of staking rewards.

Recap

You learned the staking rewards pattern used across DeFi:

  • A global reward-per-token accumulator
  • Per-user snapshots for O(1) accounting
  • An updateReward modifier settling state before stake, withdraw, and claim

This pattern fairly distributes continuous rewards while keeping gas costs low.

Frequently asked questions

Is the “Yield Farming and Staking Rewards” lesson free?

Yes — the full text of “Yield Farming and Staking Rewards” is free to read here on the web, and the Blockchain Smart Contracts with Solidity course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Blockchain Smart Contracts with Solidity course, upgrade to CoddyKit PRO.

What will I learn in “Yield Farming and Staking Rewards”?

Understand how DeFi yield farming and staking reward contracts distribute tokens over time, including the reward-per-token accounting pattern used by major protocols. You practise Blockchain Smart Contracts with Solidity with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Blockchain Smart Contracts with Solidity?

No prior experience is required. Blockchain Smart Contracts with Solidity on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Yield Farming and Staking Rewards” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Blockchain Smart Contracts with Solidity lesson?

Yes. Every Blockchain Smart Contracts with Solidity lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. AMMs and Liquidity Pools
  2. Lending and Borrowing Protocols
  3. Flash Loans and Arbitrage
  4. Yield Farming and Staking Rewards
← Back to Blockchain Smart Contracts with Solidity