12 min read
Overview
Building a sophisticated DeFi application requires access to fast, reliable, and comprehensive onchain data. For developers, this often means the complex task of data indexing multiple smart contracts, tracking liquidity events, and calculating key performance metrics like APR and TVL in real time. This process is not only resource intensive but can also be a significant barrier to launching innovative products.
In this guide, you will learn to leverage the Aerodrome Swap API add-on from the QuickNode Marketplace. This API provides a simple yet powerful interface to access deep analytics and transactional data from Aerodrome, the leading DEX on Base.
To demonstrate the add-on's capabilities, we will walk through how you can build an AI-powered yield optimizer, using our AI-Powered DeFi Yield Optimizer as a reference application. While this guide focuses on building an advanced analytics tool, the API's versatile features also support a wide range of other use cases, including trading bots, portfolio trackers, and custom swap interfaces.
What You Will Learn
- The key capabilities of the Aerodrome Swap API
- How to use the API to build a yield optimizer and analytics dashboard
- How to integrate this data with Claude AI for yield optimization
What You Will Need
- A QuickNode account to access the Aerodrome Swap API add-on
- Node.js v20+ installed on your machine
- Basic knowledge of TypeScript and React and DeFi concepts
- An Anthropic API key to implement the AI features
This guide is for educational purposes only. The AI suggestions in this project are not financial advice. Always do your own research before investing. The code and strategies are provided as-is with no guarantees.
Key Features of the Aerodrome Swap API
The Aerodrome Swap API abstracts away the complexity of direct blockchain interaction, providing developers with a unified interface to access real-time DEX prices, pool analytics, and execute swaps.
DEX Data Access
Access data from Aerodrome's liquidity pools, including token prices, pool reserves, trading volumes, and fee generation without an infrastructure overhead. The API provides instant access to pre-calculated APR, TVL metrics, and detailed pool analytics.
Simplified Swap Execution
Build a swap transaction for execution with built-in routing optimization and slippage protection through a single API endpoint. You can get accurate quotes before execution, automatically find the best trading routes across multiple pools.
Enterprise-Ready Infrastructure
Benefit from QuickNode's reliable infrastructure with built-in caching, automatic failover, and consistent response times. The API handles all RPC communication, contract ABI management, and data normalization, allowing you to focus on building features rather than maintaining infrastructure.
Available Endpoints
The API provides a set of endpoints to cover all your data and trading needs:
GET /v1/pools
GET /v1/pools/{address}
GET /v1/pools/detailed
GET /v1/pools/search
GET /v1/prices
GET /v1/prices/{address}
GET /v1/quote
POST /v1/swap/build
GET /v1/tokens
GET /v1/tokens/{address}
GET /v1/tokens/batch
GET /v1/tokens/search
GET /v1/transaction/{tx_hash}
In this app, we will focus on the following API endpoints:
/v1/pools/detailed
: Detailed information about liquidity pools, including token reserves, trading volume, fee generation, and APR. These data will be used to display pool analytics and feed the AI model for yield optimization. We use several fields from this endpoint including:
type_info
: Pool type information and label.tokens
: List of tokens in the pool.liquidity
: Liquidity related fields such astvl
andreserves
trading
: Trading related fields such asvolume_24h
,fees_24h
, andapr
voting
: Voting related fields such asrewards
/v1/tokens
: Token metadata such as symbol, decimals, and price, and if they are verified by Aerodrome. These data will be used to filter pools to display only verified tokens.
{
"tokens": [
{
"address": "0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA",
"symbol": "USDbC",
"decimals": 6,
"listed": true
},
// ...
]
}
Building the Yield Optimizer
As mentioned earlier, we will build an AI-powered DeFi yield farming optimizer that helps users build personalized portfolio strategies across Aerodrome Finance pools on Base network.
Architecture Overview
Before we start building, let's focus on the architecture of our yield optimizer application. Our yield strategy builder follows a three-phase user journey: pool discovery, risk assessment, and AI-powered optimization.
Pool Overview
Users explore available Aerodrome pools through an analytics dashboard that displays real-time metrics including TVL, APR, trading volume, and pool composition. This phase helps users understand the available opportunities in the DeFi ecosystem.
Risk Assessment Quiz
A guided questionnaire captures user preferences including risk tolerance, investment timeline, and yield expectations. This creates a personalized risk profile that informs the AI optimization process.
AI-Powered Strategy Generation
The third phase is the AI-powered optimization engine that generates yield strategies. The AI model processes the pool data and user preferences to generate a strategy that includes recommended pools, allocation percentages, and expected returns. The results are displayed in a user-friendly format, allowing users to review and implement their strategies.
Core Components
The project structure and key files are as follows:
├── app
│ ├── api
│ │ └── optimize # Server-side API route for AI optimization
│ ├── globals.css # Global styles and CSS variables
│ ├── layout.tsx # Root layout with providers and metadata
│ └── page.tsx # Main orchestrator component for the 3-phase flow
├── components
│ ├── pools
│ │ ├── enhanced-pool-card.tsx # Rich pool data display with metrics
│ │ └── pool-overview.tsx # Pool grid with sorting and filtering
│ ├── quiz
│ │ └── risk-assessment-quiz.tsx # Multi-step risk profiling interface
│ ├── strategy
│ │ └── strategy-results.tsx # AI-generated strategy visualization
│ ├── theme-provider.tsx # Theme context for dark/light mode
│ └── ui # Reusable UI components (shadcn/ui)
├── hooks
│ ├── use-mobile.tsx # Responsive design hook
│ └── use-toast.ts # Toast notification system
├── lib
│ ├── ai-optimizer.ts # Claude AI integration and prompt engineering
│ ├── api.ts # Aerodrome API client and data fetching
│ ├── mock-data.ts # Fallback data for demo mode
│ ├── optimizer.ts # Portfolio optimization orchestrator
│ └── utils.ts # Utility functions and formatting
├── types
│ ├── pool.ts # Pool data structures and API responses
│ ├── strategy.ts # Strategy and risk profile interfaces
│ └── token.ts # Token metadata and verification types
Technical Implementation Deep Dive
Let's examine the core technical implementation to understand how the application works under the hood.
Application Flow Control (app/page.tsx
)
The main orchestrator manages the three-phase user experience through React state:
const [currentStep, setCurrentStep] = useState<"pools" | "quiz" | "results">("pools")
const [riskProfile, setRiskProfile] = useState<RiskProfile | null>(null)
const [strategy, setStrategy] = useState<OptimizedStrategy | null>(null)
const [poolData, setPoolData] = useState<DetailedPool[]>([])
The flow progresses through these phases:
- Pool Discovery (
pools
): Users explore available pools and their metrics - Risk Assessment (
quiz
): Users complete a questionnaire to define their risk profile - Strategy Generation (
results
): AI generates personalized recommendations based on pools and risk profile
Pool Analytics Dashboard (components/pools/enhanced-pool-card.tsx
)
The analytics dashboard displays comprehensive pool data through rich, interactive cards. Each pool card presents:
Primary Metrics Display:
- TVL and APR: Primary financial indicators with color-coded risk assessment (Low/Medium/High based on APR thresholds)
- Trading Activity: 24-hour volume and fees to gauge pool liquidity and activity
- Pool Composition: Token reserves showing exact amounts and pool balance
Advanced Analytics:
- Pool Type Detection: Visual indicators for Stable, Volatile, or Concentrated Liquidity pools
- Fee Structure: Pool fee percentage prominently displayed for yield calculations
- Governance Integration: Weekly emissions and voting power data for veAERO holders
- Token Verification: Coinbase token detection with special badges for additional security assurance
Data Integration Process:
- Fetches verified tokens via
/v1/tokens
endpoint - Retrieves detailed pool data via
/v1/pools/detailed
- Filters pools to ensure both tokens are verified (
isPoolVerified
function) - Renders data through
enhanced-pool-card.tsx
with real-time updates
Risk Assessment System (components/quiz/risk-assessment-quiz.tsx
)
The risk profiling system captures multiple dimensions of user preference to generate personalized recommendations:
interface RiskProfile {
riskTolerance: 'conservative' | 'moderate' | 'aggressive';
timeHorizon: 'short' | 'medium' | 'long';
yieldPreference: 'stable' | 'growth' | 'max';
poolTypePreference: 'stable' | 'mixed' | 'volatile';
investmentAmount: number;
}
Portfolio Optimization Engine (lib/optimizer.ts
)
The main optimization entry point is simple but powerful:
export async function generateOptimizedStrategy(
riskProfile: RiskProfile,
pools?: DetailedPool[]
): Promise<OptimizedStrategy> {
let availablePools: DetailedPool[];
// Use provided pools or fetch from API
if (pools && pools.length > 0) {
availablePools = pools;
} else {
try {
const result = await aerodromeApi.getPoolsDetailed({
limit: 50, // Get more pools for better optimization
sort_by: "tvl",
order: "desc",
offset: 0,
});
availablePools = result.pools;
} catch (error) {
console.warn("Failed to fetch pools from API, using mock data:", error);
availablePools = mockPools;
}
}
// Use AI-powered optimization
return await generateAIOptimizedStrategy(availablePools, riskProfile);
}
AI-Powered Strategy Generation (lib/ai-optimizer.ts
)
The AI optimization system processes pool data and user preferences to generate personalized strategies:
export async function generateAIOptimizedStrategy(
pools: DetailedPool[],
riskProfile: RiskProfile
): Promise<OptimizedStrategy> {
try {
// Use Claude's own API for optimization
const aiResponse = await callAIOptimizer({ pools, riskProfile });
// Convert AI response to our expected format
const recommendations: PoolRecommendation[] = aiResponse.recommendations.map(rec => ({
pool: rec.pool,
allocation: rec.allocation,
reasoning: rec.reasoning,
riskScore: rec.riskScore,
expectedReturn: rec.expectedReturn
}));
const portfolioMetrics = {
expectedAPR: aiResponse.portfolioSummary.expectedAPR,
riskScore: aiResponse.portfolioSummary.riskScore,
diversificationScore: aiResponse.portfolioSummary.diversificationScore,
totalTVL: recommendations.reduce((sum, rec) => sum + rec.pool.liquidity.tvl, 0)
};
return {
recommendations,
portfolioMetrics,
reasoning: aiResponse.portfolioSummary.reasoning
};
} catch (error) {
console.error("AI optimization failed:", error);
throw error;
}
}
The AI system makes an API call to the /api/optimize
endpoint, which uses Claude AI to analyze pools and generate recommendations. The system includes:
- Pool categorization with predefined risk profiles for stable, major, volatile, and concentrated liquidity pools
- Risk tolerance mapping that translates user preferences into technical constraints
- Portfolio diversification logic that balances risk and return across multiple pools
- Detailed reasoning that explains why specific pools were selected
Prerequisites
To get started, let's get a QuickNode endpoint with the Aerodrome Swap API add-on enabled and Claude AI integration set up.
QuickNode Endpoint
- Log in to your QuickNode account and click Create endpoint. If you don't have an account yet, sign up first.
- Select the Base Mainnet as a network.
- Select the Aerodrome Swap API add-on from available add-ons.
- Keep your endpoint URL handy. You'll need it in the next step.
Claude AI Integration
- Log in to your Anthropic Console account.
- Create a new API key with the necessary permissions to access the Claude model.
- Keep the API key handy. You'll need it in the next step.
Setting Up the Project
Now let's walk through how to set up and run the complete application.
Step 1: Clone the Repository
git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd qn-guide-examples/sample-dapps/ai-powered-defi-yield-optimizer
Step 2: Install Dependencies
npm install
# or pnpm install or yarn install, depending on your package manager preference
Step 3: Configure Environment Variables
Copy the .env.example
file to .env
and fill in your QuickNode endpoint URL and Claude API key:
cp .env.example .env
The .env
file should look like this:
# QuickNode Aerodrome API Configuration
# Note: Get your QuickNode endpoint URL from https://dashboard.quicknode.com/
NEXT_PUBLIC_QUICKNODE_ENDPOINT=https://your-quicknode-endpoint.com/your-api-key/
# Claude AI Configuration for Portfolio Optimization
# Note: Get your API key from https://console.anthropic.com/
ANTHROPIC_API_KEY=your-claude-api-key-here
Step 4: Run the Application
To start the application, run the following command:
npm run dev
# or pnpm dev or yarn dev, depending on your package manager preferences
This will start the application in development mode, and you can access it at http://localhost:3000/
.
Step 5: Explore the Application
Once the application is running, you can explore the different pages and features. Here's a quick overview of the application:
- Pool Overview: Browse the real-time pool data sorted by TVL, APR, or volume. Check out the detailed pool analytics, including token reserves, trading volume, and fee generation
- Risk Assessment: Complete the 5-step questionnaire with your preferences
- Strategy Generation: View your personalized AI-generated recommendations and reasoning behind the strategy
Conclusion
This guide has shown you how the Aerodrome Swap API can drastically simplify development by providing clean, comprehensive, and real-time on-chain data, empowering you to build advanced DeFi applications with ease. The complete source code for this application is available in the QuickNode Guide Examples repository.
The yield optimizer is just one example of what's possible with the Aerodrome Swap API. It opens the door to a wide variety of applications:
-
Arbitrage Trading Bots: Use the
/v1/prices
and/v1/quote
endpoints to monitor price discrepancies between Aerodrome and other exchanges in real-time. When an opportunity arises, use/v1/swap/build
to execute a profitable trade automatically. -
Telegram/Discord Bots: Build a bot that provides quick information on demand. Users could query for a token price (
/v1/prices/{address}
), get a quick swap quote (/v1/quote
), or check the stats of a liquidity pool right from their chat client. -
Embeddable Swap Widgets: Create a self-contained UI component that other dApps can easily embed on their websites. This allows them to offer token swaps to their users without building the entire logic from scratch, powered by your integration with the Aerodrome Swap API.
Further Reading
- Build a Telegram Trading Bot on Base with MEV Protection
- Build a DEX Aggregator on Base
- Other guides related to the Marketplace add-ons
Subscribe to our newsletter for more articles and guides on Web3 and blockchain. If you have any questions or need further assistance, feel free to join our Discord server or provide feedback using the form below. Stay informed and connected by following us on X (@QuickNode) 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.