Demo Decentralized Exchange (DEX) Implementation

prem yekkali

1) Dex Contract - Fully functional and secure.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract DEX is ReentrancyGuard {
struct Pool {
uint256 reserveA;
uint256 reserveB;
}

mapping(address => mapping(address => Pool)) public pools;

event LiquidityAdded(address indexed tokenA, address indexed tokenB, uint256 amountA, uint256 amountB);
event TokensSwapped(address indexed tokenIn, address indexed tokenOut, uint256 amountIn, uint256 amountOut);

function addLiquidity(
address tokenA,
address tokenB,
uint256 amountA,
uint256 amountB
) external nonReentrant {
require(amountA > 0 && amountB > 0, "Amounts must be greater than zero");

IERC20(tokenA).transferFrom(msg.sender, address(this), amountA);
IERC20(tokenB).transferFrom(msg.sender, address(this), amountB);

pools[tokenA][tokenB].reserveA += amountA;
pools[tokenA][tokenB].reserveB += amountB;

emit LiquidityAdded(tokenA, tokenB, amountA, amountB);
}

function swapTokens(
address tokenIn,
address tokenOut,
uint256 amountIn
) external nonReentrant {
require(amountIn > 0, "Amount must be greater than zero");

Pool storage pool = pools[tokenIn][tokenOut];
require(pool.reserveA > 0 && pool.reserveB > 0, "Liquidity not available");

// Simple swap calculation (could be improved with a more complex formula)
uint256 amountOut = (amountIn * pool.reserveB) / pool.reserveA;

IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);
IERC20(tokenOut).transfer(msg.sender, amountOut);

// Update reserves
pool.reserveA += amountIn;
pool.reserveB -= amountOut;

emit TokensSwapped(tokenIn, tokenOut, amountIn, amountOut);
}
}

Technical Guide

2.1 Architecture

The DEX is built using Solidity and utilizes OpenZeppelin contracts for secure ERC20 token interactions and reentrancy protection. The key components include:
Liquidity Pools: Stores reserves of token pairs for trading.
Events: Tracks actions such as adding liquidity and swapping tokens.

2.2 Smart Contract Breakdown

2.2.1 DEX Contract
State Variables:
pools: A mapping to track liquidity reserves for each token pair.
Events:
LiquidityAdded: Emitted when liquidity is added to a pool.
TokensSwapped: Emitted when tokens are swapped.
Functions:
addLiquidity(address tokenA, address tokenB, uint256 amountA, uint256 amountB): Allows users to deposit tokens into the liquidity pool.
swapTokens(address tokenIn, address tokenOut, uint256 amountIn): Allows users to swap one token for another based on pool reserves.
2.2.2 Sample Code Snippet
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountA,
uint256 amountB
) external nonReentrant {
require(amountA > 0 && amountB > 0, "Amounts must be greater than zero");
...
}

2.3 Security Measures

Reentrancy Guard: Utilizes OpenZeppelin's ReentrancyGuard to prevent reentrancy attacks.
Input Validation: Ensures that amounts are greater than zero and that liquidity is available before swaps.

3. User Guide

3.1 Getting Started

3.1.1 Prerequisites
A wallet (e.g., MetaMask) with some ETH for gas fees and ERC20 tokens for trading.
Access to a compatible Ethereum network (e.g., Rinkeby, Mainnet).

3.2 Using the DEX

3.2.1 Adding Liquidity
Navigate to the DEX Interface:
Access the DEX web application (if available) or interact via a script.
Select Tokens:
Choose the tokens you want to add to the liquidity pool (Token A and Token B).
Enter Amounts:
Input the amounts of Token A and Token B you wish to provide.
Confirm Transaction:
Confirm the transaction in your wallet and wait for it to be mined.
3.2.2 Swapping Tokens
Select Tokens:
Choose the input token (token you want to swap) and output token (token you want to receive).
Enter Amount:
Input the amount of the input token you wish to swap.
Confirm Transaction:
Review the transaction details and confirm in your wallet.
Receive Tokens:
Once confirmed, the swapped tokens will be sent to your wallet.

3.3 FAQs

What is liquidity?
Liquidity refers to the availability of tokens in the exchange, enabling users to trade seamlessly.
What happens if a token runs out of liquidity?
If there is no liquidity for a token pair, swaps will fail until more liquidity is added.
Are there any fees?
The DEX may charge a small fee for swaps, which can be distributed to liquidity providers.
3) Deployment Instructions - Steps for deploying on the blockchain.
Set Up Environment:
Install Node.js and npm.
Install Truffle or Hardhat.
Create Project Directory:
Use mkdir DEX and cd into it.
Install Dependencies:
For Truffle: npm install -g truffle.
For Hardhat: npm install --save-dev hardhat.
Create Contract File:
In the contracts directory, create DEX.sol.
Configure Deployment Script:
Create a migration file in the migrations directory.
Compile the Contract:
Run truffle compile.
Deploy to Local Network:
Start Ganache and run truffle migrate --network development.
Deploy to Testnet/Mainnet:
Configure truffle-config.js for deployment to a testnet or mainnet.
Run Deployment Command:
Use truffle migrate --network <network_name>.
Verify Deployment:
Check deployment status on Etherscan.
Like this project

Posted Oct 25, 2024

This project is a demonstration of a DEX, showcasing ERC20 token trading and liquidity provisioning features for educational purposes.

Join 50k+ companies and 1M+ independents

Contra Logo

© 2025 Contra.Work Inc