Skip to content

DeFi — Decentralized Finance Explained Simply

DodaTech 6 min read

This tutorial explains Decentralized Finance (DeFi) — you will learn how DeFi protocols replace banks, brokers, and exchanges with smart contracts on Ethereum, and how you can lend, borrow, trade, and earn without intermediaries.

Why It Matters

DeFi has grown from zero to over $100 billion in total value locked. It offers financial services to anyone with an internet connection — no credit check, no approval, no geographic restriction. This is the first time in history that financial infrastructure runs on code instead of institutions.

Real-World Use

Borrow USDC against your ETH without selling it. Earn 5-15% APY on stablecoin deposits. Trade tokens on a decentralized exchange without creating an account or trusting a custodian.

flowchart LR
    A[User] --> B[Wallet]
    B --> C[DEX]
    B --> D[Lending Protocol]
    B --> E[Yield Aggregator]
    C --> F[Liquidity Pool]
    D --> G[Interest Rate Market]
    E --> H[Strategy Vaults]
    F --> I[Trader]
    G --> J[Borrower]
    H --> K[Automated Yield]
    style A fill:#4CAF50,color:#fff
    style B fill:#FF9800,color:#fff
    style C fill:#2196F3,color:#fff
    style D fill:#2196F3,color:#fff
    style E fill:#2196F3,color:#fff

Decentralized Exchanges (DEXes)

DEXes allow token swaps without a central order book. Instead of matching buyers and sellers, they use automated market makers (AMMs).

// Simplified AMM constant product formula
contract SimpleAMM {
    uint256 public reserveA;
    uint256 public reserveB;
    // k = reserveA * reserveB must remain constant

    function swap(uint256 amountAIn) public returns (uint256 amountBOut) {
        uint256 k = reserveA * reserveB;
        uint256 newReserveA = reserveA + amountAIn;
        uint256 newReserveB = k / newReserveA;
        amountBOut = reserveB - newReserveB - 1; // round down protection
        reserveA = newReserveA;
        reserveB = newReserveB;
        // transfer tokens in and out
    }

    function addLiquidity(uint256 amountA, uint256 amountB) public {
        reserveA += amountA;
        reserveB += amountB;
        // mint LP tokens to user
    }
}

Expected behavior: if the pool has 100 ETH and 200,000 USDC (price 1 ETH = 2,000 USDC), swapping 1 ETH into the pool gives approximately 1,980 USDC (less due to slippage). Adding 10 ETH and 20,000 USDC as liquidity earns the provider a share of future swap fees.

Lending Protocols

Aave and Compound let users deposit assets to earn interest and borrow against their deposits. Interest rates adjust algorithmically based on utilization.

contract SimpleLendingPool {
    mapping(address => uint256) public deposits;
    uint256 public totalDeposits;
    uint256 public borrowRate; // per block in wei

    function deposit() public payable {
        deposits[msg.sender] += msg.value;
        totalDeposits += msg.value;
    }

    function borrow() public {
        uint256 maxBorrow = deposits[msg.sender] * 75 / 100;
        require(address(this).balance >= maxBorrow, "Insufficient pool liquidity");
        deposits[msg.sender] -= maxBorrow; // used as collateral
        payable(msg.sender).transfer(maxBorrow);
    }

    function getUtilization() public view returns (uint256) {
        return (totalDeposits - address(this).balance) * 1e18 / totalDeposits;
    }
}

Expected behavior: Alice deposits 10 ETH, Bob deposits 5 ETH. Alice can borrow up to 7.5 ETH (75% loan-to-value). If ETH price drops and Alice's collateral value falls below the borrowed amount, liquidators can repay her loan and claim her collateral.

Yield Farming and Liquidity Mining

Protocols distribute governance tokens to liquidity providers as an incentive. This bootstraps liquidity and decentralizes governance.

// Example yield calculation for a liquidity provider
const dailyVolume = 5000000; // $5M daily volume
const feeRate = 0.003; // 0.3% swap fee
const dailyFees = dailyVolume * feeRate;
const totalLiquidity = 50000000; // $50M total pool
const myShare = 0.01; // 1% of pool
const myDailyFees = dailyFees * myShare;
const myDailyRewards = 100; // 100 governance tokens/day
console.log(`Daily fees earned: $${myDailyFees}`);
console.log(`Daily token rewards: ${myDailyRewards} tokens`);

Expected output:

Daily fees earned: $150
Daily token rewards: 100 tokens

Token rewards are often more valuable than fee income in early-stage protocols. When token price drops, yield farmers migrate to higher-yielding pools.

Stablecoins in DeFi

Stablecoins provide a stable unit of account within DeFi's volatile ecosystem. DAI, the largest decentralized stablecoin, is maintained by a system of collateralized debt positions (CDPs).

# DAI stability fee calculation
collateral_eth = 10
eth_price_usd = 2000
collateral_value = collateral_eth * eth_price_usd  # $20,000
debt_dai = 10000  # minted DAI
collateralization_ratio = collateral_value / debt_dai * 100
liquidation_threshold = 150
safety_buffer = collateralization_ratio - liquidation_threshold

print(f"Collateralization Ratio: {collateralization_ratio:.1f}%")
print(f"Safety Buffer: {safety_buffer:.1f}%")
if collateralization_ratio < liquidation_threshold:
    print("WARNING: Position is undercollateralized!")

Expected output:

Collateralization Ratio: 200.0%
Safety Buffer: 50.0%

If ETH price drops below $1,500, the CDP becomes undercollateralized and is liquidated — anyone can repay the 10,000 DAI debt and claim the 10 ETH as a reward.

Common Errors

  1. Impermanent loss — Providing liquidity to volatile pairs can result in less value than simply holding the two assets. Stablecoin pairs eliminate this risk.
  2. Smart contract risk — DeFi protocols can have bugs. The $600M Poly Network hack and $320M Wormhole bridge exploit are reminders to diversify across protocols.
  3. Liquidation cascades — A sudden price drop triggers mass liquidations, driving prices lower. Always maintain a large safety buffer above the liquidation threshold.
  4. Frontrunning and MEV — Bots can see your pending Transaction and execute ahead of you. Use slippage protection and consider private mempool solutions.
  5. Bridge risk — Moving assets across chains via bridges introduces additional smart contract risk. Prefer established bridges with proven security records.

Practice Questions

  1. What is the constant product formula used by AMMs? x * y = k where x and y are the reserves of two tokens in the pool, and k is a constant. Swaps maintain k, adding fees gradually increase k over time.

  2. How do DeFi lending protocols determine interest rates? Interest rates are algorithmically determined by the utilization ratio (borrowed / total deposited). High utilization means higher rates to incentivize deposits and discourage borrowing.

  3. What is total value locked (TVL) and why does it matter? TVL is the total value of assets deposited in a DeFi protocol, typically measured in USD. It indicates protocol adoption, security (more TVL means more fees for the protocol), and liquidity depth.

Frequently Asked Questions

{{< faq question="Is DeFi safe for beginners?">}} DeFi carries significant risks including smart contract bugs, price Volatility, and user error. Start on testnets to learn the workflow. Use small amounts on mainnet until you understand gas fees, Transaction confirmation, and wallet security. Never share your private key or seed phrase with any DeFi application. {{< /faq >}}

{{< faq question="What is the difference between a CEX and a DEX?">}} A centralized exchange (CEX) like Coinbase holds your funds and matches orders on a central database. A decentralized exchange (DEX) executes trades on-chain via smart contracts. DEXes require no KYC, give you full custody of funds, but may have higher slippage and slower execution. Many users use both — CEXes for fiat on-ramp, DEXes for trading. {{< /faq >}}

{{< faq question="How do DeFi protocols make money?">}} DEXes charge swap fees (typically 0.05% to 0.30% per trade). Lending protocols take a spread between deposit and borrow rates. Protocols may also charge withdrawal fees, performance fees on yield vaults, or sell newly minted governance tokens. These fees are distributed to liquidity providers, token stakers, or the protocol treasury.{{< /faq >}}

Next Steps

NFTs Creation Trading Storage — Learn about non-fungible tokens and the digital asset ecosystem.

Layer 2 Scaling Solutions — Understand how rollups make DeFi affordable.

Cross-Chain Bridges — Move assets between blockchains securely.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro