Skip to main content

Overview

The AI DeFi Copilot analyzes your portfolio and generates personalized Bitcoin DeFi strategies using Google’s Gemini AI. Every strategy is cryptographically hashed and anchored to Bitcoin via Stacks smart contracts, creating an immutable record of AI-generated financial advice.

Key Features

Personalized Strategies

AI analyzes your STX/sBTC balance, risk profile, and transaction history

Bitcoin Anchoring

Every strategy is hashed and anchored on Bitcoin for provenance

Risk Profiles

Choose HODLer (conservative), Builder (balanced), or Degen (aggressive)

Protocol Recommendations

Get specific allocations across Stacks DeFi protocols with APY projections

How It Works

Strategy Generation Flow

1

Select Risk Profile

Choose your preferred risk level:
  • HODLer - Conservative, stable yields (green)
  • Builder - Balanced growth strategy (orange)
  • Degen - High-risk, high-reward (red)
2

AI Analysis

The copilot sends your portfolio data to Gemini AI:
{
  address: 'SP2...',
  stxBalance: 5000,
  sbtcBalance: 0.05,
  totalUSD: 4500,
  riskProfile: 'Builder',
  protocols: [...], // All Stacks protocols with APY data
  strategyCount: 3,
  txCount: 12
}
3

Strategy Delivery

Receive a structured strategy with:
  • Allocation percentages across protocols
  • Projected APY and USD returns
  • Risk assessment and mitigation
  • Step-by-step execution plan
4

Bitcoin Anchoring

Strategy is automatically:
  • Hashed with SHA-256
  • Anchored to Bitcoin via Stacks contract
  • Transaction ID returned for verification

Risk Profiles

HODLer (Conservative)

Best for: Beginners, risk-averse investors, long-term holders
Focus: Capital preservation with stable yields (5-10% APY)
Protocols: StackingDAO, low-risk lending
Sample strategy for new users:
πŸ‘‹ WELCOME TO BITCOIN DEFI
[Warm welcome acknowledging first-time use]

🎯 YOUR FIRST STRATEGY: [Simple recommendation]
πŸ“– WHAT THIS MEANS: [Plain English explanation]
πŸ’° WHAT YOU COULD EARN: [Specific projections]
πŸ›‘οΈ IS IT SAFE?: [Honest risk assessment]
πŸš€ HOW TO START: [Step 1, 2, 3]

Builder (Balanced)

Best for: Active DeFi users, balanced portfolios
Focus: Growth with managed risk (10-15% APY)
Protocols: Mix of lending, yield, and stacking

Degen (Aggressive)

Best for: Experienced traders, high-risk tolerance
Focus: Maximum yield (15%+ APY)
Protocols: Leveraged positions, new protocols, liquidity provision

Strategy Format

For experienced users, strategies include:
🎯 STRATEGY: [Bold one-line recommendation]

πŸ“Š ALLOCATION:
- StackingDAO: 40% ($1,800) - 9.5% APY
- Velar Finance: 30% ($1,350) - 12% APY  
- Zest Protocol: 30% ($1,350) - 15% APY

πŸ’° PROJECTED RETURN:
Weighted APY: 11.8%
Annual Return: ~$531 USD
Monthly: ~$44 USD

⚑ OPTIMIZATION:
[Advanced tactic like compounding, rebalancing, etc.]

⚠️ KEY RISK:
[Most important risk factor to monitor]

πŸš€ EXECUTE NOW:
[Specific next action with protocol name and link]

Bitcoin Anchoring

Every strategy is permanently recorded on Bitcoin:
  1. Strategy Hashing
    const encoder = new TextEncoder();
    const hashBuffer = await crypto.subtle.digest('SHA-256', 
      encoder.encode(strategy));
    const hashHex = Array.from(new Uint8Array(hashBuffer))
      .map(b => b.toString(16).padStart(2, '0'))
      .join('');
    
  2. Smart Contract Anchoring
    (define-public (anchor-strategy (hash (buff 32)) (protocol (string-ascii 50)))
      (ok (map-set strategies 
        { user: tx-sender, strategy-id: (+ (get-strategy-count tx-sender) u1) }
        { hash: hash, protocol: protocol, timestamp: block-height })))
    
  3. Verification
    • Transaction ID links to Stacks Explorer
    • Strategy count badge shows total anchored strategies
    • Immutable proof of AI advice at specific block height
Why anchor on Bitcoin? Creates an immutable, timestamped record of AI-generated financial advice. This enables:
  • Strategy performance auditing
  • AI accountability over time
  • Proof of recommendations for tax/regulatory purposes

User Personalization

The AI adapts recommendations based on:

New Users (0 strategies, fewer than 3 transactions)

  • Extra welcoming tone
  • Simplified explanations of DeFi concepts
  • Single protocol recommendation
  • Safety-first approach
  • Step-by-step guidance

Experienced Users (5+ strategies, 20+ transactions)

  • Skip basic explanations
  • Multi-protocol diversification
  • Advanced optimization tactics
  • Compound yield strategies
  • Bold, confident recommendations

Code Reference

Key implementation files:
  • Component: src/components/AICopilot.jsx - Main UI and logic
  • Service: src/services/aiService.js - Gemini API integration
  • Contract: src/services/contractService.js - Bitcoin anchoring
  • Prompt Engineering: src/services/aiService.js:38-97 - Strategy prompt template

API Integration

The copilot uses Gemini 1.5 Flash:
const response = await fetch(
  'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent',
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      contents: [{ parts: [{ text: prompt }] }],
      generationConfig: {
        temperature: 0.7,
        maxOutputTokens: 1500
      }
    })
  }
);

Demo Mode

Demo mode includes a pre-generated strategy showcasing:
  • Full strategy format
  • Bitcoin anchoring (simulated)
  • All UI interactions
  • No API key required

Advanced Features

Strategy Regeneration

Click Regenerate Strategy to get a new recommendation:
  • Same portfolio data
  • Different protocol mix
  • Updated market conditions
  • New anchored transaction

Strategy Counter

The badge shows total strategies anchored by your address:
⛓️ 3 anchored on Bitcoin
Fetched from Stacks smart contract:
const count = await getStrategyCount(address);
// Returns: BigInt representing total strategies

Troubleshooting

β€œFailed to generate strategy” error:
  • Check that VITE_GEMINI_API_KEY is set in .env
  • Verify API key has Gemini API access enabled
  • Check browser console for detailed error messages
Anchoring fails silently:
  • Strategy will still display, anchoring is non-blocking
  • Ensure wallet has STX for transaction fees
  • Check Stacks network status
Strategy seems generic:
  • Complete more transactions for better personalization
  • Generate multiple strategies to see variation
  • Try different risk profiles

Best Practices

Start Conservative

New to DeFi? Begin with HODLer profile to learn safely

Regular Reviews

Regenerate strategies monthly as your portfolio grows

Verify Anchoring

Click the transaction ID to verify on Stacks Explorer

Compare Protocols

Use Protocol Comparison tool to validate AI recommendations

Next Steps

Yield Calculator

Simulate returns for recommended protocols

Health Score

Check portfolio diversification and risk

Build docs developers (and LLMs) love