# Explain Like I'm 13: DeFi Explain Like I'm 5? Sorry, it's not Abacus. ## Background Central Banks have ruled over finances for eternities. The era of twilight began with the collapse of Lehman Brothers in 2008, following the recent collapse of Silicon Valley Bank in 2023. People lost money. Businesses froze. People had no control over their money while this event happened. A revolution happened, Decentralized Finance (DeFi). Instead of trusting authority, people began trusting code. DeFi uses smart contracts (a piece of code) which are automated rules and behave in a deterministic way, live on the blockchain. Now, no single person or bank can control your money. ## The flow of this blog: 1. The Traditional Finance System 2. Introduction to Decentralization 3. Integration of Decentralization & Finance 4. Decentralized Finance 5. Let's Compare, TradFi vs DeFi 6. Order book method for Trading 7. AMMs - Automated Market Makers ## The Traditional Finance System ### Introduction Traditional Finance (TradFi) refers to a centralized financial system where institutions such as banks, payment processors, and regulatory bodies control the flow and management of money. Activities like storing funds, transferring assets, or earning yields (e.g., through staking or interest) are carried out with the involvement and approval of trusted third-party intermediaries. In short, it's permission based finance as permission is required from a third-party to perform any action. - Assets -> Any resource with economic value such as a possession or property owned by an individual or business. - Staking -> Locking money, tokens or assets for a period of time and earning interest or rewards on that. ### Permission based finance - **Gold** -> People trusted the currency as they knew it's backed by something real and valuable. As there isn't unlimited gold, the government couldn't just print unlimited money. - **Central Banks** -> Print currency (based on gold previously, fiat currently). Manage interest rates and inflation. Federal Reserve in the US and RBI in India. - **Member Banks** -> Member banks borrow money from central banks or hold reserves there. They offer Savings accounts, Loans, etc. - **Payment Processors** -> Companies like Visa, Mastercard, Paypal are Payment Processors. Approve or deny your transactions. Charge platform fees for transactions. - **Businesses** -> Accept payments via banks or payment gateways. They rely on Payment Processors for Accepting Card Payments or Payment Portals. - **People** -> Trust banks to hold money. Trust payment processors to send/receive it. ### Current Currencies - **Fiat Currency** -> Fiat currency dosen't have intrinsic value (not backed by gold) but derives its value from government's and public trust and is backed by government's authority. - **Cryptocurrency** -> A digital currency, which is an alternative form of payment currency created using Blockchain technology | **Currency** | **What It's Backed By** | **Type** | | ---------------------- | ----------------------------------------------------------- | -------------- | | **U.S. Dollar (USD)** | Trust in U.S. government + authority to compel participants to trade using USD | Fiat currency | | **Indian Rupee (INR)** | RBI reserves (gold + foreign currencies) + market conditions | Fiat currency | | **Bitcoin (BTC)** | Scarcity (fixed supply) + decentralized consensus | Cryptocurrency | ### The TradFi Pyramid ![image](https://hackmd.io/_uploads/S1sejYkfee.png) ## Decentralization ### Introduction Decentralization means moving control away from a single person or organization and spreading it across a network of many participants. Instead of relying on a central authority, the system lets everyone follow the same rules, so no one can take unfair control or change things for their own benefit. This helps keep the network fair, secure, functional and trustworthy for everyone. This decentralization is achieved through technologies like Tor, Torrent, Blockchain, etc. For Decentralized Finance, we are using Blockchain technology. ### Centralization & Decentralization | **Centralized** | **Decentralized** | | ---------------------------------- | ---------------------------------- | | Users connecting to a hub | Network of peers (no middleman) | | One big hub, all control in center | Everyone is connected directly, peer-to-peer | | Single point of failure | No single point of failure | ### Visual Representation ![image](https://hackmd.io/_uploads/HyTooYyzll.png) ## Integration of Decentralization & Finance ### Motivation Even though Traditional finance is a proven working model with objective rules, over a certain course of time, things crash. Because at the end, the framework is centralized which is controlled by subjective humans and the people using these services suffer when something like this happens (which has happened again and again in history). The events indicate that people using these services don’t have control over their finances and we need to find a solution for this, which is Decentralized Finance that gives power to people and removes Centralization of power. ### How to create a financial system where we don't need banks to approve every move? To achieve this, we need a decentralized rule-checking mechanism that ensures everything functions reliably and no single party has more control than others. This is accomplished through pieces of code distributed across a network, known as smart contracts. These smart contracts are typically written in a programming language called Solidity. This is in Ethereum ecosystem. In the Solana Ecosystem, the pieces of codes are called programs and are written in Rust. ## Decentralized Finance ### Introduction Decentralized Finance (DeFi) is a technology focused on creating a new financial system that is accessible to everyone and eliminates the need to trust traditional intermediaries like banks. It achieves this by using blockchain technology, cryptography and smart contracts, with smart contracts serving as the core components that power DeFi applications. **Basic Building Blocks** - Smart Contracts → Code that replaces traditional banking processes and logic - Tokens → Digital representations of value - Wallets → Tools for holding and managing tokens (your digital money) - Protocols → Open, programmable systems for lending, trading, saving, and more. All built using smart contracts ### The Terms **Here are some of the terms used in DeFi space:** - Collateral -> It's a safety deposit. Something valuable that a borrower gives to a lender to secure a loan. If you don't repay your loan, the lender can take your collateral to recover the money. - Pool -> A collection of tokens locked together in a smart contract for a specific purpose like trading, lending or staking. - Liquidity -> How easily and quickly something can be turned into cash or traded. In DeFi, it refers to the amount of tokens available in a pool for trading, lending or borrowing. - Liquidity Pool -> A collection of tokens locked in a smart contract that allows people to trade between those tokens directly and easily. - Stablecoin -> Stablecoins are a type of cryptocurrency whose value is pegged to another asset, such as a fiat currency or gold, to maintain a stable price. - Fungible Tokens -> Fungible tokens are digital assets where each unit is identical and interchangeable with every other unit of the same type. This means they have the same value and properties, and one unit can be swapped for another without any loss or change in value. - Non-Fungible Tokens (NFT) -> Non-fungible tokens are unique and hence can't be replaced by other NFT. In contrast, physical money and cryptocurrencies are fungible. ### Let's explore the space #### 1. [Bitcoin](https://bitcoin.org/en/) - After the massive bank crash of Lehman Brothers in 2008, a financial revolution was needed. The following year, in 2009, Bitcoin was launched by the pseudonymous Satoshi Nakamoto, the first successful attempt at creating decentralized digital money. It introduced the concept of a peer-to-peer electronic cash system that doesn’t rely on banks or governments, while also ensuring transparency and trust. - Bitcoin's scripting language is Turing-incomplete (simply put, limitations on computation), meaning it doesn’t support complex financial functions like the smart contracts used on Ethereum. However, Bitcoin laid the foundation for the entire DeFi movement by proving that trustless currency transfer is possible. It remains the core idea of money decentralization in its purest form. #### 2. [Ethereum](https://ethereum.org/en/) - Ethereum launched in 2015 by Vitalik Buterin, unlocked the true potential of decentralized applications. Ethereum introduced smart contracts, pieces of code that run on the blockchain that execute automatically when the given conditions are met making them the self-enforcing aggreements replacing middlemen. This innovation allowed developers to build decentralized applications. - Ethereum is the strongest of all pillars of DeFi. Most major protocols like MakerDAO, Compound, Uniswap, etc. were built on Ethereum. It hosts largest DeFi ecosystem. #### 3. [MakerDAO](https://makerdao.com/) - MakerDAO, launched in 2017, is one of the first and most influential projects in the DeFi space. It allows users to lock up crypto assets like ETH as collateral and generate DAI, a stablecoin that maintain its value close to the US Dollar through economic incentives and smart contracts. - Maker's Oasis Platform is a decentralized interface developed by MakerDAO to interact with Maker protocol. DAI can be used for earning yield through this platform. This recreates one of the pillars of the financial system, lending and borrowing. #### 4. Lending and Borrowing **Some other DeFi projects in decentralized lending:** - **[Compound](https://compound.finance/)** -> One of the largest DeFi lending protocols. It operates as an algorithmic, autonomous interest rate protocol, allowing users to: Supply Assets like ETH, USDT to earn interest. Use supplied assets as collateral to borrow other tokens. - **[Aave](https://aave.com/)** -> Supports lending and borrowing with a wide variety of crypto assets and introduces innovations like flash loans. #### 5. Stablecoins Using smart contracts and economic incentives, DeFi can create stablecoins pegged to fiat currencies without needing physical reserves. - **DAI (by MakerDAO)** -> leading algorithmic stablecoin, generated by locking collateral like ETH into smart contracts. - **Centralized Stablecoins** -> Centralized coins, relying on a company to main reserves. USDT, USDC, etc. are backed by off-chain reserves (USD and other assets). #### 6. Decentralized Exchanges (DEXs) DEXs enable users to trade cryptocurrencies without any intermediaries, maintaining full control of their assets. - **Liquidity Pool-Based DEXs** -> Use automated market makers (AMMs) for trading. Mathematical equations are used for maintaining the liquidity of pool automatically. [Uniswap](https://app.uniswap.org/) is one of the most popular player in this space. - **Order Book-Based DEXs** Use traditional order book mechanics on-chain or in a hybridized way. Trades occurs directly between two parties where both the parties agree on the terms before the trade is executed. We'll explore both slightly deeper, further down this blog. #### 7. Oracles Smart contracts can’t access external data on their own, so oracles are essential for feeding real-world information into blockchains. In DeFi, oracles feed real-world information like the price of cryptocurrencies, stock or other assets to smart contracts. - **[Chainlink](https://chain.link/)** -> The most widely used decentralized oracle network, delivering secure and trusted data to smart contracts of DeFi protocols. #### 8. Derivatives DeFi also supports derivatives, contracts that derive their value from an underlying asset. They allow traders to profit by betting on the price movements of cryptocurrencies without actually owning the underlying assets. - **[Synthetix](https://www.synthetix.io/)** -> A platform that offers on-chain exposure to stocks, commodities, and fiat currencies through synthetic assets. It creates digital versions on the blockchain that track the price of real-world assets, enabling users to trade and own these synthetic copies. #### 9. Margin Trading Margin Trading involves borrowing assets to amplify trading trading positions similar to traditional finance. Borrowing funds to increase the size of trade, potentially allowing to make bigger profits or even bigger losses. - **[dYdX](https://www.dydx.xyz/)** - **[Fulcrum](https://fulcrum.trade/)** These allow decentralized leveraged trading. #### 10. Insurance DeFi-based insurance protocols offer protection against smart contract vulnerabilities and deposit losses. ### The DeFi Pyramid ![image](https://hackmd.io/_uploads/SyeFoFJMlx.png) ## Let's Compare, TradFi vs DeFi | Feature | Traditional Finance (TradFi) | Decentralized Finance (DeFi) | | -------------------- | ---------------------------------------------------- | ------------------------------------------------------------- | | **Control** | Centralized authorities like banks and regulators | Decentralized networks with no central authority | | **Access** | Permissioned finance and limited access | Permissionless finance and equal access to everyone | | **Transparency** | Limited, relies on trust in institutions | Transparent, transactions recorded on public blockchain ledger | | **Regulation** | Heavily regulated to protect consumers | Largely unregulated as of now | | **Privacy** | Personal data collected and stored by institutions | Pseudonymous, user controls their own data | | **Risk** | Subject to systemic risks and institutional failures | Smart contract vulnerabilities and market volatility | ## Order book Method for Trading Now that we have a basic understanding of DeFi, both individually and in comparison to TradFi. Let’s explore the trading ecosystem, which is where most DeFi products are built and where Blockchain technology demonstrates its greatest strength. Order books and Automated Market Makers (AMMs) are the foundational trading protocols in this space. Understanding how they work is essential to grasping how trading functions in DeFi. ### Introduction Order book is the list of buy and sell orders for a specific asset such as cryptocurrency or stock. Order books also show the amount of discrete units the users are seeking to buy or sell at a specific price. In simple terms, a party places an order for a certain price & another party agrees to pay that price for that order and the trade gets executed. ### Platforms - Order book is the traditional method for trading stocks, forex or commodities. [NYSE](https://www.nyse.com/index) (New York Stock Exchange), [Upstox](https://upstox.com/), etc. use the Order book method for trading stocks. - Though AMMs (Automatic Market Makers) dominate DEXs, order book based trading also exists in crypto space, both centralized(CEX) and decentralized(DEX). - Some Centralized Platforms are [Binance](https://www.binance.com/en-IN), [Coinbase](coinbase.com), etc. - Some Decentralized Platforms are [HyperLiquid](https://app.hyperliquid.xyz), [dYdX](https://www.dydx.xyz/), etc. ### Working - There are two parties in the trade, buyers & sellers. The buyers bid for shares at a certain price & the sellers ask a certain price for the shares they'll sell. The order book records these demands from buyers and sellers and places them on the list. - Traders can also employ trade limit order strategy by presetting the trade demand at a certain price level at which to buy or sell. When an order matches with the set demand, the trade executes. - The first trades that will occur are the highest bids & the lowest asks. The difference between the highest bid & the lowest ask is called the spread. - Slippage is an event that happens when there aren't enough assets/shares available at a current price to fill a market order. This can result the order being filled at a higher price than desired. There will be a difference between the expected price of a trade and the actual execution price. Slippage is calculated by that difference. - $$Slippage = \frac{AvgPricePaid- BestAskPrice}{BestAskPrice} \times 100$$ ### Working Example Buyers and Sellers have placed some limit bid and ask orders. The asset here is ETH and the price is USDT. As this is a limit order, the trade won't execute till the demand is fulfilled. Until then it's just a pending order in the order book. So, the order book now looks as follows: | Price (USDT) | Buy Orders (Bids) | Sell Orders (Asks) | |--------------|-------------------|-------------| | – | – | 2 ETH @ 2,020 each | | – | – | 1 ETH @ 2,015 each | | – | – | 3 ETH @ 2,010 each | | 2,005 | 1.6 ETH | – | | 2,000 | 2 ETH | – | | 1,990 | 4 ETH | – | #### Case 1: You place a buy order for 2 ETH - No demand was placed for buying 2 ETH, hence this was not a limit buy order. - The system checks for the lowest ask, which is 3 ETH @ 2,010 each. - Hence, the 2 ETH buy order gets matched entirely at 2,010 USDT, resulting in a buy. - Let's calculate the slippage, $$Avg Price Price = 4020\div2 = 2010$$ $$Best Ask Price = 2010$$ $$Slippage = \frac{2010- 2010}{2010} \times 100 = 0\%$$ - This means our expectation was the current best ask. #### Case 2: You place a buy order for 5 ETH - No demand was placed for buying 5 ETH, hence this was not a limit buy order. - The system checks for the lowest ask, which is 3 ETH @ 2,010 each. Then jumps to next lowest ask which is 1 ETH @ 2,015. Then jumps to fill the remaining 1 ETH as 1 ETH @ 2,020 from the 2 ETH @ 2020 ask. - Hence, the 5 ETH buy order gets split into (3 ETH @ 2,010 + 1 ETH @ 2,015 + 1 ETH @ 2,020) - Let's calculate the slippage, $$Avg Price Price = (3 \times2010+1\times2015+1\times2020)\div5 = 2013$$ $$Best Ask Price = 2010$$ $$Slippage = \frac{2013- 2010}{2010} \times 100 = 0.15\%$$ - The slippage was 0.15% and it happened because there wasn't enough ETH at 2,010 USDT (Best Ask Price). In other words, not enough liquidity. ## AMMs - Automated Market Makers ### Introduction Automated Market Makers (AMMs) maintain liquidity pools based on a mathematical formula, typically $x \cdot y=k$ (where $k$ is a constant), rather than having an order book which contains the orders from buyer and seller parties for maintaining liquidity. This formula ensures that trades can be executed automatically along the pricing curve, removing the need for direct negotiation between buyers and sellers. ### Platforms - **[Uniswap](https://app.uniswap.org/)** -> Most popular AMM protocol, allows permissionless token swaps and liquidiy provision. Makes use of the Constant Product Formula $x\cdot y=k$ (where $k$ is a constant) for maintaining liquidity. - **[Balancer](https://balancer.fi/)** -> Balancer is a decentralized automated market maker (AMM) protocol built on Ethereum with a clear focus on fungible and yield-bearing liquidity. Users can create custom pools as custom pools are ideal for any team developing custom trade equations and strategies. - **[PancakeSwap](https://pancakeswap.finance)** -> PancakeSwap is another decentralized exchange on BNB Smart Chain (Binance Smart Chain) with one of the highest trading volumes in the market (Trading volume refers to the total amount of an asset traded over a specific period of time). ### Building Blocks - Asset Token -> What the trader is buying, an asset or even a currency. Token/ Payment Token -> Currency being used to pay for the Asset Token. - Liquidity Pools in AMMs -> A smart contract based pool of tokens against which trades can be made for a certain amount of fee. Asset holders are incentized to stake their asset tokens in the pool by providing them a portion of profit of the pool, proportional to the amount of their assets staked. - LP tokens -> The portion of assets that the asset holders wish to stake are converted to the form of tokens which are then staked in pools using a smart contract. These are called LP tokens minted specially for the Liquidity provider's wallet. - Trading Fees -> The charges on traders for trading on the pool which will be mostly accured to the pool. The asset stakers will receive a portion of this as a profit, which will be a certain percentage of their total assets staked on the pool. - Price Curve -> The price curve will take into account the current liquidity for the token pairs (x & y) in the pool, the price for which the trade has been initiated and then the asset tokens that will be brought/sold will be calculated based on the curve equation. After the trade, the liquidity in the pool will again be maintained by the curve equation. The price curve's most basic and common form is $x*y=k$ (where $k$ is a constant). ### Working - $x$ -> denotes the amount of X tokens in the pool $y$ -> denotes the amount of Y tokens in the pool $k$ -> is the constant $$x \cdot y = k$$ - Let's say, a trader trades $\delta x$ tokens to buy $\delta y$ asset tokens. - The equation becomes, $$(x + \delta x) \cdot (y + \delta y) = k$$ - We know $x$, $y$, $\delta x$, $k$. We can find $\delta y$ as follows, $$ \delta y = \frac{k}{(x + \delta x)} -y $$ $$ y = \frac{k}{x} $$ - From this, we can say that we received $\delta y$ asset tokens in exchange, which turns out to be negative. $\delta x$ is positive, which signified that token $X$ was put into the pool. So, the negative sign signifies that $\delta y$ amount of token $Y$ was taken out of the pool and we received them. ### Working Example - Let $x = 1000$ ETH & $y = 2000000$ USDT, which makes our $k = 2 \times 10^9$ - We trade $2$ ETH, so, $\delta x = 2$ - The equation becomes, $$(1000 + 2) \cdot (2000000 + \delta y) = 2 \times 10^9$$ - Solving for $\delta y$, we get, $$ \delta y = -3992.02$$ - This means, we traded $2$ ETH for $3992.02$ USDT. - Hence, we got the USDT at the rate of $1996.01$ USDT $per$ ETH. ## Summary - Traditional finance is centralized finance system which has been on action since a very long time. - Decentralized finance is based on Blockchain technology, which decentralizes the financial system through pieces of codes called smart contracts. - Traditional finance and Decentralized finance has been compared and Decentralized finance shows more benefits. - Order books and AMMs are trading mechanisms. - Order book maintains a list of bid and ask demands upon which trading takes place. - AMMs are Automated Market Makers which maintain the liquidity pools according to a mathematical condition, $x \cdot y = k$, and executes trades along the pricing curve based on this condition.