hedgepod

Create your own AI hedge fund! Made for 23M World users. Deposit once, earn optimally, gasless.

hedgepod

Created At

ETHGlobal Buenos Aires

Winner of

World

World - World Pool Prize

Prize Pool

Project Description

HedgePod Agent is a World mini app that makes 23M World App users their own hedge fund.

Users deposit USDC/ETH/USDT once, and autonomous AI agents handle everything:

📊 Real-Time Data: • Pyth Network price feeds (ETH/USD, BTC/USD, USDC/USD) via Hermes API for instant volatility detection • The Graph subgraphs query real Uniswap v3 liquidity ($245.8M+ TVL) and 24h volume across 5 chains no mock data • 1inch APIs (Swap, Quote, Price, Liquidity Sources) for optimal routing across 50+ DEXs • Supabase PostgreSQL stores agent performance metrics and rebalance history for real-time portfolio analytics

⛓️ Cross-Chain Intelligence: • LayerZero V2 OFT with custom APR-checking logic only moves funds if yield improvement exceeds threshold • Deployed across 8 chains (World Chain, Base, Celo, Zircuit, Polygon, Arbitrum, Optimism, Avalanche) • Batch transfers for gas optimization, emergency circuit breakers for safety

💱 Dynamic Trading: • Uniswap v4 VolatilityFeeHook adjusts swap fees (0.1%-0.3%) based on real-time Pyth volatility data • Protects LPs from impermanent loss during high volatility, increases volume during stable periods • 1inch aggregation finds best routes across all DEXs automatically

🤖 True Autonomy: • Coinbase CDP server wallets operate 24/7 without user interaction • x402 authorization pattern users grant permission once, agents rebalance forever • Pyth Entropy verifiable randomness for fair weekly reward lottery and MEV protection

🌍 Built for Everyone: • World MiniKit SDK integration with SIWE authentication and transaction commands • World ID (Orb-level) verification for sybil resistance no bots allowed • Privy gas sponsorship users NEVER pay fees • ENS everywhere human-readable addresses only (jane.eth not 0x...) • Animal Crossing UI no crypto jargon, 19 languages, consumer-grade polish

The result: Deposit once on any chain. AI agents monitor yields across 8 chains every second, using real Pyth prices, real The Graph liquidity data, and real 1inch routing. When they find a 2%+ APR improvement, LayerZero moves your funds automatically via CDP wallets. Supabase tracks every rebalance with full transaction history. You wake up to better yields. Every day. Gasless. Autonomous. Human.

For the 23M World App users who don't know what an RPC is and never should.

How it's Made

HedgePod Agent is built as a production-grade full-stack autonomous DeFi platform with deep sponsor integrations:

Smart Contracts (Solidity 0.8.24)

  1. AutoYieldToken.sol - Extended LayerZero V2 OFT: • Overrides _debit() with APR-checking logic (not just inherited) blocks transfers to lower-yield chains • Overrides _credit() for analytics tracking and custom event emission • Batch send pattern for gas-optimized multi-chain transfers in single transaction • Emergency circuit breakers (per-chain + global) for safety • Tracks totalCrossChainTransfers and totalGasSaved for on-chain analytics • Deployed across 8 chains with automated setPeers.ts script for LayerZero V2 peer configuration

  2. HedgePodVault.sol - Cross-Chain Vault: • Multi-chain deposit/withdrawal with LayerZero messaging • Grants x402 authorization to CDP agent wallets for recurring operations • Integrates with Uniswap v4 Pool Manager to initialize pools with custom hooks • Chainlink CCIP fallback for critical cross-chain operations

  3. VolatilityFeeHook.sol - Uniswap v4 Dynamic Fee Hook: • Implements beforeSwap() lifecycle hook from Uniswap v4 BaseHook • Fetches Pyth price feed on every swap via IPyth.getPriceNoOlderThan() • Calculates volatility from Pyth confidence intervals (not historical variance) • Adjusts pool fees dynamically: 0.1% (low vol) → 0.2% (medium) → 0.3% (high vol) • Calls IPoolManager.updateDynamicSwapFee() to modify fees before swap executes • LVR mitigation: higher fees during volatility protect LPs from impermanent loss

  4. YieldOracle.sol - Multi-Chain APR Aggregator: • Aggregates Pyth price feeds and Chainlink data across all chains • Provides real-time APR calculations for rebalancing decisions

  5. RandomAgentSelector.sol - Pyth Entropy Integration: • Implements IEntropyConsumer interface for verifiable randomness • Agents register via registerAgent() to enter weekly lottery • Requests randomness via requestWithCallback() with entropy fee • entropyCallback() receives random bytes32, selects agent via modulo • Used for: fair reward distribution, MEV protection (random rebalance order) • Deployed on Base Sepolia with Pyth Entropy contract integration

All deployed across 8 chains using Hardhat 3 with 94% test coverage.

Frontend (Next.js 14 App Router + TypeScript + TailwindCSS)

  1. World MiniKit Integration: • MiniKitProvider wraps entire app (frontend/app/layout.tsx) • SIWE authentication flow via MiniKitWalletAuth.tsx component • Transaction utilities in frontend/lib/minikit.ts: sendTransactionViaMiniKit(), sendContractTransactionViaMiniKit() • Backend SIWE verification route: frontend/app/api/complete-siwe/route.ts • World ID verification via IDKitWidget (Orb-level) for sybil resistance

  2. Real-Time Data Display: • Pyth Network: Live prices, volatility %, dynamic fees auto-refreshes every 30 seconds • The Graph: GraphQL queries for real Uniswap v3 pool data (liquidity $245.8M+, volume, TVL)

    • POOLS_QUERY with orderBy: totalValueLockedUSD DESC, filter > $100K liquidity
    • Multi-chain subgraphs: Ethereum, Base, Optimism, Arbitrum, Polygon
    • frontend/lib/thegraph.ts + frontend/app/api/uniswap/pools/route.ts • 1inch: Swap quotes, price feeds, liquidity sources via frontend/lib/oneinch.ts • All data displayed with "📡 Pyth + The Graph" badge users see what powers decisions
  3. Gasless UX: • Privy SDK for embedded wallets no MetaMask installation needed • ENS resolution everywhere (frontend/lib/ens.ts) users see "alice.eth" not "0x..." • RainbowKit for 100+ wallet options with custom theming

  4. Consumer-Grade Design: • Custom Animal Crossing theme (Nunito/Inter fonts, pastel colors, rounded borders) • Cherry blossom tree sidebar with layered z-index effects • Responsive mobile design (emoji-only nav on small screens) • 19-language support via next-intl (all World App languages)

Backend Autonomous Agents (Node.js + TypeScript)

  1. Coinbase CDP Server Wallets (backend/src/agent/wallet.ts): • Creates CDP wallets via Coinbase SDK: await Wallet.create({ networkId }) • Agents operate 24/7 without user interaction • x402 authorization pattern: user grants permission once, agent executes forever • Invokes contract methods: wallet.invokeContract({ contractAddress, method, args })

  2. Rebalancing Logic (backend/src/agent/rebalancer.ts): • Monitors yields every 60 seconds across all 8 chains • Fetches Pyth prices via backend/src/services/pyth.service.ts (Hermes API pull method) • Calculates APR differentials and compares with gas costs • Only rebalances if APR improvement > threshold (e.g., 2% improvement for 1000 USDC) • Executes via: LayerZero OFT transfers + 1inch optimal routing + CDP wallet • Updates Supabase agent_performance and rebalance_history tables

  3. Real-Time Price Feeds (backend/src/services/pyth.service.ts): • Fetches from Pyth Hermes API: https://hermes.pyth.network/api/latest_price_feeds • Multiple price IDs: ETH/USD, BTC/USD, USDC/USD (configured in config/priceIds.ts) • Calculates volatility from confidence intervals: (conf / price) × 100 • Used by: backend agents, frontend API routes, smart contract hook

  4. GraphQL Subgraph Queries (frontend/lib/thegraph.ts): • Custom GraphQL client with 5-chain support • POOLS_QUERY: fetches top 10 pools by TVL with token pairs, fees, liquidity, volume • 60-second cache revalidation via Next.js ISR for fresh data without rate limits • Error handling with graceful fallback no crashes if subgraph unreachable

  5. 1inch API Integration (frontend/lib/oneinch.ts): • 4 API endpoints: Swap, Quote, Price, Liquidity Sources • Agents use for optimal routing when executing rebalances • Frontend displays real-time quotes with gas estimates and multi-protocol routing

  6. Supabase PostgreSQL Database: • agent_performance table: tracks totalValue, totalRebalances, successfulRebalances, currentAPR, lastRebalanceAt for each agent • rebalance_history table: stores every rebalance with from_chain, to_chain, amount, token, tx_hash, timestamp • Row Level Security (RLS) policies ensure users can only access their own agent data • Real-time queries via @supabase/supabase-js client power portfolio analytics and agent monitoring dashboard • Enables "View History" functionality showing complete rebalance audit trail with explorer links

Key Technical Innovations:

  1. Extended LayerZero OFT (Not Just Inherited): • Problem: Standard OFT allows any transfer. We need yield-aware routing. • Solution: Override _debit() with APR logic only transfers if targetAPR > currentAPR + aprThreshold • Impact: Gas-efficient cross-chain funds only move when profitable • Evidence: contracts/AutoYieldToken.sol lines 112-230

  2. Confidence-Interval Volatility (Not Historical Variance): • Problem: Traditional volatility uses historical price variance (lagging indicator) • Solution: Use Pyth confidence intervals for instant volatility: volatility = (conf / price) × 100 • Impact: More responsive fee adjustments, better LP protection • Evidence: contracts/VolatilityFeeHook.sol lines 85-116

  3. x402 Authorization Pattern: • Problem: Standard DeFi requires user approval for every transaction (terrible UX) • Solution: User grants x402 authorization to CDP agent wallet once, agent executes recurring ops • Impact: True "set it and forget it" autonomous DeFi • Evidence: contracts/HedgePodVault.sol + backend/src/agent/rebalancer.ts

  4. Multi-API Data Layer: • Problem: Mock data is useless for real users and judges know it • Solution: Pyth (prices/volatility) + The Graph (liquidity/volume) + 1inch (routing) all live • Impact: Users make informed decisions with verified on-chain data • Evidence: All data visible live at https://hedgepod.app/swap with source badges

  5. GraphQL Optimization: • Problem: The Graph rate limits on hosted service • Solution: Request only top 10 pools (orderBy TVL), 60s cache, efficient queries • Impact: Fast, reliable data without overwhelming API • Evidence: frontend/lib/thegraph.ts POOLS_QUERY

Particularly Hacky/Notable:

• Layered Cherry Blossom Sidebar: Three separate Image components with absolute positioning and z-index management for tree trunk (z-0), sidebar divs (z-10), and flowers (z-5) to create depth effect • World Chain Rate Limit Fix: Public RPC hit 429 errors switched to env-based Alchemy RPC with fallback • LayerZero Peer Configuration: Custom setPeers.ts script auto-configures trusted peers using lzEid across all 8 chains • Modular Config System: config/networks.ts + config/priceIds.ts manage chain/oracle data for maintainability • Makefile Automation: 50+ commands (make deploy-all, make verify-base-sepolia, make kill-port-3000, etc.) • The Graph Migration: Migrated from deprecated hosted service to decentralized network gateway mid-hackathon • Animal Crossing Theme: Extracted color palette (greens, browns, blush pinks, cream) from hedgehog logo pixel art • Next.js i18n Hack: Built full 19-language support, then temporarily disabled to focus on core features while preserving logic for post-hackathon re-enable

Infrastructure & Deployment:

• Frontend: Vercel (https://hedgepod.app) with custom domain configuration • RPC: Alchemy for all 8 chains (World Chain, Base, Celo, Zircuit, Polygon, Arbitrum, Optimism, Avalanche) • Database: Supabase PostgreSQL with Row Level Security for agent data • Version Control: GitHub with atomic commits, detailed messages, and branch protection • CI/CD: Vercel auto-deploys on push to master with environment variable validation

Tools & Packages

• LayerZero V2: @layerzerolabs/lz-v2-utilities, @layerzerolabs/oapp-evm (OFT extension) • Pyth: @pythnetwork/pyth-sdk-solidity (contracts), @pythnetwork/hermes-client (backend) • Pyth Entropy: @pythnetwork/entropy-sdk-solidity, Fortuna provider on Base Sepolia • Uniswap: @uniswap/v4-core (hooks), @uniswap/v4-periphery (pool manager) • The Graph: Custom fetch client with GraphQL query builder (no SDK lighter bundle) • 1inch: Custom API client (fetch-based) for Swap, Quote, Price, Liquidity APIs • Coinbase CDP: @coinbase/coinbase-sdk for server wallets and x402 authorization • World: @worldcoin/minikit-js (MiniKit), @worldcoin/idkit (World ID) • Frontend: wagmi, viem, @rainbow-me/rainbowkit (wallet), @privy-io/react-auth (gas sponsor) • Testing: Hardhat 3.0, @nomicfoundation/hardhat-toolbox, chai, ethers.js v6 • Database: @supabase/supabase-js for real-time agent performance tracking • Tooling: chalk (colored logs), fs-extra (deployment saves), ethers-v6 (contract interaction)

All code written from scratch during ETHGlobal Buenos Aires 2025 (Nov 21-24), tested with Hardhat 3, and deployed to testnets/mainnets. No pre-existing code (except standard libraries). Production-ready with comprehensive error handling, logging, and monitoring.

background image mobile

Join the mailing list

Get the latest news and updates