6 min read
Overview
In the decentralized finance (DeFi) landscape, users often face challenges such as inaccurate gas estimations that can lead to failed or delayed transactions and complex integration across DEXs which can make it difficult to navigate multiple decentralized exchanges for optimal trading routes.
To address these issues, we'll guide you through building a DEX Aggregator dApp on the Base network. This application will leverage QuickNode's Base DeFi Power bundle, which includes the following add-ons to enable optimized swaps, real-time gas estimates, and comprehensive wallet insights.
- Gas Estimation API: Provides real-time, accurate gas estimations.
- OpenOcean v4 Lightning Swap API: Facilitates efficient token swaps across multiple DEXs such as Uniswap, Curve, PancakeSwap, and more.
- MEV Protection & Gas Recovery: Built-in protection against MEV attacks. (we will not be using this add-on in this guide)
What You Will Learn
- How to integrate the Gas Estimation API for accurate gas fee predictions
- How to utilize OpenOcean's API for optimal token swap routes
- How to build a swap dApp on the Base network
What You Will Need
- A QuickNode account with the Base DeFi Power bundle enabled
- Basic knowledge of JavaScript/TypeScript and frontend development
- Familiarity with Ethereum and the Base network
Why QuickNode’s Base DeFi Bundle?
The Base DeFi Bundle is a developer’s toolkit for building robust apps on the Base blockchain. These add-ons tackle common developer pain points:
Developer Challenge | Solution via Base DeFi Bundle |
---|---|
Unpredictable or high gas fees | Gas Estimation API offers accurate, real-time gas forecasts |
Complex multi-DEX integration | OpenOcean v4 API aggregates liquidity and optimizes routing |
The Base DeFi Bundle is designed to work seamlessly with each other. Here's how they all fit together:
Let’s set up and build the app!
Build a DEX Aggregator dApp
Step 1: Get the Starter Code
To get started, clone the QuickNode's qn-guide-examples repository, then move into the this project's directory and install the dependencies.
git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd qn-guide-examples/sample-dapps/base-dex-aggregator
npm install
Step 2: Configure the App
For the app to work properly, you'll need to configure (1) RPC URL in the app to point to the QuickNode endpoint that has the Base DeFi Power bundle add-on enabled, (2) plus your WalletConnect Project ID.
QuickNode Base Endpoint
To communicate with the Base network and use add-ons like the Gas Estimation API and OpenOcean v4 Swap API, you'll need to configure the QuickNode Base Endpoint. This is the URL of the Base node you want to connect to.
- Sign up at QuickNode and create a Base mainnet endpoint.
- Enable the Base DeFi Power bundle in your endpoint. This enables add-ons, including the Gas Estimation API and OpenOcean v4 Swap API.
- Save your endpoint URL.
Obtain WalletConnect Project ID
To support different wallets in your app easily, you'll need to obtain a WalletConnect Project ID. This identifier enables secure, multi-wallet connectivity through the WalletConnect protocol.
You can get a WalletConnect Project ID by signing up at WalletConnect Cloud.
Set Environment Variables
Copy .env.sample
to .env
and update the following variables with your QuickNode endpoint URL and WalletConnect Project ID:
VITE_WALLETCONNECT_PROJECT_ID="YOUR_WALLETCONNECT_PROJECT_ID"
VITE_QUICKNODE_ENDPOINT_URL="YOUR_QUICKNODE_ENDPOINT_URL"
Step 3: Run the Application
As a final step, run the application in development mode:
npm run dev
This command launches the app in development mode, with hot reloading enabled for easier debugging.
Open your browser and navigate to http://localhost:5173 to interact with the dApp.
Now, let’s explore how the Base DeFi Bundle powers this dApp.
Key Components of the Base DEX Aggregator App
The app’s core is a modern swap interface built with React and Tailwind CSS. Key components include:
- SwapCard.tsx: The main swap UI with token selectors and gas previews.
- TokenSelector.tsx: Searchable dropdowns for token selection.
Connecting the Wallet
In src/lib/wagmi.ts
, we configure Wagmi with connectkit's default config to use the Base chain with your QuickNode endpoint:
import { base } from 'wagmi/chains'
import { createConfig, http } from 'wagmi'
import { QUICKNODE_ENDPOINT_URL, WALLETCONNECT_PROJECT_ID } from './constants'
import { getDefaultConfig } from 'connectkit'
export const config = createConfig(
getDefaultConfig({
// Your dApps chains
chains: [base],
transports: {
// RPC URL for each chain
[base.id]: http(QUICKNODE_ENDPOINT_URL),
},
// Required API Keys
walletConnectProjectId: WALLETCONNECT_PROJECT_ID,
// Required App Info
appName: 'Base DEX Aggregator',
})
)
Implementing Gas Estimation
Gas fees can frustrate users if they’re unpredictable. The Gas Estimation API (sentio_gasPrice
) delivers real-time gas price estimates at different confidence levels.
In src/hooks/useGasEstimate.ts
, the app calls the fetchGasEstimates
function to fetch gas estimates. This function uses Axios to make a POST request to the QuickNode endpoint with the sentio_gasPrice
method, and returns the gas estimates.
// Function to fetch gas estimates on demand
const fetchGasEstimatesNow = useCallback(async () => {
try {
setIsLoadingGas(true)
const estimates = await fetchGasEstimates()
setGasEstimates(estimates)
} catch (err) {
setError(
err instanceof Error ? err : new Error('Failed to load gas estimates')
)
console.error('Error fetching gas estimates:', err)
} finally {
setIsLoadingGas(false)
}
}, [])
Token Swapping with OpenOcean v4 API
The OpenOcean v4 Swap API is the engine behind the app’s token swaps, aggregating liquidity from multiple Base DEXes to find the best routes.
Fetching Token Lists
The tokenList
endpoint of the OpenOcean v4 API returns a list of tokens supported by the API. In this app, we'll use it to populate the token dropdowns.
// Fetch new token list if cache is invalid
const tokenList = await fetchTokenList()
cachedTokens = tokenList
lastFetchTime = now
const sortedTokens = sortTokensByPopularity(tokenList)
setTokens(sortedTokens)
Getting Swap Quotes
The quote
endpoint of the OpenOcean v4 API returns a quote for a swap transaction.It requires the input and output token addresses, amount, and gas price as parameters. The API returns the estimated output amount, the minimum output amount, and the price impact.
// Fetch swap quotes from OpenOcean API
const quoteData = await fetchSwapQuote({
inTokenAddress: fromToken.address,
outTokenAddress: toToken.address,
amount,
gasPrice,
})
setQuote(quoteData)
As the API may return different routes and details of each route based on the swap parameters, we will display these routes in the UI.
Executing Swaps
The swap
endpoint of the OpenOcean v4 API prepares a swap transaction. It takes in the input token address, output token address, amount, slippage, and gas price as parameters. Then, the transaction data is used to create a transaction request.
const swapData = await executeSwap({
inTokenAddress: fromToken.address,
outTokenAddress: toToken.address,
amount: amount,
slippage: '1',
gasPrice: selectedGasPrice.toString(),
userAddress: address,
})
const txRequest = {
to: swapData.to,
data: swapData.data,
value: BigInt(swapData.value),
gasPrice: BigInt(swapData.gasPrice),
}
sendTransaction(txRequest) // Send the transaction
This application can be expanded with new features or integrated with additional services as needed, such as introducing new DEXs, adding additional analytics, or enhancing user experience with a more complex frontend. With this foundation, you're prepared to build upon the Base network and take advantage of its lower fees and scalability.
What’s Next?
Now that you’ve built a working DEX aggregator, here are a few ways to take it further:
- Add slippage controls since OpenOcean v4 API already supports this
- Integrate charting tools like TradingView
- Use QuickNode Streams to monitor swap activity in real time
- Add notification support for successful or failed transactions
Experiment with these ideas and expand your dApp’s functionality!
Conclusion
In this guide, we've walked through the process of building a DEX aggregator dApp on the Base network using QuickNode’s Base DeFi Power bundle. With the integration of the Gas Estimation API and OpenOcean v4 Swap API, you now have a fully functional application that performs token swaps and estimates gas fees.
For more inspiration, check out the How to Build a Telegram Trading Bot on Base with MEV Protection guide, which also demonstrates how to build a trading bot using the Base DeFi Power bundle.
If you have any questions, feel free to use our Discord server or provide feedback using the form below. Stay up to date with the latest by following us on Twitter and our Telegram announcement channel.
We ❤️ Feedback!
Let us know if you have any feedback or requests for new topics. We'd love to hear from you.