Skip to main content

Overview

The useAIAdvisor 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

import { useAIAdvisor } from './hooks/useAIAdvisor';

Hook Signature

function useAIAdvisor({
  address: string,
  stxBalance: string,
  sbtcBalance: string,
  totalUSD: string,
}): {
  strategy: string | null,
  loading: boolean,
  error: string | null,
  riskProfile: string,
  setRiskProfile: (profile: string) => void,
  fetchStrategy: () => Promise<void>,
}

Parameters

address
string
required
User’s Stacks wallet address. Used as context for AI strategy generation.
stxBalance
string
required
User’s STX token balance (e.g., "100.5000"). Must be formatted as a string to preserve precision.
sbtcBalance
string
required
User’s sBTC token balance (e.g., "0.00500000"). Must be formatted as a string with full precision.
totalUSD
string
required
Total portfolio value in USD (e.g., "285.50"). Used by AI to recommend appropriate protocols.

Return Values

strategy
string | null
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
loading
boolean
true while AI is generating a strategy, false otherwise. Use this to show loading indicators.
error
string | null
Error message if strategy generation fails. null if no error. Example: "Failed to generate strategy. Please try again."
riskProfile
string
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
setRiskProfile
function
Update the risk profile. Automatically clears previous strategy and error states.Signature: (profile: string) => voidValid values: "Conservative", "Balanced", "Aggressive"
fetchStrategy
function
Trigger AI strategy generation. Requires address to be set. Automatically manages loading and error states.Signature: () => Promise<void>

Usage Example

import { useWallet } from './hooks/useWallet';
import { usePortfolio } from './hooks/usePortfolio';
import { useAIAdvisor } from './hooks/useAIAdvisor';

function AIStrategyPanel() {
  const { address } = useWallet();
  const { portfolio } = usePortfolio(address);
  
  const { 
    strategy, 
    loading, 
    error, 
    riskProfile, 
    setRiskProfile, 
    fetchStrategy 
  } = useAIAdvisor({
    address,
    stxBalance: portfolio.stxBalance,
    sbtcBalance: portfolio.sbtcBalance,
    totalUSD: portfolio.totalUSD,
  });

  return (
    <div>
      <select 
        value={riskProfile} 
        onChange={(e) => setRiskProfile(e.target.value)}
      >
        <option value="Conservative">Conservative</option>
        <option value="Balanced">Balanced</option>
        <option value="Aggressive">Aggressive</option>
      </select>
      
      <button onClick={fetchStrategy} disabled={loading || !address}>
        {loading ? 'Generating...' : 'Get Strategy'}
      </button>
      
      {error && <div className="error">{error}</div>}
      
      {strategy && (
        <div className="strategy-output">
          <pre>{strategy}</pre>
        </div>
      )}
    </div>
  );
}

State Management

The hook automatically manages several states:
1

Initial State

All states are null or default values. Strategy is not loaded until fetchStrategy() is called.
2

Loading State

When fetchStrategy() is called:
  • loading becomes true
  • error is cleared
  • strategy is cleared (previous strategy is removed)
3

Success State

When AI responds successfully:
  • strategy contains the generated markdown text
  • loading returns to false
  • error remains null
4

Error State

If generation fails:
  • error contains descriptive message
  • loading returns to false
  • strategy remains null

Risk Profile Behavior

The riskProfile state affects AI recommendations:
const { riskProfile, setRiskProfile } = useAIAdvisor({...});

// Change risk profile
setRiskProfile('Aggressive');

// Then regenerate strategy
fetchStrategy();

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:
try {
  const result = await getAIStrategy({...});
  setStrategy(result);
} catch (err) {
  setError('Failed to generate strategy. Please try again.');
  console.error('AI strategy error:', err);
}
Common errors:
  • API key missing or invalid
  • Network request failed
  • Rate limit exceeded
  • Invalid portfolio data

Protocol Integration

The hook automatically includes current protocol data:
import { PROTOCOLS } from '../services/protocolData';

// Passed to AI service automatically
const result = await getAIStrategy({
  address,
  stxBalance,
  sbtcBalance,
  totalUSD,
  riskProfile,
  protocols: PROTOCOLS, // Current protocol list with APY, TVL, etc.
});

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

import { useEffect } from 'react';

function AutoStrategy({ address, stxBalance, sbtcBalance, totalUSD }) {
  const { strategy, loading, fetchStrategy } = useAIAdvisor({
    address, stxBalance, sbtcBalance, totalUSD
  });
  
  // Generate strategy automatically when component mounts
  useEffect(() => {
    if (address) {
      fetchStrategy();
    }
  }, [address]);
  
  return <div>{loading ? 'Loading...' : strategy}</div>;
}

Regenerate on Risk Change

function SmartAdvisor(props) {
  const { riskProfile, setRiskProfile, fetchStrategy } = useAIAdvisor(props);
  
  const handleRiskChange = (newRisk) => {
    setRiskProfile(newRisk);
    // Automatically regenerate with new risk profile
    fetchStrategy();
  };
  
  return (
    <select value={riskProfile} onChange={(e) => handleRiskChange(e.target.value)}>
      <option value="Conservative">Conservative</option>
      <option value="Balanced">Balanced</option>
      <option value="Aggressive">Aggressive</option>
    </select>
  );
}

Build docs developers (and LLMs) love