What is DeFi? Decentralised exchanges, lending, AMMs and the risks
DeFi replaces exchanges and lenders with smart contracts that anyone can use. This guide shows how automated market makers price trades, how crypto lending and liquidations work, with worked numbers, and why hacks, bugs and scams have cost DeFi users billions.
- DeFi (decentralised finance) means financial services such as trading, lending and borrowing run by smart contracts on public blockchains, without a company holding your funds.
- Most decentralised exchanges use automated market makers: pools of two tokens priced by a formula, so large trades move the price against the trader.
- Liquidity providers earn fees but face impermanent loss: if prices move, they can end up worse off than simply holding the tokens.
- DeFi loans are over-collateralised and liquidated automatically, often with a penalty, if the collateral’s value falls too far.
- Smart-contract bugs, bridge hacks, oracle manipulation, malicious approvals and rug pulls have caused very large losses, and there is usually no one to reverse them.
DeFi, short for decentralised finance, is the name for financial services such as trading, lending and borrowing that run on public blockchains through smart contracts rather than through a bank, broker or exchange company. You connect a self-custody wallet, interact directly with the code, and keep control of your assets until the moment a transaction executes. The appeal is open access and transparency; the cost is that there is no customer service, no deposit protection, and code bugs, hacks and scams can wipe out funds permanently.
This guide explains the main building blocks with worked numbers: how decentralised exchanges price trades, what liquidity providers actually earn and risk, how DeFi lending and liquidations work, and the specific ways people lose money. It assumes you know roughly what a blockchain and a smart contract are; if not, read what a blockchain is and Ethereum and altcoins first.
Risk first. DeFi involves volatile crypto-assets, experimental software and, often, no regulated firm you can complain to. You can lose everything you put in. Nothing here is a recommendation to use any protocol.
What makes it "decentralised"
A traditional exchange or lender is a company. It holds your money, keeps its own records, decides who can use it, and can freeze or reverse transactions. A DeFi protocol is a set of smart contracts: programs deployed on a blockchain, most often Ethereum or networks built around it, that hold assets and follow fixed rules.
- Non-custodial. You keep assets in your own wallet and approve each interaction. The protocol holds assets only while they are deposited in its contracts.
- Open access. Anyone with a wallet can use the contracts directly, though website front ends may block some users or regions.
- Transparent. Contract code and every transaction are public on the blockchain.
- Composable. Contracts can call other contracts, so protocols are built on top of each other like building blocks.
"Decentralised" is often a matter of degree. Many protocols have developers or token holders who can upgrade the contracts, change parameters, or pause them in an emergency. Some rely on a small group holding administrator keys. Before trusting a protocol, it is worth knowing who can change the rules and how.
Decentralised exchanges and automated market makers
A centralised exchange matches buyers and sellers in an order book, as explained in how crypto exchanges work. Most decentralised exchanges (DEXs) work differently. They use an automated market maker (AMM): a pool of two tokens, supplied by liquidity providers, and a formula that sets the price.
The constant-product formula
The simplest and best-known AMM design keeps the product of the two token balances in the pool constant. If a pool holds x of token A and y of token B, then x multiplied by y must equal the same number, k, before and after every trade (ignoring fees). The pool's price is just the ratio of the balances.
When you buy token A from the pool, you add token B and remove token A. Because x times y must stay at k, every extra unit of A you take costs more B than the last. Large trades relative to the pool's size therefore move the price sharply. This is called price impact.
Worked example: a swap in a small pool
An illustrative example with round numbers; the pool sizes and prices are not real.
- A pool holds 100 ETH and 300,000 USDC (a dollar stablecoin). The pool price is 300,000 ÷ 100 = 3,000 USDC per ETH.
- k = 100 × 300,000 = 30,000,000.
- You swap 30,000 USDC for ETH. Ignoring fees, the pool now holds 330,000 USDC, so it must hold 30,000,000 ÷ 330,000 ≈ 90.909 ETH.
- You receive 100 − 90.909 ≈ 9.091 ETH.
- Your average price is 30,000 ÷ 9.091 ≈ 3,300 USDC per ETH, 10% above the starting price.
- The pool's new price is 330,000 ÷ 90.909 ≈ 3,630 USDC per ETH.
With a typical 0.3% pool fee deducted from your input, you would receive about 9.066 ETH instead. Now compare a trade one-tenth the size: swapping 3,000 USDC (with the 0.3% fee) returns about 0.987 ETH, an average price of about 3,030, roughly 1% above the starting price. Same pool, same formula: the bigger the trade relative to the pool, the worse the price.
Two practical consequences follow:
- Slippage tolerance. DEX interfaces ask you to set a maximum acceptable slippage. If the price moves beyond it before your transaction is included, the trade fails rather than executing at a worse price. Setting this too wide invites others to exploit you (see sandwich attacks below).
- Arbitrage keeps prices in line. After your trade, the pool price is above prices elsewhere. Arbitrage traders sell ETH into the pool until the price matches other markets, profiting from the gap.
Order-book depth on centralised venues is a different mechanism with a similar effect, covered in crypto order books and liquidity.
Liquidity providers and impermanent loss
The tokens in a pool come from liquidity providers (LPs), who deposit both tokens in proportion to the current price. In return they receive a share of the trading fees the pool collects.
The risk LPs take on is called impermanent loss. Because the pool rebalances with every trade, it automatically sells the token that is rising and buys the one that is falling. If prices move a lot, the LP ends up holding more of the weaker token than they would have if they had simply held their original tokens.
Worked example: impermanent loss
An illustrative example in a constant-product pool, ignoring fees:
- You deposit 1 ETH and 3,000 USDC when ETH is 3,000. Your deposit is worth 6,000 USDC.
- ETH's price doubles to 6,000 elsewhere, and arbitrage brings the pool into line.
- Your share of the pool now holds about 0.7071 ETH and about 4,242.64 USDC, worth about 0.7071 × 6,000 + 4,242.64 ≈ 8,485.28 USDC.
- Had you simply held 1 ETH and 3,000 USDC, you would have 6,000 + 3,000 = 9,000 USDC.
- The shortfall is about 514.72 USDC, or about 5.7% compared with holding.
The same 5.7% shortfall applies if ETH's price halves instead of doubling; the formula is symmetric in that sense. Larger moves cause larger losses. It is called "impermanent" because it disappears if prices return to where they were when you deposited, but if you withdraw after prices have moved, it is very real. Whether fees make up for it depends on trading volume and how far prices move, and in volatile markets they often do not.
LP positions in newer, thinly traded tokens add a further risk: if one token collapses to near zero, arbitrage traders will drain the pool of the valuable token, leaving LPs holding mostly the worthless one.
Lending and borrowing
DeFi lending protocols run pooled markets. Lenders deposit tokens into a pool and earn interest. Borrowers take tokens from the pool and pay interest. Rates are usually set by formula according to how much of the pool is borrowed: the more that is borrowed, the higher the rate.
Because there are no credit checks and borrowers are pseudonymous, loans are over-collateralised. You must deposit collateral worth more than you borrow. If the value of your collateral falls too far relative to your loan, anyone can liquidate your position: they repay part of your loan and receive your collateral at a discount. The discount, called the liquidation penalty, is a cost to you.
Worked example: a DeFi loan and its liquidation price
An illustrative example; the parameters are typical of the kind protocols use, not those of any specific protocol.
- You deposit 10 ETH as collateral when ETH is priced at 3,000 USDC. Collateral value: 30,000 USDC.
- The protocol's maximum loan-to-value for ETH is 75%, so you could borrow up to 22,500 USDC. You borrow 15,000 USDC, a loan-to-value of 50%.
- The liquidation threshold is 80%: you become liquidatable when your loan exceeds 80% of your collateral's value.
- That happens when collateral value falls to 15,000 ÷ 0.80 = 18,750 USDC, which is 1,875 USDC per ETH.
- So a fall of 37.5% in ETH's price, from 3,000 to 1,875, makes your position liquidatable. Interest owed on the loan brings that point a little closer over time.
If you are liquidated with a 5% penalty, a liquidator might repay, say, 7,500 USDC of your debt and receive ETH worth 7,875 USDC from your collateral. You lose the extra 375 USDC on top of whatever the price fall cost you. Liquidations are executed by automated bots and happen within seconds of the threshold being crossed, at any hour, including weekends.
Margin rules on regulated CFD accounts work differently, with a margin close-out level rather than an on-chain liquidation; see crypto leverage and liquidation and the glossary entry on margin close-out.
Why people borrow in DeFi
The common reasons are to get spending money without selling crypto (which may be a taxable event), to take leveraged positions by borrowing stablecoins to buy more crypto, or to borrow a token to sell it short. The leveraged uses are where many of DeFi's largest losses happen, because a sharp price fall can trigger waves of liquidations that push prices down further.
Stablecoins in DeFi
Most DeFi activity is priced in stablecoins: tokens designed to track a currency, usually the US dollar. They are the main thing borrowed and the main unit for pricing trades. Their designs, and the ways they have lost their pegs, are covered in stablecoins explained and stablecoin depegs explained. If a stablecoin used heavily in DeFi loses its peg, the effects spread through every protocol that accepts it as collateral or pairs it in pools.
Where DeFi yields come from
Advertised DeFi yields have three broad sources:
- Real activity. Trading fees paid to LPs and interest paid by borrowers. These depend on demand and fall when activity falls.
- Token incentives. Many protocols pay users in their own newly issued tokens to attract deposits. The headline rate depends on the price of that token, which often falls as the rewards are sold. Tokenomics and token supply explains why this matters.
- Risk you may not see. Leverage, exposure to unaudited contracts, or dependence on another protocol staying solvent.
If you cannot identify where a yield comes from, assume it is coming from risk you are taking on. Very high, stable-looking yields were a feature of several schemes that collapsed in 2022.
The risks in detail
Smart-contract bugs
A smart contract does exactly what its code says, including what its authors did not intend. The best-known early example is The DAO in 2016, a smart-contract fund on Ethereum that was drained of about 3.6 million ether through a flaw in its code. The episode ended with a contested hard fork of Ethereum. Audits reduce the risk of bugs but do not eliminate it; audited protocols have been exploited too.
Bridge hacks
Bridges move tokens between blockchains, usually by locking tokens on one chain and issuing a representation on another. They hold large pools of locked assets and have been among the most heavily attacked parts of crypto. In March 2022, the Ronin bridge, used by a popular blockchain game, was drained of about $625 million in ether and USDC after attackers gained control of enough of the keys used to approve withdrawals. If you hold a bridged token and the bridge is drained, the token you hold may lose most of its value. Layer 2 networks, which also move assets between chains, are covered in layer 2 scaling explained.
Oracle manipulation
Lending protocols need to know the price of collateral. They get it from price feeds called oracles. If an attacker can push the price an oracle reports, for example by trading heavily in a thin market, they can borrow far more than their collateral is really worth and leave the protocol with bad debt.
Admin keys and rug pulls
If a small group controls upgrade or withdrawal rights, they can change the rules or take the funds. A rug pull is when the people behind a project drain its liquidity or abandon it after attracting deposits. New tokens and protocols with anonymous teams and unaudited code are where this happens most. See crypto pump and dump schemes for the red flags.
Front-running and sandwich attacks
Pending transactions are visible before they are included in a block. Bots can spot a large swap, buy just before it, and sell just after, profiting from the price impact the victim's trade causes. This is a sandwich attack. A wide slippage tolerance makes you an easier target.
Approvals, phishing and wallet drainers
To let a contract move your tokens, you sign an approval. Many interfaces ask for unlimited approvals by default. If that contract is malicious or later exploited, it can take everything you approved. Fake DeFi websites, copied front ends and malicious signature requests are among the most common ways people lose crypto. Crypto phishing and wallet drainers explains how they work and how to review and revoke approvals.
Liquidation cascades
When prices fall sharply, liquidations sell collateral into a falling market, which can push prices lower and trigger more liquidations. DeFi borrowers can be liquidated in seconds, with no warning and no chance to add funds once the threshold is crossed.
Regulation and recourse
In the EU, MiCA regulates crypto-asset service providers, but its recitals indicate that services provided in a fully decentralised manner, without an intermediary, fall outside its scope. In practice that means many DeFi protocols have no authorised firm behind them, no complaints procedure and no compensation scheme. Front-end operators and token issuers may be regulated in some cases; the protocols themselves often are not. MiCA regulation explained covers the rules for providers that are in scope.
DeFi compared with a regulated CFD account
These are very different things, and it is worth being clear about what each gives and takes away.
- Custody. In DeFi you hold your keys and bear all security risk. With a regulated CFD broker, the broker holds client money under segregation rules and you hold no crypto at all.
- Leverage. DeFi leverage is limited only by collateral rules and can be stacked. EU retail clients can use at most 2:1 leverage on crypto CFDs under ESMA rules, with negative balance protection.
- Recourse. A regulated broker has complaint procedures and a regulator. A DeFi protocol usually has neither.
- Costs. DeFi has network fees, pool fees, price impact and slippage. CFDs have spreads, commissions and overnight financing; see crypto CFD overnight fees.
Most retail CFD accounts lose money too, so neither is a safe option. Our comparison of crypto CFDs vs buying crypto goes further.
Common mistakes
- Chasing headline yields. A high rate paid in a protocol's own token can disappear as the token falls.
- Ignoring price impact. Large trades in small pools can cost far more than the quoted price suggests.
- Setting wide slippage tolerances. It invites sandwich attacks and bad fills.
- Borrowing close to the limit. Leave a large buffer between your loan and the liquidation threshold.
- Granting unlimited approvals and never revoking them. Old approvals to forgotten contracts are a standing risk.
- Trusting a link. Reach DeFi sites from bookmarks you have verified, not from search ads, messages or social media replies.
- Assuming audited means safe. Audits reduce risk; they do not remove it.
- Putting in money you cannot afford to lose. Losses in DeFi are usually permanent.
Frequently asked questions
What is DeFi in simple terms?
Financial services, such as swapping tokens, lending and borrowing, run by smart contracts on public blockchains instead of by a company. You use them directly from your own wallet, with no account opening, and nobody can reverse your transactions.
How does a decentralised exchange set prices?
Most use an automated market maker: a pool holding two tokens and a formula that keeps a relationship between the two balances. The price is the ratio of the balances, and each trade moves it. Arbitrage traders keep pool prices close to prices on other markets.
What is impermanent loss?
The shortfall a liquidity provider suffers compared with simply holding the two tokens, caused by the pool rebalancing as prices move. In a constant-product pool, a doubling or halving of one token's price relative to the other leaves the LP about 5.7% worse off than holding, before fees.
Why are DeFi loans over-collateralised?
Because borrowers are pseudonymous and there are no credit checks or courts to chase unpaid debts. Requiring more collateral than the loan, and liquidating automatically if the collateral falls in value, protects lenders.
Is DeFi regulated?
Partly, and unevenly. In the EU, MiCA applies to crypto-asset service providers, but services provided in a fully decentralised way are indicated to fall outside its scope. Many DeFi protocols therefore offer no regulated protections, complaints process or compensation.
Can I get my money back if a DeFi protocol is hacked?
Usually not. Some protocols have compensated users after exploits, and some stolen funds have been recovered, but there is no obligation or scheme to do so. Treat any money in DeFi as money you could lose entirely. Our guide to crypto wallets and custody explains how to reduce the risk on your side.
Not investment advice. This is general information and education, written without knowledge of your circumstances. It is not a recommendation to buy or sell any instrument. Past performance is not a reliable indicator of future results. Trading leveraged products carries a high risk of losing money. Risk warning