0Pricing
Blockchain Smart Contracts with Solidity · Lekcja

Yield farming i nagrody za staking

Poznaj sposób, w jaki kontrakty DeFi do yield farmingu i nagród za staking dystrybuują tokeny w czasie, w tym wzorzec rozliczania reward-per-token używany przez główne protokoły.

Yield farming i nagrody za staking to bezpłatna lekcja Blockchain Smart Contracts with Solidity na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Blockchain Smart Contracts with Solidity, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Yield farming i nagrody za staking” jest bezpłatna?

Tak — pełny tekst „Yield farming i nagrody za staking” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Blockchain Smart Contracts with Solidity, przejdź na CoddyKit PRO. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Co nauczysz się w „Yield farming i nagrody za staking”?

Poznaj sposób, w jaki kontrakty DeFi do yield farmingu i nagród za staking dystrybuują tokeny w czasie, w tym wzorzec rozliczania reward-per-token używany przez główne protokoły. Ćwiczysz Blockchain Smart Contracts with Solidity z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Blockchain Smart Contracts with Solidity?

Nie wymagamy żadnego doświadczenia. Blockchain Smart Contracts with Solidity w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Yield farming i nagrody za staking”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Blockchain Smart Contracts with Solidity?

Tak. Każda lekcja Blockchain Smart Contracts with Solidity zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. AMM-y i pule płynności
  2. Protokoły pożyczek i kredytów
  3. Pożyczki błyskawiczne i arbitraż
  4. Yield farming i nagrody za staking
← Powrót do Blockchain Smart Contracts with Solidity