Ether.js

What is the process for implementing a decentralized exchange with Ethersjs


Overview

A decentralized exchange (DEX) allows users to trade cryptocurrencies directly with one another without the need for a centralized authority. In this guide, we will create a simple DEX using Ethers.js, which will include smart contracts for trading and a front-end application to interact with those contracts.

1. Writing the Smart Contracts

We will create a simple DEX smart contract that allows users to deposit tokens, create orders, and execute trades. Below is a basic implementation in Solidity:

        
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            interface IERC20 {
                function transfer(address to, uint amount) external returns (bool);
                function transferFrom(address from, address to, uint amount) external returns (bool);
                function balanceOf(address account) external view returns (uint);
            }
            contract SimpleDEX {
                struct Order {
                    address user;
                    address token;
                    uint amount;
                    uint price; // Price in wei
                }
                Order[] public orders;
                function deposit(address token, uint amount) public {
                    IERC20(token).transferFrom(msg.sender, address(this), amount);
                }
                function createOrder(address token, uint amount, uint price) public {
                    orders.push(Order(msg.sender, token, amount, price));
                }
                function executeOrder(uint orderIndex) public {
                    Order storage order = orders[orderIndex];
                    require(order.amount > 0, `Order does not exist`);
                    require(msg.sender != order.user, `Cannot execute your own order`);
                    uint totalCost = order.amount * order.price;
                    IERC20(order.token).transfer(msg.sender, order.amount);
                    IERC20(order.token).transfer(order.user, totalCost);
                    order.amount = 0; // Mark order as executed
                }
            }
            

2. Deploying the Smart Contract

To deploy the smart contract, you can use Ethers.js. Below is an example of how to deploy the DEX contract:

        
            // deploy.js
            const { ethers } = require(`ethers`);
            async function main() {
                const provider = new ethers.providers.JsonRpcProvider(`https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID`);
                const wallet = new ethers.Wallet(`YOUR_PRIVATE_KEY`, provider);
                const SimpleDEX = await ethers.getContractFactory(`SimpleDEX`, wallet);
                const simpleDEX = await SimpleDEX.deploy();
                console.log(`SimpleDEX deployed to:`, simpleDEX.address);
            }
            main().catch((error) => {
                console.error(error);
                process.exit(1);
            });
            

3. Building the Front-End Application

Now that we have our smart contract deployed, we can build a front-end application using React and Ethers.js to interact with the DEX. Below is a simple example:

        
            // src/App.js
            import React, { useEffect, useState } from 'react';
            import { ethers } from 'ethers';
            import SimpleDEX from './artifacts/SimpleDEX.json'; // ABI file
            function App() {
                const [account, setAccount] = useState(null);
                const [dexContract, setDexContract] = useState(null);
                const [orders, setOrders] = useState([]);
                useEffect(() => {
                    const connectWallet = async () => {
                        if (window.ethereum) {
                            const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                            setAccount(accounts[0]);
                            const provider = new ethers.providers.Web3Provider(window.ethereum);
                            const contract = new ethers.Contract(`DEPLOYED_CONTRACT_ADDRESS`, SimpleDEX.abi, provider.getSigner());
                            setDexContract(contract);
                        }
                    };
                    connectWallet();
                }, []);
                const createOrder = async (token, amount, price) => {
                    if (dexContract) {
                        const tx = await dexContract.createOrder(token, amount, price);
                        await tx.wait();
                        fetchOrders();
                    }
                };
                const fetchOrders = async () => {
                    if (dexContract) {
                        const orderCount = await dexContract.orders.length;
                        const fetchedOrders = [];
                        for (let i = 0; i < orderCount; i++) {
                            const order = await dexContract.orders(i);
                            fetchedOrders.push(order);
                        }
                        setOrders(fetchedOrders);
                    }
                };
                return (
                    <div>
                        <h1>Decentralized Exchange</h1>
                        <p>Connected account: {account}</p>
                        <h2>Create Order</h2>
                        <button onclick={() => createOrder(`TOKEN_ADDRESS`, ethers.utils.parseUnits(`1.0`, 18), ethers.utils.parseUnits(`0.01`, 18))}>
                            Create Order
                        </button>
                        <h2>Orders</h2>
                        <ul>
                            {orders.map((order, index) => (
                                <li key={index}>
                                    {order.amount.toString()} at {ethers.utils.formatUnits(order.price, 18)} ETH
                                </li>
                            ))}
                        </ul>
                    </div>
                );
            }
            export default App;
            

Conclusion

In this guide, we created a simple decentralized exchange using Ethers.js. We wrote smart contracts for trading, deployed them to the Ethereum blockchain, and built a front-end application to interact with those contracts. This approach allows users to trade cryptocurrencies directly with one another, enhancing security and control over their assets.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.