I built a full stack dex. For building this first I decoded uniswap v2 code line by line to understand everything and then built my minimum viable dex. For this project I also learned typescript.
-
Basically there are two types of users liquidity providers and traders
-
Liquidity providers provide liquidity to the pool and in return they get third token that represents the partial ownership of the pool called liquidity token.
-
Traders can swap tokens means then can provide a token and receive another token. The exchange rate is determined by the relative number of tokens in the pool e.g. pool has 8 USDC & 10 DAI then the value of USDC will be high. The pool takes a small percent as a reward for the liquidity pool.
-
When liquidity providers want their assets back they can burn the liquidity token and receive back their assets, including the share of reward.
- There are three main contracts, Factory Contract, Pool contract and Router contract.
- Trader/liquidity provider interacts with Router contract not with main pool contract directly
- Approve periphery contract to use trader's tokens
- Trader uses router contract to swap tokens
- Sends tokenA to core contract
- Calculates tokenOut
- Then iterate over path array and swap tokens untill desired token come
- Then we sends the token to trader
- Update the reserves
- Approve periphery contract to use liquidity provider's tokens
- Liquidity provider uses router contract to add liquidity
- Sends assets of liquidity provider to core contract
- Calculate liquidity tokens to be minted
- Mint liquidity tokens for liquidity provider
- Update the reserves
- Approve periphery contract to use liquidity provider's tokens
- Liquidity provider uses router contract to withdraw liquidity
- Sends liquidity tokens of liquidity provider to core contract
- Burn liquidity tokens
- Send assets back to liquidity provider
- Update the reserves