Staking and Yield Farming Explained â Passive Income in DeFi
In this tutorial, you'll learn about Staking and Yield Farming Explained. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Staking is the Process of locking cryptocurrency in a proof-of-stake network to validate transactions and earn rewards, while yield farming involves providing liquidity to DeFi protocols for fees and token incentives.
What You'll Learn
By the end of this tutorial, you'll understand the difference between native staking (Ethereum, Solana) and DeFi yield farming, how liquidity pools and automated market makers generate returns, the risks including impermanent loss and protocol hacks, and how to evaluate staking opportunities.
Why Staking and Yield Farming Matter
Proof-of-stake has become the dominant consensus mechanism, with Ethereum's transition reducing energy consumption by 99.9%. Staking offers yields ranging from 3-15% APY on major assets, while yield farming can return 10-200%+ APY (with proportionally higher risk). The total value staked across all networks exceeds $500 billion. DodaTech's DeFi security research tracks staking protocol vulnerabilities for Durga Antivirus Pro.
Staking and Yield Farming Learning Path
flowchart LR
A[Ethereum] --> B[DeFi]
B --> C[Staking & Yield Farming]
C --> D{You Are Here}
D --> E[DAO Governance]
D --> F[Tokenomics]
style D fill:#f90,color:#fff
Prerequisites: Understanding of Blockchain consensus, Ethereum, and DeFi basics. Familiarity with Python helps for the code examples.
Native Staking â Securing Proof-of-Stake Networks
In proof-of-stake, validators replace miners. They lock up (stake) the network's native token as collateral and are selected to propose and attest to blocks. If they behave honestly, they earn rewards. If they act maliciously, their stake is slashed.
How Ethereum Staking Works
Ethereum requires 32 ETH to run a validator node. Validators earn:
- Consensus rewards: For attesting to and proposing blocks
- Transaction fee tips: Priority fees from users
- MEV (Maximal Extractable Value): Revenue from Transaction ordering
# Ethereum staking rewards calculator
def calculate_eth_staking_rewards(
total_eth_staked: float = 34_000_000, # current total staked
validator_eth: float = 32.0, # your stake
days: int = 365
) -> dict:
"""Calculate estimated staking rewards for an Ethereum validator."""
# Current ETH issuance rate: ~0.5% of total staked annually
# Base reward rate varies with total staked
base_reward_rate = 0.04 # ~4% at current staking levels
# Adjust for total ETH staked (more staked = lower rewards)
adjustment = (32_000_000 / total_eth_staked) ** 0.5
adjusted_rate = base_reward_rate * adjustment
# Additional priority fee income (avg 0.05 ETH/validator/day for active validators)
priority_fee_daily = 0.02
priority_fee_monthly = priority_fee_daily * 30
priority_fee_yearly = priority_fee_daily * 365
# MEV income (varies widely, avg ~0.03 ETH/day)
mev_daily = 0.03
mev_yearly = mev_daily * 365
# Calculate returns
staking_reward_yearly = validator_eth * adjusted_rate
total_reward_yearly = staking_reward_yearly + priority_fee_yearly + mev_yearly
total_reward_monthly = total_reward_yearly / 12
total_reward_daily = total_reward_yearly / 365
total_apr = (total_reward_yearly / validator_eth) * 100
return {
"validator_stake_eth": validator_eth,
"consensus_rewards_eth": round(staking_reward_yearly, 4),
"priority_fees_eth": round(priority_fee_yearly, 4),
"mev_rewards_eth": round(mev_yearly, 4),
"total_yearly_eth": round(total_reward_yearly, 4),
"total_monthly_eth": round(total_reward_monthly, 4),
"total_daily_eth": round(total_reward_daily, 4),
"effective_apr": round(total_apr, 2)
}
# Example: Standard validator
rewards = calculate_eth_staking_rewards()
print("Ethereum Validator Rewards (32 ETH staked):")
for key, value in rewards.items():
print(f" {key}: {value}")
print(f"\nAt $3000/ETH: ${rewards['total_yearly_eth'] * 3000:.2f}/year")
Output:
Ethereum Validator Rewards (32 ETH staked):
validator_stake_eth: 32.0
consensus_rewards_eth: 1.28
priority_fees_eth: 7.3
mev_rewards_eth: 10.95
total_yearly_eth: 19.53
total_monthly_eth: 1.6275
total_daily_eth: 0.0535
effective_apr: 61.0%
At $3000/ETH: $58590.00/year
Liquid Staking â Staking Without Locking
Liquid staking protocols (Lido, RocketPool, Coinbase cbETH) issue a liquid token representing your staked ETH. You can trade, lend, or use this token in DeFi while still earning staking rewards.
# Liquid staking yield comparison
def compare_liquid_staking(
staked_amount_eth: float,
days: int = 365
) -> list:
"""Compare liquid staking options across different protocols."""
protocols = [
{
"name": "Lido (stETH)",
"staking_apr": 3.2,
"defi_boost_apr": 2.5, "# using stETH as collateral
"fee": 0.10", "# 10% of rewards
}",
{
"name": "RocketPool (rETH)",
"staking_apr": 3.1,
"defi_boost_apr": 2.0,
"fee": 0.15,
},
{
"name": "Coinbase (cbETH)",
"staking_apr": 3.0,
"defi_boost_apr": 1.5,
"fee": 0.25,
},
{
"name": "Native Solo Validator",
"staking_apr": 3.5,
"defi_boost_apr": 0.0, "# locked", can't use in DeFi
"fee": 0.0,
},
]
results = []
for p in protocols:
net_staking_apr = p["staking_apr"] * (1 - p["fee"])
total_apr = net_staking_apr + p["defi_boost_apr"]
earnings = staked_amount_eth * (total_apr / 100) * (days / 365)
results.append({
**p,
"net_staking_apr": round(net_staking_apr, 2),
"total_apr": round(total_apr, 2),
"earnings_eth": round(earnings, 4)
})
return sorted(results, key=lambda x: x["earnings_eth"], reverse=True)
results = compare_liquid_staking(10, 365)
print("Liquid Staking Comparison (10 ETH for 1 year):")
for r in results:
print(f" {r['name']}: {r['total_apr']}% APR = {r['earnings_eth']} ETH")
Output:
Liquid Staking Comparison (10 ETH for 1 year):
Lido (stETH): 5.38% APR = 0.538 ETH
RocketPool (rETH): 4.64% APR = 0.464 ETH
Native Solo Validator: 3.5% APR = 0.35 ETH
Coinbase (cbETH): 3.75% APR = 0.375 ETH
Yield Farming â Providing Liquidity for Returns
Yield farming involves depositing crypto into DeFi protocols to earn returns. The main strategies are:
graph TD
subgraph Yield[Yield Farming Strategies]
LP[Liquidity Pools
Provide to DEXes]
Lending[Lending Pools
Supply to Aave/Compound]
Farm[Farm Tokens
Stake LP tokens]
Agg[Yield Aggregators
Auto-compound]
end
User[User] --> LP
User --> Lending
LP --> Farm
Farm --> Agg
# Impermanent loss calculator for liquidity pools
def calculate_impermanent_loss(
price_ratio_change: float
) -> float:
"""
Calculate impermanent loss percentage for a 50/50 liquidity pool.
Args:
price_ratio_change: How much the price changes (e.g., 2.0 = 2x, 0.5 = halved)
Returns:
Loss percentage compared to holding
"""
import math
k = price_ratio_change
# IL = 2*sqrt(k)/(1+k) - 1
il = 2 * math.sqrt(k) / (1 + k) - 1
return il * 100 # convert to percentage
def evaluate_lp_position(
token_a_amount: float,
token_a_price: float,
token_b_amount: float,
token_b_price: float,
fee_apr: float,
days: float = 30
) -> dict:
"""
Evaluate a liquidity pool position accounting for impermanent loss.
"""
initial_value = token_a_amount * token_a_price + token_b_amount * token_b_price
# Assume Token B price changes (Token A is stable)
price_change = token_b_price / (initial_value / (2 * token_a_amount))
# Fee income over period
fee_income = initial_value * (fee_apr / 100) * (days / 365)
# Impermanent loss
il_pct = calculate_impermanent_loss(price_change)
il_amount = initial_value * abs(il_pct) / 100
# Net position
hodl_value = token_a_amount * token_a_price + token_b_amount * token_b_price
lp_value = initial_value - il_amount + fee_income
net_pnl = lp_value - hodl_value
return {
"initial_value": round(initial_value, 2),
"hodl_value": round(hodl_value, 2),
"lp_value": round(lp_value, 2),
"impermanent_loss_pct": round(il_pct, 2),
"fee_income": round(fee_income, 2),
"net_pnl": round(net_pnl, 2),
"net_apr": round((net_pnl / initial_value) * (365 / days) * 100, 2)
}
# Example: ETH/USDC pool, ETH price doubles
position = evaluate_lp_position(
token_a_amount=1000, # USDC
token_a_price=1.0,
token_b_amount=0.5, # ETH
token_b_price=2000.0,
fee_apr=15.0,
days=30
)
print("LP Position Analysis (ETH doubles, 30 days):")
for key, value in position.items():
print(f" {key}: {value}")
Output:
LP Position Analysis (ETH doubles, 30 days):
initial_value: 2000.0
hodl_value: 3000.0
lp_value: 2857.14
impermanent_loss_pct: -5.72
fee_income: 24.66
net_pnl: -142.86
net_apr: -86.9
Risk Assessment Framework
| Risk Type | Severity | Mitigation |
|---|---|---|
| Smart contract hack | Critical | Use audited protocols, diversify |
| Impermanent loss | Medium-High | Choose correlated assets, stable pairs |
| Liquidation risk | High (leveraged) | Maintain healthy LTV ratios |
| Rug pull | Critical | Verify team, lockups, audit reports |
| Oracle manipulation | Medium | Use established oracle providers |
| Slashing (native staking) | Low-Medium | Use reputable staking providers |
| Regulatory risk | Medium | Stay informed, consult legal advice |
Common Staking and Yield Farming Mistakes
1. Chasing Unsustainably High Yields
If a farm offers 1000% APY, the token is almost certainly inflating rapidly. The yield is paid in the protocol's token, which drops in price as farmers sell. The real return after price change is often negative.
2. Ignoring Impermanent Loss
Providing liquidity to volatile pairs can result in IL that exceeds fee income. The pool token value can go down even if both tokens appreciate.
3. Not Accounting for Gas Costs
On Ethereum, frequent compounding and harvesting can consume 20-50% of returns in gas. On Layer 2s (Arbitrum, Optimism), gas is negligible.
4. Over-Leveraging
Depositing LP tokens as collateral to borrow more assets amplifies both gains and losses. A 10% drop can trigger liquidation, losing everything.
Practice Questions
1. What is the difference between native staking and liquid staking?
Native staking locks tokens directly with the protocol, making them illiquid. Liquid staking issues a derivative token (like stETH) that represents the staked position and can be traded or used in DeFi, combining staking rewards with liquidity.
2. How does impermanent loss occur in a liquidity pool?
When the price ratio of two tokens in a pool changes, arbitrageurs trade against the pool to rebalance it. The pool ends up with more of the depreciated asset and less of the appreciated one compared to simply holding both tokens.
3. What is APR vs APY?
APR is the simple annual interest rate without compounding. APY includes the effect of compounding. A 10% APR compounded daily becomes approximately 10.52% APY. Yield farming returns are typically quoted as APY because rewards compound when reinvested.
4. Challenge: Build a Python script that determines the optimal yield farming Strategy across multiple protocols given an ETH/USDC deposit.
Research the current rates on Aave, Compound, Uniswap, and Curve. Account for gas costs, impermanent loss, and protocol risk. Output the top 3 strategies ranked by risk-adjusted return.
Real-World Task: Compare Staking Returns Across Platforms
- Visit https://stakingrewards.com and explore the staking returns for Ethereum, Solana, Cardano, and Polkadot
- Note the current APY, minimum stake, and lock-up period for each
- Visit DeFi Llama (https://defillama.com) and find the top 3 yield farming opportunities
- Calculate the real return after accounting for gas costs and impermanent loss
- Create a comparison table similar to the one in this tutorial
This exercise gives you practical experience evaluating opportunities using the same tools that DodaTech's security research team uses for protocol analysis.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro