In decentralized finance (DeFi), liquidity is fragmented across hundreds of decentralized exchanges (DEXs), causing the same token pair to trade at different prices. This means traders may often miss out on the best swap rates.
For example, when swapping ETH for USDC, multiple liquidity pools exist across different DEXs like Uniswap or SushiSwap. Each pool may have different liquidity levels and fees, resulting in different output amounts. A DEX aggregator automates the process of finding the best rates across multiple DEXs, preventing time-consuming manual checks and suboptimal trades.
This step-by-step tutorial shows you how to build a simple, multi-chain DEX aggregator dashboard using the CoinGecko API. The app compares pools and ranks them by their estimated output for a given input amount.
What Is a DEX Aggregator?
A DEX aggregator is a tool that queries multiple DEXs to find the optimal swap rate for a given pair and amount.
Modern aggregators like 1inch, Paraswap, and Matcha have become essential DeFi infrastructure, processing billions in volume monthly. Building your own aggregator provides several advantages:
-
Best Price Execution: Scanning multiple DEXes simultaneously to find optimal rates.
-
Informed Trading Decisions: Provides data on liquidity and fees, helping traders understand which pools can handle larger trades with minimal price impact (slippage).
-
Time Efficiency: Saves time from manually checking prices and liquidity on multiple DEX interfaces.
What Is the Best API for Building a DEX Aggregator?
CoinGecko’s On-chain API is an excellent choice for building a DEX aggregator, providing comprehensive data with the widest coverage of DEXs and networks supported on GeckoTerminal, all in a single API. Its reliable endpoints and consistent data schemas make discovering and comparing pools straightforward.
The following are the key endpoints powering our DEX aggregator:
-
To Discover Pools: The /onchain/networks/{network}/tokens/{token_address}/pools endpoint discovers all available liquidity pools on a specific network that contain a given token.
-
To Get Detailed Pool Data: In order to compare rates across various pools, we use the /onchain/networks/{network}/pools/multi/{addresses} endpoint to efficiently fetch detailed data such as real-time prices, liquidity, and fees of multiple pool addresses in a single API call.
Prerequisites
You’ll need the following to build the DEX aggregator:
-
CoinGecko API Key: The on-chain endpoints used in this tutorial are available on the free Demo API plan. If you don’t have a key, follow this guide on how to get your free Demo API key.
-
Application Framework: This guide uses React 18 for the frontend and an Express proxy server for the backend. You will also need Node.js (version 18 or higher) to run the application.
Setting up the project environment
Let’s start by setting up the development environment for our DEX aggregator. We will be using Node.js with Express for the backend and React for the frontend.
Step 1: Initialize the project
First, create a new directory and initialize the Node.js project:
mkdir dex-aggregator-dashboard
cd dex-aggregator-dashboard
npm init -y
Step 2: Install dependencies
Install the required packages for both backend and frontend:
npm install express axios cors dotenv
npm install --save-dev nodemon
Step 3: Create the project structure
Set up the basic file structure:
dex-aggregator-dashboard/
├── server.js # Express backend
├── package.json # Dependencies
├── .env # API keys (create this)
└── public/ # Frontend files
├── index.html # Main HTML
├── app.jsx # React application
└── styles.css # Styling
Step 4: Configure environment variables
Create a .env file in the project root with your API keys:
CG_DEMO_API_KEY=your_demo_key_here
CG_PRO_API_KEY=your_pro_key_here # optional
How to Find All Available Swap Pools for a Token Pair?
The initial step is to use the /onchain/networks/{network}/tokens/{token_address}/pools endpoint to get a list of all potential pools under the selected network. This endpoint returns every liquidity pool on a specific network containing the “base” token (the token you want to swap from). We then filter these results to find pools that also contain the “quote” token (the token you want to receive).
Here’s a script function that takes a network ID and token address as input and fetches the pool data:
To find pools for a specific token pair, we call this function and then filter the results:
Sample (abbreviated) discovery response:
Comparing rates across pools
With the list of relevant pool addresses from the previous step, we can now use the /onchain/networks/{network}/pools/multi/{addresses} endpoint to get the specific data needed for our comparison. This bulk endpoint is much more efficient than making individual requests for each pool.
Here’s the function, that take the array of addresses from the previous step, format it correctly, and make a call to this endpoint:
The multi endpoint returns detailed pool information including prices, liquidity, and fees. Here’s a sample response showing the key attributes:
Key attributes for rate comparison:
-
base_token_price_usd / quote_token_price_usd: Current USD prices for each token in the pair, which are useful for displaying dollar values in the dashboard.
-
base_token_price_quote_token / quote_token_price_base_token: The direct exchange rates between the two tokens in the pair. This is what we use to calculate swap outputs.
-
reserve_in_usd: Total liquidity in the pool, measured in USD. Higher liquidity typically means lower slippage for large trades.
-
pool_fee_percentage: The fee charged by this pool (e.g., “0.05” means a 0.05% fee). Lower fees result in a better net output for traders.
How To Calculate The Best Swap Quote?
The best quote is found by calculating the final output amount for each pool based on its real-time price data and the user’s input amount. We then rank pools by their estimated output, with the highest output representing the best deal for the trader.
Here’s a simplified formula used for calculating the estimated output:
estimated_output = amount_in × price_factor × (1 − pool_fee_percentage/100)
include_volume_breakdown=true
when calling the /onchain/networks/{network}/pools/multi/{addresses} endpoint.This code snippet iterates through the detailed pool data, performs the calculation for each pool, and returns a sorted list from best quote to worst:
This function processes the detailed pool data, handles the swap direction logic, applies pool fees, and returns a final list of pools ranked by the highest estimated output.
Building The DEX Aggregator Dashboard
The dashboard creates a user-friendly interface for comparing swap rates across DEXs. We’ll build this using React components that handle user input and display results in a sorted table.
Implementing the input form
The input form captures the essential swap parameters. Users first select the Network, then provide the From Token and To Token contract addresses, and finally enter the Amount. Submitting the form triggers the pool discovery process:
Results Table Implementation
The results table displays pool data sorted by estimated output, with the best rates prominently shown at the top:
Complete Dashboard Integration
Here’s how the components work together in the main application:
The dashboard presents the results in a table, automatically sorted to show the best pool (highest estimated output) at the top. A copy button for the pool address is included, providing a convenient way for users to find that specific pool on the specific DEX.
Opportunities & Enhancements
Once your basic aggregator is working, consider these enhancements:
-
Spotting Arbitrage: The dashboard’s pool comparison data naturally reveals arbitrage opportunities when the same token pair shows significant price discrepancies across different DEXs. You can enhance the results table to highlight significant price differences between DEXs to reveal profit opportunities for traders.
-
Adding Price Charts: Historical price data helps users understand whether current rates represent good value. CoinGecko’s OHLCV endpoints can power price charts for each pool, showing price trends over time.
-
Advanced Pool Discovery: The Search Pools endpoint can be used to add a powerful token search engine for a better user experience. It allows searching for pools by token symbols (e.g. WETH) instead of requiring full contract addresses.
Conclusion
You’ve built a working, multi-chain DEX aggregator dashboard using CoinGecko’s On-chain API. The application discovers pools across multiple networks, fetches detailed pricing data in bulk, calculates transparent swap quotes with fees, and ranks results by estimated output so users can identify the best rates quickly.
CoinGecko API provides comprehensive, reliable on-chain data across many networks and DEXs that serves as a solid foundation for building production-grade DeFi applications. If you’re ready to make the most of CoinGecko API, consider subscribing to a paid API plan to unlock higher rate limits and access to exclusive API endpoints.
If you enjoyed this article, be sure to check out others like how to build a liquidity pool finder with advanced filtering and sorting options.