How Uniswap pools are implemented

Nazar Ilamanov
2 min readFeb 23, 2022

--

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.

An example

When an LP wants to add liquidity, Uniswap will transfer tokenA and tokenB (in the right proportions) from the LP to itself. This transfer happens in the tokenA's and tokenB’s ERC20 contracts.

When a trader wants to swap tokenA for tokenB, Uniswap will

  • subtract the trading fee (which in this case is paid in tokenA)
  • calculate the right amount of tokenB to return
  • transfer all tokenA from the trader to itself
  • transfer calculated amount of tokenB from itself to the trader

The transfers again happen entirely in the ERC20s.

Summary

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.

--

--

No responses yet