Skip to main content

DeFi Course Lesson 5 - Building a DEX Frontend

Updated on
Oct 23, 2026

53 min read

Overview​

In lesson 5 of Quicknode's DeFi DEX course, we will dive into the world of frontend development for your decentralized exchange. The frontend is the user-facing aspect of your DEX, where traders interact with the platform, such as swapping and providing liquidity. By the end of this section, you will have a solid understanding of creating an engaging and functional frontend for the DEX you've built over the last several lessons.

Building the Frontend​

The frontend of a DEX is crucial for providing a seamless and intuitive user experience. This is where you will implement various user interfaces and components that allow users to interact with the underlying smart contracts you deployed on the blockchain. Here are the key steps involved in building the frontend:

  • User Interface Design: Design the user interface elements, keeping in mind your platform's ease of use, visual aesthetics, and overall branding.
  • Component Development: Develop individual components for utilities and features such as the wallet connection, navigation bar, swap and liquidity tabs.
  • Responsive Design: Ensure your frontend is responsive and accessible across different devices and screen sizes.
  • Integration with Smart Contracts: Connect the frontend with the smart contracts that handle the user to smart contract interaction.

You generally follow the steps below in order to interact with a smart contract on a frontend application:


  1. You connect your wallet and use the frontend to tell the application what you want to do, like doing a swap.
  2. The frontend takes the information you provided and prepares the transaction to be sent to the blockchain.
  3. When the wallet interface pops up, you confirm the transaction details.
  4. Transaction details is sent to the blockchain with JSON-RPC calls using an endpoint (RPC URL) and libraries like Viem.
  5. The smart contract executes the function call and updates the contract state accordingly.
  6. The frontend updates its values to align with the new state in the smart contract.
One swap in four steps. The frontend simulates the call through your Quicknode endpoint. The wallet signs and sends the write. The Exchange contract runs it. The frontend reads the receipt and new state through the same endpoint.One swap in four steps. The frontend simulates the call through your Quicknode endpoint. The wallet signs and sends the write. The Exchange contract runs it. The frontend reads the receipt and new state through the same endpoint.

Tech Stack​

We will use the following frameworks and libraries to create the frontend and interact with our DEX smart contracts:

  • TypeScript is a typed superset of JavaScript that adds type safety to the language. This makes it easier to write more robust and maintainable code. TypeScript is also becoming increasingly popular in the web development community, as it can be used to build large and complex applications.

  • React is a JavaScript library for building user interfaces. It is one of the most popular JavaScript libraries in the world. React is known for its declarative nature, which makes it easy to write code that is both efficient and maintainable.

  • Vite is a modern JavaScript build tool that is designed to be fast and efficient. Vite can be used to build both static and dynamic websites, and it supports a wide range of JavaScript frameworks, including React, Vue, and Angular.

  • Tailwind CSS is a utility-first CSS framework. This means that it provides a set of small, reusable CSS classes that can be combined to create custom styles. Tailwind CSS is becoming increasingly popular in the web development community, as it can be used to quickly and easily create beautiful and responsive websites.

  • Viem is a TypeScript library for interacting with EVM blockchains like Ethereum. It is a modern, lightweight, and easy-to-use library that is designed to make building Web3 dApps easy and blazing fast.

  • Sonner is a small React library for toast messages. The app uses it to show the status of each transaction.

Components of dApps​

The frontend has six components and one file of shared UI parts. Each component handles one part of the user's interaction with the DEX.

  1. The Header component shows the app name, the Swap, Liquidity, and Create Exchange tabs, the network status, and the wallet button.

  2. The Swap component trades ETH for your token, or your token for ETH. It shows a live quote, the price, the minimum amount after slippage, and the LP fee.

  3. The AddLiquidity component deposits ETH and tokens into the pool. After the first deposit, it calculates the token amount from the pool ratio.

  4. The RemoveLiquidity component burns LP tokens and returns your share of ETH and tokens. It shows a preview before you confirm.

  5. The Liquidity component shows the pool reserves and switches between AddLiquidity and RemoveLiquidity.

  6. The CreateExchange component checks a token address and calls the Factory to deploy an Exchange contract for it.

The ui.tsx file holds the parts that all components share: cards, buttons, amount fields, rows, and notices. The square cards, mono labels, and green accent follow the look of the Quicknode website.

Helper Functions​

Helper functions keep contract calls and shared logic out of the components. Here is the list of helper files. The next section shows the code.


  1. client.tsx
  • publicClient: Reads from the Sepolia chain through your Quicknode endpoint.
  • getWalletClient: Creates a signing client from the browser wallet when a provider is available.
  • waitForSuccess: Waits for the receipt and throws an error if the transaction reverted.
  1. addLiquidity.tsx
  • addLiquidity: Approves the token, then adds ETH and tokens to the pool.
  • calculateToken: Calculates the token amount that matches the pool ratio.
  1. getData.tsx
  • getExchangeAddress: Gets the Exchange address for a token from the Factory.
  • getEtherBalance: Gets the ETH balance of an address.
  • getTokenBalance: Gets the token balance of an address.
  • getLpTokenBalance: Gets the LP (Liquidity Provider) token balance of an address.
  • getReserveOfToken: Gets the token reserve of the pool.
  • getTokenData: Gets the token symbol.
  1. removeLiquidity.tsx
  • removeLiquidity: Burns LP tokens and returns ETH and tokens to the user.
  • getTokensAfterRemove: Calculates the ETH and tokens that an LP amount returns.
  1. swap.tsx
  • getAmountOfTokensReceivedFromSwap: Gets a swap quote from the Exchange contract.
  • minimumReceived: Applies the slippage limit to a quote.
  • swapTokens: Runs the swap in either direction and returns the amount received.
  1. createExchange.tsx
  • createNewExchange: Calls the Factory to deploy an Exchange contract for a token.
  1. format.tsx
  • shortAddress, formatAmount, and toWei: Format addresses and amounts, and parse user input.
  • runTx: Runs a transaction and shows its status in a toast.
  1. hooks.tsx
  • useWallet: Tracks the account and network. It also connects, disconnects, and switches the network.
  • usePool: Loads wallet balances and pool reserves, and reloads them after each transaction.

Deep Dive into the Code​

Now, it is time to get to work. Open a terminal window and let's get started.

Setting the Environment​

If your terminal is in the defi_dex folder that we currently use for smart contract deployment, you can go to the parent folder and run the following command. Use Node.js 22.12 or later.

npm create vite@9.3.0 defi_dex_frontend -- --template react-ts

The command creates a React and TypeScript project named defi_dex_frontend. Install Viem, the UI dependencies, and Tailwind's Vite plugin:

cd defi_dex_frontend
npm install
npm install --save-exact viem@2.57.7 react-icons@5.7.0 sonner@2.0.8
npm install -D --save-exact tailwindcss@4.3.3 @tailwindcss/vite@4.3.3

Add the Tailwind plugin to vite.config.ts:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";

export default defineConfig({
plugins: [react(), tailwindcss()],
});

Replace src/index.css with the code below. It sets the color tokens that the components use.

@import "tailwindcss";

@theme {
--color-ink: #2b2b2b;
--color-paper: #ffffff;
--color-canvas: #f7f7f7;
--color-line: #dbdbdb;
--color-muted: #6b6b6b;
--color-accent: oklch(89% 0.22 144.5);
--color-lavender: oklch(94.8% 0.029 298.9);
--color-link: oklch(54.4% 0.228 290.4);
--color-danger: oklch(63.7% 0.237 25.331);
--color-danger-soft: oklch(97.1% 0.013 17.38);
}

body {
@apply bg-canvas text-ink antialiased;
}

Delete src/App.css. The app uses only Tailwind classes and index.css.

Keep package-lock.json in Git. Use npm ci when installing this project on another machine or in deployment.

Create an .env file in the frontend project directory:

touch .env

Then, modify it like the sample below:

VITE_VERCEL_QUICKNODE_ENDPOINT = "QUICKNODE_ENDPOINT_HTTP_PROVIDER"

Replace QUICKNODE_ENDPOINT_HTTP_PROVIDER with the HTTP Provider URL from lesson 4. Vite embeds VITE_ variables in the public JavaScript bundle. Anyone who opens your site can read this URL. Keep account API keys and wallet private keys out of the frontend.

Secure the endpoint before you deploy. Use a dedicated endpoint for the browser. Add a domain whitelist as a first layer. A domain whitelist alone is weak, because a caller can fake the origin. For stronger control, use JWT authentication or a server-side proxy. Read the endpoint security best practices guide for details.

Directory Structure​

The directory structure in the project folder defi_dex_frontend includes node_modules for installed packages, public for public assets, and src for your application's source code.

├── .env // This file typically contains environment variables used by the application.
├── .git // The Git version control system directory, which tracks changes in your project.
├── .gitignore // A file that specifies which files and directories Git should ignore when tracking changes.
├── README.md // A markdown file that contains essential information about your project.
├── index.html // The HTML template that serves as the entry point for your application.
├── node_modules // A directory where installed packages are stored.
├── package-lock.json // Files that manage the dependencies and configuration of your project.
├── package.json // Files that manage the dependencies and configuration of your project.
├── public // A directory for static assets that will be served as-is.
├── src // The directory where you'll write your application's source code.
├── tsconfig.json // TypeScript configuration files that define how TypeScript should behave in your project.
├── tsconfig.node.json // TypeScript configuration files that define how TypeScript should behave in your project.
└── vite.config.ts // Configuration file for Vite, the build tool and development server you're using for your project.

As the src directory is the heart of the source code, let's review the directory structure of it. As moving forward through this lesson, we will create other files and folders to create our components and helper functions.

├── App.tsx // The main TypeScript file that contains the root component of your application.
├── assets // A directory where you can store assets like images (e.g., react.svg).
│ └── react.svg
├── index.css // CSS file for styling your application.
├── main.tsx // The entry point of your Vite application, where the app is initialized.
└── vite-env.d.ts // A TypeScript declaration file for environment variables and types used in your Vite app.

Before jumping into the coding, let's create some folders and files in the src folder.


caution

Make sure your terminal points to your project folder (i.e., defi_dex_frontend) before running the command below.

Run the command below to create the files and folders:

mkdir src/components
mkdir src/components/utils
mkdir src/components/utils/constants

touch src/components/utils/addLiquidity.tsx
touch src/components/utils/client.tsx
touch src/components/utils/createExchange.tsx
touch src/components/utils/format.tsx
touch src/components/utils/getData.tsx
touch src/components/utils/hooks.tsx
touch src/components/utils/removeLiquidity.tsx
touch src/components/utils/swap.tsx

touch src/components/utils/constants/index.tsx

touch src/components/ui.tsx
touch src/components/AddLiquidity.tsx
touch src/components/CreateExchange.tsx
touch src/components/Header.tsx
touch src/components/Liquidity.tsx
touch src/components/RemoveLiquidity.tsx
touch src/components/Swap.tsx

Setting Constants​

Storing constant variables in a separate file has many advantages, including readability and reusability. Thus, it is preferable to define ABIs and addresses of smart contracts in a separate file.

Modify the src/components/utils/constants/index.tsx file and include the constants below:

export const TOKEN_CONTRACT_ADDRESS = "ADDRESS_OF_TOKEN_CONTRACT";
export const FACTORY_CONTRACT_ADDRESS = "ADDRESS_OF_FACTORY_CONTRACT";
export const TOKEN_CONTRACT_ABI = ABI_OF_TOKEN_CONTRACT as const;
export const FACTORY_CONTRACT_ABI = ABI_OF_FACTORY_CONTRACT as const;
export const EXCHANGE_CONTRACT_ABI = ABI_OF_EXCHANGE_CONTRACT as const;

In the next steps, we will retrieve the ABIs of the smart contracts we deployed in lesson 4, along with their associated contract addresses.

Token Smart Contract Address and ABI​

Retrieve the address of the token contract you deployed in lesson 4 and paste it in the TOKEN_CONTRACT_ADDRESS variable.

To retrieve the ABI, navigate to the defi_dex directory and go to the out folder. Find the ERC20.sol/MyToken.json file and copy the ABI section.

Factory Smart Contract Address and ABI​

Perform the same steps to retrieve the Factory contract address and ABI. Alternatively, to fetch the ABI, you can either run the following code in your project folder (i.e., defi_dex) to print out the ABI in your terminal:

jq '.abi' out/Factory.sol/Factory.json

Or, if you verified your Factory contract as demonstrated in lesson 4, obtain the ABI of the Factory smart contract by going to the Code section under the Contract tab on Etherscan.

Factory Contract ABI

Exchange Smart Contract ABI​

Apply one of the methods mentioned above (excluding Etherscan) to retrieve the ABI of the Exchange smart contract. Since the Exchange smart contract will be deployed later, its address will be fetched automatically. So, it is enough to define only the ABI of Exchange smart contract.

Creating Helper Functions​

As we explained the functionalities of helper functions before, we will build these helper functions in this section. Any code editor (like VS Code) can modify the files.

NOTE: All helper function files are located in the ./src/components/utils/ folder.

Keep as const after each pasted ABI array so Viem can infer event names and return types.

Modifying the client.tsx file​

The client.tsx file creates a public Viem client for reads through Quicknode. getWalletClient creates a signing client only when a browser wallet is available, so the app can render without an extension. waitForSuccess checks the receipt status before the UI continues.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { createPublicClient, createWalletClient, custom, http, type Hash } from "viem";
import { sepolia } from "viem/chains";
import "viem/window";

export const publicClient = createPublicClient({
chain: sepolia,
transport: http(import.meta.env.VITE_VERCEL_QUICKNODE_ENDPOINT),
});

export const getWalletClient = () => {
if (!window.ethereum) {
throw new Error("Install a browser wallet to connect.");
}
return createWalletClient({ chain: sepolia, transport: custom(window.ethereum) });
};

export const waitForSuccess = async (hash: Hash) => {
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Transaction reverted.");
return receipt;
};

Modifying the addLiquidity.tsx file​

The addLiquidity.tsx file adds liquidity to the pool. The addLiquidity function first approves the Exchange contract to spend your tokens. Then it calls addLiquidity on the Exchange contract and returns the transaction hash. The calculateToken function uses the current reserve ratio and adds one wei to match the contract's rounding.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

// Import necessary modules and constants
import {
TOKEN_CONTRACT_ABI,
TOKEN_CONTRACT_ADDRESS,
EXCHANGE_CONTRACT_ABI,
} from "./constants"; // Import contract ABIs and addresses

import type { Address } from "viem";
import { sepolia } from "viem/chains"; // Import a blockchain context

import { publicClient, getWalletClient, waitForSuccess } from "./client"; // Import blockchain clients

// Function to add liquidity to the exchange pool
export const addLiquidity = async (
addTokenAmountWei: bigint,
addEtherAmountWei: bigint,
account: Address,
exchangeAddress: Address
) => {
// Increase the allowance of tokens for the exchange contract
const { request: requestOne } = await publicClient.simulateContract({
account,
address: TOKEN_CONTRACT_ADDRESS,
abi: TOKEN_CONTRACT_ABI,
functionName: "approve",
args: [exchangeAddress, addTokenAmountWei],
chain: sepolia,
});

// Write the transaction to the blockchain and wait for receipt
let hash = await getWalletClient().writeContract(requestOne);
await waitForSuccess(hash);
console.log(`approve Tx is: ${hash}`);

// Add liquidity to the exchange pool
const { request: requestTwo } = await publicClient.simulateContract({
account,
address: exchangeAddress,
abi: EXCHANGE_CONTRACT_ABI,
functionName: "addLiquidity",
args: [addTokenAmountWei],
value: addEtherAmountWei,
chain: sepolia,
});

// Write the transaction to the blockchain and wait for receipt
hash = await getWalletClient().writeContract(requestTwo);
await waitForSuccess(hash);
console.log(`AddLiquidity Tx is: ${hash}`);
return hash;
};

// Function to calculate the token amount that matches the pool ratio
export const calculateToken = (
addEtherAmountWei: bigint,
etherReserve: bigint,
tokenReserve: bigint
): bigint => {
if (addEtherAmountWei === 0n || etherReserve === 0n) return 0n;

// Add 1 wei to match the contract's rounding
return (addEtherAmountWei * tokenReserve) / etherReserve + 1n;
};

Modifying the getData.tsx file​

These utility functions in the getData.tsx file can be used to fetch exchange contract address, various balances and reserve amounts from the blockchain. Note that error handling is included in each function to handle potential errors that may occur during contract interactions.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { zeroAddress, type Address } from "viem";
import { publicClient } from "./client";
import {
TOKEN_CONTRACT_ABI, TOKEN_CONTRACT_ADDRESS, EXCHANGE_CONTRACT_ABI,
FACTORY_CONTRACT_ADDRESS, FACTORY_CONTRACT_ABI,
} from "./constants";

const isUnset = (address: Address) => address === "0x" || address === zeroAddress;

export const getExchangeAddress = async (address: Address): Promise<Address> =>
publicClient.readContract({
address: FACTORY_CONTRACT_ADDRESS, abi: FACTORY_CONTRACT_ABI,
functionName: "getExchange", args: [address],
}) as Promise<Address>;

export const getEtherBalance = async (address: Address): Promise<bigint> =>
isUnset(address) ? 0n : publicClient.getBalance({ address });

export const getTokenBalance = async (address: Address): Promise<bigint> =>
isUnset(address) ? 0n : publicClient.readContract({
address: TOKEN_CONTRACT_ADDRESS, abi: TOKEN_CONTRACT_ABI,
functionName: "balanceOf", args: [address],
}) as Promise<bigint>;

export const getLpTokenBalance = async (address: Address, exchangeAddress: Address): Promise<bigint> =>
isUnset(address) || isUnset(exchangeAddress) ? 0n : publicClient.readContract({
address: exchangeAddress, abi: EXCHANGE_CONTRACT_ABI,
functionName: "balanceOf", args: [address],
}) as Promise<bigint>;

export const getReserveOfToken = async (exchangeAddress: Address): Promise<bigint> =>
isUnset(exchangeAddress) ? 0n : publicClient.readContract({
address: exchangeAddress, abi: EXCHANGE_CONTRACT_ABI, functionName: "getTokenReserves",
}) as Promise<bigint>;

export const getTokenData = async (address: Address): Promise<string> => {
try {
return await publicClient.readContract({ address, abi: TOKEN_CONTRACT_ABI,
functionName: "symbol" }) as string;
} catch {
return "Unknown";
}
};

Modifying the removeLiquidity.tsx file​

The removeLiquidity.tsx file removes liquidity from the Exchange contract. The removeLiquidity function simulates and sends the transaction, then returns the transaction hash. The getTokensAfterRemove function calculates the ETH and tokens that a given amount of LP tokens returns.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { EXCHANGE_CONTRACT_ABI } from "./constants"; // Import the contract ABI and address
import { sepolia } from "viem/chains"; // Import the chain details
import { publicClient, getWalletClient, waitForSuccess } from "./client"; // Import the client instances
import type { Address } from "viem";

// Simulate and execute the removal of liquidity tokens from the pool
export const removeLiquidity = async (
removeLPTokensWei: bigint,
account: Address,
exchangeAddress: Address
) => {
const { request } = await publicClient.simulateContract({
account,
address: exchangeAddress,
abi: EXCHANGE_CONTRACT_ABI,
functionName: "removeLiquidity",
args: [removeLPTokensWei],
chain: sepolia,
});

const hash = await getWalletClient().writeContract(request);
await waitForSuccess(hash);
console.log(`RemoveLiquidity Tx is: ${hash}`);
return hash;
};

// Calculate the amounts of Ether and tokens after removing liquidity
export const getTokensAfterRemove = async (
removeLPTokenWei: bigint,
ethReserve: bigint,
tokenReserve: bigint,
exchangeAddress: Address
): Promise<TokenAfterRemove> => {
try {
// Get the total supply of liquidity tokens in the pool
const _totalSupply = (await publicClient.readContract({
address: exchangeAddress,
abi: EXCHANGE_CONTRACT_ABI,
functionName: "totalSupply",
})) as bigint;

// Calculate the amount of Ether that will be received after removing liquidity
const _removeEther = (ethReserve * removeLPTokenWei) / _totalSupply;

// Calculate the amount of tokens that will be received after removing liquidity
const _removeToken = (tokenReserve * removeLPTokenWei) / _totalSupply;

// Return the calculated amounts of Ether and tokens
return {
_removeEther,
_removeToken,
};
} catch (err) {
console.error(err);
return { _removeEther: BigInt(0), _removeToken: BigInt(0) };
}
};

// Define the TokenAfterRemove interface
interface TokenAfterRemove {
_removeEther: bigint;
_removeToken: bigint;
}

Modifying the swap.tsx file​

The swap.tsx file holds the swap logic:

  • getAmountOfTokensReceivedFromSwap asks the Exchange contract for a quote. It calls getTokenAmount for ETH to token swaps and getEthAmount for token to ETH swaps.
  • minimumReceived sets the lowest amount that the swap accepts. With SLIPPAGE_PERCENT set to 10, the swap reverts if you receive less than 90% of the quote. Production DEXs usually let the user set this value.
  • swapTokens runs the swap. For ETH to token, it calls swapEthForTokens. For token to ETH, it calls approve first, then tokenForEthSwap. It reads the amount received from the swap event and returns it with the transaction hash.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

// Import contract ABIs and addresses
import {
TOKEN_CONTRACT_ABI,
TOKEN_CONTRACT_ADDRESS,
EXCHANGE_CONTRACT_ABI,
} from "./constants";

// Import the Sepolia chain information
import { sepolia } from "viem/chains";

import { parseEventLogs, type Address } from "viem";

// Import the public and wallet clients for interacting with the blockchain
import { publicClient, getWalletClient, waitForSuccess } from "./client";

// Accept up to 10% less than the quote
export const SLIPPAGE_PERCENT = 10;

// Function to calculate the minimum amount accepted after slippage
export const minimumReceived = (quote: bigint) =>
(quote * BigInt(100 - SLIPPAGE_PERCENT)) / 100n;

// Function to calculate the amount of tokens to be received from a swap
export const getAmountOfTokensReceivedFromSwap = async (
ethSelected: boolean,
swapAmountWei: bigint,
exchangeAddress: Address
): Promise<bigint> => {
let amountOfTokens;

// Check if ETH is being swapped for tokens or vice versa
if (ethSelected) {
// Calculate the amount of tokens to be received when swapping ETH for tokens
amountOfTokens = (await publicClient.readContract({
address: exchangeAddress,
abi: EXCHANGE_CONTRACT_ABI,
functionName: "getTokenAmount",
args: [swapAmountWei],
})) as bigint;
} else {
// Calculate the amount of tokens to be received when swapping tokens for ETH
amountOfTokens = (await publicClient.readContract({
address: exchangeAddress,
abi: EXCHANGE_CONTRACT_ABI,
functionName: "getEthAmount",
args: [swapAmountWei],
})) as bigint;
}

return amountOfTokens;
};

// Function to perform a token swap
export const swapTokens = async (
ethSelected: boolean,
swapAmountWei: bigint,
tokenToBeReceivedAfterSwap: bigint,
account: Address,
exchangeAddress: Address
) => {
const minimumTokenToBeReceivedAfterSwap = minimumReceived(tokenToBeReceivedAfterSwap);

if (ethSelected) {
// Swap ETH for tokens
const { request } = await publicClient.simulateContract({
account,
address: exchangeAddress,
abi: EXCHANGE_CONTRACT_ABI,
functionName: "swapEthForTokens",
args: [minimumTokenToBeReceivedAfterSwap, account],
value: swapAmountWei,
chain: sepolia,
});

// Write the contract transaction and wait for confirmation
const hash = await getWalletClient().writeContract(request);
const receipt = await waitForSuccess(hash);
const [event] = parseEventLogs({ abi: EXCHANGE_CONTRACT_ABI,
eventName: "TokenPurchased", logs: receipt.logs.filter(log =>
log.address.toLowerCase() === exchangeAddress.toLowerCase()) });
const args = event?.args as { tokensReceived?: bigint } | undefined;
if (args?.tokensReceived === undefined) throw new Error("Swap event not found.");
return { hash, received: args.tokensReceived };
} else {
// Increase allowance for the token contract
const { request: requestOne } = await publicClient.simulateContract({
account,
address: TOKEN_CONTRACT_ADDRESS,
abi: TOKEN_CONTRACT_ABI,
functionName: "approve",
args: [exchangeAddress, swapAmountWei],
chain: sepolia,
});

// Write the contract transaction and wait for confirmation
let hash = await getWalletClient().writeContract(requestOne);
await waitForSuccess(hash);

// Swap tokens for ETH
const { request: requestTwo } = await publicClient.simulateContract({
account,
address: exchangeAddress,
abi: EXCHANGE_CONTRACT_ABI,
functionName: "tokenForEthSwap",
args: [swapAmountWei, minimumTokenToBeReceivedAfterSwap],
chain: sepolia,
});

// Write the contract transaction and wait for confirmation
hash = await getWalletClient().writeContract(requestTwo);
const receipt = await waitForSuccess(hash);
const [event] = parseEventLogs({ abi: EXCHANGE_CONTRACT_ABI,
eventName: "TokenSold", logs: receipt.logs.filter(log =>
log.address.toLowerCase() === exchangeAddress.toLowerCase()) });
const args = event?.args as { ethReceived?: bigint } | undefined;
if (args?.ethReceived === undefined) throw new Error("Swap event not found.");
return { hash, received: args.ethReceived };
}
};

Modifying the createExchange.tsx file​

The createExchange.tsx file calls the Factory contract to create a new Exchange contract for a token. The createNewExchange function simulates and sends the transaction, then returns the transaction hash.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

// Import necessary modules and constants
import { FACTORY_CONTRACT_ADDRESS, FACTORY_CONTRACT_ABI } from "./constants";

import type { Address } from "viem";
import { sepolia } from "viem/chains";

import { publicClient, getWalletClient, waitForSuccess } from "./client";

// Function to create a new exchange contract for a token
export const createNewExchange = async (
tokenAddress: Address,
account: Address
) => {
// Simulate the "createNewExchange" contract function call
const { request: requestOne } = await publicClient.simulateContract({
account,
address: FACTORY_CONTRACT_ADDRESS,
abi: FACTORY_CONTRACT_ABI,
functionName: "createNewExchange",
args: [tokenAddress],
chain: sepolia,
});

// Write the transaction to the blockchain and wait for receipt
const hash = await getWalletClient().writeContract(requestOne);
await waitForSuccess(hash);
console.log(`createNewExchange Tx is: ${hash}`);
return hash;
};

Modifying the format.tsx file​

The format.tsx file holds display and input helpers. formatAmount shows at most six decimals. toWei converts user input to wei and returns 0n for empty or invalid input. runTx wraps each transaction flow. It shows a loading toast, then a success toast with an Etherscan link, or an error toast with the reason.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { formatEther, parseEther, type Hash } from "viem";
import { toast } from "sonner";

export const EXPLORER_URL = "https://sepolia.etherscan.io";

// Shorten an address or hash, e.g. 0x1234...abcd
export const shortAddress = (address: string) =>
`${address.slice(0, 6)}...${address.slice(-4)}`;

// Format a wei amount with at most 6 decimals
export const formatAmount = (wei: bigint) => {
const [whole, fraction = ""] = formatEther(wei).split(".");
const decimals = fraction.slice(0, 6).replace(/0+$/, "");
if (wei > 0n && whole === "0" && !decimals) return "<0.000001";
return decimals ? `${whole}.${decimals}` : whole;
};

// Parse an input string to wei, 0n when empty or invalid
export const toWei = (value: string) => {
try {
return value && value !== "." ? parseEther(value) : 0n;
} catch {
return 0n;
}
};

// Prefer viem's short error message
export const errorMessage = (err: unknown) =>
(err as { shortMessage?: string }).shortMessage ?? (err as Error).message;

// Run a transaction flow and report each state in a toast
export const runTx = async (label: string, send: () => Promise<Hash>) => {
const id = toast.loading(label, { description: "Confirm in your wallet, then wait for the block." });
try {
const hash = await send();
toast.success(`${label}: done`, {
id,
description: `Transaction ${shortAddress(hash)}`,
action: { label: "View", onClick: () => window.open(`${EXPLORER_URL}/tx/${hash}`, "_blank") },
});
return true;
} catch (err) {
toast.error(`${label}: failed`, { id, description: errorMessage(err) });
return false;
}
};

Modifying the hooks.tsx file​

The hooks.tsx file holds two React hooks. The App component calls each hook once and passes the result to every tab.

  • useWallet reads the account and the network from the browser wallet. It listens for account and network changes. Browser wallets have no standard disconnect call, so disconnect saves a flag in localStorage. The app then stays disconnected after a reload until you click Connect wallet.
  • usePool loads the wallet balances, the pool reserves, and the token symbol in one Promise.all call. Call reload after a transaction to load fresh values.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { useCallback, useEffect, useState } from "react";
import { zeroAddress, type Address } from "viem";
import { sepolia } from "viem/chains";
import { toast } from "sonner";
import { getWalletClient } from "./client";
import { TOKEN_CONTRACT_ADDRESS } from "./constants";
import {
getEtherBalance, getTokenBalance, getLpTokenBalance,
getReserveOfToken, getTokenData,
} from "./getData";
import { errorMessage } from "./format";

// Remember a manual disconnect across reloads
const DISCONNECTED_KEY = "walletDisconnected";

// Track the connected account and its network
export const useWallet = () => {
const [account, setAccount] = useState<Address>();
const [chainId, setChainId] = useState<number>();

const sync = useCallback(async (request: boolean) => {
const client = getWalletClient();
const [address] = request ? await client.requestAddresses() : await client.getAddresses();
const id = await client.getChainId();
setAccount(address);
setChainId(id);
}, []);

useEffect(() => {
if (!window.ethereum) return;
const onChange = () => {
if (localStorage.getItem(DISCONNECTED_KEY)) return;
sync(false).catch(console.error);
};
onChange();
window.ethereum.on("accountsChanged", onChange);
window.ethereum.on("chainChanged", onChange);
return () => {
window.ethereum?.removeListener("accountsChanged", onChange);
window.ethereum?.removeListener("chainChanged", onChange);
};
}, [sync]);

const connect = async () => {
try {
localStorage.removeItem(DISCONNECTED_KEY);
await sync(true);
} catch (err) {
toast.error("Could not connect", { description: errorMessage(err) });
}
};

const disconnect = () => {
localStorage.setItem(DISCONNECTED_KEY, "true");
setAccount(undefined);
};

const switchNetwork = async () => {
try {
await getWalletClient().switchChain({ id: sepolia.id });
} catch (err) {
toast.error("Could not switch network", { description: errorMessage(err) });
}
};

const wrongNetwork = account !== undefined && chainId !== sepolia.id;
return { account, wrongNetwork, connect, disconnect, switchNetwork };
};

export type Wallet = ReturnType<typeof useWallet>;

export type Pool = {
ethBalance: bigint;
tokenBalance: bigint;
lpBalance: bigint;
ethReserve: bigint;
tokenReserve: bigint;
symbol: string;
};

// Load wallet balances and pool reserves, reload after each transaction
export const usePool = (account?: Address, exchange?: Address) => {
const [pool, setPool] = useState<Pool>();
const [version, setVersion] = useState(0);

useEffect(() => {
let active = true;
const user = account ?? zeroAddress;
const pair = exchange ?? zeroAddress;
Promise.all([
getEtherBalance(user),
getTokenBalance(user),
getLpTokenBalance(user, pair),
getEtherBalance(pair),
getReserveOfToken(pair),
getTokenData(TOKEN_CONTRACT_ADDRESS),
])
.then(([ethBalance, tokenBalance, lpBalance, ethReserve, tokenReserve, symbol]) => {
if (active) setPool({ ethBalance, tokenBalance, lpBalance, ethReserve, tokenReserve, symbol });
})
.catch(console.error);
return () => {
active = false;
};
}, [account, exchange, version]);

const reload = useCallback(() => setVersion((v) => v + 1), []);
return { pool, reload };
};

// Props shared by the Swap and Liquidity tabs
export type DexProps = {
wallet: Wallet;
pool?: Pool;
reload: () => void;
exchange?: Address;
goToCreate: () => void;
};

Creating Components​

After completing the helper functions and the constants file, we will build our components one by one.

NOTE: All component files are located in the ./src/components/ folder.

UI​

The ui.tsx file holds the shared UI parts. Card draws a panel with a title bar. Button has a solid style and an outline style. AmountField shows an amount input with a token label, a balance, and an optional Max link. It accepts only numbers with one decimal point. ActionButton is the main button of each form. It asks the user to connect the wallet, then to switch to Sepolia. Then it shows the action label, or the reason the action is blocked, such as Insufficient ETH.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import type { ButtonHTMLAttributes, ReactNode } from "react";
import type { Wallet } from "./utils/hooks";
import { formatAmount } from "./utils/format";

// Panel with a title bar
export const Card = ({ title, children }: { title: string; children: ReactNode }) => (
<section className="mx-auto w-full max-w-md border border-ink bg-paper">
<h2 className="border-b border-ink px-4 py-2 font-mono text-xs uppercase tracking-widest">{title}</h2>
<div className="space-y-4 p-4">{children}</div>
</section>
);

type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & { variant?: "primary" | "outline" };

export const Button = ({ variant = "primary", className = "", ...props }: ButtonProps) => (
<button
className={`px-4 py-3 font-mono text-xs uppercase tracking-widest transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
variant === "primary"
? "bg-ink text-paper enabled:hover:bg-accent enabled:hover:text-ink"
: "border border-ink bg-paper enabled:hover:bg-accent"
} ${className}`}
{...props}
/>
);

// Amount input with a token label, balance, and optional MAX
export const AmountField = ({ label, value, onChange, symbol, balance, onMax }: {
label: string; value: string; onChange?: (value: string) => void;
symbol: string; balance?: bigint; onMax?: () => void;
}) => (
<div className="border border-line bg-canvas p-3 focus-within:border-ink">
<div className="flex items-center justify-between gap-3 font-mono text-xs uppercase text-muted">
<span>{label}</span>
{balance !== undefined && (
<span>
Balance {formatAmount(balance)}
{onMax && (
<button onClick={onMax} className="ml-2 text-link hover:underline">Max</button>
)}
</span>
)}
</div>
<div className="mt-2 flex items-center gap-3">
<input
inputMode="decimal"
placeholder="0"
value={value}
readOnly={!onChange}
onChange={(e) => {
const next = e.target.value.replace(",", ".");
if (/^\d*\.?\d*$/.test(next)) onChange?.(next);
}}
className="w-full min-w-0 bg-transparent text-3xl font-medium outline-none placeholder:text-line"
/>
<span className="shrink-0 border border-ink bg-paper px-2 py-1 font-mono text-sm">{symbol}</span>
</div>
</div>
);

export const Row = ({ label, value }: { label: string; value: ReactNode }) => (
<div className="flex items-center justify-between gap-4 text-sm">
<span className="text-muted">{label}</span>
<span className="whitespace-nowrap font-mono">{value}</span>
</div>
);

export const Notice = ({ tone = "info", children }: {
tone?: "info" | "error"; children: ReactNode;
}) => (
<div className={`border px-3 py-2 text-sm ${
tone === "error" ? "border-danger bg-danger-soft" : "border-ink bg-lavender"
}`}>
{children}
</div>
);

// Main action: connect first, then switch network, then explain what blocks the action
export const ActionButton = ({ wallet, label, blocker, busy, onClick }: {
wallet: Wallet; label: string; blocker?: string; busy: boolean; onClick: () => void;
}) => {
if (!wallet.account) {
return <Button className="w-full" onClick={wallet.connect}>Connect wallet</Button>;
}
if (wallet.wrongNetwork) {
return <Button className="w-full" onClick={wallet.switchNetwork}>Switch to Sepolia</Button>;
}
return (
<Button className="w-full" disabled={busy || blocker !== undefined} onClick={onClick}>
{busy ? "Waiting for wallet..." : blocker ?? label}
</Button>
);
};

// Shown on Swap and Liquidity until the exchange exists
export const NoExchange = ({ title, onCreate }: { title: string; onCreate: () => void }) => (
<Card title={title}>
<Notice>No exchange exists for your token yet. Create it first.</Notice>
<Button variant="outline" className="w-full" onClick={onCreate}>Go to Create Exchange</Button>
</Card>
);

The Header.tsx file shows the app name, the tabs, and the wallet status. It gets the wallet state from useWallet through props. When the wallet is on another network, the network label changes to a Wrong network: switch button. On small screens, the tabs move to their own row.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { FiLogOut } from "react-icons/fi";
import { Button } from "./ui";
import { shortAddress } from "./utils/format";
import type { Wallet } from "./utils/hooks";

export type Tab = "swap" | "liquidity" | "create";

const TABS: { id: Tab; label: string }[] = [
{ id: "swap", label: "Swap" },
{ id: "liquidity", label: "Liquidity" },
{ id: "create", label: "Create Exchange" },
];

const Header = ({ tab, setTab, wallet }: {
tab: Tab; setTab: (tab: Tab) => void; wallet: Wallet;
}) => (
<header className="border-b border-ink bg-paper">
<div className="mx-auto flex max-w-5xl flex-wrap items-center justify-between gap-3 px-4 py-3">
<div className="flex items-center gap-2 text-lg font-semibold tracking-tight">
<span className="size-6 bg-accent outline outline-ink" />
DeFi Course DEX
</div>

{/* Tabs move to their own row on small screens */}
<nav className="order-last flex w-full border border-ink sm:order-none sm:w-auto">
{TABS.map(({ id, label }) => (
<button
key={id}
onClick={() => setTab(id)}
className={`flex-auto whitespace-nowrap border-ink px-3 py-2 font-mono text-xs uppercase tracking-widest not-first:border-l sm:flex-none ${
tab === id ? "bg-accent" : "hover:bg-canvas"
}`}
>
{label}
</button>
))}
</nav>

<div className="flex items-center gap-2">
{wallet.account && (
wallet.wrongNetwork ? (
<button
onClick={wallet.switchNetwork}
className="border border-danger bg-danger-soft px-3 py-2 font-mono text-xs uppercase tracking-widest"
>
Wrong network: switch
</button>
) : (
<span className="hidden items-center gap-2 border border-line px-3 py-2 font-mono text-xs uppercase tracking-widest sm:flex">
<span className="size-2 rounded-full bg-accent" />
Sepolia
</span>
)
)}
{wallet.account ? (
<div className="flex border border-ink">
<span className="px-3 py-2 font-mono text-xs">{shortAddress(wallet.account)}</span>
<button
onClick={wallet.disconnect}
aria-label="Disconnect wallet"
className="border-l border-ink px-3 hover:bg-accent"
>
<FiLogOut />
</button>
</div>
) : (
<Button onClick={wallet.connect} className="py-2">Connect wallet</Button>
)}
</div>
</div>
</header>
);

export default Header;

AddLiquidity​

The AddLiquidity.tsx file deposits ETH and tokens. When the pool is empty, you enter both amounts, and your deposit sets the price. After that, you enter only the ETH amount, and calculateToken fills in the token amount. The button stays disabled until the pool loads and both amounts are valid and within your balance.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { useState } from "react";
import { formatEther, type Address } from "viem";
import { ActionButton, AmountField, Notice } from "./ui";
import { formatAmount, runTx, toWei } from "./utils/format";
import type { DexProps } from "./utils/hooks";
import { addLiquidity, calculateToken } from "./utils/addLiquidity";

const AddLiquidity = ({ wallet, pool, reload, exchange }: DexProps & { exchange: Address }) => {
const [ethAmount, setEthAmount] = useState("");
const [tokenAmount, setTokenAmount] = useState("");
const [busy, setBusy] = useState(false);

const symbol = pool?.symbol ?? "TOKEN";
const balances = wallet.account ? pool : undefined;
const firstDeposit = pool?.tokenReserve === 0n;
const ethWei = toWei(ethAmount);

// The first deposit sets the price, later deposits follow the pool ratio
const tokenWei = firstDeposit
? toWei(tokenAmount)
: calculateToken(ethWei, pool?.ethReserve ?? 0n, pool?.tokenReserve ?? 0n);

const blocker =
!pool ? "Loading pool"
: ethWei === 0n || tokenWei === 0n ? "Enter an amount"
: balances && ethWei > balances.ethBalance ? "Insufficient ETH"
: balances && tokenWei > balances.tokenBalance ? `Insufficient ${symbol}`
: undefined;

const onAdd = async () => {
const account = wallet.account;
if (!account) return;
setBusy(true);
const ok = await runTx("Add liquidity", () => addLiquidity(tokenWei, ethWei, account, exchange));
setBusy(false);
if (ok) {
setEthAmount("");
setTokenAmount("");
reload();
}
};

return (
<>
{firstDeposit && <Notice>The pool is empty. Your first deposit sets the price.</Notice>}
<AmountField
label="Deposit"
value={ethAmount}
onChange={setEthAmount}
symbol="ETH"
balance={balances?.ethBalance}
/>
<AmountField
label={firstDeposit ? "Deposit" : "Deposit (pool ratio)"}
value={firstDeposit ? tokenAmount : tokenWei > 0n ? formatAmount(tokenWei) : ""}
onChange={firstDeposit ? setTokenAmount : undefined}
symbol={symbol}
balance={balances?.tokenBalance}
onMax={firstDeposit && balances ? () => setTokenAmount(formatEther(balances.tokenBalance)) : undefined}
/>
<ActionButton
wallet={wallet}
label="Approve and add liquidity"
blocker={blocker}
busy={busy}
onClick={onAdd}
/>
<p className="text-xs text-muted">Your wallet asks twice: approve {symbol}, then add liquidity.</p>
</>
);
};

export default AddLiquidity;

RemoveLiquidity​

The RemoveLiquidity.tsx file burns LP tokens. You enter an amount, or you select 25%, 50%, 75%, or Max. The component calls getTokensAfterRemove to preview the ETH and tokens you receive.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { useEffect, useState } from "react";
import { formatEther, type Address } from "viem";
import { ActionButton, AmountField, Notice, Row } from "./ui";
import { formatAmount, runTx, toWei } from "./utils/format";
import type { DexProps } from "./utils/hooks";
import { getTokensAfterRemove, removeLiquidity } from "./utils/removeLiquidity";

const SHARES = [25n, 50n, 75n, 100n];
const NO_PREVIEW = { _removeEther: 0n, _removeToken: 0n };

const RemoveLiquidity = ({ wallet, pool, reload, exchange }: DexProps & { exchange: Address }) => {
const [lpAmount, setLpAmount] = useState("");
const [latestPreview, setLatestPreview] = useState(NO_PREVIEW);
const [busy, setBusy] = useState(false);

const symbol = pool?.symbol ?? "TOKEN";
const lpBalance = wallet.account ? pool?.lpBalance ?? 0n : 0n;
const lpWei = toWei(lpAmount);

// Preview the ETH and tokens this LP amount returns
useEffect(() => {
if (!pool || lpWei === 0n) return;
let active = true;
getTokensAfterRemove(lpWei, pool.ethReserve, pool.tokenReserve, exchange)
.then((result) => active && setLatestPreview(result));
return () => {
active = false;
};
}, [lpWei, pool, exchange]);

if (wallet.account && lpBalance === 0n) {
return <Notice>You have no LP tokens yet. Add liquidity first.</Notice>;
}

const preview = lpWei > 0n ? latestPreview : NO_PREVIEW;
const blocker =
lpWei === 0n ? "Enter an amount"
: lpWei > lpBalance ? "Insufficient LP tokens"
: undefined;

const onRemove = async () => {
const account = wallet.account;
if (!account) return;
setBusy(true);
const ok = await runTx("Remove liquidity", () => removeLiquidity(lpWei, account, exchange));
setBusy(false);
if (ok) {
setLpAmount("");
reload();
}
};

return (
<>
<AmountField
label="Withdraw"
value={lpAmount}
onChange={setLpAmount}
symbol="LP"
balance={wallet.account ? lpBalance : undefined}
/>
<div className="grid grid-cols-4 border border-ink">
{SHARES.map((share) => (
<button
key={share}
onClick={() => setLpAmount(formatEther((lpBalance * share) / 100n))}
className="py-2 font-mono text-xs uppercase not-first:border-l not-first:border-ink hover:bg-accent"
>
{share === 100n ? "Max" : `${share}%`}
</button>
))}
</div>
<div className="space-y-1 border-t border-line pt-3">
<Row label="You receive ETH" value={formatAmount(preview._removeEther)} />
<Row label={`You receive ${symbol}`} value={formatAmount(preview._removeToken)} />
</div>
<ActionButton
wallet={wallet}
label="Remove liquidity"
blocker={blocker}
busy={busy}
onClick={onRemove}
/>
</>
);
};

export default RemoveLiquidity;

Liquidity​

The Liquidity.tsx file holds the Liquidity tab. It shows the pool reserves and your LP tokens. A two-part switch shows the AddLiquidity or the RemoveLiquidity form. If the exchange does not exist, it shows a button that opens the Create Exchange tab.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { useState } from "react";
import AddLiquidity from "./AddLiquidity";
import RemoveLiquidity from "./RemoveLiquidity";
import { Card, NoExchange, Row } from "./ui";
import { formatAmount } from "./utils/format";
import type { DexProps } from "./utils/hooks";

const Liquidity = (props: DexProps) => {
const [mode, setMode] = useState<"add" | "remove">("add");
const { pool, exchange, wallet } = props;

if (!exchange) return <NoExchange title="Liquidity" onCreate={props.goToCreate} />;

const symbol = pool?.symbol ?? "TOKEN";
const show = (wei?: bigint) => (wei === undefined ? "..." : formatAmount(wei));

return (
<Card title="Liquidity">
{/* Add or remove, one form at a time */}
<div className="grid grid-cols-2 border border-ink">
{(["add", "remove"] as const).map((id) => (
<button
key={id}
onClick={() => setMode(id)}
className={`py-2 font-mono text-xs uppercase tracking-widest not-first:border-l not-first:border-ink ${
mode === id ? "bg-accent" : "hover:bg-canvas"
}`}
>
{id}
</button>
))}
</div>

<div className="space-y-1 bg-canvas p-3">
<Row label="Pool ETH" value={show(pool?.ethReserve)} />
<Row label={`Pool ${symbol}`} value={show(pool?.tokenReserve)} />
{wallet.account && <Row label="Your LP tokens" value={show(pool?.lpBalance)} />}
</div>

{mode === "add"
? <AddLiquidity {...props} exchange={exchange} />
: <RemoveLiquidity {...props} exchange={exchange} />}
</Card>
);
};

export default Liquidity;

Swap​

The Swap.tsx file trades ETH and tokens. When you type an amount, it asks the Exchange contract for a quote. A quote is used only when its input amount, direction, and Exchange match the current form; the swap button stays disabled while a new quote loads. The arrow button between the fields switches the swap direction. Below the fields, it shows the price, the minimum received after slippage, and the LP fee. A token to ETH swap needs two wallet confirmations: approve, then swap.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { useEffect, useState } from "react";
import { formatEther } from "viem";
import { FiArrowDown } from "react-icons/fi";
import { ActionButton, AmountField, Card, NoExchange, Notice, Row } from "./ui";
import { formatAmount, runTx, toWei } from "./utils/format";
import type { DexProps } from "./utils/hooks";
import {
getAmountOfTokensReceivedFromSwap, minimumReceived, swapTokens, SLIPPAGE_PERCENT,
} from "./utils/swap";

const Swap = ({ wallet, pool, reload, exchange, goToCreate }: DexProps) => {
const [ethSelected, setEthSelected] = useState(true);
const [amount, setAmount] = useState("");
const [latestQuote, setLatestQuote] = useState<{
amountWei: bigint;
ethSelected: boolean;
exchange: string;
value: bigint;
}>();
const [busy, setBusy] = useState(false);
const [lastReceived, setLastReceived] = useState<string>();

const amountWei = toWei(amount);
const symbol = pool?.symbol ?? "TOKEN";
const [fromSymbol, toSymbol] = ethSelected ? ["ETH", symbol] : [symbol, "ETH"];
const balances = wallet.account ? pool : undefined;
const fromBalance = ethSelected ? balances?.ethBalance : balances?.tokenBalance;
const toBalance = ethSelected ? balances?.tokenBalance : balances?.ethBalance;

// Ask the Exchange contract for a quote when the input changes
useEffect(() => {
setLatestQuote(undefined);
if (!exchange || amountWei === 0n) return;
let active = true;
getAmountOfTokensReceivedFromSwap(ethSelected, amountWei, exchange)
.then((value) => active && setLatestQuote({ amountWei, ethSelected, exchange, value }))
.catch(() => active && setLatestQuote(undefined));
return () => {
active = false;
};
}, [ethSelected, amountWei, exchange]);

if (!exchange) return <NoExchange title="Swap" onCreate={goToCreate} />;

const quote = amountWei > 0n
&& latestQuote?.amountWei === amountWei
&& latestQuote.ethSelected === ethSelected
&& latestQuote.exchange === exchange
? latestQuote.value : 0n;

const emptyPool = pool?.ethReserve === 0n;
const blocker =
amountWei === 0n ? "Enter an amount"
: fromBalance !== undefined && amountWei > fromBalance ? `Insufficient ${fromSymbol}`
: quote === 0n ? "No quote"
: undefined;

const flip = () => {
setEthSelected(!ethSelected);
setAmount("");
setLatestQuote(undefined);
};

const onSwap = async () => {
const account = wallet.account;
if (!account || quote === 0n) return;
setBusy(true);
let received = 0n;
const ok = await runTx(`Swap ${fromSymbol} for ${toSymbol}`, async () => {
const result = await swapTokens(ethSelected, amountWei, quote, account, exchange);
received = result.received;
return result.hash;
});
setBusy(false);
if (ok) {
setLastReceived(`${formatAmount(received)} ${toSymbol}`);
setAmount("");
reload();
}
};

return (
<Card title="Swap">
{emptyPool && <Notice>The pool is empty. Add liquidity before you swap.</Notice>}

<div className="relative space-y-1">
<AmountField
label="You pay"
value={amount}
onChange={setAmount}
symbol={fromSymbol}
balance={fromBalance}
onMax={!ethSelected && balances ? () => setAmount(formatEther(balances.tokenBalance)) : undefined}
/>
<AmountField
label="You receive"
value={quote > 0n ? formatAmount(quote) : ""}
symbol={toSymbol}
balance={toBalance}
/>
<button
onClick={flip}
aria-label="Switch swap direction"
className="absolute top-1/2 left-1/2 -translate-1/2 border border-ink bg-paper p-2 hover:bg-accent"
>
<FiArrowDown />
</button>
</div>

{quote > 0n && (
<div className="space-y-1 border-t border-line pt-3">
<Row label="Price" value={`1 ${fromSymbol} = ${formatAmount((quote * 10n ** 18n) / amountWei)} ${toSymbol}`} />
<Row label={`Minimum received (${SLIPPAGE_PERCENT}% slippage)`} value={`${formatAmount(minimumReceived(quote))} ${toSymbol}`} />
<Row label="LP fee" value="0.3%" />
</div>
)}

<ActionButton
wallet={wallet}
label={ethSelected ? "Swap" : "Approve and swap"}
blocker={blocker}
busy={busy}
onClick={onSwap}
/>

{!ethSelected && <p className="text-xs text-muted">Your wallet asks twice: approve {symbol}, then swap.</p>}
{lastReceived && <Notice>Last swap: you received {lastReceived}.</Notice>}
</Card>
);
};

export default Swap;

CreateExchange​

The CreateExchange.tsx file deploys an Exchange contract for a token. When you enter a valid address, it reads the token symbol and asks the Factory if an exchange already exists. The button stays disabled for an invalid address or an existing exchange.

This application trades one ERC-20 token: the token in your constants file. To trade a different token, update TOKEN_CONTRACT_ADDRESS in the constants file.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { useEffect, useState } from "react";
import { isAddress, isAddressEqual, zeroAddress, type Address } from "viem";
import { ActionButton, Card, Notice, Row } from "./ui";
import { EXPLORER_URL, runTx, shortAddress } from "./utils/format";
import type { Wallet } from "./utils/hooks";
import { createNewExchange } from "./utils/createExchange";
import { getExchangeAddress, getTokenData } from "./utils/getData";
import { TOKEN_CONTRACT_ADDRESS } from "./utils/constants";

const CreateExchange = ({ wallet, onCreated }: { wallet: Wallet; onCreated: () => void }) => {
const [tokenAddress, setTokenAddress] = useState("");
const [lookup, setLookup] = useState<{ address: string; symbol: string; exchange: Address }>();
const [busy, setBusy] = useState(false);
const valid = isAddress(tokenAddress);

// Look up the token symbol and exchange, again after each transaction
useEffect(() => {
if (!isAddress(tokenAddress)) return;
let active = true;
Promise.all([getTokenData(tokenAddress), getExchangeAddress(tokenAddress)])
.then(([symbol, exchange]) => active && setLookup({ address: tokenAddress, symbol, exchange }))
.catch(console.error);
return () => {
active = false;
};
}, [tokenAddress, busy]);

// Ignore a lookup for an older input
const info = lookup?.address === tokenAddress ? lookup : undefined;
const exists = info !== undefined && info.exchange !== zeroAddress;
const otherToken = valid && !isAddressEqual(tokenAddress, TOKEN_CONTRACT_ADDRESS);
const blocker =
tokenAddress === "" ? "Enter a token address"
: !valid ? "Invalid address"
: !info ? "Checking token"
: exists ? "Exchange already exists"
: undefined;

const onCreate = async () => {
const account = wallet.account;
if (!account || !valid) return;
setBusy(true);
const ok = await runTx("Create exchange", () => createNewExchange(tokenAddress, account));
setBusy(false);
if (ok) onCreated();
};

return (
<Card title="Create Exchange">
<p className="text-sm text-muted">
The Factory deploys one Exchange contract for each token. Each token can have only one exchange.
</p>

<label className="block border border-line bg-canvas p-3 focus-within:border-ink">
<span className="font-mono text-xs uppercase text-muted">Token address</span>
<input
value={tokenAddress}
onChange={(e) => setTokenAddress(e.target.value.trim())}
placeholder="0x..."
spellCheck={false}
className="mt-2 w-full bg-transparent font-mono text-sm outline-none placeholder:text-line"
/>
</label>
<button
onClick={() => setTokenAddress(TOKEN_CONTRACT_ADDRESS)}
className="font-mono text-xs uppercase text-link hover:underline"
>
Use the token from constants
</button>

{info && (
<div className="space-y-1 bg-canvas p-3">
<Row label="Token" value={info.symbol} />
<Row
label="Exchange"
value={exists ? (
<a href={`${EXPLORER_URL}/address/${info.exchange}`} target="_blank" className="text-link underline">
{shortAddress(info.exchange)}
</a>
) : "Not created"}
/>
</div>
)}
{otherToken && <Notice>This app trades only the token in your constants file.</Notice>}

<ActionButton
wallet={wallet}
label="Create exchange"
blocker={blocker}
busy={busy}
onClick={onCreate}
/>
</Card>
);
};

export default CreateExchange;

App​

The App component is the root component of your application. It is located in the ./src/ folder.

The App component calls useWallet and usePool and passes the results to each tab. It also gets the Exchange address for your token from the Factory. The Toaster component from Sonner shows the transaction toasts. React 19 moves the <title> element into the document head, so the app needs no extra package for the page title.

Modify the file like the below example. For detailed explanations, you can refer to the comments in the code.

import { useEffect, useState } from "react";
import { zeroAddress, type Address } from "viem";
import { Toaster } from "sonner";
import Header, { type Tab } from "./components/Header";
import Swap from "./components/Swap";
import Liquidity from "./components/Liquidity";
import CreateExchange from "./components/CreateExchange";
import { getExchangeAddress } from "./components/utils/getData";
import { TOKEN_CONTRACT_ADDRESS } from "./components/utils/constants";
import { usePool, useWallet } from "./components/utils/hooks";

function App() {
const [tab, setTab] = useState<Tab>("swap");
const [exchange, setExchange] = useState<Address>();
const wallet = useWallet();
const { pool, reload } = usePool(wallet.account, exchange);

// Find the exchange for your token, if it exists
const loadExchange = () =>
getExchangeAddress(TOKEN_CONTRACT_ADDRESS)
.then((address) => setExchange(address === zeroAddress ? undefined : address))
.catch(console.error);

useEffect(() => {
loadExchange();
}, []);

const dex = { wallet, pool, reload, exchange, goToCreate: () => setTab("create") };

return (
<div className="min-h-screen">
<title>DeFi Course DEX</title>
<Header tab={tab} setTab={setTab} wallet={wallet} />

<main className="px-4 py-10 sm:py-16">
<h1 className="mb-10 text-center text-4xl font-medium tracking-tight sm:text-5xl">
Swap and pool <mark className="bg-accent px-1 text-ink">on Sepolia</mark>
</h1>
{tab === "swap" && <Swap {...dex} />}
{tab === "liquidity" && <Liquidity {...dex} />}
{tab === "create" && <CreateExchange wallet={wallet} onCreated={() => { loadExchange(); reload(); }} />}
</main>

<Toaster position="bottom-right" />
</div>
);
}

export default App;

Previewing the App​

After all these modifications, you can preview the app locally by running the command below. It provides a live development area. It means that whenever you change anything in your code, it will be reflected immediately in the app in your browser.


caution

Ensure that your terminal points to your project directory ./defi_dex_frontend/.

npm run dev

After calling the command, the console output should be similar to the one below. Go to the localhost URL (http://localhost:5173/ in this case) in your browser to preview the app.

VITE v8.3.4 ready in 308 ms

➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h to show help

If everything goes well, the app looks like the image below. Click Connect wallet. Your browser wallet (e.g., Rabby, MetaMask, Phantom) asks you to approve the connection.

DEX Home Page No Wallet

After you connect, the header shows your address and the network. The Swap tab shows the ETH and token balances of your wallet.

Note that although the website runs locally, it interacts with the smart contracts that are deployed on the Sepolia testnet.

DEX Home Page

Now, let's create the Exchange smart contract through the UI.


  • Click the Create Exchange tab.
  • Click Use the token from constants, or paste the token address from the Setting Constants section.
  • Click Create exchange and confirm the transaction in your wallet.

DEX Exchange

tip

If your wallet shows an HTTP request failed error, the RPC URL of its Sepolia network may be down. Edit the Sepolia network in your wallet and set the RPC URL to your Quicknode endpoint.

After the exchange is created, open the Liquidity tab and add some liquidity. Your first deposit sets the price. Then, swap on the Swap tab to test your dApp locally.

Quiz​

To reinforce what you've learned, let's finish off with a quiz. This quiz will cover the topics discussed during this lesson, including questions on the design and functionality of your frontend.


Sign in to track your course progress and interact with quizzes
Create a free Quicknode account to save your progress, complete knowledge checks, and mark lessons complete.
Create AccountSign In

Conclusion​

Congratulations! 🎉 In this section of our guide, we've explored the foundational components constituting a DEX platform's frontend. From understanding the importance of smart contracts and frontend interactions to leveraging essential helper functions and maintaining a well-organized structure, you've gained insights into the core elements of building a successful decentralized exchange. Armed with this knowledge, you're well-equipped to move forward and dive into the implementation details, bringing your DEX to life. In the next section, we'll shift our focus to the critical aspect of security, governance, and risk management.