DeFi Basics untuk Devs — Web3

DeFi Basics untuk Devs DeFi (Decentralized Finance) adalah ekosistem aplikasi keuangan yang berjalan di blockchain tanpa perantara (bank, broker). Sebagai…

DeFi Basics untuk Devs

DeFi (Decentralized Finance) adalah ekosistem aplikasi keuangan yang berjalan di blockchain tanpa perantara (bank, broker). Sebagai developer, memahami primitif DeFi penting untuk membangun atau mengintegrasikan protokol.

Primitif Utama DeFi

AMM (Automated Market Maker)

Uniswap menggunakan formula x * y = k (constant product) untuk menentukan harga:

// Liquidity Pool: ETH/USDC
// Pool berisi: 100 ETH dan 200,000 USDC
// k = 100 * 200000 = 20,000,000

// User mau beli 1 ETH:
// Pool ETH setelahnya: 99 ETH
// Pool USDC harus: k / 99 = 202,020.20 USDC
// User bayar: 202,020.20 - 200,000 = 2,020.20 USDC per ETH

// Semakin besar trade → semakin besar slippage (price impact)

// Swap via Uniswap Router (simplified):
// router.swapExactTokensForTokens(
//   amountIn,     // jumlah token input
//   amountOutMin, // minimum output (slippage protection)
//   path,         // [tokenIn, tokenOut]
//   to,           // recipient
//   deadline      // max timestamp
// )

Lending Protocol (Aave/Compound)

// Lender menyetor aset → dapat bunga
// Borrower setor collateral → bisa pinjam aset lain

// Contoh flow:
// 1. Alice deposit 10 ETH sebagai collateral
// 2. Alice bisa pinjam sampai ~75% nilai (LTV ratio)
//    → Pinjam 15,000 USDC (jika ETH = $2000)
// 3. Alice bayar bunga per detik (variable rate)
// 4. Jika nilai collateral turun → LIQUIDATION

// Sebagai developer, kamu interact via contract:
// aave.deposit(asset, amount, onBehalfOf, referralCode);
// aave.borrow(asset, amount, interestRateMode, referralCode, onBehalfOf);

Composability (Money Legos)

DeFi protocol bisa saling berinteraksi karena semuanya on-chain dan open-source:

// "Flash Loan Arbitrage" — pinjam tanpa collateral, untung, bayar balik
// Semua dalam 1 transaksi:
// 1. Pinjam 1000 USDC dari Aave (flash loan)
// 2. Swap USDC → ETH di Uniswap (harga lebih murah)
// 3. Swap ETH → USDC di Sushiswap (harga lebih mahal)
// 4. Bayar balik 1000 USDC + fee ke Aave
// 5. Profit!

Oracles (Chainlink)

// Smart contract tidak bisa akses data luar blockchain
// Oracle menyediakan data off-chain secara trustless

// Contoh: Baca harga ETH/USD dari Chainlink
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumer {
    AggregatorV3Interface internal priceFeed;

    constructor() {
        // ETH/USD Mainnet
        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
    }

    function getLatestPrice() public view returns (int) {
        (, int price,,,) = priceFeed.latestRoundData();
        return price; // 8 decimals (200000000000 = $2000.00)
    }
}

Risiko DeFi

Yang akan kamu pelajari