This time the Code Review project is the decentralized exchange Uniswap, and the lead reader is Tiny Bear.
Introduction to Uniswap
The core principle of Uniswap uses a simple constant product model: K = x * y, where x and y are the number of tokens. During the transaction, the value of K needs to be kept constant, so the direction of change of x and y is opposite. You can refer to the three pictures below to understand how to trade and increase liquidity in Uniswap.
Code interpretation
Uniswap has two core projects:
uniswap-v2-core project
The code in this project is usually not called directly by users, but called by the routing contract in the uniswap-v2-periphery project, because the interface of the routing contract is more friendly.
Contract: UniswapV2Factory.sol
Core method:
createPair : Used to create a trading pair. Receive the addresses of the two tokens as parameters, then call the assembly method create2 to create a pair, and then call the initialize method of IUniswapV2Pair to initialize the pair. After successful creation, the PairCreated event is emitted.
Contract: UniswapV2Pair.sol
This contract is equivalent to
Core method:
- mint: Mint LP token to the specified address.
- burn: burn off the LP token and send to the user corresponding token0 and token1.
- swap: transaction.
uniswap-v2-periphery project
This project will be called directly by the front end, and then the corresponding method in the uniswap-v2-core project will be called.
Contract: UniswapV2Router02.sol
Core method:
- addLiquidity: Provide two ERC-20 tokens to add liquidity to ERC-20⇄ERC-20 pool
- removeLiquidity: Remove the liquidity of the ERC-20⇄ERC-20 pool and receive two ERC-20 tokens
- removeLiquidityWithPermit: Allow users to sign the name authorization (approve) contract in advance, which saves the approve transaction, and only one transaction is needed to complete the approve + transferFrom operation.
- swapExactTokensForTokens: transaction. Specify the number of token0 sent (in) and let the contract calculate the number of token1 (out)
- swapTokensForExactTokens: transaction. Specify the number of token1 that you want to get (out), and let the contract calculate the number of token0 that needs to be sent (in)
For more descriptions of contract methods, please refer to Uniswap's documentation .