UniSwap Version 2 Architecture

Does Uniswap make sense to you? Uniswap isn’t far-fetched from the name. The uni meaning one and a swap, which means exchange. Uniswap is a DeFi app that exchanges one token for another in a trustworthy manner. It is an automated market maker for trading.
Automated Market Maker
Automated Market Maker (AMM) is a better alternative to the Order Book, where buyers and sellers set the exchange rate for tokens. AMM allows the two tokens to be exchanged and held in the pool. For example Token A and Token B, for Token A to be exchanged for Token B in the pool, Token B must be deposited such that the total assets of the two tokens are not reduced after the exchange. Assets are provided to the pool by liquidity providers, who receive so-called LP tokens to represent their share of the pool.
Advantages of AMM
Prices are automatically determined. The more an asset is in the pool, the lower the price and vice versa.
It is used as a Price oracle for other smart contracts, as it provides free price data
It is highly gas efficient compared to the Order Books
Disadvantages of AMM
Continuous Price Shift.
Impermanent loss for liquidity providers.
Architecture of Uniswap V2
The Architecture of Uniswap V2 involves the UniswapV2Pair contract that holds two ERC 20 tokens that traders can swap against, or liquidity providers can provide liquidity for. Every UniswapV2Pair has a UniswapV2Pair Contract to manage it, and if not available, a UniswapV2Factory contract is created.
In locating the pool given two token addresses, the smart contracts calculate the address of the pool by predicting the create2 address as a function of the token addresses and the factory address, instead of mapping token pairs to addresses. This is highly gas-efficient. Clones are not used to create pools because of the introduction of an extra 2,600 gas per transaction after the deployment. Hence, the deployment of a new contract is preferred.
The Constant Product formula theory
This is the theory for calculating the swap rates
Calculation for Swap
When calculating the Swap with a fee, you will use the Formula belo
Calculation for a Swap with Fee
Swap requires a smart contract, because an EOA cannot simultaneously send the incoming ERC20 tokens and call swap in one transaction without the aid of another smart contract. When users do not use the swap function for trading tokens, they use it as a flash loan. The borrowing contract simply requests the amount of tokens the borrower wishes to borrow without collateral, and they will be transferred to the other contract.
You can learn more about the UniSwap version 2 architecture here.https://rareskills.io/post/uniswap-v2-swap-function, https://rareskills.io/uniswap-v2-book
Subscribe to my newsletter
Read articles from Ifeoluwa Sanni directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ifeoluwa Sanni
Ifeoluwa Sanni
I am a Web3 Software developer