DEV Community

Cover image for Build your own Decentralized Exchange
Chandan | Web3 for BuildBear

Posted on

Build your own Decentralized Exchange

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!

Prerequisites
Before getting started, please ensure that you have the following prerequisites installed on your system:

  • NodeJS (version >= 10)
  • Yarn
  • Git

Getting Started
To begin, navigate to the scaffold-eth x BuildBear repository.

Here’s why we recommend using scaffold-eth x BuildBear:

  1. It allows you to easily fork EVM-compatible chains (such as Ethereum, Polygon, Binance Smart Chain, Fantom, Optimism, and Arbitrum Mainnet) directly from the CLI. Saving you valuable time that would otherwise be spent searching for working RPCs.
  2. You can mint native and ERC20 tokens effortlessly using the CLI, eliminating the need to waste time searching for functional faucets.

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:

yarn install
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.

yarn fork-bb

Image description
Deploying the contracts

yarn deploy

Image description
Starting the frontend

yarn start
Once the application is running, you can access it at http://localhost:3000 and you should see the following:

Image description

Before diving deeper into the smart contract, let’s start by exploring the functionalities of the DEX. To begin, navigate to the DEX page.

Image description
To claim free ETH, Connect your wallet and Click on grab funds from the faucet.

Image description

Token Swap

  1. Enter the desired token amount: As you enter the amount, please note that the graph will display the corresponding number of balloon tokens you will receive, along with the associated fee.
  2. Once you’ve entered the token amount, click on the “💸” to proceed with the swap.
  3. Approve the transaction on MetaMask: A MetaMask prompt will appear, requesting your approval for the token swap transaction.

Image description
To Check your Balloon token balance copy and paste your address and click on read.

Image description

Providing liquidity.

  1. Enter the desired amount you wish to provide as liquidity.
  2. Once you have entered the desired amount, click on the “📥” .
  3. Approve the transaction on MetaMask: A MetaMask prompt will appear, requesting your approval for the liquidity provision transaction. In the same way, you can also withdraw the liquidity you have provided.

Image description

Once the transaction is completed, the total liquidity will be updated.

Image description

Let’s dive deep into the Smart contract

We can find DEX.sol contract in packages/hardhat/contracts:

The contract uses the Solidity version pragma >=0.8.0 <0.9.0 and is licensed under the MIT license.
The contract imports two external contracts: IERC20.solfrom the OpenZeppelin library and SafeMath.sol from the OpenZeppelin library. These contracts provide standardized ERC20 token functionality and safe mathematical operations.
Global variables:
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 IERC20 contract.
Main functions in the contract:

Image description

init(uint256 tokens): This function initializes the DEX with an amount of tokens transferred to the contract. It sets the totalLiquidity variable 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.

Image description
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 EthToTokenSwap event.

Image description
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 TokenToEthSwap event.

Image description
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 LiquidityProvided event.

Image description
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 (xReserves and yReserves). It uses thex * y = k where x and y are the reserves of the pool.
The formula (amount of ETH in DEX) * (amount of tokens in DEX) = krepresents an invariant that remains constant during trades (except when liquidity is added). Graphing this formula produces a curve as shown in the image below:

Image description

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.

Congratulations

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

About BuildBear:

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.

Read our past articles and keep learning :

Learn how to Create, Deploy an NFT Smart Contract and Develop a Front End App in 15mins
Learn how to create, Deploy a Soul Bound Token(SBT)
Generate NFT with AI and Deploy the NFT smart contract, and the Front End App
Learn, code, and deploy your own MultiSig Wallet
Let’s understand Subscription NFTs and mint a few

Top comments (0)