Decentralised Exchanges, Pools and Swaps
Section 1 of 4
DeFi exchanges and the AMM story
Your learning goal
Trace a swap and distinguish the protocol from its interface and quote.
A decentralised exchange can execute through contracts rather than a provider's internal customer ledger. Many use liquidity pools, but not every DEX uses the same model. We will study one simple constant-product pool to understand reserves and price impact, then keep its assumptions separate from real applications and versions.
Key idea
State the pool model and its assumptions before calculating.
Education only. Crypto assets can lose substantial value or become worthless. No lesson requires buying an asset, depositing money or sharing real passwords, private keys or recovery words.
Ask what decentralised finance means
Think about a self-service petrol station at night. Nobody stands behind the counter. You insert your card, pick the pump and the machine follows its rules. It works at 3 a.m. because the rules are built into the equipment, not carried in a person's head.
Decentralised finance, usually shortened to DeFi, applies that idea to money. In Level 4 you met smart contracts, the vending machines of Ethereum. DeFi is the family of financial services built from them: swapping tokens, lending, borrowing and staking. Anyone with a wallet and some ether for gas can use them, at any hour, without opening an account.
That openness is the attraction, and it is also the risk. There is no branch to visit, no complaints desk and usually no compensation scheme. A mistake in the code, or in what you sign, can be permanent. Regulators are watching: in December 2023 IOSCO, the international body for securities regulators, published nine policy recommendations for DeFi, aiming for consistent investor protection across countries.
The analogy stops working in one place. A petrol station has an owner who fixes a broken pump; many DeFi contracts have no one who can step in (the DeFi dependency lesson in Level 6 examines who can). The most-used DeFi service is the swap, so start there.
Compare a DEX with a centralised exchange
In the exchange and order lessons in Level 3 you learned that a centralised exchange (CEX) is a company that holds your funds and matches orders in an order book. A decentralised exchange (DEX) also swaps one token for another, but the trade happens between your wallet and a smart contract. Your tokens stay in your wallet until the swap, which settles on the blockchain in a single transaction.
| Question | Centralised exchange (CEX) | Decentralised exchange (DEX) |
|---|---|---|
| Who holds your funds? | The exchange, in its own wallets | You, in your own wallet, until the swap |
| How is the price set? | Buyers' and sellers' orders in an order book | A formula applied to the tokens in a pool |
| Sign-up and identity checks | Usually an account and identity checks | Usually none: connect a wallet |
| Bank money in and out | Often possible | Not directly; token-to-token only |
| Who can help if it goes wrong? | Support team, possibly a regulator | Usually nobody; transactions are final |
| Main risks | Exchange failure, hacks, frozen withdrawals | Code bugs, fake tokens, harmful approvals, your own mistakes |
Neither column is "safe". A DEX removes the risk of a company losing your deposits (the exchange failure lesson in Level 3) but hands every other check to you. Many DEXs list any token anyone creates, so the red flags in the token research lesson in Level 5 matter here.
How can a contract quote a price without anyone placing orders? The answer came from a small group of builders in 2017 and 2018.
Meet the people behind the first popular AMM
Order books on Ethereum struggled, because every order and cancellation cost gas. In June 2017 Vitalik Buterin, Ethereum's co-founder, wrote a blog post called "On Path Independence". It discussed an automated market maker that keeps the balance of one token multiplied by the balance of the other at a fixed number. A market maker is someone always ready to buy or sell; here, the "someone" is a formula.
On 6 July 2017, a mechanical engineer named Hayden Adams was laid off from Siemens. His friend Karl Floersch encouraged him to learn Ethereum programming, and Adams chose to build the market-maker idea. In 2018 the project received an Ethereum Foundation grant. On 2 November 2018, the last day of the Devcon 4 conference in Prague, Adams announced Uniswap and deployed it on Ethereum. Uniswap launched in November 2018 and popularised the constant-product automated market maker, x × y = k.
Many DEXs have since adapted the design. Before looking at the formula in symbols, picture it in a market.
A common interface does not establish common contract behaviour. You still depend on token contracts, network inclusion, permissions and the application route. DEX does not mean that every dependency has disappeared. This is a project's history, not a claim that one person invented every automated market maker or that all current DEXs use its original rules.
Section 2 of 4
Pool models, swap calculations and routes
One constant product model
In a simple two-asset model, reserves x and y satisfy x multiplied by y equals k. A swap removes one asset and adds the other, with the curve changing the effective price. For teaching, begin with 100 practice units and 10,000 quote units, so k is one million. We ignore fees and assume no other trades, arbitrage or reserve changes during the calculation.
If a buyer removes ten practice units, the remaining x is 90. Keeping k fixed requires y to become 1,000,000 divided by 90, or approximately 11,111.11 quote units. The buyer therefore adds approximately 1,111.11 quote units. The average cost is about 111.11 quote units per practice unit, above the initial reserve ratio of 100. This simplified model explains why order size matters; it does not describe every pool version.
Imagine a fruit stall in Mexico City with two baskets: one holds 100 mangoes, the other MX$2,000 in coins (invented amounts for this example). The stallholder follows one strange rule: after every sale, mangoes multiplied by pesos must still equal 200,000.
Work through a swap and a route
Work through a swap in a liquidity pool
A liquidity pool is the crypto version of the baskets: a smart contract holding two tokens, such as ether and a US-dollar stablecoin. Uniswap's documentation explains that each trade shifts the ratio of the reserves, and that ratio is the new price.
That gap is price impact: the change in price caused by your own trade. It grows quickly with size. Selling 10 ETH into the same pool returns 200,000 − (20,000,000 ÷ 110) = 18,181.82 USDC, an average of 1,818.18 per ETH, about 9.1% below the starting price. Uniswap's documentation notes that trades large relative to the pool always get worse rates.
Then there is the fee. In Uniswap's version 2 pools each trade pays 0.30%, which stays in the pool for liquidity providers. With the fee, only 0.997 of Ananya's 1 ETH counts towards the formula, and she receives about 1,974.32 USDC.
After her trade the pool's ETH is cheaper than elsewhere, so arbitrage traders buy it and sell it on other markets until prices match. Arbitrage keeps pools in line with the wider market, and it drives a cost for liquidity providers you will meet soon.
Price impact comes from your trade size. Other people's trades can also move the pool before yours lands.
Use aggregators knowing what they add
A flight comparison website checks many airlines at once and may suggest a route with a change of planes because it is cheaper overall.
A DEX aggregator does the same for swaps. As 1inch's learning guide describes, it compares prices across many DEXs and routes your order along the best path. For a large trade, it may split the order across several pools so each piece causes less price impact, or route through a third token.
The trade-offs are real. Each extra pool adds gas, slippage settings still matter, and you are trusting another set of smart contracts. The gas and token lessons in Level 4 showed that approvals outlive the moment; an aggregator is one more address that may hold a permission over your tokens, so set a limited approval and revoke it when finished.
Now put the formula, the settings and the risks together.
A pool with larger reserves can ordinarily absorb the same relative trade more easily under otherwise identical model assumptions. Version-specific concentrated liquidity can produce a different depth profile from the simple full-range model. A low headline fee does not guarantee the lowest total cost. A pool containing a token with transfer restrictions can behave unexpectedly, and an apparent large balance may be unavailable for the intended action.

Read diagram as text
The illustrative pool has x × y = 20,000,000 with x in ETH and y in quote units labelled USDC. Point A is (100, 200,000).
Point B is (101, 198,019.80); point C is (110, 181,818.18), rounded. The inset contrasts the small A-to-B move with the larger A-to-C move.
The schematic labels approximately 1% and 9% impact; the comparison measure must be identified when calculating impact. Fees are ignored. This 100-ETH model differs from the smaller classroom example.
Section 3 of 4
Execution limits, ordering and security
Impact slippage limits and transaction ordering
Price impact is the effect of the trade itself interacting with the liquidity curve or book. Slippage is the difference between the expected reference or quote and actual execution. Market movement, transaction ordering and your own impact can contribute depending on how the reference is defined. Keep the definitions explicit so the same effect is not counted twice.
Slippage tolerance usually sets an execution condition such as a minimum received amount. A wide tolerance can permit a worse result; a narrow one can cause failure if conditions change. It is not a guarantee against all losses, token problems or malicious transaction ordering. A transaction that fails the condition may still cost gas. Inspect the exact minimum output and route rather than assuming a percentage label is a complete protection.
Imagine telling a queue at a Johannesburg market that you are about to buy all the tomatoes on one stall. A fast trader overhears, buys them first, then sells them to you at a higher price.
Apply the security checks to the swap
Verify token identity and allowances, obtain the application independently and read the transaction effect. Consider whether an approval is needed, its amount and the spender. After the action, check the receipt, received asset and remaining permission. A successful swap does not prove that the destination token is valuable or easily sellable later.
For course practice, use the supplied pool reserves and paper calculations. Do not connect a funded wallet to test a new token. If an interface asks you to increase tolerance dramatically or grant unexplained permission, pause and investigate. The next lesson examines liquidity provision, which exposes a holder to a different position from simply buying through the pool.
Section 4 of 4
Everyday example, practice and review
Try the following questions aloud or on paper before opening the worked answers. Compare your reasoning as well as your final answer.
Try it yourself
Try each question on paper or explain your answer aloud before opening the worked answers. This practice is for learning; it is not scored.
1. Start with 100 practice units and 10,000 quote units. Ignoring fees, calculate the quote input needed to remove five practice units.
2. In that practice pool, does the initial ratio of 100 guarantee ten units at a total cost of 1,000?
3. Why can a tight slippage tolerance still leave a fee cost?
Compare with the worked answers
Worked answers
1. Remaining x is 95. New y is 1,000,000 ÷ 95 = 10,526.3158. Quote input is 526.3158; average is about 105.2632.
2. No. Removing units changes reserves and the curve. Ten units require about 1,111.11 under the stated model.
3. An included action can revert after consuming gas. The output condition does not make computation free.
Quick knowledge check
Try each question on paper or explain your answer aloud before opening the worked answers. This practice is for learning; it is not scored.
Does every DEX obey the same x times y formula?
Compare with the worked answers
Worked answers
No. It is one illustrative model. Designs and versions can use different mechanisms.
What to remember
✓ Execution depends on a specific contract route.
✓ Order size changes the average in the illustrated pool.
✓ Tolerance is an execution condition with limited scope.
Lesson completion check
References and further reading
References
Hayden Adams and Uniswap: A Short History of Uniswap ↗
Uniswap: What is price impact ↗
Ethereum: Ethereum security and scam prevention ↗
MetaMask: What is a token approval ↗
MetaMask: Disconnect wallet from a dapp ↗
Uniswap docs: Uniswap docs — How Uniswap works (v2 protocol overview) ↗