Skip to content
Published on

The Complete DeFi and Blockchain Guide for Developers: From Smart Contracts to Profit Strategies

Authors
  • Name
    Twitter

Introduction

In 2026, the DeFi market is rapidly blurring the boundaries with TradFi (Traditional Finance). With tokenized securities, on-chain privacy, and accelerating institutional investor inflows, DeFi is no longer a niche market. For developers, understanding this technology is becoming increasingly important.

In this article, we dissect the core mechanisms of DeFi through a developer's lens.

Blockchain Basics — A Developer's Perspective

What Are Smart Contracts?

Smart contracts are programs deployed on the blockchain. Once deployed, they are immutable, anyone can verify the code, and they execute automatically when conditions are met.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

// Simple token swap contract
contract SimpleSwap {
    mapping(address => uint256) public balanceA;
    mapping(address => uint256) public balanceB;

    uint256 public reserveA;
    uint256 public reserveB;

    // Add liquidity
    function addLiquidity(uint256 amountA, uint256 amountB) external {
        // Transfer tokens to the contract (in practice, ERC20 transferFrom)
        reserveA += amountA;
        reserveB += amountB;
    }

    // Swap Token A -> B (AMM: x * y = k)
    function swapAforB(uint256 amountA) external returns (uint256 amountB) {
        uint256 k = reserveA * reserveB;  // Constant product invariant
        uint256 newReserveA = reserveA + amountA;
        uint256 newReserveB = k / newReserveA;
        amountB = reserveB - newReserveB;

        reserveA = newReserveA;
        reserveB = newReserveB;

        return amountB;
    }
}

Ethereum Transaction Flow

User Wallet (MetaMask)
Transaction Signing
Node (Infura/Alchemy)
Broadcast
Mempool
Block Inclusion (Gas Fee Competition)
Block Finalization
State Change
Smart Contract Execution

DeFi Core Protocol Analysis

1. DEX (Decentralized Exchange) — Uniswap

Uniswap uses the AMM (Automated Market Maker) mechanism, automatically swapping tokens from liquidity pools without an Order Book.

Core Formula: x * y = k

# AMM Simulation
class ConstantProductAMM:
    def __init__(self, reserve_a: float, reserve_b: float, fee: float = 0.003):
        self.reserve_a = reserve_a
        self.reserve_b = reserve_b
        self.fee = fee
        self.k = reserve_a * reserve_b

    def get_price(self) -> float:
        """Price of Token A (in Token B terms)"""
        return self.reserve_b / self.reserve_a

    def swap_a_for_b(self, amount_a: float) -> float:
        """Swap Token A for Token B"""
        # Deduct fees
        amount_a_after_fee = amount_a * (1 - self.fee)

        # Apply x * y = k formula
        new_reserve_a = self.reserve_a + amount_a_after_fee
        new_reserve_b = self.k / new_reserve_a
        amount_b_out = self.reserve_b - new_reserve_b

        self.reserve_a = new_reserve_a
        self.reserve_b = new_reserve_b
        self.k = self.reserve_a * self.reserve_b

        return amount_b_out

    def calculate_price_impact(self, amount_a: float) -> float:
        """Calculate price impact"""
        price_before = self.get_price()
        # Temporary swap
        amount_b = self.swap_a_for_b(amount_a)
        price_after = self.get_price()
        # Rollback
        self.reserve_a -= amount_a * (1 - self.fee)
        self.reserve_b += amount_b
        self.k = self.reserve_a * self.reserve_b

        return abs(price_after - price_before) / price_before * 100

# Usage example
pool = ConstantProductAMM(1_000_000, 1_000_000)  # 1:1 pool
print(f"Initial price: {pool.get_price():.4f}")
# Initial price: 1.0000

amount_out = pool.swap_a_for_b(10_000)
print(f"10,000 A -> {amount_out:.2f} B")
# 10,000 A -> 9,940.18 B (slippage occurs)

print(f"Price after swap: {pool.get_price():.4f}")
# Price after swap: 1.0202 (price movement)

2. Lending Protocol — Aave

# Lending protocol mechanism simulation
class LendingPool:
    def __init__(self):
        self.deposits = {}      # Deposits per user
        self.borrows = {}       # Borrows per user
        self.total_deposits = 0
        self.total_borrows = 0
        self.base_rate = 0.02   # Base interest rate 2%
        self.slope1 = 0.04      # Slope below optimal utilization
        self.slope2 = 0.75      # Slope above optimal utilization
        self.optimal_utilization = 0.80  # Optimal utilization 80%

    def utilization_rate(self) -> float:
        """Utilization = Total Borrows / Total Deposits"""
        if self.total_deposits == 0:
            return 0
        return self.total_borrows / self.total_deposits

    def borrow_rate(self) -> float:
        """Variable borrow interest rate based on utilization"""
        u = self.utilization_rate()
        if u <= self.optimal_utilization:
            return self.base_rate + (u / self.optimal_utilization) * self.slope1
        else:
            excess = (u - self.optimal_utilization) / (1 - self.optimal_utilization)
            return self.base_rate + self.slope1 + excess * self.slope2

    def supply_rate(self) -> float:
        """Supply interest rate = Borrow rate * Utilization"""
        return self.borrow_rate() * self.utilization_rate()

    def deposit(self, user: str, amount: float):
        self.deposits[user] = self.deposits.get(user, 0) + amount
        self.total_deposits += amount

    def borrow(self, user: str, amount: float, collateral_value: float):
        # LTV (Loan-to-Value) check
        max_borrow = collateral_value * 0.75  # 75% LTV
        current_borrow = self.borrows.get(user, 0)
        if current_borrow + amount > max_borrow:
            raise ValueError(f"LTV exceeded: max {max_borrow}, current {current_borrow}")

        self.borrows[user] = current_borrow + amount
        self.total_borrows += amount

# Simulation
pool = LendingPool()
pool.deposit("Alice", 1_000_000)  # Deposit $1 million
pool.borrow("Bob", 600_000, 1_000_000)  # Borrow $600K

print(f"Utilization rate: {pool.utilization_rate():.1%}")
# Utilization rate: 60.0%
print(f"Borrow rate: {pool.borrow_rate():.2%}")
# Borrow rate: 5.00%
print(f"Supply rate: {pool.supply_rate():.2%}")
# Supply rate: 3.00%

3. Yield Farming

# Yield Farming profit calculation
class YieldFarm:
    def __init__(self, pool_name: str, tvl: float, daily_rewards: float):
        self.pool_name = pool_name
        self.tvl = tvl  # Total Value Locked
        self.daily_rewards = daily_rewards

    def apr(self) -> float:
        """Annual Percentage Rate (simple interest)"""
        return (self.daily_rewards * 365) / self.tvl * 100

    def apy(self, compounds_per_year: int = 365) -> float:
        """Annual Percentage Yield (compound interest)"""
        daily_rate = self.daily_rewards / self.tvl
        return ((1 + daily_rate) ** compounds_per_year - 1) * 100

    def impermanent_loss(self, price_ratio: float) -> float:
        """Impermanent loss calculation
        price_ratio: current price / initial price
        """
        il = 2 * (price_ratio ** 0.5) / (1 + price_ratio) - 1
        return il * 100  # Percentage

# ETH-USDC pool example
farm = YieldFarm("ETH-USDC", tvl=10_000_000, daily_rewards=5_000)
print(f"APR: {farm.apr():.1f}%")
# APR: 18.2%
print(f"APY: {farm.apy():.1f}%")
# APY: 20.0%

# If ETH price doubles
il = farm.impermanent_loss(2.0)
print(f"Impermanent loss (2x price): {il:.2f}%")
# Impermanent loss (2x price): -5.72%

DeFi Risk Analysis

1. Smart Contract Risks

// Vulnerable code example - Reentrancy attack
// Never use this pattern!
contract Vulnerable {
    mapping(address => uint256) public balances;

    // Dangerous: state change after external call
    function withdraw() external {
        uint256 amount = balances[msg.sender];
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success);
        balances[msg.sender] = 0;  // State change after external call!
    }
}

// Safe pattern: Checks-Effects-Interactions
contract Safe {
    mapping(address => uint256) public balances;

    function withdraw() external {
        uint256 amount = balances[msg.sender];
        balances[msg.sender] = 0;  // State change first!
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success);
    }
}

2. Key Risk Summary

RiskDescriptionMitigation
Smart contract bugsAsset theft through code vulnerabilitiesOnly use audited protocols
Impermanent lossLoss from price fluctuation during LP provisionChoose correlated asset pairs
Oracle manipulationUnfair liquidation through price feed tamperingChoose protocols using multiple oracles
Regulatory riskRegulatory changes by countryMonitor regulatory trends
Rug pullDevelopers stealing fundsCheck TVL, team history, code verification

DeFi Participation Strategies for Developers

Conservative Strategy: Stablecoin Deposits

Risk: ★☆☆☆☆
Expected return: 3-8% APY

Method:
1. Deposit USDC/USDT on Aave
2. Earn lending interest
3. Bonus: Aave token rewards

Note: Stablecoins also carry depegging risk

Moderate Strategy: Correlated Asset Liquidity Provision

Risk: ★★★☆☆
Expected return: 10-25% APY

Method:
1. Provide liquidity to correlated asset pair pools (e.g., ETH-stETH)
2. Earn trading fees + reward tokens
3. Low impermanent loss (since prices move similarly)

Note: Smart contract risk still exists

Aggressive Strategy: Leveraged Yield Farming

Risk: ★★★★★
Expected return: 30-100%+ APY

Method:
1. Deposit assets
2. Borrow against deposited assets
3. Provide liquidity again with borrowed funds (leverage)
4. Fees + rewards exceed interest

Note: Liquidation risk, complex position management required

Web3 Development Tools

# Hardhat - Smart contract development environment
npm install --save-dev hardhat
npx hardhat init

# Foundry - Fast development tool based on Rust
curl -L https://foundry.paradigm.xyz | bash
foundryup

# ethers.js - Frontend integration
npm install ethers
// Querying DeFi protocols with ethers.js
import { ethers } from 'ethers'

const provider = new ethers.JsonRpcProvider('https://eth.llamarpc.com')

// Uniswap V3 pool price query
const poolAddress = '0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8' // USDC/ETH
const poolABI = [
  'function slot0() view returns (uint160, int24, uint16, uint16, uint16, uint8, bool)',
]
const pool = new ethers.Contract(poolAddress, poolABI, provider)

const [sqrtPriceX96] = await pool.slot0()
const price = (Number(sqrtPriceX96) / 2 ** 96) ** 2 * 1e12 // Price calculation
console.log(`ETH/USDC: $${price.toFixed(2)}`)

Taxes and Regulations

In South Korea, cryptocurrency taxation has been deferred to 2027, but it is wise to prepare in advance:

  • Trading gains: 22% tax on amounts exceeding 2.5 million KRW (planned)
  • DeFi income: Likely to be classified as miscellaneous income
  • Record keeping: Mandatory to record the KRW-converted value of all transactions
# Transaction record management example
import csv
from datetime import datetime

def log_transaction(tx_type, asset, amount, usd_value, tx_hash):
    with open('defi_transactions.csv', 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([
            datetime.now().isoformat(),
            tx_type,  # deposit, withdraw, swap, harvest
            asset,
            amount,
            usd_value,
            tx_hash,
        ])

Summary

DeFi offers developers a unique opportunity to understand the inner workings of financial systems through code:

  • AMM mathematics: Orderbook-free trading realized with the x * y = k formula
  • Lending protocols: Supply/demand balance through utilization-based variable interest rates
  • Yield Farming: Maximizing returns through compound effects + reward tokens
  • Risk management: Smart contract audits and understanding impermanent loss are essential

Quiz: DeFi Knowledge Check (8 Questions)

Q1. What does k represent in the AMM formula x * y = k?

It is the constant product invariant — the product of the two token quantities in the liquidity pool, which remains constant before and after a swap.

Q2. Why does slippage occur?

In an AMM, the larger the trade volume, the more the pool ratio changes, resulting in a difference between the expected and actual exchange rates.

Q3. What is Impermanent Loss?

When providing liquidity, if token prices change, the asset value decreases compared to simply holding the tokens.

Q4. What happens when the utilization rate increases in a Lending Protocol?

The borrow interest rate rises sharply, suppressing borrowing demand and incentivizing deposits.

Q5. What pattern prevents reentrancy attacks?

The Checks-Effects-Interactions pattern: update state before making external calls.

Q6. What is the difference between APR and APY?

APR is the simple interest rate, APY is the compound interest rate. The more frequently compounding occurs, the higher APY is compared to APR.

Q7. How can you identify a rug pull?

Check for audit status, TVL size, team identity disclosure, open-source code, and liquidity lock duration.

Q8. What information should be recorded for cryptocurrency taxation in Korea?

You should record the date, type, asset, quantity, KRW-converted value, and transaction hash for all transactions.