Skip to content
This repository was archived by the owner on Dec 2, 2025. It is now read-only.
This repository was archived by the owner on Dec 2, 2025. It is now read-only.

Automated Health Factor Monitoring System #254

@JosueBrenes

Description

@JosueBrenes

Description

Implement an automated background monitoring system that continuously tracks user position health factors and sends proactive alerts before liquidation risk becomes critical. This system will help users avoid liquidations and maintain healthy positions.

What to Implement

  • Background health factor monitoring service
  • Configurable alert thresholds and preferences
  • Multi-channel notification system (in-app, email, browser)
  • Health factor calculation engine with real-time price feeds
  • Position risk assessment and recommendations

Acceptance Criteria

  • Monitor all user positions in real-time
  • Send alerts before liquidation risk (configurable thresholds)
  • Provide actionable recommendations to improve health
  • Support multiple notification channels
  • Efficient monitoring without impacting app performance
  • Historical health factor tracking and analytics

Technical Requirements

Files to Create

  1. Health Monitor Service

    • Path: src/services/health-monitor.service.ts
    • Purpose: Core monitoring logic and orchestration
  2. Health Factor Calculator

    • Path: src/helpers/health-factor.helper.ts
    • Purpose: Health factor calculations and validations
  3. Risk Assessment Engine

    • Path: src/services/risk-assessment.service.ts
    • Purpose: Risk analysis and recommendation generation
  4. Monitoring Hook

    • Path: src/hooks/useHealthMonitoring.ts
    • Purpose: React integration and state management
  5. Health Monitor Types

    • Path: src/@types/health-monitor.entity.ts
    • Purpose: TypeScript interfaces and enums

Files to Modify

  • src/providers/notification.provider.tsx - Integrate health alerts
  • src/components/modules/dashboard/ui/pages/DashboardPage.tsx - Add health monitoring UI
  • User profile settings - Add monitoring preferences

Implementation Details

Health Factor Monitoring

export interface HealthFactorData {
  current: number;
  trend: 'improving' | 'declining' | 'stable';
  riskLevel: RiskLevel;
  timeToLiquidation?: number; // hours until liquidation at current trend
  recommendations: HealthRecommendation[];
  lastUpdated: Date;
}

export enum RiskLevel {
  SAFE = 'safe',           // HF > 2.0
  MODERATE = 'moderate',   // HF 1.5 - 2.0
  HIGH = 'high',          // HF 1.2 - 1.5
  CRITICAL = 'critical'   // HF < 1.2
}

export interface HealthRecommendation {
  type: RecommendationType;
  description: string;
  actionUrl?: string;
  priority: 'low' | 'medium' | 'high';
  estimatedImprovement: number; // HF improvement if action taken
}

Monitoring Thresholds

Default Alert Levels:

  • Warning: Health Factor < 1.8
  • Alert: Health Factor < 1.5
  • Critical: Health Factor < 1.2
  • Emergency: Health Factor < 1.1

Customizable Settings:

  • User-defined threshold levels
  • Notification frequency limits
  • Preferred notification channels
  • Monitoring enable/disable

Real-time Calculation Engine

  1. Price Feed Integration

    • Oracle price data integration
    • Multi-source price validation
    • Price change impact calculation
    • Volatility-based risk adjustment
  2. Position Analysis

    • Collateral value tracking
    • Debt position monitoring
    • Asset correlation analysis
    • Liquidation threshold calculation
  3. Trend Analysis

    • Health factor historical tracking
    • Price movement prediction
    • Volatility impact assessment
    • Time-to-liquidation estimation

Core Features

1. Background Monitoring

  • Web Worker implementation for non-blocking monitoring
  • Configurable monitoring intervals (30s - 5min)
  • Efficient API polling with exponential backoff
  • Local caching to reduce API calls

2. Smart Alerting

  • Risk-based alert frequency
  • Escalating notification urgency
  • Duplicate alert prevention
  • Snooze functionality

3. Recommendation Engine

  • Add Collateral: Specific amounts and assets
  • Repay Debt: Optimal repayment strategies
  • Rebalance Portfolio: Asset allocation suggestions
  • Exit Positions: Gradual position unwinding

4. Historical Analytics

  • Health factor trends over time
  • Risk event history
  • Alert effectiveness metrics
  • User response tracking

Notification Integration

Alert Types

export enum HealthAlertType {
  THRESHOLD_WARNING = 'threshold_warning',
  RAPID_DECLINE = 'rapid_decline',
  PRICE_VOLATILITY = 'price_volatility',
  LIQUIDATION_RISK = 'liquidation_risk',
  RECOVERY_OPPORTUNITY = 'recovery_opportunity'
}

Multi-Channel Notifications

  1. In-App Notifications

    • Toast notifications for immediate alerts
    • Dashboard warning indicators
    • Health factor progress bars
  2. Browser Notifications

    • Critical alerts when app not in focus
    • Configurable notification permissions
    • Rich notification content
  3. Email Notifications (Future)

    • Daily/weekly health summaries
    • Critical alert emails
    • Recommendation reports

Monitoring Architecture

Service Worker Implementation

// health-monitor.worker.ts
class HealthMonitorWorker {
  private monitoring: boolean = false;
  private interval: number = 60000; // 1 minute default

  async startMonitoring(userPositions: Position[]) {
    this.monitoring = true;
    while (this.monitoring) {
      await this.checkHealthFactors(userPositions);
      await this.sleep(this.interval);
    }
  }

  private async checkHealthFactors(positions: Position[]) {
    for (const position of positions) {
      const healthData = await this.calculateHealthFactor(position);
      if (this.shouldAlert(healthData)) {
        await this.sendAlert(position, healthData);
      }
    }
  }
}

Performance Optimizations

  • Position data caching
  • Incremental health factor updates
  • Batch API requests
  • Smart polling intervals based on risk level
  • Memory-efficient monitoring loops

Risk Assessment Features

Liquidation Scenarios

  • Price drop simulations
  • Multi-asset correlation analysis
  • Stress testing under various market conditions
  • Monte Carlo risk modeling

Recommendation Accuracy

  • Historical recommendation tracking
  • User action outcome analysis
  • Algorithm improvement based on results
  • A/B testing for recommendation strategies

UI Components

Health Monitor Dashboard

┌─ Health Factor Overview ────────────┐
│  Current HF: 2.1 ● Safe            │
│  Trend: ↗ Improving (+0.1 in 24h)  │
│  Next Alert: HF < 1.8               │
├─ Position Breakdown ───────────────┤
│  USDC Collateral: $10,000          │
│  XLM Borrowed: $4,500              │
│  Risk Level: ●●○○○ Moderate         │
├─ Recommendations ──────────────────┤
│  • Add $500 USDC to improve HF     │
│  • Consider repaying $200 debt     │
│  • Monitor XLM price volatility    │
├─ Monitoring Settings ──────────────┤
│  ☑ Real-time monitoring enabled    │
│  ☑ Browser notifications          │
│  Alert threshold: [1.8____] [Set]  │
└────────────────────────────────────┘

Alert Settings Interface

  • Threshold configuration sliders
  • Notification channel toggles
  • Alert frequency preferences
  • Historical alert review

Security and Privacy

Data Protection

  • Sensitive data encryption in transit
  • Local storage encryption for user settings
  • No personal data sharing with third parties
  • Compliance with privacy regulations

Monitoring Safety

  • Position data validation
  • Calculation verification
  • Anomaly detection for false alerts
  • Emergency monitoring disable

Integration Requirements

Price Oracle Integration

  • Multiple price feed sources
  • Price update frequency optimization
  • Failover mechanisms for price feeds
  • Price manipulation detection

Blend Protocol Integration

  • Real-time position data fetching
  • Health factor calculation alignment
  • Liquidation threshold accuracy
  • Contract event monitoring

Performance Benchmarks

  • Alert Latency: < 30 seconds from threshold breach
  • Monitoring Overhead: < 5% CPU usage
  • Memory Usage: < 50MB for monitoring service
  • API Efficiency: Batch requests to minimize calls

Dependencies

  • Web Workers API for background processing
  • Real-time price feed APIs
  • Notification system integration
  • Local storage for settings persistence
  • Chart libraries for health factor visualization

Definition of Done

  • Health factor monitoring runs continuously in background
  • Alerts trigger correctly at configured thresholds
  • Recommendations are accurate and actionable
  • User preferences are saved and respected
  • Performance meets efficiency requirements
  • Security measures protect user data
  • Comprehensive testing covers all scenarios
  • Documentation for configuration and usage

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions