Implementation tutorial for Dex contract on SmartWeave
This tutorial shows how to implement a simple token exchange.
π‘ The smart contract ideaβ
Inspiration for this project is the Uniswap protocol, one of the most successful Dapps in the history of Ethereum. It is so widely used, that in June 2022 the fees generated by Uniswap surpassed all the fees collected by Ethreum miners.
The key of the success of Uniswap is ease of use. The implementation is based on the Automatic Market Maker model allowing users to change one token into another without the need of waiting for a counter-party. The idea was proposed in 2017 by Vitalik Buterin in a post describing a protocol that would allow a smart contract to perform swaps between tokens using a ratio of its reserves rather than an order book. The original idea was excellently implemented by Hayden Adams creating one of the pillars of the emerging DeFi movement.
The Automating Market Maker (AMM) uses a simple formula to determine the exchange rate between the two. It's called a constant product function and it can be expressed as:
x * y = k where x and y are the reserves
( amount of token X in DEX ) * ( amount of token Y in DEX ) = k
The k is called an invariant because it doesnβt change during trades. (The k only changes as liquidity is added.) If we plot this formula, weβll get a curve that looks something like:
(The picture is taken from V. Buterin post about market makers)
A market controlled by this curve will automatically adapt the price according to the current supply and demand. As the ratio becomes more and more unbalanced, you will get less and less of the weaker asset from the same trade amount. Again, if the smart contract has too much token A and not enough token B, the price to swap tokens should be more desirable.
To work poperly the AMM requires certain amoount of tokens to be deposited to the contract. Theses tokens are usually described as liquidity and the actors that supply them are called liquidity providers
π Final version (cheat sheet)β
The final implementation is available in the github repo.
πββοΈ Need help?β
Please feel free to contact us on Discord if you have any questions.
π§° Prerequisitesβ
- Prepared Node.js environment
yarn
installed- Elementary Javascript coding skills
- Basic understanding of SmartWeave and Warp contracts
πͺ What will you learnβ
- Deploying multiple contracts
- Implementing cross-contract interactions (aka internal writes)
- Architecting a contract that may control other assets
- Fully understanding how one of the most important DeFi protocol works under the hood (Tons of satisfaction guaranteed :) )