Bird
Raised Fist0
Blockchain / Solidityprogramming~5 mins

Staking mechanisms in Blockchain / Solidity

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

Staking helps secure a blockchain by letting users lock up their coins to support network operations. It rewards them for helping keep the system safe and running smoothly.

When you want to earn rewards by holding and locking your cryptocurrency.
When you want to help validate transactions and secure a blockchain network.
When you want to participate in governance decisions by staking tokens.
When you want to reduce the chance of attacks by increasing the cost to cheat.
When you want to support a blockchain project and earn passive income.
Syntax
Blockchain / Solidity
function stakeTokens(amount) {
    if (amount <= 0) {
        throw new Error('Amount must be positive');
    }
    userBalance -= amount;
    stakedBalance += amount;
    updateRewards();
}
This example shows a simple function to stake tokens by moving them from user balance to staked balance.
Real staking mechanisms often include locking periods, reward calculations, and unstaking rules.
Examples
User stakes 100 tokens to participate in network security.
Blockchain / Solidity
stakeTokens(100);
Function to remove tokens from staking and return them to user balance.
Blockchain / Solidity
function unstakeTokens(amount) {
    if (amount > stakedBalance) {
        throw new Error('Not enough staked tokens');
    }
    stakedBalance -= amount;
    userBalance += amount;
    updateRewards();
}
Simple reward calculation based on amount staked and time.
Blockchain / Solidity
function calculateRewards() {
    return stakedBalance * rewardRate * timeStaked;
}
Sample Program

This program shows a user staking 200 tokens from their balance. It then calculates rewards based on the staked amount, a fixed reward rate, and time staked.

Blockchain / Solidity
let userBalance = 1000;
let stakedBalance = 0;
const rewardRate = 0.05; // 5% per time unit
let timeStaked = 10; // example time units

function stakeTokens(amount) {
    if (amount <= 0) {
        throw new Error('Amount must be positive');
    }
    if (amount > userBalance) {
        throw new Error('Not enough balance');
    }
    userBalance -= amount;
    stakedBalance += amount;
    console.log(`Staked ${amount} tokens.`);
}

function calculateRewards() {
    return stakedBalance * rewardRate * timeStaked;
}

stakeTokens(200);
console.log(`User balance: ${userBalance}`);
console.log(`Staked balance: ${stakedBalance}`);
console.log(`Rewards earned: ${calculateRewards()}`);
OutputSuccess
Important Notes

Staking usually requires locking tokens for a set time before you can withdraw.

Rewards depend on how much you stake and how long you keep it staked.

Always check the rules of the blockchain you are staking on, as they can vary.

Summary

Staking means locking tokens to help secure a blockchain and earn rewards.

You stake by moving tokens from your balance to a locked state.

Rewards grow based on staked amount and time locked.

Practice

(1/5)
1. What is the main purpose of staking tokens in a blockchain network?
easy
A. To create new tokens instantly
B. To transfer tokens to another user
C. To help secure the network and earn rewards
D. To delete tokens from the blockchain

Solution

  1. Step 1: Understand staking concept

    Staking means locking tokens to support blockchain security.
  2. Step 2: Identify staking benefits

    Users earn rewards for staking, helping network stability.
  3. Final Answer:

    To help secure the network and earn rewards -> Option C
  4. Quick Check:

    Staking = Security + Rewards [OK]
Hint: Staking locks tokens to secure network and gain rewards [OK]
Common Mistakes:
  • Confusing staking with token transfer
  • Thinking staking creates new tokens
  • Believing staking deletes tokens
2. Which of the following is the correct way to represent staking tokens in a smart contract pseudocode?
easy
A. stakeAmount = userBalance - lockedTokens
B. lockedTokens = stakeAmount + userBalance
C. userBalance = stakeAmount + lockedTokens
D. lockedTokens = stakeAmount

Solution

  1. Step 1: Understand staking variables

    Locked tokens represent the amount staked by user.
  2. Step 2: Match correct assignment

    lockedTokens should equal stakeAmount to show tokens locked.
  3. Final Answer:

    lockedTokens = stakeAmount -> Option D
  4. Quick Check:

    Locked tokens = stake amount [OK]
Hint: Locked tokens equal the stake amount directly [OK]
Common Mistakes:
  • Adding stakeAmount to userBalance incorrectly
  • Subtracting lockedTokens from userBalance wrongly
  • Mixing variable roles in assignment
3. Consider this pseudocode for calculating staking rewards:
reward = stakedAmount * rewardRate * stakingDuration
print(reward)
If stakedAmount = 100, rewardRate = 0.05, and stakingDuration = 10, what is the output?
medium
A. 50
B. 5
C. 0.5
D. 500

Solution

  1. Step 1: Substitute values into formula

    reward = 100 * 0.05 * 10
  2. Step 2: Calculate reward

    100 * 0.05 = 5; then 5 * 10 = 50
  3. Final Answer:

    50 -> Option A
  4. Quick Check:

    100 * 0.05 * 10 = 50 [OK]
Hint: Multiply all values stepwise: amount * rate * duration [OK]
Common Mistakes:
  • Multiplying only two values
  • Confusing rewardRate as 5 instead of 0.05
  • Adding values instead of multiplying
4. The following pseudocode has an error. What is the problem?
function stakeTokens(userBalance, stakeAmount) {
  if (stakeAmount > userBalance) {
    return "Error: Not enough balance";
  }
  lockedTokens = stakeAmount;
  userBalance = userBalance - stakeAmount;
  return lockedTokens;
}
medium
A. lockedTokens is not declared before assignment
B. The function does not return userBalance
C. The if condition should be stakeAmount < userBalance
D. The subtraction should add stakeAmount instead

Solution

  1. Step 1: Check variable declarations

    lockedTokens is assigned without declaration, causing error in strict languages.
  2. Step 2: Understand variable scope

    lockedTokens should be declared (e.g., let or var) before use.
  3. Final Answer:

    lockedTokens is not declared before assignment -> Option A
  4. Quick Check:

    Undeclared variable causes error [OK]
Hint: Always declare variables before assigning [OK]
Common Mistakes:
  • Ignoring variable declaration errors
  • Misreading the if condition logic
  • Thinking subtraction should be addition
5. You want to write a function that calculates total rewards for multiple users staking different amounts for different durations. Which approach correctly applies staking mechanisms?
hard
A. Add all staked amounts first, then multiply by rewardRate and total duration
B. Loop through each user, calculate reward = stakedAmount * rewardRate * duration, then sum all rewards
C. Calculate reward only for the user with the highest stake
D. Multiply rewardRate by duration only once, ignoring staked amounts

Solution

  1. Step 1: Understand reward calculation per user

    Each user's reward depends on their own stake and duration.
  2. Step 2: Sum individual rewards for total

    Calculate each reward separately, then add for total rewards.
  3. Final Answer:

    Loop through each user, calculate reward = stakedAmount * rewardRate * duration, then sum all rewards -> Option B
  4. Quick Check:

    Calculate per user, then sum [OK]
Hint: Calculate rewards individually, then add for total [OK]
Common Mistakes:
  • Summing stakes before multiplying
  • Ignoring individual durations
  • Calculating reward for only one user