Overview
TheuseAIAdvisor hook provides a React interface to the AI strategy generation service. It manages loading states, error handling, risk profile selection, and strategy caching for a seamless user experience.
Source: src/hooks/useAIAdvisor.js
Import
Hook Signature
Parameters
User’s Stacks wallet address. Used as context for AI strategy generation.
User’s STX token balance (e.g.,
"100.5000"). Must be formatted as a string to preserve precision.User’s sBTC token balance (e.g.,
"0.00500000"). Must be formatted as a string with full precision.Total portfolio value in USD (e.g.,
"285.50"). Used by AI to recommend appropriate protocols.Return Values
The AI-generated strategy text in markdown format.
null before first generation or while loading.Contains:- Welcome message (for new users) or strategy overview
- Specific protocol recommendations
- Allocation percentages
- Projected returns
- Risk assessment
- Step-by-step execution instructions
true while AI is generating a strategy, false otherwise. Use this to show loading indicators.Error message if strategy generation fails.
null if no error. Example: "Failed to generate strategy. Please try again."Current risk profile selection. One of:
"Conservative", "Balanced" (default), or "Aggressive".Affects AI recommendations:- Conservative: Lower APY, established protocols, minimal risk
- Balanced: Mixed allocation, moderate returns
- Aggressive: Higher APY opportunities, newer protocols, higher risk
Update the risk profile. Automatically clears previous strategy and error states.Signature:
(profile: string) => voidValid values: "Conservative", "Balanced", "Aggressive"Trigger AI strategy generation. Requires
address to be set. Automatically manages loading and error states.Signature: () => Promise<void>Usage Example
State Management
The hook automatically manages several states:Initial State
All states are
null or default values. Strategy is not loaded until fetchStrategy() is called.Loading State
When
fetchStrategy() is called:loadingbecomestrueerroris clearedstrategyis cleared (previous strategy is removed)
Success State
When AI responds successfully:
strategycontains the generated markdown textloadingreturns tofalseerrorremainsnull
Risk Profile Behavior
TheriskProfile state affects AI recommendations:
Conservative
Focus: Capital preservationRecommendations:
- Established protocols only
- Lower APY (5-8%)
- Minimal smart contract risk
- Single-asset strategies
Balanced
Focus: Risk-adjusted returnsRecommendations:
- Mix of established and emerging protocols
- Moderate APY (8-15%)
- Diversified allocations
- Multi-protocol strategies
Aggressive
Focus: Maximum yieldRecommendations:
- New and high-yield protocols
- Higher APY (15%+)
- Leverage and compounding
- Advanced strategies
Error Handling
The hook catches and formats errors from the AI service:- API key missing or invalid
- Network request failed
- Rate limit exceeded
- Invalid portfolio data
Protocol Integration
The hook automatically includes current protocol data:Best Practices
Require Address
Always check if
address exists before calling fetchStrategy(). Display a connect prompt if not.Loading Indicators
Show loading state during generation. AI responses can take 2-5 seconds.
Error Display
Always display the
error message to users when strategy generation fails.Strategy Caching
Consider caching strategies in localStorage to avoid unnecessary API calls.
Common Patterns
Automatic Generation on Mount
Regenerate on Risk Change
Related Hooks
- useWallet - Get connected wallet address
- usePortfolio - Fetch portfolio data for AI input
- useProtocols - Browse available DeFi protocols
Related Services
- AI Service - Underlying AI strategy generation service
- Protocol Data - Protocol information used by AI