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!


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

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

Deploying the contracts

yarn deploy

Starting the frontend

yarn start

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.

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.

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

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.

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 packages/hardhat/contracts:

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

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 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.
  • 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.
  • 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.
  • 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.
  • 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 the x * y = k where x and y are the reserves of the pool.

The formula (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

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.

Let’s get started then, Shall we?