
Yield Opportunities
- 208 installs
- 31 repo stars
- Updated May 4, 2026
- kukapay/crypto-skills
Compare DeFi yield pools, staking routes, and APY risks so users or agents can allocate capital across protocols with clearer return expectations.
About
yield-opportunities is a crypto-skills capability for discovering and comparing decentralized finance yield sources, helping agents evaluate APYs, protocols, and risks when advising on where to deploy on-chain capital.
- DeFi yield comparison
- APY and risk framing
- Protocol route discovery
- Staking and LP scanning
- Capital allocation hints
Yield Opportunities by the numbers
- 208 all-time installs (skills.sh)
- +3 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #89 of 479 Web3 & Blockchain skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/kukapay/crypto-skills --skill yield-opportunitiesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 208 |
|---|---|
| repo stars | ★ 31 |
| Last updated | May 4, 2026 |
| Repository | kukapay/crypto-skills ↗ |
What it does
Compare DeFi yield pools, staking routes, and APY risks so users or agents can allocate capital across protocols with clearer return expectations.
Files
Yield Opportunities
This skill provides comprehensive workflows for discovering and analyzing DeFi yield opportunities across multiple protocols, blockchains, and yield-generating strategies.
Core Research Methodology
Parallel Exploration Strategy (MAXIMIZE EFFORT)
When researching yield opportunities, launch multiple background agents IN PARALLEL:
1. Librarian Agents (3-6 concurrent) - Best for external research:
- Protocol-specific yield documentation
- Yield aggregator platforms
- GitHub repositories for yield trackers
- Liquidity mining programs
- Staking/restaking opportunities
- Cross-chain bridging options (if applicable)
2. Direct Tools - Use in parallel with librarian agents:
websearch_web_search_exa- For current APYs, platform comparisonsgrep_app_searchGitHub- For open-source yield trackerswebfetch- To fetch specific documentation pages
Yield Categories to Research
1. Staking (Delegation)
What to find:
- Native chain staking (validator delegation)
- Liquid staking protocols (LSTs)
- Restaking opportunities (EigenLayer, etc.)
- Minimum staking amounts
- Lock-up periods and unbonding times
- Current APY ranges
- Validator selection criteria
Key Platforms by Chain:
- ETH: Lido (stETH), Rocket Pool (rETH), EigenLayer
- BNB: Native BSC delegation, Ankr, Trust Wallet staking
- SOL: Marinade, Jito, Lido
- Other Chain-Specific: Research native staking options
2. Lending Protocols
What to find:
- Major lending platforms on the chain
- Supply APYs for the asset
- Borrow APYs (for leverage strategies)
- Protocol TVL and security/audit status
- Collateral factors and LTV limits
- Liquidation risks
Top Platforms:
- ETH: Aave, Compound, Morpho, Euler
- BSC: Venus, Alpaca Finance, Cream
- Arbitrum/Optimism: Aave V3, Radiant
3. Liquidity Farming (LP Pools)
What to find:
- Major DEXs on the chain (Uniswap, PancakeSwap, Curve, etc.)
- Top LP pools involving the asset
- APR/APY breakdown (trading fees + farm rewards)
- Impermanent loss risk assessment
- Pool liquidity and volume data
- Reward token quality
Pool Types:
- Stablecoin pairs: Lower impermanent loss, lower yields
- Token pairs: Higher impermanent loss, higher yields
- V3 vs V2: Different mechanics, active vs passive management
4. Yield Aggregators (Auto-Compounding)
What to find:
- Aggregator platforms supporting the chain
- Vault strategies for the asset
- Auto-compounding frequency
- Performance fee structure
- Vault TVL and track record
- Strategy description (what they do with your funds)
Top Aggregators:
- Multi-chain: Beefy Finance, Yearn Finance, Autofarm, Harvest
- Chain-specific: ACryptoS (BSC), Idle Finance (ETH)
5. Cross-Chain Opportunities (If applicable)
What to find:
- Can asset be bridged to other chains?
- Bridge options and fees
- Yield opportunities on destination chains
- Bridge security track record
- Whether bridging is worth the risk/cost
Decision Framework:
- Bridging only recommended if yield differential >5-10%
- Verify bridge security (official bridges preferred)
- Consider gas costs + bridge fees
Reference Sources
Primary Aggregators (Start Here)
| Platform | Coverage | Daily Updates |
|---|---|---|
| DefiLlama | 14,149 pools, 495 protocols, 110 chains | Yes |
| Vaults.fyi | 500+ vaults | Yes |
| DexLender | Stablecoin lending rates | Yes |
| CoinMarketCap Yield | Multi-asset, DeFi & CeFi | Yes |
Protocol Documentation
Always reference official docs:
- Aave: https://docs.aave.com/
- Venus: https://docs-v4.venus.io/
- Beefy: https://docs.beefy.finance/
- PancakeSwap: https://docs.pancakeswap.finance/
- Curve: https://docs.curve.fi/
Workflow for Single Asset Request
Example: "I have BNB, how to earn?"
Step 1: Launch 5-6 librarian agents in parallel:
- BNB staking options (delegation, liquid staking)
- BSC lending protocols (Venus, Alpaca)
- BNB liquidity farming (PancakeSwap, Biswap pools)
- BSC yield aggregators (Beefy, Autofarm vaults)
- BNB bridging options (if worth exploring)
Step 2: Run parallel websearch queries:
- Current APYs for BNB staking
- Venus Protocol BNB supply rates
- PancakeSwap BNB pool APRs
- Beefy BNB vault performance
Step 3: Collect and synthesize findings:
- Organize by risk tolerance (Low/Medium/High)
- Include current rates, requirements, risks
- Provide decision framework
Step 4: Output structured recommendations:
- Safest options (staking, single-token vaults)
- Medium risk (lending, stablecoin LP)
- High risk (volatile LP, farming)
- Risk assessment for each optionRisk Assessment Framework
Risk Levels
| Level | Examples | Typical APY Range | Key Risks |
|---|---|---|---|
| Low | Native staking, liquid staking, CeFi vaults | 3-8% | Chain risks, price volatility |
| Medium | Lending, stablecoin LP, single-token vaults | 5-28% | Smart contract risk, liquidation |
| High | Token LP farming, yield aggregators | 20-100%+ | Impermanent loss, protocol risk |
| Extreme | New protocols, high-IL positions | 100%+ | Hack risks, rug scams |
Must-Include Warnings
1. Impermanent Loss (IL)
- Explain IL for liquidity pools
- Note: Stablecoin pairs = minimal IL, Token pairs = high IL
2. Smart Contract Risk
- Only recommend audited protocols with significant TVL
- Check: Is this protocol audited? What's the TVL?
3. Price Risk
- All yields are in the native asset
- If asset drops, USD value drops
4. Liquidation Risk
- For lending collateral positions
- Keep LTV < 50% if borrowing
5. Bridge Risk (if bridging recommended)
- Document bridge security
- Note historical bridge hacks
Output Structure
When presenting yield opportunities, use this format:
1. Safest Options (Low Risk)
- Method | APY | Requirements | Lock Period | Risk Notes
2. Medium Risk (Solid DeFi)
- Method | APY | Strategy | Trade-offs
3. High Risk (Maximum Yield)
- Method | APY | Strategy | Risks
4. Risk Assessment
- Detailed breakdown of each risk category
- What to watch out for
5. Recommendation by Profile
- Conservative / Balanced / Aggressive
- Best options for each user type
6. Quick Start Guide
- Step-by-step checklist
- Required tools (wallets, gas)
- Where to check current rates
Agent Delegation Prompts
Template for Librarian Agents
1. TASK: [Atomic task description]
2. EXPECTED OUTCOME: [Concrete deliverables with success criteria]
3. REQUIRED TOOLS: [Explicit tool whitelist]
4. MUST DO:
- [Exhaustive requirements, leave nothing implicit]
- [Get current 2025 information]
- [Include URLs to official sources]
5. MUST NOT DO:
- [Don't provide specific APY numbers - change too fast]
- [Don't suggest protocols with known issues]
- [Don't ignore risks]
6. CONTEXT: [User's situation and constraints]Example Prompt for Staking Research
1. TASK: Research [ASSET] staking options on [CHAIN]
2. EXPECTED OUTCOME: Complete list of staking options with validator info, APY ranges, how to stake, and requirements
3. REQUIRED TOOLS: websearch_web_search_exa, webfetch
4. MUST DO:
- Research native chain staking validators (official docs)
- Find current validator APYs and delegation process
- Research liquid staking protocols
- Document minimum amounts, lock periods, unbonding times
- Include URLs to official staking interfaces
5. MUST NOT DO:
- Don't recommend specific validators unless top-tier
- Don't ignore staking risks (slashing, unbonding)
- Don't speculate on future APY changes
6. CONTEXT: User has [ASSET] and wants safe staking yieldSearch Optimization
Efficient Search Queries
Instead of broad queries, use specific patterns:
Good:
- "BNB BSC staking validators APY 2025"
- "Venus protocol BNB supply APY BSC"
- "PancakeSwap BNB liquidity pool APR"
Avoid:
- "yield opportunities" (too broad)
- "how to earn with BNB" (not specific enough)
Time Management
- Stop searching when: Same info appearing across 3+ sources, or 2 iterations yielded no new data
- Parallel execution: Launch all librarian agents first, then direct tools
- Don't wait for librarian results - collect them all when needed
Common Chains and Resources
Ethereum
- Staking: Lido, Rocket Pool, EigenLayer
- Lending: Aave, Compound, Morpho
- DEX: Uniswap, Curve, Balancer
- Aggregators: Yearn, Beefy, Idle
- Track yields: DefiLlama /yields?chain=Ethereum
BNB Smart Chain
- Staking: Native delegation (1 BNB min), Ankr, Trust Wallet
- Lending: Venus (largest), Alpaca Finance, Cream
- DEX: PancakeSwap (largest), Biswap
- Aggregators: Beefy BSC vaults, Autofarm, ACryptoS
- Track yields: DefiLlama /yields?chain=Bsc
Solana
- Staking: Marinade, Jito, Lido
- Lending: Solend, Tulip
- DEX: Raydium, Orca, Jupiter
- Track yields: DefiLlama /yields?chain=Solana
Arbitrum/Optimism
- Lending: Aave V3, Radiant
- DEX: Uniswap V3, Velodrome, Camelot
- Track yields: DefiLlama /yields?chain=Arbitrum
References
See references/ for detailed guides:
- Risk Assessment Framework - Detailed risk evaluation
- Protocol Security Checklist - Protocol vetting process
- Yield Tracking Tools - Tools and APIs
Scripts
- scripts/fetch-defillama-yields.py: Fetch current yields from DefiLlama API
- scripts/compare-protocols.sh: Compare yields across protocols
Risk Assessment Framework for DeFi Yield
This guide provides comprehensive risk assessment criteria for evaluating DeFi yield opportunities.
Risk Categories
1. Smart Contract Risk
Assessment Criteria:
- Audit Status: Is the protocol audited? By whom? When?
- Top auditors: OpenZeppelin, ConsenSys Diligence, Certik, Trail of Bits
- Recent audits (last 12 months) preferred
- Code Complexity: Simple contracts vs. complex vaults/strategies
- Bug History: Has the protocol had exploits? How were they handled?
- TVL as Proxy: Higher TVL = more battle-tested
- >$100M: Battle-tested, lower risk
- $10-100M: Moderate risk
- <$10M: Higher risk (due diligence required)
Risk Levels:
- Low: Multiple audits, $500M+ TVL, no major exploits
- Medium: Single audit, $50-500M TVL, minor bug fixes
- High: No audit or old audit, <$50M TVL
- Extreme: Unaudited, <24h old, anonymous team
2. Impermanent Loss (IL) Risk
Understanding IL:
- IL occurs when LP token values diverge from simply holding assets
- Formula: IL = (Current Pool Value) / (Held Value) - 1
Risk by Pool Type:
| Pool Type | Typical IL | Example Pair | Typical APY |
|---|---|---|---|
| Stable-Stable | Minimal (0-2%) | USDC/USDT, DAI/USDC | 3-10% |
| Stable-Tier 1 | Low (2-10%) | USDC/ETH, USDT/BTC | 5-20% |
| Token-Tier 1 | Medium (10-30%) | ETH/BTC, SOL/USDC | 10-50% |
| Token-Token | High (30-100%+) | ALT1/ALT2, new tokens | 20-100%+ |
| V3 Concentrated | Very High | Any V3 range | Variable |
Mitigation:
- Prefer stablecoin pairs for risk-averse users
- Use single-token vaults (Beefy, ACryptoS) to avoid IL completely
- Set wider price ranges in V3 (reduces IL, reduces yield)
3. Price Risk (Asset Volatility)
Key Points:
- All yields are denominated in the native asset
- If the asset drops 50%, your USD value drops 50% regardless of APY earned
- High APY often compensates for high price volatility
Assessment Questions:
- Is the asset volatile (altcoins, meme tokens)?
- Is the asset stable (ETH, BTC, stables)?
- Is yield strategy dependent on price staying in range (V3)?
- Can you handle drawdown in the underlying asset?
Mitigation:
- Prefer stablecoins for risk-averse yield
- Hedge with futures/options if experienced
- Consider if you want long-term exposure to the asset
4. Liquidation Risk (Lending/Borrowing)
When Applicable:
- Using assets as collateral to borrow
- Leverage farming (borrow to farm)
Risk Factors:
- Loan-to-Value (LTV) ratio: How much borrowed vs. collateral
- Safe: <50% LTV
- Moderate: 50-70% LTV
- Risky: >70% LTV
- Collateral Factor: Maximum borrow % of collateral value
- Asset Correlation: If collateral and borrowed asset move together
Liquidation Threshold:
If LTV = 70% and asset drops 30%, you get liquidated
If LTV = 40% and asset drops 60%, you get liquidatedMitigation:
- Keep LTV <50% for safety
- Monitor collateral value regularly
- Use safe collateral (ETH, BTC) when borrowing volatile assets
5. Protocol Governance/Regulatory Risk
Assessment Criteria:
- Team Anonymity: Anonymous vs. doxxed team
- DAO Governance: Token voting vs. centralized control
- Regulatory Scrutiny: Is protocol operating in gray area?
- Upgrade Path: Can protocol changes be forced?
- Revenue Model: Does protocol have sustainable revenue?
Risk Levels:
- Low: Doxxed team, active governance, clear revenue model
- Medium: Pseudonymous team, early-stage governance
- High: Anonymous team, no governance, unaudited
- Extreme: Newly deployed, no track record, suspicious
6. Bridge Risk (Cross-Chain)
When Applicable:
- Bridging assets to other chains for yield
Key Considerations:
- Bridge Type: Official bridge vs. third-party
- Official: Best (Chain-native bridge, LayerZero)
- Established: Second best (Multichain, Celer)
- New/Unverified: Avoid
- Bridge Track Record: Has it been hacked?
- Liquidity: Can you bridge back easily?
- Cost: Bridge fees + gas costs
- Is It Worth It? Yield differential >5-10% to justify risk/cost
Historical Bridge Hacks:
- Ronin Bridge: $622M
- Wormhole: $326M
- Horizon Bridge: $100M
Mitigation:
- Use official bridges (BNB Chain Bridge, Arbitrum Bridge)
- Only bridge if yield significantly higher
- Keep bridged amounts small relative to portfolio
- Verify bridge is currently operational (some paused)
7. Token Incentive Risk
Understanding Token Rewards:
- Many high APYs come from emissions of protocol reward tokens
- These tokens often have poor fundamentals and dump on markets
- High emissions = high risk of token devaluation
Assessment:
- Emission Rate: How many tokens minted per day?
- Token Distribution: Is distribution fair or whale-heavy?
- Token Utility: Does token have real governance/utility or just rewards?
- Price Trend: Is token devaluing rapidly?
Risk Levels:
- Low: Mature protocols (AAVE, CRV), stable emissions
- Medium: Established protocols, moderate emissions
- High: New protocols, high emissions to bootstrap
- Extreme: Anonymous, massive emissions, obvious dumping patterns
8. Concentration Risk
Definition: Putting too much capital in one protocol or strategy
Safe Allocations:
- Conservative: No position >10% of portfolio
- Balanced: No position >25% of portfolio
- Aggressive: Can concentrate for higher yield (but acknowledge risk)
Mitigation:
- Diversify across protocols
- Diversify across chains
- Mix of staking, lending, LP (different risk profiles)
- Keep some in "risk-free" yield (native staking, CeFi vaults)
Composite Risk Scoring
When evaluating a specific yield opportunity, score each category 1-5:
| Category | Score (1-5) | Weight |
|---|---|---|
| Smart Contract Risk | 1=Safe, 5=Unsafe | 25% |
| Impermanent Loss Risk | 1=Minimal, 5 Extreme | 20% |
| Price Risk | 1=Stable, 5=Volatile | 20% |
| Liquidation Risk | 1=None, 5=High | 10% |
| Protocol Risk | 1=Mature, 5=New/Unvetted | 15% |
| Bridge Risk (if bridging) | 1=None, 5=Unsafe | 0-10% |
Overall Risk Score = Sum(Score × Weight)
Score Interpretation:
- 1.0-1.5: Very Low Risk
- 1.6-2.0: Low Risk
- 2.1-2.5: Medium Risk
- 2.6-3.5: High Risk
- 3.6+ : Very High Risk
Risk Tolerance Profiles
Conservative Profile
Max Risk Score: 2.0 Preferred Strategies:
- Native staking / liquid staking
- Lending (single asset)
- Stablecoin-stablecoin LP
- Single-token vaults (no IL)
- CeFi vaults (Binance Earn, etc.)
Balanced Profile
Max Risk Score: 2.5 Preferred Strategies:
- Mix of staking + lending + stable LP
- Tier 1 asset LP (ETH/USDC, BTC/USDC)
- Yield aggregators (Beefy, Yearn)
- Small allocation to higher-yield farms
Aggressive Profile
Max Risk Score: 3.5 Preferred Strategies:
- Token-token LP (higher yield, higher IL)
- V3 concentrated positions
- New protocol incentives
- Leverage farming (borrow to farm)
- Higher allocation to volatile assets
Due Diligence Checklist
Before deploying to any yield strategy:
Essential (Mandatory)
- [ ] Protocol has at least one audit from a recognized auditor
- [ ] TVL >$10M (higher is better)
- [ ] Documentation exists and is clear
- [ ] Contract addresses verified on block explorer
- [ ] Understand how yield is generated (fees, emissions, etc.)
- [ ] Understand fees and lock-up periods
Important (Should Do)
- [ ] Check protocol's social media and Discord for activity
- [ ] Read recent governance proposals/updates
- [ ] Check for any past exploits or incidents
- [ ] Verify team (doxxed or at least known in community)
- [ ] Test with small amount first
- [ ] Understand withdrawal process and fees
Nice to Have
- [ ] Read contract code (if technically inclined)
- [ ] Check on-chain data (utilization, TVL history)
- [ ] Monitor for whale movements
- [ ] Set up alerts for protocol news
- [ ] Community sentiment check
Example Assessments
Example 1: Lido Staking (stETH)
| Category | Score | Reason |
|---|---|---|
| Smart Contract | 1 | Multi-audited, $10B+ TVL |
| Impermanent Loss | 1 | No IL (single asset) |
| Price Risk | 2 | ETH exposure (moderately volatile) |
| Liquidation | 1 | No borrowing involved |
| Protocol | 1 | Market leader, mature |
| Bridge | 1 | No bridging (native) |
Overall: 1.15 - Very Low Risk
Example 2: PancakeSwap USDT-BNB LP
| Category | Score | Reason |
|---|---|---|
| Smart Contract | 2 | Audited, battle-tested, but large attack surface |
| Impermanent Loss | 2 | Medium IL (stablecoin + volatile) |
| Price Risk | 3 | BNB volatility exposure |
| Liquidation | 1 | No borrowing involved |
| Protocol | 2 | Mature, largest BSC DEX |
| Bridge | 1 | Native to BSC |
Overall: 2.05 - Low-Medium Risk
Example 3: New Protocol Farm (Random Alt-Alt LP)
| Category | Score | Reason |
|---|---|---|
| Smart Contract | 4 | No audit, $1M TVL, new deployment |
| Impermanent Loss | 4 | High IL (alt-alt pair) |
| Price Risk | 5 | Highly volatile altcoins |
| Liquidation | 2 | Possible if using leverage |
| Protocol | 5 | Anonymous team, 2 days old |
| Bridge | 1 | Native (or 4 if bridged) |
Overall: 3.65+ - Very High Risk - Avoid or Ape with Caution
Protocol Security Checklist
Use this checklist to vet DeFi protocols before recommending or using them.
Phase 1: Basic Vetting (Do This First)
Documentation & Transparency
- [ ] Official website exists and is professional
- [ ] Clear documentation site (docs.*, not just Medium posts)
- [ ] Smart contract addresses publicly disclosed on official site
- [ ] Tokenomics page exists (if Protocol has token)
- [ ] Team section with profiles (even if pseudonymous)
- [ ] Social media presence (Twitter, Discord, Telegram)
- [ ] Activity level: Recent posts/announcements (last 30 days)
Contract Verification
- [ ] Contracts verified on block explorer (Etherscan, BscScan, etc.)
- [ ] Source code is open-source and readable
- [ ] Proxy contract pattern used properly (upgradeability transparent)
- [ ] Implementation contract accessible
Phase 2: Security Audits
Audit Presence
- [ ] At least one audit from reputable firm
- [ ] Recent audit (within last 12-18 months)
- [ ] Audit reports publicly available (PDF on website)
- [ ] Findings addressed publicly (issues fixed/mitigated)
Reputable Audit Firms (In Order of Preference)
Tier 1 (Best):
- OpenZeppelin
- ConsenSys Diligence
- Trail of Bits
- Certik
- Quantstamp
- Sigma Prime
- PeckShield
Tier 2 (Good but lower):
- SlowMist
- Haechi Labs
- MixBytes
- Paladin Blockchain Security
- Armors
Tier 3 (Questionable):
- Unknown or very small firms
- Self-audits
- "Audit in progress" for months
Audit Review Checklist
- [ ] Critical findings: Were any? Fixed?
- [ ] High findings: Were any? Addressed?
- [ ] Medium findings: Addressed or acknowledged?
- [ ] Low findings: Minor issues?
- [ ] Total findings: <10 is ideal, 10-25 common, >25 concerning
Phase 3: Track Record & Battle Testing
TVL and Age
- [ ] Total Value Locked (TVL) on DefiLlama
- >$500M: Excellent, highly battle-tested
- $100-500M: Good, moderate track record
- $10-100M: New, emerging
- <$10M: Experimental, high diligence required
- [ ] Protocol age: How long has it been deployed?
- >2 years: Very mature
- 1-2 years: Mature
- 6-12 months: New
- <6 months: Very new, caution
Incident History
- [ ] No major hacks or exploits
- [ ] No critical incidents on Rekt.news or similar
- [ ] Past issues handled transparently with post-mortems
- [ ] Response to incidents: Quick, appropriate compensation if applicable
Community Sentiment
- [ ] Active Discord/Telegram with real users
- [ ] Moderators respond to questions and issues
- [ ] No major FUD campaigns without addressing
- [ ] Respected in crypto community (not on scam lists)
Phase 4: Technical Deep Dive
Code Quality
- [ ] Clean, readable code (not obfuscated)
- [ ] Follows industry standards (ERC-20, ERC-4626, etc.)
- [ ] Uses battle-tested libraries (OpenZeppelin, etc.)
- [ ] Not overly complex (simpler is often safer)
- [ ] No suspicious patterns (hidden fees, backdoors, etc.)
Upgradeability
- [ ] Proxy pattern transparent (UUPS, Transparent, Beacon)
- [ ] Upgrade delay (timelocks implemented)
- [ ] Governance for upgrades (not admin keys)
- [ ] Past upgrades documented and explained
Permission Controls
- [ ] Admin role: Limited permissions, ideally only upgrades
- [ ] Timelocks: In place for privileged operations
- [ ] Multi-sig used for critical operations (preferably >2 signers)
- [ ] Team wallet addresses trackable on-chain
Phase 5: Token & Governance
Token Economics (if applicable)
- [ ] Vesting schedule clear and reasonable
- [ ] Team not dumping tokens (check recent transfers)
- [ ] Circulating vs. Total supply disclosed
- [ ] Inflation schedule sustainable
- [ ] Token has utility (governance, rewards, etc.)
Governance
- [ ] DAO governance active (or clear reason why not)
- [ ] Governance proposals visible and discussed
- [ ] Voting power decentralized (not just insiders)
- [ ] Treasury management transparent
Phase 6: Red Flags (Immediate Disqualification)
Critical Red Flags (Don't Use)
- [ ] No audit or extremely old audit (>2 years)
- [ ] Contracts not verified on block explorer
- [ ] Anonymous owner + no community presence
- [ ] Team tokens dumped recently (check Etherscan/BscScan)
- [ ] Obfuscated code or code hidden behind proxy only
- [ ] Unlimited minting function accessible to admin
- [ ] Unlimited withdraw/steal function accessible to admin
- [ ] Backdoor or hidden code patterns
- [ ] Promises unrealistic APY (>1000% not sustainable)
- [ ] Pump and dump patterns (high initial APY, then crash)
- [ ] Copy-paste of known exploited contracts
- [ ] Team involved in previous scams/exploits
- [ ] No contact/support channel
- [ ] Pressure to deposit quickly (FOMO tactics)
Warning Signs (Proceed with Caution)
- [ ] TVL fluctuating wildly (possible manipulation)
- [ ] Anonymous team but good community/support
- [ ] New audit from unknown firm
- [ ] Governance inactive or controlled by insiders
- [ ] Token heavily manipulated on DEX
- [ ] Social media full of shilling vs. real discussion
- [ ] Aggressive marketing vs. substance
- [ ] Paying influencers (some may be legitimate, some not)
Phase 7: Operational Security
Oracle Usage
- [ ] Oracles secure and decentralized (Chainlink, Band)
- [ ] Not using single-source price feeds that can be manipulated
- [ ] Flash loan protection implemented
Reentrancy Protection
- [ ] Reentrancy guards on critical functions
- [ ] Checks-Effects-Interactions pattern followed
- [ ] No external calls in critical state changes
Integer Overflow/Underflow
- [ ] Solidity 0.8+ used (handles overflow/underflow automatically)
- [ ] SafeMath used if Solidity <0.8
Emergency Functionality
- [ ] Emergency pause function exists
- [ ] Emergency withdraw function exists (in case of bugs)
- [ ] Pause mechanism not easily abused
Scoring System
Score Calculation
| Category | Points Possible |
|---|---|
| Documentation | 0-10 |
| Audits | 0-15 |
| Track Record | 0-15 |
| Technical Quality | 0-20 |
| Token/Governance | 0-15 |
| Operational Security | 0-15 |
| Red Flags (subtraction) | -0 to -50 |
Total Possible Score: 0-90 (Red flags can push negative)
Score Interpretation
| Score Range | Rating | Recommendation |
|---|---|---|
| 70-90 | Excellent | Safe to use, recommend |
| 50-69 | Good | Generally safe, use with normal precautions |
| 30-49 | Moderate | Use smaller amounts, due diligence required |
| 10-29 | Poor | High risk, avoid unless comfortable with risk |
| 0-9 or below | Very Poor | Do not use, likely scam |
Quick Vetting Workflow (5 minutes)
Step 1 (1 min): Basic Check
- Visit official website
- Check docs exist
- Find contract address on block explorer
- Check for audit badge/link
Fail if: No docs, no audit, contracts not verified
Step 2 (2 min): Security & Track Record
- Open audit PDF, check critical findings
- Check DefiLlama for TVL and age
- Google "[Protocol] hack" or "[Protocol] exploit"
- Check Twitter/Discord for activity
Fail if: Critical audit findings unfixed, >$10M hack history, inactive community
Step 3 (2 min): Red Flags & Tokenomics
- Scan smart contracts for suspicious functions (mint, withdraw)
- Check recent team token transfers (on explorer)
- Check token chart for pump-dump patterns
- Verify team doxxing or at least community trust
Fail if: Unlimited mint to admin, team dumping, obvious pump-dump
Example Vetting
Example 1: Lido Finance (Should Pass)
Documentation: ✅ Professional, extensive docs Audits: ✅ OpenZeppelin, ConsenSys, multiple others Track Record: ✅ $10B+ TVL, 2+ years, no major hacks Technical: ✅ Solidity 0.8+, battle-tested, standard patterns Token: ✅ LDO has governance, reasonable vesting Security: ✅ Chainlink oracles, reentrancy guards, pause functions
Score: ~85/90 - Excellent
Example 2: New Yield Farm Ape (Should Fail)
Documentation: ❌ Only Medium posts, no docs site Audits: ❌ No audit or audit in progress for months Track Record: ❌ Deployed 2 days ago, $50k TVL Technical: ❌ Contracts not verified, can't review Token: ❌ Anonymous team, 95% of supply to team Security: ❌ Can't assess (contracts not verified)
Score: ~-20/90 - Do Not Use
References
Tools for Vetting
- DefiLlama: https://defillama.com/ (TVL, age, protocol data)
- Etherscan/BscScan: https://etherscan.io/ (contract verification, code)
- Rekt.news: https://rekt.news/ (exploit history)
- Token Unlocks: https://token.unlocks.app/ (vesting schedules)
- Open Source: https://github.com/ (code review if repo exists)
Audit Repositories
- OpenZeppelin: https://blog.openzeppelin.com/
- ConsenSys Diligence: https://diligence.consensys.net/audits/
- Certik: https://www.certik.com/projects/
- Quantstamp: https://www.quantstamp.com/audits
Community Resources
- Crypto Twitter: Search for protocol name + sentiment
- Discord/Telegram: Join, read discussions, ask questions
- Twitter Lists: Follow reputable DeFi researchers
- Governance Forums: Read recent proposals and discussions
Yield Tracking Tools and APIs
This comprehensive guide covers tools, APIs, and dashboards for tracking DeFi yields in real-time.
Primary Yield Aggregators (Best Place to Start)
DefiLlama Yields
URL: https://defillama.com/yields Coverage: 14,149 pools across 495 protocols on 110 chains Update Frequency: Daily
Features:
- Filter by chain (Ethereum, BSC, Arbitrum, Solana, etc.)
- Filter by token (ETH, BTC, BNB, stablecoins, etc.)
- Filter by protocol (Aave, Compound, PancakeSwap, etc.)
- Filter by APY range
- Filter by TVL range
- Filter by category (lending, staking, LP, single asset)
- Sort by APY, TVL, pool name
- View pool details (token, chain, protocol, APY, TVL)
- 30-day APY mean
- Reputation score (protocol risk indicator)
API Endpoints:
# All pools
GET https://yields.llama.fi/pools
# Pools by chain
GET https://yields.llama.fi/pools?chain=ethereum
# Pools by token
GET https://yields.llama.fi/pools?token=bnb
# Pool details (chart history)
GET https://yields.llama.fi/chart/{pool}
# Borrow APY
GET https://yields.llama.fi/borrow
# LSD rates (liquid staking)
GET https://yields.llama.fi/lsdRatesPros:
- Most comprehensive coverage
- Open-source and free
- Daily updates
- Multiple filter options
- API access for automation
- Reputation scores included
Cons:
- Some newer protocols may not be listed
- APYs are delayed (not real-time)
---
Vaults.fyi
URL: https://vaults.fyi/complete-list-of-defi-vaults-yields-updated-daily/ Coverage: 500+ vaults across 50+ protocols Update Frequency: Daily
Features:
- Yield aggregator vaults only (Beefy, Yearn, etc.)
- Daily updated APYs
- Protocol filtering
- Chain filtering
- Token filtering
- On-chain data transparency
Pros:
- Specialized for vaults/yield aggregators
- Daily updates
- Focus on auto-compounding strategies
- Transparent APY calculation methodology
Cons:
- Only covers vaults, not direct lending/staking
- Smaller dataset than DefiLlama
---
DexLender
URL: https://dexlender.com/ Coverage: Stablecoin lending rates across chains Update Frequency: Live (as of page load date)
Features:
- Stablecoin APYs (USDC, USDT, DAI, etc.)
- Multi-chain support
- Current base APY
- Protocol comparison
- Sort by highest APY
Pros:
- Great for stablecoin yield comparison
- Real-time rates
- Simple interface
Cons:
- Only stablecoins
- Only lending protocols (not staking/LP)
---
CoinMarketCap Yield
URL: https://coinmarketcap.com/yield/ Coverage: Multi-asset, DeFi and CeFi options Update Frequency: Periodic
Features:
- Yield type categorization (Earn, Staking, etc.)
- Provider type (DeFi/CeFi)
- Net APY display
- Multiple assets supported
- FAQ section on yield mechanics
Pros:
- Covers both DeFi and CeFi
- Easy to understand interface
- Good for beginners
Cons:
- Less comprehensive than DefiLlama
- Not real-time for many entries
- Some data may be outdated
---
Chain-Specific Dashboards
Ethereum
- DefiPulse: https://defipulse.com/ (legacy but still useful)
- Curve.fi: https://curve.fi/ (Curve pool yields)
- Convex Finance: https://www.convexfinance.com/ (Curve optimizer yields)
- Yearn.fi: https://yearn.fi/ (Yearn vault yields)
- Lido: https://stake.lido.fi/ (stETH staking APY)
- Rocket Pool: https://rocketpool.net/ (rETH staking APY)
BNB Smart Chain
- PancakeSwap: https://pancakeswap.finance/farms (CAKE farm yields)
- Venus Protocol: https://venus.io/ (Lending/borrowing APYs)
- Alpaca Finance: https://app.alpacafinance.org/lend (Lending vault APYs)
- Beefy BSC: https://app.beefy.com/ (Vault yields on BSC)
Solana
- Marinade: https://marinade.finance/ (mSOL staking)
- Jito: https://www.jito.network/ (JitoSOL staking with MEV rewards)
- Raydium: https://raydium.io/clmm/pools (Liquidity pool yields)
- Orca: https://www.orca.so/pools (Whirlpool yields)
Arbitrum/Optimism
- Aave V3: https://app.aave.com/markets (Arbitrum/Optimism yields)
- Uniswap V3: https://app.uniswap.org/pools (L3 pool yields)
- Velodrome: https://app.velodrome.finance/ (Optimism yields)
- Camelot: https://app.camelot.exchange/ (Arbitrum yields)
Polygon
- QuickSwap: https://quickswap.exchange/ (DEX yields)
- Aave Polygon: https://aave.com/markets (Lending on Polygon)
---
Yield Aggregator Platforms (For Checking Vault Yields)
Beefy Finance
URL: https://beefy.com/ Chains: 39 chains Coverage: 500+ vaults
API:
# All vaults
GET https://api.beefy.finance/vaults
# Vaults by chain
GET https://api.beefy.finance/vaults/tvl?chain=bsc
# Single vault details
GET https://api.beefy.finance/vaults/{vault_address}Yearn Finance
URL: https://yearn.fi/ Chains: Ethereum, Arbitrum, Optimism
API:
# All vaults
GET https://api.yearn.fi/v1/chains/ethereum/vaults/all
# Single vault
GET https://api.yearn.fi/v1/chains/ethereum/vaults/{vault_address}Autofarm
URL: https://autofarm.network/ Chains: Multi-chain (BSC, Polygon, etc.)
ACryptoS
URL: https://app.acryptos.com/ Chains: BSC, Cronos, Polygon, etc.
---
Open Source Yields Trackers (GitHub)
DefiLlama Yield Server
Repo: https://github.com/DefiLlama/yield-server Description: Open-source APY server powering DefiLlama Language: TypeScript/JavaScript Features:
- Adapter-based architecture
- On-chain data fetching
- APY calculation methodology (minimum attainable yield)
- Schema for pool data (apyBase, apyReward)
Usage:
git clone https://github.com/DefiLlama/yield-server
cd yield-server
npm install
npm run start
# Server runs on port 3001
# GET http://localhost:3001/poolsDefiLlama DefiLlama-Adapters
Repo: https://github.com/DefiLlama/DefiLlama-Adapters Description: Adapters for computing TVL Language: TypeScript Usage: Learn protocol integration for custom yield tracking
DefiLlama App
Repo: https://github.com/DefiLlama/defillama-app Description: Main DefiLlama application code Language: TypeScript Usage: Build custom dashboard using DefiLlama data
defi-yields-mcp
Repo: https://github.com/kukapay/defi-yields-mcp Description: MCP server for AI agents to explore DeFi yields Language: JavaScript Features:
get_yield_poolstool- Powered by DefiLlama
- Built for AI agent integration
defi-yield-aggregator
Repo: https://github.com/obinnafranklinduru/defi-yield-aggregator Description: Yield aggregator smart contract example Language: Solidity Features:
- Dynamic allocation between Aave and Compound
- Switches based on higher APY
yapt
Repo: https://github.com/yaptfi/yapt Description: Stablecoin portfolio tracker with true APY Language: TypeScript Features:
- True APY tracking (realized, not advertised)
- Multi-protocol support (Aave, Curve, Yearn, Uniswap)
defi-yield-dashboard
Repo: https://github.com/leningradtank/defi-yield-dashboard Description: DeFi yield dashboard with Jupyter Notebook Language: Jupyter Notebook Features:
- Pulls lending/borrowing data from multiple protocols
- Analyze and visualize yields
---
APIs for Programmatic Access
DefiLlama API (Yields)
Base URL: https://yields.llama.fi/
Endpoints:
# Get all yield pools
curl https://yields.llama.fi/pools
# Get pools by chain
curl https://yields.llama.fi/pools?chain=ethereum
# Get pools by token
curl https://yields.llama.fi/pools?token=bnb
# Get specific pool
curl https://yields.llama.fi/chart/{pool_id}
# Get borrow rates
curl https://yields.llama.fi/borrow
# Get LSD rates
curl https://yields.llama.fi/lsdRates
# Get yields history
curl https://yields.llamaifi/chart/{pool}Python Example:
import requests
def get_defillama_yields(chain=None, token=None):
base_url = "https://yields.llama.fi/pools"
params = {}
if chain:
params['chain'] = chain
if token:
params['token'] = token
response = requests.get(base_url, params=params)
return response.json()
# Get BNB yields on BSC
bnb_yields = get_defillama_yields(chain='bsc', token='bnb')
for pool in bnb_yields['data']:
print(f"{pool['pool']}: {pool['apy']}% APY, TVL: ${pool['tvlUsd']:,.0f}")Beefy API
Base URL: https://api.beefy.finance/
Endpoints:
# All vaults
curl https://api.beefy.finance/vaults
# Vaults by chain
curl https://api.beefy.finance/vaults/tvl?chain=bsc
# Single vault details
curl https://api.beefy.finance/vaults/{vault_address}Yearn API
Base URL: https://api.yearn.fi/v1/
Endpoints:
# All Ethereum vaults
curl https://api.yearn.fi/v1/chains/ethereum/vaults/all
# Single vault
curl https://api.yearn.fi/v1/chains/ethereum/vaults/{vault_address}---
Custom Yield Tracking Scripts
Fetch DefiLlama Yields (Python)
#!/usr/bin/env python3
import requests
import json
from datetime import datetime
def fetch_yields(chain=None, token=None, min_apy=0):
"""Fetch yields from DefiLlama"""
url = "https://yields.llama.fi/pools"
params = {}
if chain:
params['chain'] = chain
if token:
params['token'] = token
response = requests.get(url, params=params)
data = response.json()
# Filter by min APY
filtered_pools = [
p for p in data['data'] if p.get('apy', 0) >= min_apy
]
# Sort by APY descending
filtered_pools.sort(key=lambda x: x.get('apy', 0), reverse=True)
return filtered_pools
def display_pools(pools, top_n=10):
"""Display top pools"""
print(f"\n{'Pool':<50} {'Chain':<10} {'Protocol':<15} {'APY':<10} {'TVL':<15}")
print("=" * 100)
for i, pool in enumerate(pools[:top_n], 1):
pool_name = pool['pool'][:47] + '...' if len(pool['pool']) > 50 else pool['pool']
chain = pool['chain']
protocol = pool['project'][:12] + '...' if len(pool['project']) > 15 else pool['project']
apy = f"{pool.get('apy', 0):.2f}%"
tvl = f"${pool.get('tvlUsd', 0):,.0f}"
print(f"{pool_name:<50} {chain:<10} {protocol:<15} {apy:<10} {tvl:<15}")
if __name__ == "__main__":
# Example: Get BNB yields on BSC with >5% APY
print(f"Fetching yields at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}...")
pools = fetch_yields(chain='bsc', token='bnb', min_apy=5)
display_pools(pools, top_n=20)Compare Protocols (Bash)
#!/bin/bash
# Compare BNB yields across protocols
echo "Fetching BNB yields from DefiLlama..."
curl -s "https://yields.llama.fi/pools?token=bnb" | \
jq -r '.data[] | "\(.pool) | \(.chain) | \(.project) | \(.apy)% APY | TVL: $\(.tvlUsd)"' | \
grep -E "(BSC|Binance)" | \
sort -t'|' -k4 -rn | \
head -20
echo ""
echo "--- Top 20 BNB Yields on BSC ---"Monitor Specific Pool (Node.js)
// monitor-pool.js
async function monitorPool(poolId) {
const response = await fetch(`https://yields.llama.fi/chart/${poolId}`);
const data = await response.json();
const apyHistory = data.data;
const currentApy = apyHistory[apyHistory.length - 1].apy;
const tvl = apyHistory[apyHistory.length - 1].tvlUsd;
console.log(`Pool ID: ${poolId}`);
console.log(`Current APY: ${currentApy.toFixed(2)}%`);
console.log(`Current TVL: $${tvl.toLocaleString()}`);
console.log(`Data points: ${apyHistory.length}`);
// Calculate 7-day average
const last7Days = apyHistory.slice(-7);
const avgApy = last7Days.reduce((sum, point) => sum + point.apy, 0) / last7Days.length;
console.log(`7-day average APY: ${avgApy.toFixed(2)}%`);
}
// Usage
monitorPool('0x1234...'); // Replace with pool ID---
Alerting and Notifications
Set Up APY Alerts
import requests
import smtplib
from email.mime.text import MIMEText
def check_apy_and_alert(pool_id, threshold_apy, email, password, to_email):
"""Check if APY dropped below threshold and send email alert"""
url = f"https://yields.llama.fi/chart/{pool_id}"
response = requests.get(url)
data = response.json()
current_apy = data.data[-1].apy
if current_apy < threshold_apy:
msg = MIMEText(f"Alert: APY dropped to {current_apy:.2f}% (threshold: {threshold_apy}%)")
msg['Subject'] = 'Yield Alert'
msg['From'] = email
msg['To'] = to_email
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(email, password)
server.send_message(msg)
print("Alert sent!")
else:
print(f"APY is {current_apy:.2f}%, above threshold")---
Data Quality Tips
Verify Data
1. Cross-check multiple sources: DefiLlama + protocol dashboard 2. Check timestamps: Ensure data is recent (last 24 hours) 3. Verify pool addresses: Match with official protocol docs 4. Check TVL: Low TVL may indicate stale or inactive pools 5. Look for outliers: Extremely high APYs may be temporary or risky
Common Issues
- Stale data: Some aggregators don't update frequently
- Inaccurate APY calculation: Some show gross APY before fees
- Pool deactivation: Check if pool is still active
- Incentive programs: Short-term APY boosts may expire soon
- Reward token price volatility: APY can swing wildly with token price
---
Best Practices
For Research
1. Start with DefiLlama (most comprehensive) 2. Cross-reference with official protocol dashboards 3. Check DefiLlama "Reputation Score" for protocol risk 4. Look at 30-day mean APY (more stable than snapshot) 5. Consider TVL as proxy for safety
For Automation
1. Use DefiLlama API (reliable, well-documented) 2. Implement retry logic for API calls 3. Cache data to avoid rate limiting 4. Set up monitoring for data anomalies 5. Log all data fetches for audit trail
For Decision Making
1. Don't chase highest APY (often highest risk) 2. Consider sustainable yields (protocol fees) vs. token emissions 3. Factor in transaction costs (gas fees eat yield) 4. Consider lock-up periods and liquidity 5. Diversify across protocols and strategies
#!/bin/bash
# Compare Yields Across Protocols
# This script fetches yield data from DefiLlama and compares protocols for a specific token
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
usage() {
cat << EOF
Usage: $0 [OPTIONS]
Compare DeFi yields across protocols for a specific token.
OPTIONS:
-t, --token TOKEN Token to compare (e.g., bnb, eth, usdc) [required]
-c, --chain CHAIN Chain to filter by (e.g., bsc, ethereum, arbitrum) [optional]
-m, --min-apy APY Minimum APY threshold (default: 0) [optional]
-n, --top N Number of top protocols to display (default: 10) [optional]
-e, --export FILE Export results to CSV file [optional]
-h, --help Show this help message
EXAMPLES:
# Compare BNB yields on BSC
$0 --token bnb --chain bsc
# Compare ETH yields, top 20, >5% APY
$0 --token eth --min-apy 5 --top 20
# Compare stablecoin yields, export to CSV
$0 --token usdc --min-apy 3 --export stablecoin-yields.csv
EOF
}
TOKEN=""
CHAIN=""
MIN_APY=0
TOP_N=10
EXPORT_FILE=""
while [[ $# -gt 0 ]]; do
case $1 in
-t|--token)
TOKEN="$2"
shift 2
;;
-c|--chain)
CHAIN="$2"
shift 2
;;
-m|--min-apy)
MIN_APY="$2"
shift 2
;;
-n|--top)
TOP_N="$2"
shift 2
;;
-e|--export)
EXPORT_FILE="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo -e "${RED}Unknown option: $1${NC}"
usage
exit 1
;;
esac
done
if [[ -z "$TOKEN" ]]; then
echo -e "${RED}Error: TOKEN is required${NC}"
usage
exit 1
fi
URL="https://yields.llama.fi/pools?token=${TOKEN^^}"
if [[ -n "$CHAIN" ]]; then
URL="${URL}&chain=${CHAIN}"
fi
echo -e "${BLUE}Fetching yields from DefiLlama...${NC}"
echo "Token: ${TOKEN^^}"
if [[ -n "$CHAIN" ]]; then
echo "Chain: $CHAIN"
fi
echo "Min APY: $MIN_APY%"
echo ""
DATA=$(curl -s "$URL")
if [[ $? -ne 0 ]]; then
echo -e "${RED}Error: Failed to fetch data from DefiLlama${NC}"
exit 1
fi
if ! command -v jq &> /dev/null; then
echo -e "${RED}Error: jq is required but not installed${NC}"
echo "Install jq: sudo apt-get install jq (Ubuntu/Debian) or brew install jq (macOS)"
exit 1
fi
PROTOCOLS=$(echo "$DATA" | \
jq -r ".data[] | select(.apy >= $MIN_APY) | \"\(.project)|\(.pool)|\(.chain)|\(.apy)|\(.tvlUsd)|\(.stablecoin)\"" | \
sort -t'|' -k4 -rn | \
head -n "$TOP_N" \
)
if [[ -z "$PROTOCOLS" ]]; then
echo -e "${YELLOW}No protocols found matching criteria${NC}"
exit 0
fi
printf "\n${GREEN}%-20s %-40s %-10s %-12s %-15s %-10s${NC}\n" \
"Protocol" "Pool" "Chain" "APY" "TVL" "Stable?"
printf "${GREEN}%-20s %-40s %-10s %-12s %-15s %-10s${NC}\n" \
"--------" "----" "-----" "---" "---" "------"
CSV_DATA="Protocol,Pool,Chain,APY,TVL,Stablecoin,count"
PROTOCOL_COUNT=1
while IFS='|' read -r protocol pool chain apy tvl stable; do
tvl_formatted=$(printf "%'d" $(echo "$tvl" | cut -d'.' -f1))
apy_formatted=$(printf "%.2f%%" "$apy")
if [[ "$stable" == "true" ]]; then
stable_formatted="${GREEN}Yes${NC}"
else
stable_formatted="${YELLOW}No${NC}"
fi
pool_display="${pool:0:35}"
if (( ${#pool} > 35 )); then
pool_display="${pool_display}..."
fi
printf "%-20s %-40s %-10s %-12s $%-14s %-10s\n" \
"$protocol" "$pool_display" "$chain" "$apy_formatted" "$tvl_formatted" "$stable_formatted"
CSV_DATA="${CSV_DATA}\n${protocol},${pool},${chain},${apy_formatted},$${tvl_formatted},${stable}"
PROTOCOL_COUNT=$((PROTOCOL_COUNT + 1))
done <<< "$PROTOCOLS"
echo ""
echo -e "${BLUE}Showing $((PROTOCOL_COUNT - 1)) protocols${NC}"
if [[ -n "$EXPORT_FILE" ]]; then
echo -e "\n${BLUE}Exporting to ${EXPORT_FILE}...${NC}"
echo -e "$CSV_DATA" > "$EXPORT_FILE"
echo -e "${GREEN}Export complete!${NC}"
fi
echo ""
echo -e "${BLUE}Statistics:${NC}"
TOTAL_APY=$(echo "$DATA" | jq -r "[.data[] | select(.apy >= $MIN_APY) | .apy] | add")
TOTAL_COUNT=$(echo "$DATA" | jq -r "[.data[] | select(.apy >= $MIN_APY)] | length")
if [[ -n "$TOTAL_APY" ]] && [[ -n "$TOTAL_COUNT" ]] && [[ "$TOTAL_COUNT" -gt 0 ]]; then
AVG_APY=$(awk "BEGIN {printf \"%.2f\", ${TOTAL_APY}/${TOTAL_COUNT}}")
echo "Average APY: ${AVG_APY}%"
echo "Total protocols found: $((PROTOCOL_COUNT - 1))"
else
echo "No statistics available"
fi
echo ""
echo -e "${GREEN}Done!${NC}"
#!/usr/bin/env python3
"""
Fetch Yields from DefiLlama API
This script fetches yield opportunities from DefiLlama for specified chains and tokens,
filters by APY, and displays top results.
Usage:
python fetch-defillama-yields.py --chain bsc --token bnb --min-apy 5 --top 20
python fetch-defillama-yields.py --token eth --min-apy 3
python fetch-defillama-yields.py --chain ethereum --top 50
"""
import requests
import argparse
import json
from datetime import datetime
from typing import List, Dict, Optional
def fetch_yields(
chain: Optional[str] = None, token: Optional[str] = None, min_tvl: float = 0
) -> List[Dict]:
"""
Fetch yield pools from DefiLlama API.
Args:
chain: Filter by blockchain (e.g., 'ethereum', 'bsc', 'arbitrum')
token: Filter by token (e.g., 'bnb', 'eth', 'usdc')
min_tvl: Minimum TVL in USD
Returns:
List of yield pool dictionaries
"""
base_url = "https://yields.llama.fi/pools"
params = {}
if chain:
params["chain"] = chain
if token:
params["token"] = token
try:
response = requests.get(base_url, params=params, timeout=30)
response.raise_for_status()
data = response.json()
filtered_pools = [p for p in data["data"] if p.get("tvlUsd", 0) >= min_tvl]
return filtered_pools
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
return []
def filter_by_apy(pools: List[Dict], min_apy: float) -> List[Dict]:
"""Filter pools by minimum APY."""
return [p for p in pools if p.get("apy", 0) >= min_apy]
def sort_by_apy(pools: List[Dict]) -> List[Dict]:
"""Sort pools by APY in descending order."""
return sorted(pools, key=lambda x: x.get("apy", 0), reverse=True)
def display_pools(pools: List[Dict], top_n: int = 20, show_details: bool = False):
"""
Display yield pools in formatted table.
Args:
pools: List of pool dictionaries
top_n: Number of top pools to display
show_details: Show additional details (30-day mean, stablecoin, etc.)
"""
if not pools:
return
top_pools = pools[:top_n]
print(
f"\n{'Pool':<50} {'Chain':<10} {'Protocol':<15} {'APY':<10} {'30d Mean':<10} {'TVL':<15}"
)
print("=" * 115)
for pool in top_pools:
pool_name = (
pool["pool"][:47] + "..." if len(pool["pool"]) > 50 else pool["pool"]
)
chain = pool["chain"]
protocol = (
pool["project"][:12] + "..."
if len(pool["project"]) > 15
else pool["project"]
)
apy = f"{pool.get('apy', 0):.2f}%" if pool.get("apy") else "N/A"
apy_mean30d = (
f"{pool.get('apyMean30d', 0):.2f}%" if pool.get("apyMean30d") else "N/A"
)
tvl = f"${pool.get('tvlUsd', 0):,.0f}"
print(
f"{pool_name:<50} {chain:<10} {protocol:<15} {apy:<10} {apy_mean30d:<10} {tvl:<15}"
)
if show_details:
print(
f" Symbol: {pool.get('symbol', 'N/A')} | "
f"Stablecoin: {pool.get('stablecoin', False)} | "
f"Base APY: {pool.get('apyBase', 0):.2f}% | "
f"Reward APY: {pool.get('apyReward', 0):.2f}%"
)
print(f"\nShowing {len(top_pools)} of {len(pools)} total pools")
def get_summary_stats(pools: List[Dict]) -> Dict:
"""Get summary statistics for the pools."""
if not pools:
return {}
apys = [p.get("apy", 0) for p in pools if p.get("apy")]
tvls = [p.get("tvlUsd", 0) for p in pools if p.get("tvlUsd")]
return {
"total_pools": len(pools),
"avg_apy": sum(apys) / len(apys) if apys else 0,
"max_apy": max(apys) if apys else 0,
"min_apy": min(apys) if apys else 0,
"total_tvl": sum(tvls),
"median_apy": sorted(apys)[len(apys) // 2] if apys else 0,
}
def export_to_json(pools: List[Dict], filename: str):
"""Export pools to JSON file."""
with open(filename, "w") as f:
json.dump(pools, f, indent=2)
print(f"\nExported {len(pools)} pools to {filename}")
def main():
parser = argparse.ArgumentParser(
description="Fetch and display DeFi yields from DefiLlama"
)
parser.add_argument(
"--chain", "-c", help="Filter by blockchain (e.g., ethereum, bsc, arbitrum)"
)
parser.add_argument("--token", "-t", help="Filter by token (e.g., bnb, eth, usdc)")
parser.add_argument(
"--min-apy",
"-a",
type=float,
default=0,
help="Minimum APY threshold (default: 0)",
)
parser.add_argument(
"--min-tvl", type=float, default=0, help="Minimum TVL in USD (default: 0)"
)
parser.add_argument(
"--top",
"-n",
type=int,
default=20,
help="Number of top pools to display (default: 20)",
)
parser.add_argument("--export", "-e", help="Export results to JSON file")
parser.add_argument(
"--details", "-d", action="store_true", help="Show additional pool details"
)
parser.add_argument(
"--json-only", action="store_true", help="Only export JSON, no table output"
)
args = parser.parse_args()
print(
f"Fetching yields from DefiLlama at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
)
filters = []
if args.chain:
filters.append(f"chain={args.chain}")
if args.token:
filters.append(f"token={args.token}")
if args.min_apy > 0:
filters.append(f"min_apy={args.min_apy}%")
if args.min_tvl > 0:
filters.append(f"min_tvl=${args.min_tvl:,.0f}")
if filters:
print(f"Filters: {', '.join(filters)}")
pools = fetch_yields(chain=args.chain, token=args.token, min_tvl=args.min_tvl)
if not pools:
print("No pools found.")
return
# Filter by APY
if args.min_apy > 0:
pools = filter_by_apy(pools, args.min_apy)
if not pools:
print(f"No pools found with APY >= {args.min_apy}%.")
return
pools = sort_by_apy(pools)
stats = get_summary_stats(pools)
print(f"\nSummary:")
print(f" Total pools: {stats['total_pools']}")
print(f" Average APY: {stats['avg_apy']:.2f}%")
print(f" Median APY: {stats['median_apy']:.2f}%")
print(f" Max APY: {stats['max_apy']:.2f}%")
print(f" Total TVL: ${stats['total_tvl']:,.0f}")
if not args.json_only:
display_pools(pools, top_n=args.top, show_details=args.details)
if args.export:
export_to_json(pools, args.export)
if __name__ == "__main__":
main()