Build your own Decentralized Exchange
Published: 2023-05-05 07:16:00

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4s02twdygej1v3fqy2l.gif)
Deploying the contracts

`yarn deploy`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5aaaupn3mahjzbzo8i5s.png)
Starting the frontend

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0it3izkjtispae7csv82.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25pcp6p0s94d4ixlx8co.png)
To claim free ETH, Connect your wallet and Click on grab funds from the faucet.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1k3s7qw6k17qss7kj1vx.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lbl7f5q9d1h5d9j38iwa.png)
To Check your Balloon token balance copy and paste your address and click on read.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c71g40530hwgrc1fmu7f.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scalnwp7hduhh4t0g22c.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7phczx0mfbfoqz0dk0by.png)

**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.sol `from 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3kkmrtk9fqkrl384ps9.png)

`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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qdlpr9h7biwnlzgkfcps.png)
`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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7y7tzkr4gzskj02ovod.png)
`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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5f3ck4zot7xjo8o2sx0.png)
`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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iwjrffdjxvdhuf0phc8r.png)
`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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rblprghb556f18guhdn.png)

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](https://twitter.com/_BuildBear), and [LinkedIn](https://www.linkedin.com/company/build-bear/) and Join the [Telegram group](https://t.me/+6mjOnBFUR9xjN2U1) if you haven’t done yet.

And please give us a clap 👏 if you like our work.

Github Repo : [Buildbear Tutorials](https://github.com/BuildBearLabs/scaffold-eth)

About BuildBear:

[BuildBear](https://buildbear.io/) 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](https://medium.com/buildbear/learn-how-to-create-deploy-an-nft-smart-contract-and-develop-a-front-end-app-in-15mins-a7d9c2a16237)
[Learn how to create, Deploy a Soul Bound Token(SBT)](https://medium.com/buildbear/find-out-what-is-sbt-auth-and-learn-to-create-your-own-system-12c5f65e40b7)
[Generate NFT with AI and Deploy the NFT smart contract, and the Front End App](https://medium.com/buildbear/generate-nft-with-ai-and-deploy-the-nft-smart-contract-and-the-front-end-app-94c64a93d8b1)
[Learn, code, and deploy your own MultiSig Wallet](https://medium.com/buildbear/learn-code-and-deploy-your-own-multisig-wallet-and-test-it-with-your-friends-now-cb86cdcb8c8)
[Let’s understand Subscription NFTs and mint a few](https://medium.com/buildbear/lets-understand-subscription-nfts-and-mint-a-few-6ae9e695a1fc)