Skip to content

Emmy123222/Yield-Hunter

Repository files navigation

YieldHunter - Autonomous DeFi Yield Optimization Agent

YieldHunter is an autonomous agent that continuously monitors NEAR-based DeFi platforms and automatically reallocates funds to maximize yield returns. The agent operates 24/7, analyzing real-time data from multiple protocols and executing smart contract transactions to optimize your DeFi portfolio.

๐ŸŽฏ What YieldHunter Does

Core Functionality

  • Continuous Monitoring: Tracks yield opportunities across NEAR DeFi protocols in real-time
  • Autonomous Decision Making: Analyzes market conditions and automatically moves funds to higher-yielding opportunities
  • Smart Contract Execution: Performs actual blockchain transactions to withdraw, swap, and deposit tokens
  • Risk Assessment: Evaluates protocol safety, lockup periods, and historical volatility
  • Performance Tracking: Logs every decision with detailed reasoning and transaction hashes

Supported NEAR DeFi Protocols

  1. Ref Finance - DEX and liquidity pools
  2. Burrow - Lending and borrowing platform
  3. Meta Pool - NEAR staking and liquid staking

๐Ÿš€ Key Features

Autonomous Agent

  • Real-time Data: Fetches live APY data from NEAR blockchain via RPC calls and protocol APIs
  • Yield Optimization: Automatically identifies and moves to higher-yielding opportunities
  • Transaction Execution: Signs and submits real blockchain transactions using NEAR wallet integration
  • Configurable Parameters: Set minimum yield improvements, check intervals, and risk tolerance

Smart Decision Engine

  • Net Return Calculation: Factors in fees, gas costs, and slippage
  • Risk Analysis: Considers protocol safety ratings and historical performance
  • Threshold Management: Only moves funds when improvement exceeds configured minimums
  • Emergency Controls: Built-in safety mechanisms and emergency stop functionality

Comprehensive Logging

  • Decision Tracking: Every agent action is logged with timestamp, reasoning, and transaction hash
  • Performance Analytics: Track total gains, successful trades, and portfolio improvements
  • Error Monitoring: Comprehensive error logging for debugging and optimization
  • Database Storage: All data persisted to Supabase for analysis and reporting

๐Ÿ—๏ธ Architecture

Frontend Dashboard

  • React + TypeScript: Modern web interface built with Vite
  • NEAR Wallet Integration: Connect with MyNearWallet, HereWallet, or Meteor Wallet
  • Real-time Updates: Live portfolio tracking and agent status monitoring
  • Analytics Dashboard: Visualize yield trends and agent performance

Backend Services

  • NEAR Service: Handles blockchain interactions via near-api-js
  • DeFi Aggregator: Integrates with multiple protocol APIs and smart contracts
  • Yield Agent: Core autonomous decision-making engine
  • Database Layer: Supabase integration for data persistence

Database Schema

-- Agent decisions with full transaction details
agent_decisions (
  id, timestamp, from_protocol, to_protocol, 
  amount, token, reason, old_apy, new_apy, 
  expected_gain, tx_hash, status, gas_used
)

-- Error logging for monitoring and debugging
agent_errors (
  id, timestamp, error_message, stack_trace
)

-- Protocol data caching for performance
protocol_data (
  id, protocol_name, pool_name, apy, tvl, 
  token, fees, net_apy, risk_level
)

๐Ÿ› ๏ธ Setup Instructions

Prerequisites

  • Node.js 18+ and npm
  • NEAR Testnet wallet with test tokens
  • Supabase account and project

Environment Configuration

Create a .env file with:

VITE_SUPABASE_URL=your_supabase_project_url
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key

Installation

# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build

Database Setup

  1. Create a new Supabase project
  2. Run the migration file in supabase/migrations/ to create tables
  3. Configure Row Level Security policies (included in migration)

๐ŸŽฎ How to Use

1. Connect Your Wallet

  • Click "Connect NEAR Wallet" in the top right
  • Authorize the application to interact with your wallet
  • Ensure you have test tokens on NEAR testnet

2. Configure the Agent

  • Navigate to the "Agent" tab
  • Set your preferences:
    • Check Interval: How often to scan for opportunities (hours)
    • Min Yield Improvement: Minimum APY increase required to move funds (%)
    • Max Slippage: Maximum acceptable slippage for trades (%)
    • Dry Run Mode: Test mode that simulates trades without executing

3. Start the Agent

  • Click "Start Agent" to begin autonomous operation
  • Monitor the dashboard for real-time updates
  • View decision logs and transaction history

4. Monitor Performance

  • Dashboard: Overview of portfolio value and active positions
  • Protocols: Real-time APY data from all supported platforms
  • Analytics: Historical yield trends and performance charts
  • Agent Logs: Detailed decision history with reasoning

๐Ÿ”’ Security Features

Wallet Security

  • Non-custodial: Your private keys never leave your wallet
  • Permission-based: Agent only has access to approved contract methods
  • Testnet First: All development and testing on NEAR testnet

Smart Contract Safety

  • Dry Run Mode: Test all operations before going live
  • Emergency Stop: Immediate halt mechanism for the agent
  • Transaction Limits: Configurable maximum amounts and gas limits
  • Error Recovery: Comprehensive error handling and logging

Data Protection

  • Row Level Security: Database access controlled by authentication
  • Encrypted Storage: All sensitive data encrypted in Supabase
  • Audit Trail: Complete transaction history for accountability

๐Ÿ“Š Agent Decision Logic

Opportunity Analysis

  1. Fetch Current Portfolio: Get token balances from connected wallet
  2. Scan Protocols: Query all supported DeFi platforms for current APYs
  3. Calculate Net Returns: Factor in fees, gas costs, and slippage
  4. Risk Assessment: Evaluate protocol safety and lockup periods
  5. Decision Making: Compare opportunities against current allocations

Execution Process

  1. Validate Opportunity: Confirm yield improvement meets thresholds
  2. Prepare Transactions: Construct withdrawal and deposit calls
  3. Execute Trades: Submit signed transactions to NEAR blockchain
  4. Monitor Results: Track transaction status and update records
  5. Log Performance: Record all details for analysis and reporting

๐Ÿ”ง Configuration Options

Agent Parameters

  • Check Interval: 0.1 - 24 hours (how often to scan for opportunities)
  • Min Yield Improvement: 0.1 - 10% (minimum APY increase to trigger move)
  • Max Slippage: 0.1 - 5% (maximum acceptable price impact)
  • Min Amount Threshold: Minimum token amount to consider for moves
  • Emergency Stop: Immediate halt mechanism
  • Dry Run Mode: Simulation mode for testing

Risk Management

  • Protocol Whitelisting: Only interact with approved, audited protocols
  • Amount Limits: Maximum amounts per transaction and per day
  • Gas Limits: Maximum gas spending per transaction
  • Cooldown Periods: Minimum time between moves for same token

๐Ÿ“ˆ Performance Metrics

Tracking & Analytics

  • Total Portfolio Value: Real-time USD value of all holdings
  • Yield Improvements: Cumulative APY gains from agent decisions
  • Transaction Success Rate: Percentage of successful vs failed trades
  • Gas Efficiency: Average gas costs per optimization
  • Protocol Distribution: Allocation across different DeFi platforms

Reporting Features

  • Decision History: Complete log of all agent actions with reasoning
  • Performance Charts: Visual representation of yield trends over time
  • Error Analysis: Detailed logs for troubleshooting and optimization
  • ROI Calculations: Return on investment from agent operations

๐Ÿšจ Important Notes

Testnet Operation

  • Development Phase: Currently operates on NEAR testnet only
  • Test Tokens: Use testnet tokens with no real value
  • Mainnet Ready: Architecture designed for easy mainnet deployment

Risk Disclaimer

  • Experimental Software: This is cutting-edge DeFi automation technology
  • Smart Contract Risk: DeFi protocols carry inherent risks
  • Market Volatility: Cryptocurrency markets are highly volatile
  • No Guarantees: Past performance does not guarantee future results

Best Practices

  • Start Small: Begin with small amounts to test the system
  • Monitor Closely: Regularly check agent decisions and performance
  • Stay Updated: Keep the application updated with latest security patches
  • Backup Data: Regularly export decision logs and performance data

๐Ÿค Contributing

YieldHunter is open for contributions! Areas where help is needed:

  • Additional DeFi protocol integrations
  • Enhanced risk assessment algorithms
  • UI/UX improvements
  • Security audits and testing
  • Documentation and tutorials

๐Ÿ“ž Support

For questions, issues, or feature requests:

  • Check the agent logs in the dashboard
  • Review error messages in the database
  • Monitor NEAR blockchain transaction status
  • Consult NEAR and DeFi protocol documentation

โš ๏ธ Disclaimer: YieldHunter is experimental software for educational and research purposes. Use at your own risk. Always test thoroughly on testnet before considering mainnet deployment.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors