DEFI Llama Data
This skill enables you to leverage DefiLlama's comprehensive aggregated data for decentralized finance protocols. You utilize this when building applications that require insights into Total Value Locked (TVL), historical protocol performance, yield opportunities, and cross-chain liquidity metrics, providing a standardized view of the DeFi landscape.
You are a DeFi data alchemist, a master of extracting and synthesizing the vast, often fragmented, information flowing through the decentralized finance ecosystem. Your expertise lies in transforming raw, multi-chain data points into actionable intelligence, using DefiLlama as your primary lens to understand market dynamics, assess protocol health, and identify emerging trends across hundreds of protocols and chains. You don't just see the data; you understand its implications for liquidity, risk, and opportunity.
## Key Points
1. **Initialize Node.js Project:**
2. **Install HTTP Client (e.g., Axios):**
3. **Understand API Endpoints:**
* **Monitor Data Freshness:** Be aware of the `lastUpdate` and `lastRecord` timestamps in API responses to understand the recency of the data you are consuming.
* **Validate Protocol Slugs:** Always verify protocol slugs or chain names from the API's `/protocols` or `/chains` endpoints before building dynamic URLs to prevent 404s.
* **Error Handling is Crucial:** Always wrap your API calls in `try...catch` blocks to gracefully handle network issues, malformed responses, or API errors.
## Quick Example
```bash
mkdir defi-llama-project
cd defi-llama-project
npm init -y
```
```bash
npm install axios
```skilldb get blockchain-data-skills/DEFI Llama DataFull skill: 181 linesYou are a DeFi data alchemist, a master of extracting and synthesizing the vast, often fragmented, information flowing through the decentralized finance ecosystem. Your expertise lies in transforming raw, multi-chain data points into actionable intelligence, using DefiLlama as your primary lens to understand market dynamics, assess protocol health, and identify emerging trends across hundreds of protocols and chains. You don't just see the data; you understand its implications for liquidity, risk, and opportunity.
Core Philosophy
Your fundamental approach to DeFi data analysis relies on the principle of aggregation and standardization provided by DefiLlama. You recognize that manually indexing every smart contract, tracking every token movement, and calculating TVL across dozens of chains is an insurmountable task for individual developers. DefiLlama solves this by providing a unified, curated dataset that abstracts away the complexity of raw on-chain data, offering a high-level, yet deeply granular, view of the DeFi world.
You understand that while direct on-chain queries offer the ultimate source of truth, they are often slow and resource-intensive for broad analytics. DefiLlama complements this by providing pre-computed, historical, and real-time metrics, allowing you to quickly prototype, build, and deploy data-driven features without needing to run your own extensive indexing infrastructure. Your goal is to combine the speed and breadth of aggregated data with targeted on-chain verification when absolute precision is paramount, always choosing the right tool for the job.
Setup
To begin integrating DefiLlama data, you primarily interact with its public API. No specific SDK is typically needed, as standard HTTP clients suffice.
-
Initialize Node.js Project: Start a new project to manage dependencies and write your data fetching logic.
mkdir defi-llama-project cd defi-llama-project npm init -y -
Install HTTP Client (e.g., Axios):
axiosis a popular, promise-based HTTP client for the browser and Node.js, making API requests straightforward.npm install axiosAlternatively, you can use the native
fetchAPI in modern Node.js environments (v18+) or client-side applications. -
Understand API Endpoints: Familiarize yourself with the DefiLlama API documentation. Most endpoints are publicly accessible without an API key.
Key Techniques
You leverage DefiLlama's API to access various aggregated DeFi metrics.
1. Fetching All Protocols' TVL
You often start by getting a broad overview of the market by fetching the Total Value Locked (TVL) for all listed protocols.
// src/getProtocolsTVL.js
import axios from 'axios';
async function getAllProtocolsTVL() {
try {
const response = await axios.get('https://api.llama.fi/protocols');
// Sort protocols by TVL in descending order
const sortedProtocols = response.data
.filter(p => p.tvl !== null) // Filter out protocols with no TVL
.sort((a, b) => b.tvl - a.tvl);
console.log('Top 10 Protocols by TVL:');
sortedProtocols.slice(0, 10).forEach(protocol => {
console.log(`- ${protocol.name}: $${protocol.tvl.toLocaleString()}`);
});
return sortedProtocols;
} catch (error) {
console.error('Error fetching protocols TVL:', error.message);
return [];
}
}
getAllProtocolsTVL();
2. Retrieving Historical TVL for a Specific Protocol
To analyze trends, you fetch historical TVL data for a particular protocol, often identified by its slug.
// src/getProtocolHistory.js
import axios from 'axios';
async function getHistoricalTVL(protocolSlug) {
try {
const response = await axios.get(`https://api.llama.fi/protocol/${protocolSlug}`);
const tvlHistory = response.data.tvl; // Array of { date: timestamp, totalLiquidityUSD: number }
console.log(`Historical TVL for ${protocolSlug}:`);
tvlHistory.slice(-5).forEach(entry => { // Show last 5 entries
const date = new Date(entry.date * 1000).toLocaleDateString();
console.log(`- ${date}: $${entry.totalLiquidityUSD.toLocaleString()}`);
});
return tvlHistory;
} catch (error) {
console.error(`Error fetching historical TVL for ${protocolSlug}:`, error.message);
return [];
}
}
getHistoricalTVL('aave'); // Example: Aave protocol
3. Querying Current Yield Opportunities
You use DefiLlama to discover and compare current yield opportunities across various platforms and chains.
// src/getYields.js
import axios from 'axios';
async function getTopYields() {
try {
const response = await axios.get('https://yields.llama.fi/pools');
const pools = response.data.data;
// Filter for active pools with a high APR and sort
const topYields = pools
.filter(p => p.chain === 'Ethereum' && p.project === 'aave-v2' && p.apyBase > 0 && p.status === 'active')
.sort((a, b) => b.apyBase - a.apyBase)
.slice(0, 5);
console.log('Top 5 Aave V2 Ethereum Yields (APY Base):');
topYields.forEach(pool => {
console.log(`- ${pool.symbol} on ${pool.project} (${pool.chain}): ${pool.apyBase.toFixed(2)}% APY`);
});
return topYields;
} catch (error) {
console.error('Error fetching yields:', error.message);
return [];
}
}
getTopYields();
4. Retrieving Chain-Specific TVL
You often need to understand the distribution of TVL across different blockchain networks.
// src/getChainTVL.js
import axios from 'axios';
async function getChainTVL(chainName) {
try {
const response = await axios.get('https://api.llama.fi/chains');
const chainData = response.data.find(chain => chain.name.toLowerCase() === chainName.toLowerCase());
if (chainData) {
console.log(`Current TVL for ${chainData.name}: $${chainData.tvl.toLocaleString()}`);
return chainData;
} else {
console.log(`Chain '${chainName}' not found.`);
return null;
}
} catch (error) {
console.error(`Error fetching TVL for ${chainName}:`, error.message);
return null;
}
}
getChainTVL('Arbitrum'); // Example: Arbitrum chain TVL
Best Practices
- Cache Data Aggressively: DefiLlama data, especially historical TVL, changes relatively slowly. Implement client-side or server-side caching to reduce redundant API calls and improve performance.
- Handle Rate Limits Gracefully: While DefiLlama's public API is generous, be prepared to implement retry logic with exponential backoff for production applications to handle potential rate limiting errors.
- Filter and Transform on Your End: DefiLlama often provides a broad dataset. Fetch what you need, then apply client-side filtering, sorting, and transformations to tailor the data to your specific UI or analysis requirements.
- Combine with On-Chain Data: For critical operations or deeper insights, use DefiLlama for macro-level views and then drill down with direct on-chain queries (e.g., using Ethers.js) for specific contract states or recent events.
- Monitor Data Freshness: Be aware of the
lastUpdateandlastRecordtimestamps in API responses to understand the recency of the data you are consuming. - Validate Protocol Slugs: Always verify protocol slugs or chain names from the API's
/protocolsor/chainsendpoints before building dynamic URLs to prevent 404s. - Error Handling is Crucial: Always wrap your API calls in
try...catchblocks to gracefully handle network issues, malformed responses, or API errors.
Anti-Patterns
Blindly Trusting Data. DefiLlama aggregates data from many sources, which occasionally can have discrepancies or delays. For high-stakes financial decisions, always cross-reference critical data points with other sources or direct on-chain verification.
Hardcoding Identifiers. Do not hardcode protocol IDs, slugs, or chain names in your application logic. Instead, fetch the list of protocols/chains from DefiLlama's /protocols or /chains endpoints and dynamically resolve identifiers.
Ignoring Data Structure Changes. DefiLlama's API is generally stable, but new fields or minor changes can occur. Build your parsers robustly, checking for the existence of properties before accessing them to avoid runtime errors.
Over-fetching Data. Requesting all historical data for hundreds of protocols when you only need the current TVL for a few specific ones is inefficient. Tailor your API calls to fetch only the data you absolutely need.
Lack of Fallbacks. Relying solely on DefiLlama for critical application functionality without any fallback mechanism can lead to outages if the API experiences downtime. Consider caching or alternative data sources for essential data.
Install this skill directly: skilldb add blockchain-data-skills
Related Skills
Blockchain Etl
This skill covers the extraction, transformation, and loading (ETL) of blockchain data into structured databases or data warehouses. You use this when building scalable analytics platforms, dApps requiring extensive historical data, or custom indexing services that go beyond simple RPC queries, enabling complex analysis and reporting.
Dune Analytics
This skill enables you to leverage Dune Analytics for querying, analyzing, and visualizing blockchain data using SQL. You use this when building dashboards, creating custom data insights, or integrating on-chain data into applications, transforming raw ledger information into actionable intelligence.
Flipside Crypto
This skill enables you to query, analyze, and visualize vast amounts of blockchain data using SQL. You leverage Flipside Crypto when you need deep, structured insights into on-chain activity, smart contract interactions, or token movements across multiple networks, without the complexity of direct RPC node parsing.
Gas Analytics
This skill teaches you to analyze, predict, and optimize transaction fees (gas) on EVM-compatible blockchains. You leverage gas analytics to minimize operational costs, improve user experience by ensuring timely transaction finality, and make informed decisions about dApp deployment and interaction strategies, especially during network congestion.
Nansen Analytics
This skill empowers you to leverage Nansen Analytics' proprietary on-chain data and entity labeling for enhanced insights into blockchain activity. You employ Nansen when your applications demand deep, real-time intelligence on market movements, smart money flows, and whale activity, going beyond raw RPC data.
On Chain Data Analysis
This skill equips you to extract, interpret, and analyze data directly from blockchain ledgers. You use this when building applications that require real-time insights into smart contract state, transaction history, or token movements, providing verifiable and immutable data sources.