The concept behind decentralized exchanges is straightforward: enabling users to trade their cryptocurrencies directly on the blockchain through smart contracts while retaining control over their private keys.
By the end of this tutorial, you will have a solid understanding of the fundamental principles behind decentralized exchanges and gain hands-on experience in building one.
Let’s get started!
Before getting started, please ensure that you have the following prerequisites installed on your system:
To begin, navigate to the scaffold-eth x BuildBear repository.
Here’s why we recommend using scaffold-eth x BuildBear:
To get started, click on the “Fork” button to create a copy of the repository on your own GitHub account. Please wait for the forking process to complete before proceeding.
Next, open a terminal and clone the forked repository, which includes all the necessary components for building a decentralized application:
git clone <paste the URL you fork repo> cd scaffold-eth
To install all the required packages, execute the following command:
To fork the Mainnet, use the following command: Choose your desired blockchain and enter the block number from which you wish to fork. Alternatively, you can leave the default value as is.
Deploying the contracts
Starting the frontend
Once the application is running, you can access it at http://localhost:3000 and you should see the following:
Before diving deeper into the smart contract, let’s start by exploring the functionalities of the DEX. To begin, navigate to the DEX page.
To claim free ETH, Connect your wallet and Click on grab funds from the faucet.
To Check your Balloon token balance copy and paste your address and click on read.
In the same way, you can also withdraw the liquidity you have provided.
Once the transaction is completed, the total liquidity will be updated.
Let’s dive deep into the Smart contract
We can find
DEX.sol contract in
>=0.8.0 <0.9.0and is licensed under the MIT license.
IERC20.solfrom the OpenZeppelin library and
SafeMath.solfrom the OpenZeppelin library. These contracts provide standardized ERC20 token functionality and safe mathematical operations.
totalLiquidity: Represents the total amount of liquidity provider tokens (LPTs) minted in the DEX.
liquidity: Stores the liquidity balance of each depositor.
token: An instance of the imported
4. Main functions in the contract:
init(uint256 tokens): This function initializes the DEX with an amount of tokens transferred to the contract. It sets the
totalLiquidityvariable to the current balance of Ether in the contract, sets the liquidity balance of the caller (
msg.sender) to the total liquidity, and transfers the specified number of tokens from the caller to the DEX contract.
ethToToken(): This function allows users to swap Ether for the token. It calculates the token output based on the current reserves and performs the token transfer to the caller. It emits an
tokenToEth(uint256 tokenInput): This function allows users to swap the token for Ether. It calculates the Ether output based on the current reserves and performs the token transfer from the caller to the DEX contract. It then transfers the Ether to the caller. It emits a
deposit(): This function allows users to deposit tokens and Ether into the liquidity pool. The amount of tokens deposited is determined based on the amount of Ether sent with the function call and the current reserves. It mints new liquidity provider tokens (LPTs) and updates the liquidity balances and total liquidity. It emits a
withdraw(uint256 amount): This function allows users to withdraw tokens and Ether from the liquidity pool based on the amount of liquidity provider tokens (
amount) they want to withdraw. It calculates both ETH and tokens at the correct ratio.
price(uint256 xInput, uint256 xReserves, uint256 yReserves): This function calculates the output amount (
yOutput) based on the input amount (
xInput) and the reserves of the tokens (
yReserves). It uses the
x * y = kwhere
yare the reserves of the pool.
(amount of ETH in DEX) * (amount of tokens in DEX) = k represents an invariant that remains constant during trades (except when liquidity is added). Graphing this formula produces a curve as shown in the image below:
This curve determines the “price” in terms of how much output an asset would receive by inputting a specific amount of the asset. As the ratio becomes more unbalanced, the trade yields progressively lesser of the weaker asset. If the smart contract holds excessive ETH and lacks sufficient tokens, the price for swapping tokens for ETH should become more favorable.
We have successfully developed a basic decentralized exchange that enables users to provide liquidity and swap assets. By participating as liquidity providers, users have the opportunity to earn fees for their contributions.
Share your project on Twitter and LinkedIn and tag BuildBear.
If you appreciate what we are doing, please follow us on Twitter, and LinkedIn and Join the Telegram group if you haven’t done yet.
And please give us a clap 👏 if you like our work.
Github Repo : Buildbear Tutorials
BuildBear is a platform for testing Dapps at scale, for teams. It provides users with their own private Testnet to test their smart contracts and Dapps, which can be forked from any EVM chain. It also provides a Faucet, Explorer, and RPC for testing purposes.
BuildBear aims to build an ecosystem of tools for testing Dapps at scale for the teams.