The smart contracts behind the exchange pools
What is a pool?
- Uniswap has an exchange pool for each token pair (like UNI ↔ ETH above).
- Think of a pool as a bag filled with 2 types of tokens.
- Liquidity providers(LPs) can deposit/withdraw funds from this bag.
- Traders can submit one token and get another in return.
Uniswap uses 3 smart contracts
To implement the pools, Uniswap uses
- Two ERC20 smart contracts for each token.
- And another contract to manage/keep track of everything.
Let me elaborate on the first point above: every token on Ethereum has an associated ERC20 contract. Uniswap does not implement new ERC20 contracts for each token. Uniswap just uses pointers (stored in the 3rd contract) to the ERC20s of the tokens and updates its balances in the ERC20s when necessary.
How trading fees are stored
Trading fees are stored alongside the actual tokens. Uniswap just uses clever math and tracker variables (stored in the 3rd contract), to deduce how much fees have accumulated in the pool.
When an LP wants to add liquidity, Uniswap will transfer
tokenB (in the right proportions) from the LP to itself. This transfer happens in the
tokenB’s ERC20 contracts.
When a trader wants to swap
tokenB, Uniswap will
- subtract the trading fee (which in this case is paid in
- calculate the right amount of
- transfer all
tokenAfrom the trader to itself
- transfer calculated amount of
tokenBfrom itself to the trader
The transfers again happen entirely in the ERC20s.
A pool just consists of 3 contracts:
- One ERC20 for each token (not implemented by Uniswap)
- One contract for the math and the connecting glue.