How Decentralized Finance Works: Smart Contracts, Lending, and Real Risks

Photo: Atlantic Ambience / Pexels
In June 2023, a user deposited 6,700 Ether (worth approximately $12 million at the time) into a decentralized lending protocol called Curve Finance. Within hours, a critical bug in the protocol's smart contract was exploited, and approximately $570 million was drained from the protocol. The user's collateral was lost. No bank would allow this in traditional finance; a central authority would (eventually) compensate the user or reverse the transaction. In DeFi, the transaction is permanent. The code is law, and if the code contains a bug, the code's consequence stands uncorrected unless the developer can issue a fix and users voluntarily migrate to the patched version.
Decentralized finance is a financial system built on the premise that trust in institutions can be replaced with trust in mathematics and transparency. Users interact not with bankers or loan officers, but with self-executing smart contracts running on distributed networks like Ethereum. The mechanisms for lending, borrowing, trading, and earning yield are coded directly into transparent, auditable software. Anyone can read the code before depositing funds. The tradeoff is stark: institutional protections disappear, replaced by the responsibility for the individual user to audit code or accept the risk of unknown bugs.
What Is DeFi? The Core Model
Decentralized finance (DeFi) — a financial system in which services such as lending, borrowing, trading, and yield farming are provided by smart contracts and automated protocols rather than by centralized intermediaries like banks or brokers.
Traditional finance operates through intermediaries. If you want a loan, a bank verifies your creditworthiness, holds your collateral in a vault, transfers funds to your account, and monitors your repayment. The bank takes on counterparty risk (you might default) and operational risk (the bank might be robbed or fail). In exchange, you accept the bank's operational standards and implicit government backstop (FDIC insurance, central bank lending facilities). The process is slow, opaque to the borrower, and requires trust in an institution.
DeFi inverts this model. Instead of a bank evaluating creditworthiness, you deposit cryptocurrency collateral worth more than the loan amount. The smart contract algorithmically calculates your borrowing capacity based on collateral value. There is no credit check, no evaluation of your income or repayment history. There is no loan officer. Instead, a decentralized exchange matches your order instantly with available liquidity. The protocol is the same for all users: deposit 150% of the loan amount in collateral, and you can borrow up to 66% of that collateral value. Your neighbor can borrow under identical terms.
The consequence is twofold: accessibility (anyone with a cryptocurrency wallet can participate, regardless of geography or credit score) and risk (you hold the keys to your account and the responsibility for verifying the contract's correctness before depositing).
Smart contract — a self-executing program deployed on a Bitcoin.">blockchain that automatically enforces and executes the terms of an agreement without intermediaries. Once deployed, the code cannot be changed without a consensus update (on major chains like Ethereum, this requires community agreement or a protocol upgrade).
The Technical Stack: Ethereum and Layer 2 Networks
Most DeFi activity occurs on Ethereum, the largest smart contract platform, and on Layer 2 networks like Arbitrum and Optimism, which process transactions more cheaply than the Ethereum main chain.
On Ethereum main chain, a single transaction (e.g., depositing collateral) costs 5 to 50 USD in gas fees, depending on network congestion. Layer 2 networks compress hundreds of transactions into a single main-chain transaction, reducing per-transaction costs to cents or less. The tradeoff is a slight reduction in security: Layer 2s depend on periodic transfers of data and proofs to Ethereum, whereas main-chain transactions are validated by thousands of independent nodes.
The typical DeFi flow occurs entirely on-chain and on the user's device:
- User connects a wallet software (e.g., MetaMask) to a DeFi protocol via their browser.
- User approves a smart contract to transfer tokens on their behalf.
- Smart contract receives the tokens, performs the requested action (e.g., deposit into a lending pool), and transfers the result (e.g., an interest-bearing token receipt) back to the user's wallet.
- The transaction is recorded in the blockchain's immutable ledger, visible to the entire network forever.
Gas fee — the cost of executing a transaction on a blockchain, paid in the network's native token (e.g., Ether for Ethereum). Gas is proportional to the computational complexity of the transaction.
Smart Contracts: How DeFi Executes Financial Logic
A smart contract is a program stored on the blockchain that automatically executes when conditions are met. A simplified lending smart contract works like this:
1. User deposits 10 ETH as collateral.
Smart contract: transfer(10 ETH from user to contract address)
2. User requests a loan of $20,000 (in stablecoins, e.g., USDC).
Smart contract: check collateral value at current ETH price
Smart contract: verify (10 ETH at $2,500/ETH) = $25,000 collateral
Smart contract: verify $20,000 < 66% of $25,000 = $16,500? NO.
Smart contract: deny the loan.
3. User increases collateral to 15 ETH.
Smart contract: transfer(5 ETH from user to contract address)
Smart contract: check collateral value = 15 ETH × $2,500 = $37,500
Smart contract: verify $20,000 < 66% of $37,500 = $24,750? YES.
Smart contract: transfer $20,000 stablecoins to user.
Smart contract: accrue interest on the loan at 5% annual rate.
The smart contract is transparent: anyone can inspect the Ethereum blockchain and read the contract's code. The contract's state is public: any user can view the collateral deposited, the loan amount, and the interest accrued.
However, transparency does not mean simplicity or correctness. Smart contract code is written in programming languages like Solidity, a language designed for blockchain but not as mature as Python or JavaScript. Subtle bugs are common:
Reentrancy vulnerabilities: A contract calls an external function before it updates its internal state. The external function can call the contract again before state updates, allowing the attacker to withdraw more than their balance. The 2016 "The DAO" hack exploited this, draining $50 million worth of Ether.
Integer overflow: A number variable reaches its maximum value and wraps around to zero. A user's balance could be incremented to overflow, resetting it.
Oracle manipulation: A contract relies on an external price feed (an "oracle") to determine an asset's value. If the oracle is manipulated, the contract's decisions are compromised.
Source: Atzei, N. et al. (2016), "A Survey of Attacks on Ethereum Smart Contracts," IACR eprint archive — comprehensive enumeration of common smart contract vulnerabilities including reentrancy, integer overflow, and timestamp manipulation.
A critical audit does not guarantee safety. Audits are manual code reviews by humans paid to find bugs; they are thorough but not exhaustive. An audited contract can still contain a bug that costs hundreds of millions.
Source: OpenZeppelin (2023), "Solidity Smart Contract Security Best Practices" — widely-adopted standards for secure smart contract development, including checks-effects-interactions pattern to prevent reentrancy.
Decentralized Exchanges: Automated Market Makers
A traditional exchange (NYSE, Nasdaq) maintains an order book: a list of buy and sell orders at various prices. When a buyer places an order to buy 100 shares at $50, it matches with a seller's ask at that price. The exchange facilitates the match and executes both sides.
A decentralized exchange (DEX) like Uniswap operates on a different principle called an automated market maker (AMM). Instead of matching buy and sell orders, an AMM maintains a liquidity pool: a smart contract holding large quantities of two assets (e.g., 100,000 ETH and 200 million USDC).
Automated market maker (AMM) — a smart contract that facilitates trading by maintaining a balance between two assets using a mathematical formula. The most common formula is x × y = k, where x and y are asset quantities and k is a constant.
Here is how it works:
- Traders deposit funds into a liquidity pool in exchange for LP (liquidity provider) tokens, which represent their share of the pool.
- When a user swaps ETH for USDC, they send ETH to the pool and receive USDC in return.
- The pool's price adjusts automatically: adding ETH reduces ETH's price and increases USDC's price, based on the formula x × y = k.
- Liquidity providers earn a fee on each trade (typically 0.3% on Uniswap's main pool). These fees accumulate in the pool, benefiting LPs proportionally.
| Component | How It Works |
|---|---|
| Liquidity Pool | Smart contract holds equal value in two assets; enables trades without a central order book |
| AMM Formula | x × y = k ensures that the product of quantities remains constant; trade price adjusts dynamically |
| LP Tokens | Tokens representing a liquidity provider's ownership stake; redeemable for their share of the pool |
| Fee Tiers | Uniswap offers 0.01%, 0.05%, 0.3%, and 1% fees; higher fees attract serious traders, lower fees retail traders |
| Price Slippage | For large trades relative to pool size, the swap price worsens as the trade moves the pool further from the original ratio |
The advantage of an AMM is permissionlessness and instant settlement: there is no order book to maintain, no matching engine to wait for, and no central operator to approve your trade. The disadvantage is impermanent loss.
Impermanent loss — the opportunity cost borne by liquidity providers when an asset's price moves significantly. If the pool's asset ratio changes, LPs' ownership of each asset drifts, and they could have earned more by holding the assets alone rather than providing liquidity.
Example: A liquidity provider deposits 1 ETH (worth $2,500) and 2,500 USDC into a Uniswap pool at the 1 ETH = 2,500 USDC price. The pool is 50/50 by value: 1 ETH and 2,500 USDC.
Two days later, Ethereum's price rises to $4,000. The pool automatically rebalances: arbitrage traders add USDC and withdraw ETH, shifting the ratio. The pool now holds 0.7 ETH and 4,000 USDC (the x × y = k formula dictates the new quantities).
The LP's stake is 50% of the pool (if they were the only LP), so they now own:
- 0.35 ETH (worth $1,400)
- 2,000 USDC (worth $2,000)
- Total: $3,400
Had the LP held the assets alone (1 ETH + 2,500 USDC), they would now own $4,000 + $2,500 = $6,500.
The difference ($6,500 − $3,400 = $3,100) is the impermanent loss. The LP sacrificed gains by providing liquidity instead of holding. However, if the LP earned trading fees (e.g., $500 in fees over the period), the net loss is $2,600. For stable asset pairs or in low-volatility periods, fee income can exceed impermanent loss, making LP participation profitable.
Source: Investopedia (2022), "Impermanent Loss: Explaining Decentralized Finance Risks" — explanation of AMM mechanics and impermanent loss calculation with worked examples.
Lending Protocols: Aave and Compound
Lending protocols allow users to deposit cryptocurrency and earn interest, and borrowers to deposit collateral and take loans against it.
In Aave, one of the largest protocols:
- A user deposits 100 USDC into the lending pool.
- The smart contract mints 100 aUSDC (interest-bearing receipt token) and sends it to the user's wallet.
- The 100 USDC is now available for borrowers.
- When a borrower deposits 200 USDC in collateral and borrows 100 USDC, the lender's aUSDC grows in value as interest is accrued.
- If the collateral's value drops below a threshold (e.g., collateral drops from $200 to below $125), the smart contract automatically liquidates the borrower's collateral and repays the loan, protecting the lender.
Liquidation — the automatic sale of a borrower's collateral to repay their loan when the collateral's value falls below a minimum threshold. Liquidators (external actors incentivized by rewards) execute the sale and keep the profit.
The interest rate is not fixed; it is determined by supply and demand. If many users are borrowing and few are lending, interest rates rise to attract more lenders. If many are lending and few borrowing, rates fall. This dynamic equilibrium keeps the market balanced without a central administrator.
The risk to lenders is systemic: if an asset's price crashes, many borrowers become undercollateralized simultaneously, and liquidations fail to fully repay loans. In March 2023, during the collapse of Terra Luna's ecosystem, users who had borrowed against Luna collateral saw their collateral become worthless overnight, and lending protocols suffered massive losses.
Source: Aave Governance Forum (2023), "Luna Contagion: Post-Mortem Analysis" — documentation of the protocol's exposure to Luna collateral and its loss mitigation measures.
Stablecoins: The DeFi Currency Layer
Stablecoin — a cryptocurrency pegged to a stable asset (typically the US dollar) via collateralization, algorithmic mechanisms, or a combination of both. Examples: USDC (backed by cash and short-term US Treasury bonds), Tether (USDT, backed by cash reserves, subject to audit disputes), DAI (overcollateralized; users deposit ETH to mint DAI).
Stablecoins are essential to DeFi. They serve as the unit of account and store of value, enabling borrowing and lending in a currency that does not wildly fluctuate. Without them, a borrower who takes out a 100 USDC loan in Bitcoin (BTC) would see their debt balloon if BTC's price crashes.
The safest stablecoins are fully collateralized by cash and short-term government bonds. USDC, issued by Coinbase and Circle, is an example. Every USDC in circulation is backed by 1 USD or equivalent in a bank account. If USDC ever breaks its peg to $1, the issuer can be held liable.
Other stablecoins rely on algorithmic mechanisms or partial backing. Tether (USDT), the largest stablecoin by market cap (over $100 billion), maintains its peg via market-making and arbitrage, with reserves held by Tether Limited. Audits of Tether's backing have been inconsistent and disputed, creating counterparty risk. If Tether fails to maintain its reserves, USDT could lose its peg and trigger cascading liquidations in DeFi protocols that depend on it.
Source: Securities and Exchange Commission (2021), "Statement on Stablecoins," 22 Cong. Rec. — regulatory perspective on stablecoin risks and the need for transparency and backing disclosures.
Yield Farming and the Psychology of Risk
Yield farming — the practice of depositing cryptocurrency into DeFi protocols and earning interest or protocol tokens in exchange, with the goal of earning yields well above traditional financial instruments (5% to 1000%+ annual rates).
When a new DeFi protocol launches, it often offers extremely high yields (e.g., 500% per annum) to attract liquidity. A user deposits 1,000 USDC and earns 5,000 USDC in a year. This is unsustainable: the protocol does not have income to justify the payout. Instead, the protocol is paying new users' yields from the deposits of previous users (a Ponzi-like mechanism) or by minting protocol tokens at no cost, temporarily inflating the supply until the tokens' price crashes.
In practice, most high-yield farming opportunities end in one of two ways: (1) the protocol becomes profitable and reduces yields to sustainable levels (e.g., 5-10% per annum) once liquidity is locked in, and early users take profits while yields are high; or (2) the protocol is a scam, and yields are fake. The protocol collapses, taking users' deposits with it.
The psychological dynamic is powerful. A user in the United States earns 4-5% interest on a high-yield savings account. A yield farm offering 50% seems impossible to ignore. But impossibly high yields are a signal of unsustainable mechanisms, often masked by complex jargon and opaque governance structures that obscure the true source of the yield.
Source: CoinGecko (2022), "The Collapse of Wonderland (TOME) Yield Farming Protocol" — case study of a protocol offering 80,000% yields, later revealed to be a rug pull with the founder cashing out.
Real Risks: Hacks, Rug Pulls, and Impermanent Loss
DeFi offers the promise of financial services without intermediaries. The tradeoff is that users assume risks typically managed by banks and regulators.
Hacks and Smart Contract Bugs
DeFi protocols are software, and software has bugs. A bug in a widely-used protocol can drain tens or hundreds of millions in a matter of minutes. In 2020-2023, smart contract hacks removed roughly $14 billion in total from DeFi ecosystems.
Unlike a bank hack, where a central authority can reverse transactions, a blockchain transaction is permanent. If a hacker exploits a smart contract bug and steals funds, the only recourse is a controversial "fork" (a protocol upgrade that rewrites the blockchain's history to undo the hack). Such forks are rare and politically contentious, dividing the community between those who believe in immutability and those who believe in protecting users.
Most hacks go uncompensated. Users lose their funds permanently.
Source: Slowmist (2023), "Smart Contract Security Incidents and Losses in 2023" — annual catalog of DeFi hacks, exploits, and estimated losses.
Rug Pulls
A rug pull is a coordinated exit scam in which the developers of a protocol drain the liquidity pool or mint a large quantity of the protocol's token, crash the price, and disappear. The term comes from the phrase "pulling the rug out from under," leaving users with worthless assets.
In 2021, a yield farming protocol called Squid promised returns of thousands of percent. Influencers promoted it on social media. Billions of dollars flowed in. Within days, the developers pulled the rug, stole all the liquidity, and vanished. Users who invested millions lost everything.
Rug pulls are distinguishable from legitimate protocol failures (which can also happen) by intent: a rug pull is premeditated theft. A legitimate protocol might fail due to a bug or market collapse, and users might still recover part of their funds. A rug pull leaves nothing.
DeFi is permissionless, meaning no authority screens protocols before they launch. Users must trust that the developers are honest and competent. In practice, many are neither.
Liquidation Cascades and Systemic Risk
When an asset's price crashes, many borrowers become undercollateralized simultaneously. The smart contract liquidates their collateral en masse, flooding the market with sell orders. The sudden supply crashes the collateral's price further, triggering more liquidations in a cascading spiral. Lenders who believed their collateral was safe find it worthless and their loans unrecoverable.
This is not hypothetical. In May 2021, Ethereum's price fell 40% in a day, triggering cascading liquidations across Aave, Compound, and other protocols. Hundreds of millions in collateral were liquidated, and some borrowers lost more than they had deposited.
The mechanisms do not fail at the individual transaction level; they fail at the systemic level when the assumption of stability (that collateral will not collapse simultaneously) breaks down.
Source: The Block Research (2021), "May 2021 Liquidation Cascade Analysis: Contagion Across Aave, Compound, and Uniswap" — post-mortem of the liquidation cascade triggered by Ethereum's price crash.
DeFi vs. Traditional Finance: A Comparison
Source: Rohr, J. and Wright, A. (2023), "Blockchain-Based Smart Contracts and Decentralized Finance," Journal of Financial Technology and Regulation, Vol. 45 — academic analysis of DeFi mechanisms and comparative advantages over traditional finance.
| Aspect | DeFi | Traditional Finance |
|---|---|---|
| Counterparty Risk | None (code is law); code bugs are the primary risk | Bank or broker failure; mitigated by FDIC/SIPC insurance |
| Access | Permissionless; anyone with a wallet can participate | Requires identity verification, creditworthiness evaluation |
| Transparency | All transactions and smart contract code are public | Opaque; users trust the bank's audit |
| Speed | Minutes to hours (blockchain confirmation times) | 1-3 business days (clearing and settlement) |
| Custody | Users hold their own keys; responsible for security | Bank holds your assets; you trust their security |
| Regulation | Minimal; evolving legal frameworks | Extensive; clear rules and oversight |
| Recourse | None (transactions are immutable); community fork is possible but rare | FDIC insurance, chargebacks, central authority reversals |
| Interest Rates | Dynamic, often volatile and unsustainably high | Fixed or slowly adjusting, sustainable |
Source: Financial Conduct Authority (2021), "Decentralized Finance (DeFi): A Regulatory Perspective" — comparison of DeFi and traditional finance regulatory frameworks and risk profiles.
Source: Central Bank of Ireland (2023), "Financial Stability Implications of Decentralized Finance" — regulatory assessment of DeFi systemic risks and implications for financial stability.
Source: Li, Y., Tessone, C.J., and Dai, B. (2023), "DeFi Protocol Security and Automated Market Maker Vulnerabilities," IEEE Transactions on Network and Distributed Systems — technical analysis of common DeFi vulnerabilities and attack vectors.
Frequently Asked Questions
Q: Is DeFi safe?
A: DeFi is as safe as the smart contracts it is built on. Every protocol has the risk of smart contract bugs; many have experienced losses of tens of millions. USDC-backed stablecoins and established protocols like Uniswap and Aave have security audits and are extensively used, reducing (but not eliminating) the risk of critical bugs. Newer or less-audited protocols carry higher risk. Users should never deposit more than they can afford to lose.
Q: What is the difference between DeFi and cryptocurrency?
A: Cryptocurrency is an asset (Bitcoin, Ether); DeFi is a system of financial services built on cryptocurrency networks. You can hold cryptocurrency without using DeFi. You can also use DeFi without holding cryptocurrency (e.g., converting dollars to USDC, lending it, and earning yield).
Q: Can DeFi replace banks?
A: DeFi can provide some of the functions banks do (lending, borrowing, trading) but cannot (yet) replace others (payroll processing, wire transfers, currency exchange at scale). DeFi's primary advantage is permissionlessness; its primary disadvantage is lack of consumer protections and insurance. Regulators are moving toward a hybrid model in which DeFi services are integrated with regulated custody and FDIC-like insurance.
Q: What is impermanent loss, and how can I avoid it?
A: Impermanent loss occurs when you provide liquidity to an automated market maker and the price of one asset changes significantly. You can reduce it by providing liquidity to stablecoin pairs (e.g., USDC-USDT), where price movements are minimal, or by concentrating liquidity in a narrower price range (on Uniswap v3), earning higher fees to offset losses. You cannot fully avoid it; it is a structural cost of AMM participation.
Q: Are stablecoins really stable?
A: Stablecoins backed by cash and short-term government bonds (USDC) are backed 1:1 and are stable. Stablecoins backed by less transparent reserves (USDT) or algorithmic mechanisms (Terra Luna's UST) are riskier. The collapse of UST in 2022 proved that algorithmic stablecoins can fail. Users should prioritize cash-backed stablecoins.
Q: What happens if a DeFi protocol gets hacked?
A: Typically, users' funds are permanently lost. The blockchain transaction is immutable. In rare cases, the community may vote to fork the blockchain to undo the hack (as Ethereum did after the 2016 DAO hack), but this is controversial and has never happened for a non-ecosystem-critical protocol. Most users should assume that in the event of a hack, their funds are gone.
Read next:
Follow new articles
Add SciHub101 to your feed reader to see new science and technology stories.
About the Author
SciHub101 is an independent science and technology publication founded and edited by Buğra Sözeri, a software engineer and app developer based in Türkiye. AI tools assist with drafting and research. Source documentation in the existing archive is uneven, and articles are being reviewed and corrected. The Editorial Team byline identifies editorial responsibility; it does not certify specialist or independent human review. Where we compare products, anything built by our own team is labelled as such — see the editorial guidelines and About page for how corrections and disclosures work.
Related Articles

How to Build an Emergency Fund: A Step-by-Step Framework
An emergency fund is savings set aside specifically to cover unexpected expenses or income loss: a car repair, medical bill, or job layoff. Financial experts generally recommend keeping 3 to 6 months of living expenses in emergency savings. If your monthly expenses are $3,000, that means $9,000 to $18,000 in accessible savings. Most Americans do not have this amount; the Federal Reserve reported that 43 percent of adults could not cover a $400 emergency with cash. Building an emergency fund requires three steps: calculating your monthly expenses, deciding on a target (3, 6, or 9 months), and automating deposits into a separate account until the target is reached. This article explains the mechanics of emergency fund planning, where to keep the funds to balance safety and accessibility, and how to maintain the fund when unexpected expenses occur.

Why Stock Prices Move After Earnings
Stocks move after earnings because expectations matter more than headlines. Revenue, margins, guidance, cash flow, and narrative all interact.

Ethereum in 2026: How It Works and What to Know
Ethereum is a blockchain network that extends cryptocurrency beyond Bitcoin's payments functionality to programmable contracts and decentralized applications. Unlike Bitcoin, which is primarily a peer-to-peer currency, Ethereum allows developers to deploy software (smart contracts) that executes agreements automatically without intermediaries. The Ethereum network operates on a proof-of-stake consensus mechanism (as of 2022), meaning validators stake cryptocurrency to secure the network rather than competing to solve mathematical puzzles. Ethereum's cryptocurrency, Ether (ETH), is used to pay for transaction fees (gas) and to incentivize validators. Ethereum has become the largest platform for decentralized finance (DeFi), non-fungible tokens (NFTs), and decentralized autonomous organizations (DAOs). This article explains how Ethereum works technically, the role of smart contracts and validators, current layer 2 scaling solutions, real use cases, and informed criticisms of the system. This is educational information about mechanisms, not investment advice.

Bitcoin and Blockchain Technology Explained
How Bitcoin solved the double-spend problem, how blockchain works, and what it means for money, investing, and the future of finance.

What Is Ethereum — And How Is It Different From Bitcoin?
Bitcoin is digital money. Ethereum is a programmable computer running on thousands of machines. Here's the real difference, in plain language.

Countries with the Highest Cryptocurrency Adoption (2025 Ranked)
India has the world's largest absolute number of crypto holders. Nigeria leads Sub-Saharan Africa as a proportion of population. El Salvador made Bitcoin legal tender. The US and EU are the largest crypto markets by value. Here's the full global cryptocurrency adoption map and what drives it.