From 84c0f3374f2e25987ad7d19b4c8d195a9bf8cc93 Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Thu, 18 Dec 2025 15:09:14 -0600 Subject: [PATCH 1/8] Add comprehensive Flow Credit Market (FCM) documentation This commit introduces complete documentation for Flow Credit Market (FCM), a DeFi yield platform that combines automated lending, yield farming strategies, and a synthetic stablecoin. ## Documentation Structure ### ALP (Automated Lending Platform) - 8 documents - Overview and architecture - Credit market mechanics with health factor calculations - Position lifecycle management - Automated rebalancing system - Liquidation mechanisms and safety features - MOET integration and role - DeFi Actions composability framework ### FCM (Flow Credit Market) - 4 documents - Product overview and component integration - Basics tutorial progressing from traditional lending to FCM - Technical architecture with data flow diagrams - Mathematical foundations with formulas and proofs ## Key Features - Visual mermaid diagrams throughout for clarity - Progressive learning path from basics to advanced topics - Cross-referenced sections linking related concepts - Practical examples with real-world scenarios - Mathematical formulas with step-by-step derivations - Professional narrative flow with minimal bullet points ## Content Highlights - Yield-powered liquidation prevention mechanism - Automated capital efficiency through rebalancing - Multi-component architecture (ALP + FYV + MOET) - Complete position lifecycle documentation - Security features and risk management - Integration patterns and best practices This documentation provides comprehensive coverage for users, developers, and DeFi builders looking to understand or integrate with FCM. --- docs/defi/alp/architecture.md | 440 ++++++++++++++ docs/defi/alp/credit-market-mechanics.md | 477 +++++++++++++++ docs/defi/alp/defi-actions.md | 362 ++++++++++++ docs/defi/alp/index.md | 95 +++ docs/defi/alp/liquidation-system.md | 683 ++++++++++++++++++++++ docs/defi/alp/moet-role.md | 437 ++++++++++++++ docs/defi/alp/position-lifecycle.md | 533 +++++++++++++++++ docs/defi/alp/rebalancing.md | 679 ++++++++++++++++++++++ docs/defi/fcm/architecture.md | 510 ++++++++++++++++ docs/defi/fcm/basics.md | 444 ++++++++++++++ docs/defi/fcm/index.md | 184 ++++++ docs/defi/fcm/math.md | 705 +++++++++++++++++++++++ 12 files changed, 5549 insertions(+) create mode 100644 docs/defi/alp/architecture.md create mode 100644 docs/defi/alp/credit-market-mechanics.md create mode 100644 docs/defi/alp/defi-actions.md create mode 100644 docs/defi/alp/index.md create mode 100644 docs/defi/alp/liquidation-system.md create mode 100644 docs/defi/alp/moet-role.md create mode 100644 docs/defi/alp/position-lifecycle.md create mode 100644 docs/defi/alp/rebalancing.md create mode 100644 docs/defi/fcm/architecture.md create mode 100644 docs/defi/fcm/basics.md create mode 100644 docs/defi/fcm/index.md create mode 100644 docs/defi/fcm/math.md diff --git a/docs/defi/alp/architecture.md b/docs/defi/alp/architecture.md new file mode 100644 index 0000000000..8c762db2ec --- /dev/null +++ b/docs/defi/alp/architecture.md @@ -0,0 +1,440 @@ +--- +title: Architecture Overview +sidebar_position: 2 +--- + +# Architecture Overview + +ALP is built on a modular architecture with several core components that work together to provide a secure and efficient lending protocol. + +## Core Components + +```mermaid +graph TB + subgraph "ALP Core" + Pool[Pool
Central Logic Hub] + Position[Position
User Accounts] + TokenState[TokenState
Per-Token Metrics] + Oracle[Price Oracle
Price Feeds] + end + + User[User Wallet] -->|Creates/Manages| Position + Position -->|Operations| Pool + Pool -->|Tracks| TokenState + Pool -->|Queries Prices| Oracle + Pool -->|Stores| Reserves[Token Reserves] + + Position -->|Auto-Push| Sink[DrawDownSink
Automated Flows] + Position -->|Auto-Pull| Source[TopUpSource
Automated Flows] + + style Pool fill:#f9f,stroke:#333,stroke-width:4px + style Position fill:#bbf,stroke:#333,stroke-width:2px +``` + +### Pool + +The **Pool** is the central smart contract that manages all protocol operations. It serves as the primary logic hub for: + +```mermaid +graph LR + subgraph "Pool Responsibilities" + R1[Track All
Positions] + R2[Manage Token
Balances] + R3[Store
Reserves] + R4[Calculate
Interest] + R5[Execute
Liquidations] + end + + R1 --> Pool[Pool Contract] + R2 --> Pool + R3 --> Pool + R4 --> Pool + R5 --> Pool + + style Pool fill:#f9f,stroke:#333,stroke-width:3px +``` + +The Pool tracks global state for all positions, manages credit and debit balances for each supported token, stores reserves as they are deposited, coordinates interest rate calculations, and executes liquidations and rebalancing operations. It maintains a global ledger that tracks the state of each token type, including interest indices, total deposits, total borrows, and reserve factors. + +### Position + +A **Position** represents a user's credit account within the protocol. Each position tracks: + +```mermaid +graph TD + subgraph "Position Components" + C[Collateral
Deposits] + D[Debt
Obligations] + H[Health
Factor] + A[DeFi Actions
Connectors] + end + + C --> Position[Your Position] + D --> Position + H --> Position + A --> Position + + Position --> Operations[Operations:
Deposit, Borrow
Repay, Withdraw] + + style Position fill:#bbf,stroke:#333,stroke-width:3px +``` + +- **Collateral deposits**: Assets deposited to back borrowing +- **Debt obligations**: Amount borrowed against collateral +- **Health factor**: Ratio of collateral value to debt (must stay above 1.0) +- **DeFi Actions connectors**: Optional Sink and Source for automated flows + +Positions are external objects representing ownership of deposited value, with each position capable of holding multiple token balances (both deposits and borrows). They can be configured with different min/max health targets and support composability through DeFi Actions interfaces. + +### TokenState + +Each supported token in the protocol has an associated **TokenState** that tracks per-token metrics: + +```mermaid +graph LR + Token[Token
e.g., FLOW] --> State[TokenState] + + State --> I[Interest
Indices] + State --> TD[Total
Deposits] + State --> TB[Total
Borrows] + State --> CF[Collateral
Factor 0.8] + State --> IR[Interest Rate
Parameters] + + style State fill:#bfb,stroke:#333,stroke-width:2px +``` + +TokenState maintains interest indices for scaled balance calculations, tracks total deposits and borrows for each token, stores the collateral factor (percentage of token value usable as collateral, e.g., 0.8 = 80%), applies borrow factors as multipliers to borrowed amounts, and configures interest rate parameters for rate curves. + +### Scaled Balance System + +ALP uses a **scaled balance** system to track user balances efficiently: + +```mermaid +sequenceDiagram + participant User + participant Position + participant Pool + participant Index + + User->>Position: Borrow 1000 MOET + Position->>Pool: Record balance + Note over Pool: Index = 1.0
Scaled = 1000 / 1.0 = 1000 + + Note over Index: Time passes...
Interest accrues + + Index->>Index: Index grows to 1.05 + + User->>Position: Check balance + Position->>Pool: Query + Pool->>Pool: Calculate: 1000 Γ— 1.05 + Pool-->>User: Balance = 1050 MOET + + Note over User,Index: No transaction needed
for interest to accrue! +``` + +Instead of updating every user's balance when interest accrues, the protocol: + +1. Tracks each user's "scaled balance" (actual balance / interest index) +2. Updates the global interest index as time passes +3. Calculates true balance on-demand as: scaled balance Γ— current interest index + +This means balances grow automatically without requiring transactions, as the interest index increases over time. + +This system is highly gas efficient since it eliminates per-user balance updates, enables automatic compounding for all users simultaneously, provides precise calculations using UFix128 precision, and scales to unlimited users without additional overhead. See [FCM Mathematical Foundations](../fcm/math.md#interest-mathematics) for detailed formulas. + +### Price Oracle + +The **Price Oracle** provides token prices in terms of the default token (MOET): + +```mermaid +graph TB + subgraph "Oracle Safety Features" + S1[Staleness Checks
Price not too old] + S2[Deviation Guards
Prevent extreme moves] + S3[TWAP Support
Time-weighted prices] + S4[Fallback Sources
Redundancy] + end + + Oracle[Price Oracle] --> S1 + Oracle --> S2 + Oracle --> S3 + Oracle --> S4 + + Oracle --> Prices[Token Prices
in MOET terms] + + Prices --> HF[Health Factor
Calculations] + Prices --> Liq[Liquidation
Triggers] + + style Oracle fill:#bfb,stroke:#333,stroke-width:3px +``` + +The oracle implements the DeFi Actions PriceOracle interface, enabling standardized price queries across the protocol. + +The oracle includes multiple safety features: configurable staleness thresholds per token (typically 5 minutes), maximum deviation checks against the last price snapshot, additional DEX price deviation checks during liquidations, and TWAP (Time-Weighted Average Price) support for manipulation resistance. + +## Key Interfaces + +### FungibleToken.Vault + +```mermaid +graph LR + Vault[FungibleToken.Vault
Standard Interface] --> Op1[Deposit
Tokens] + Vault --> Op2[Withdraw
Tokens] + Vault --> Op3[Balance
Queries] + Vault --> Op4[Transfer
Tokens] + + Op1 --> Compat[Flow Ecosystem
Compatibility] + Op2 --> Compat + Op3 --> Compat + Op4 --> Compat + + style Compat fill:#bfb,stroke:#333,stroke-width:2px +``` + +ALP integrates with Flow's standard `FungibleToken.Vault` interface for token operations, ensuring compatibility with all Flow fungible tokens and wallets. + +### DeFi Actions Framework + +ALP implements the **DeFi Actions** framework for protocol composability: + +```mermaid +graph TB + subgraph "Sink Pattern (Push)" + S1[Position
Overcollateralized] --> S2[Auto-Borrow
MOET] + S2 --> S3[Push to
DrawDownSink] + S3 --> S4[User Wallet
or DeFi Protocol] + end + + subgraph "Source Pattern (Pull)" + P1[Position
Undercollateralized] --> P2[Need to
Repay Debt] + P2 --> P3[Pull from
TopUpSource] + P3 --> P4[User Wallet
or DeFi Protocol] + end + + style S1 fill:#bbf + style P1 fill:#fbb +``` + +The **Sink Interface** receives tokens when positions are overcollateralized, automatically pushing borrowed funds to user wallets or other protocols through the `drawDownSink` configuration on positions, enabling automated value flows out of positions. The **Source Interface** provides tokens when positions need rebalancing, automatically pulling funds to repay debt when undercollateralized through the `topUpSource` configuration, enabling automated value flows into positions. + +Learn more: [DeFi Actions Integration](./defi-actions.md) + +### ViewResolver + +The **ViewResolver** interface provides metadata for wallet integration, including position details and balance sheets, supported token types, protocol parameters and configuration, and user-friendly data formatting. This enables wallets and dApps to display ALP positions with rich, contextual information. + +## System Architecture Diagram + +```mermaid +graph TB + User[User Wallet] -->|Deposit/Withdraw| Position[Position] + Position -->|Manages| Pool[Pool Contract] + Pool -->|Stores| Reserves[Token Reserves] + Pool -->|Queries| Oracle[Price Oracle] + Pool -->|Updates| TokenState[TokenState per Token] + Position -->|Auto-Push| Sink[DrawDown Sink] + Position -->|Auto-Pull| Source[TopUp Source] + Pool -->|Liquidates| Liquidator[Liquidators/Keepers] + + style Pool fill:#f9f,stroke:#333,stroke-width:4px + style Position fill:#bbf,stroke:#333,stroke-width:2px + style Oracle fill:#bfb,stroke:#333,stroke-width:2px +``` + +## Data Flow + +### Deposit Flow + +```mermaid +sequenceDiagram + participant User + participant Position + participant Pool + participant TokenState + participant Sink + + User->>Position: deposit() + Position->>Pool: Transfer tokens to reserves + Pool->>Pool: Update scaled balance + Pool->>TokenState: Update totals + Pool->>Pool: Check if overcollateralized + alt Overcollateralized & DrawDownSink enabled + Pool->>Pool: Auto-borrow + Pool->>Sink: Push borrowed tokens + end +``` + +**Steps**: +1. User calls `deposit()` on their Position +2. Position transfers tokens to Pool reserves +3. Pool updates user's scaled balance +4. Pool updates global TokenState +5. If `drawDownSink` enabled and overcollateralized β†’ auto-borrow + +### Borrow Flow + +```mermaid +sequenceDiagram + participant User + participant Position + participant Pool + participant Reserves + + User->>Position: withdraw(debt token) + Position->>Pool: Check health factor + alt Health would remain safe + Pool->>Pool: Update debt scaled balance + Pool->>Reserves: Transfer tokens + Reserves-->>User: Receive tokens + Pool->>Position: Update health + else Health would drop too low + Pool-->>User: Revert: Insufficient health + end +``` + +**Steps**: +1. User calls `withdraw()` for debt token +2. Pool checks health factor would remain above minimum +3. Pool updates user's debt scaled balance +4. Pool transfers tokens from reserves to user +5. Position health is recalculated + +### Interest Accrual + +```mermaid +graph LR + Time[Time Passes] --> Touch[Any Position
Touched] + Touch --> Update[Pool Updates
Interest Index] + Update --> Index[Index Increases
Based on Utilization] + Index --> All[All Positions'
Balances Grow
Automatically] + + style All fill:#bfb,stroke:#333,stroke-width:2px +``` + +**Process**: +1. Time passes, interest accumulates +2. When any position is touched, Pool updates interest indices +3. Interest index increases based on utilization and rates +4. All positions' true balances grow automatically via scaled balance math + +## Security Architecture + +ALP includes multiple layers of security: + +```mermaid +graph TB + subgraph "Security Layers" + L1[Health Factor
Monitoring] + L2[Oracle
Safety] + L3[Liquidation
Mechanisms] + L4[Circuit
Breakers] + L5[Access
Controls] + end + + Protocol[Protocol
Operations] --> L1 + L1 -->|Pass| L2 + L2 -->|Pass| L3 + L3 -->|Pass| L4 + L4 -->|Pass| L5 + L5 -->|Pass| Execute[Execute
Operation] + + style Execute fill:#bfb +``` + +1. **Health factor monitoring**: Continuous tracking of position solvency +2. **Oracle safety**: Staleness and deviation checks +3. **Liquidation mechanisms**: Multiple paths to resolve undercollateralized positions +4. **Circuit breakers**: Ability to pause operations in emergencies +5. **Access controls**: Permissioned functions for admin operations + +## Gas Optimization + +The architecture is optimized for gas efficiency: + +```mermaid +graph LR + subgraph "Gas Optimizations" + O1[Scaled Balances
No per-user updates] + O2[Batch Operations
Multiple in one tx] + O3[Efficient Storage
Compact structures] + O4[Lazy Updates
Calculate on-demand] + end + + O1 --> Result[Minimal
Gas Costs] + O2 --> Result + O3 --> Result + O4 --> Result + + style Result fill:#bfb,stroke:#333,stroke-width:3px +``` + +The architecture is optimized for gas efficiency through scaled balances that eliminate per-user interest updates, batch operations that allow single transactions to update multiple positions, efficient storage using compact data structures for on-chain state, and lazy updates that only calculate interest when needed. + +## Upgradability + +The protocol includes mechanisms for upgrades and parameter adjustments: + +```mermaid +graph TD + Admin[Protocol Admin] --> Functions[Admin Functions] + + Functions --> Rate[Adjust Interest
Rates] + Functions --> Factor[Update Collateral
Factors] + Functions --> Token[Add New
Tokens] + Functions --> Oracle[Switch Price
Feeds] + Functions --> Feature[Enable/Disable
Features] + + Rate --> Protocol[Protocol
Configuration] + Factor --> Protocol + Token --> Protocol + Oracle --> Protocol + Feature --> Protocol + + style Protocol fill:#f9f,stroke:#333,stroke-width:2px +``` + +The protocol supports admin functions to adjust interest rates and collateral factors, dynamic token addition to support new tokens, oracle updates to switch price feed sources, and feature flags to enable or disable features like liquidations. + +## Summary + +**Core Architecture**: +- πŸ—οΈ Modular design with Pool, Position, TokenState, and Oracle +- πŸ”— DeFi Actions framework for composability +- πŸ“Š Scaled balance system for efficiency +- πŸ›‘οΈ Multiple security layers + +**Key Benefits**: +- βœ… Gas efficient scaled balance system +- βœ… Automated flows via Sink/Source interfaces +- βœ… Robust oracle safety features +- βœ… Multi-layer security architecture +- βœ… Flexible and upgradable design + +**Integration Points**: +- Flow FungibleToken standard +- DeFi Actions Sink/Source +- ViewResolver for wallets +- Price Oracle interface + +## Mathematical Foundation + +The architecture implements these mathematical principles: +- **Scaled Balances**: [Interest Mathematics](../fcm/math.md#scaled-balance-system) +- **Health Calculations**: [Health Factor Formula](../fcm/math.md#health-factor) +- **Effective Collateral**: [Collateral Calculation](../fcm/math.md#effective-collateral) +- **Multi-Token Support**: [Multi-Collateral Math](../fcm/math.md#multi-collateral-mathematics) + +See [FCM Mathematical Foundations](../fcm/math.md) for complete formulas and proofs. + +## Next Steps + +- **Understand operations**: [Credit Market Mechanics](./credit-market-mechanics.md) +- **Learn about safety**: [Liquidation System](./liquidation-system.md) +- **Explore automation**: [Position Lifecycle](./position-lifecycle.md) +- **See the big picture**: [FCM Architecture](../fcm/architecture.md) + +--- + +:::tip Key Takeaway +ALP's modular architecture combines efficiency with security. The scaled balance system eliminates gas overhead, DeFi Actions enable composability, and multiple security layers protect users. This design makes ALP both powerful for developers and accessible for users. +::: diff --git a/docs/defi/alp/credit-market-mechanics.md b/docs/defi/alp/credit-market-mechanics.md new file mode 100644 index 0000000000..3f62c435fc --- /dev/null +++ b/docs/defi/alp/credit-market-mechanics.md @@ -0,0 +1,477 @@ +--- +title: Credit Market Mechanics +sidebar_position: 3 +--- + +# Credit Market Mechanics + +ALP operates as a decentralized lending protocol where users can deposit collateral and borrow assets. Understanding the core mechanics is essential for effectively managing positions and maximizing capital efficiency. + +## Basic Lending Mechanics + +### Collateral Deposits + +When you deposit tokens into ALP, they become **collateral** that backs your borrowing capacity. However, not all collateral value is usable for borrowing. + +```mermaid +graph LR + Deposit[Deposit
1000 FLOW
@ $1 each] --> Factor[Apply
Collateral Factor
0.8] + Factor --> Effective[Effective Collateral
$800] + + Effective --> Borrow[Can Borrow
$615 @ HF 1.3] + + style Effective fill:#bfb,stroke:#333,stroke-width:2px +``` + +Each token has a **collateral factor** that determines what percentage of its value can be used. For example, depositing 1,000 FLOW worth $1,000 with a collateral factor of 0.8 results in $800 of effective collateral. This safety buffer protects the protocol against price volatility and ensures positions remain solvent even with market fluctuations. + +### Borrowing Limits + +Your borrowing capacity depends on two key factors: + +1. **Effective Collateral**: Total collateral value Γ— collateral factor +2. **Target Health Ratio**: Minimum ratio of collateral to debt + +**Formula**: +``` +Maximum Borrow = Effective Collateral / Target Health Ratio +``` + +See [FCM Mathematical Foundations](../fcm/math.md#auto-borrowing-mathematics) for detailed formulas and derivations. + +**Example with target health of 1.3**: +- Effective collateral: $800 (from 1,000 FLOW at 0.8 factor) +- Target health: 1.3 +- Maximum borrow: $800 / 1.3 β‰ˆ $615.38 + +### Health Factor + +The **health factor** is the most important metric for your position: + +``` +Health Factor = Effective Collateral Value / Effective Debt Value +``` + +```mermaid +graph TD + subgraph "Health Factor States" + HF1[HF > 1.5
Overcollateralized] + HF2[HF: 1.3 - 1.5
Healthy] + HF3[HF: 1.1 - 1.3
Below Target] + HF4[HF: 1.0 - 1.1
At Risk] + HF5[HF < 1.0
Liquidatable] + end + + HF1 --> Action1[Can borrow more] + HF2 --> Action2[Optimal state] + HF3 --> Action3[Should repay
or add collateral] + HF4 --> Action4[Urgent action
needed] + HF5 --> Action5[Liquidation
imminent] + + style HF1 fill:#bbf + style HF2 fill:#bfb + style HF3 fill:#ffa + style HF4 fill:#fbb + style HF5 fill:#f00,color:#fff +``` + +Your position's health can be understood across a spectrum: when HF > 1.5 you're overcollateralized and can borrow more; HF between 1.3 and 1.5 represents the healthy range; HF between 1.1 and 1.3 means you're below target and should repay or add collateral; HF between 1.0 and 1.1 puts you at risk of liquidation; and HF < 1.0 means your position is liquidatable and requires immediate action. + +## Auto-Borrowing Feature + +ALP includes an innovative **auto-borrowing** feature that automatically manages your position to maintain optimal health ratios. + +### How Auto-Borrowing Works + +```mermaid +sequenceDiagram + participant User + participant ALP + participant DrawDownSink + + User->>ALP: Deposit 1000 FLOW
pushToDrawDownSink=true + ALP->>ALP: Calculate effective
collateral: $800 + ALP->>ALP: Calculate max borrow
at HF 1.3: $615.38 + ALP->>ALP: Auto-borrow 615.38 MOET + ALP->>DrawDownSink: Push MOET + DrawDownSink->>User: Funds deployed + ALP->>User: Position created
HF = 1.3 βœ“ + + Note over User,DrawDownSink: Automatic optimization! +``` + +When you create a position with `pushToDrawDownSink=true`, you deposit collateral (e.g., 1,000 FLOW), the system calculates your maximum safe borrowing capacity, automatically borrows MOET to reach target health (1.3), and sends the borrowed MOET to your DrawDown Sink. + +**Example**: +``` +Deposit 1000 Flow with collateralFactor=0.8 +Target health = 1.3 + +Effective collateral = 1000 * 1.0 (price) * 0.8 = 800 +Auto-borrow amount = 800 / 1.3 β‰ˆ 615.38 MOET + +Result: +- Position health: 1.3 (at target) +- User receives: ~615.38 MOET via DrawDownSink +- Collateral locked: 1000 FLOW +``` + +### Opting Out of Auto-Borrowing + +You can disable auto-borrowing by setting `pushToDrawDownSink=false` when creating your position. With auto-borrowing disabled, your collateral is deposited without any automatic borrowing occurring, your health factor starts very high (>1.5), and you manually borrow when needed. + +### Benefits of Auto-Borrowing + +```mermaid +graph LR + subgraph "Auto-Borrowing Benefits" + B1[Maximized
Capital Efficiency] + B2[Simplified
Management] + B3[Immediate
Liquidity] + B4[Automated
Rebalancing] + end + + B1 --> Result[Optimal
Position] + B2 --> Result + B3 --> Result + B4 --> Result + + style Result fill:#bfb,stroke:#333,stroke-width:3px +``` + +1. **Maximized Capital Efficiency**: Automatically uses available borrowing capacity +2. **Simplified Position Management**: No need to manually calculate safe borrow amounts +3. **Immediate Liquidity**: Receive borrowed funds instantly upon deposit +4. **Automated Rebalancing**: System maintains optimal health as market conditions change + +### When to Use Auto-Borrowing + +**Use auto-borrowing when**: +- You want to maximize capital efficiency +- You're comfortable with leveraged positions +- You trust automated position management +- You want immediate access to borrowed funds + +**Don't use auto-borrowing when**: +- You want conservative collateralization +- You prefer manual position control +- You're testing or learning the protocol +- You don't need immediate borrowing + +## Interest System + +ALP uses a sophisticated interest system based on **scaled balances** and **interest indices**. + +### How Interest Accrues + +```mermaid +graph TD + User[User Borrows
1000 MOET] --> Scaled[Record Scaled Balance
1000 / 1.0 = 1000] + Scaled --> Time[Time Passes] + Time --> Index[Interest Index
Grows to 1.05] + Index --> Current[Current Debt
1000 Γ— 1.05 = 1050] + + Note1[No transaction
needed!] + Time -.-> Note1 + + style Current fill:#fbb +``` + +Instead of updating every user's balance constantly, ALP: + +1. Tracks your **scaled balance**: `actual balance / interest index at deposit` +2. Updates a global **interest index** as time passes +3. Calculates your current balance: `scaled balance Γ— current interest index` + +This means your debt and deposits grow automatically without requiring transactions. + +See [FCM Mathematical Foundations](../fcm/math.md#interest-mathematics) for detailed formulas. + +### Interest Rates + +Interest rates in ALP are determined by the utilization rate (percentage of available capital currently borrowed), a base rate (minimum interest rate when utilization is low), slope rates (how quickly rates increase as utilization rises), and optimal utilization (target utilization for balanced rates). + +```mermaid +graph LR + subgraph "Utilization vs Interest Rate" + Low[0-80%
Low Utilization
Gradual increase] + Opt[80%
Optimal
Target balance] + High[80-100%
High Utilization
Steep increase] + end + + Low --> Opt + Opt --> High + + style Opt fill:#bfb + style High fill:#fbb +``` + +**Typical Rate Curve**: +``` +Low Utilization (0-80%): Gradual rate increase +Optimal Zone (80%): Target balance point +High Utilization (80-100%): Steep rate increase to encourage repayment +``` + +### Compound Interest + +Interest in ALP compounds continuously as the interest index grows, with borrowers paying compound interest on debt, lenders earning compound interest on deposits, and interest index updates reflecting accumulated compounding. + +**Example**: +``` +Initial borrow: 1000 MOET +Interest index at borrow: 1.0 +After 1 year at 10% APY: +- New interest index: ~1.105 (continuous compounding) +- Debt owed: 1000 * 1.105 = 1,105 MOET +``` + +## Price Oracle System + +Accurate pricing is critical for maintaining protocol solvency. ALP uses a price oracle with multiple safety features. + +### Price Feeds + +All token prices are quoted in terms of the **default token** (MOET): + +```mermaid +graph TD + MOET[MOET
Unit of Account] --> P1[FLOW/MOET
Price] + MOET --> P2[USDC/MOET
Price] + MOET --> P3[stFLOW/MOET
Price] + MOET --> P4[Other Tokens
Prices] + + P1 --> Calc[Health Factor
Calculations] + P2 --> Calc + P3 --> Calc + P4 --> Calc + + style MOET fill:#fbb,stroke:#333,stroke-width:3px +``` + +All token prices are quoted in terms of MOET (FLOW/MOET, USDC/MOET, and other token prices), which simplifies calculations and ensures consistency across the protocol. + +### Oracle Safety Features + +```mermaid +graph LR + subgraph "Oracle Protections" + S1[Staleness Checks
<5 min old] + S2[Deviation Guards
Large jumps flagged] + S3[Fallback Sources
Alternative feeds] + S4[TWAP Support
Manipulation resistant] + end + + S1 --> Safe[Safe Price
Feed] + S2 --> Safe + S3 --> Safe + S4 --> Safe + + style Safe fill:#bfb,stroke:#333,stroke-width:3px +``` + +The oracle employs staleness checks to ensure prices are recent (typically < 5 minutes old), deviation guards that reject or flag large price jumps, fallback mechanisms providing alternative price sources if the primary fails, and TWAP support using time-weighted average prices to reduce manipulation risk. + +### How Prices Affect Positions + +Price changes directly impact your health factor: + +```mermaid +graph TD + Initial[Initial State
1000 FLOW @ $1
Debt: $600
HF: 1.67] + + Initial --> Up[Price Increase
FLOW β†’ $1.20] + Initial --> Down[Price Decrease
FLOW β†’ $0.80] + + Up --> UpResult[New HF: 2.0
Can borrow more!] + Down --> DownResult[New HF: 1.33
May trigger rebalancing] + + style UpResult fill:#bfb + style DownResult fill:#ffa +``` + +**Collateral price increases**: Health improves, can borrow more +``` +Before: 1000 FLOW @ $1 = $1000, Debt = $600, HF = 1.67 +After: 1000 FLOW @ $1.20 = $1200, Debt = $600, HF = 2.0 +β†’ Can borrow additional ~$108 MOET +``` + +**Collateral price decreases**: Health worsens, may need to repay +``` +Before: 1000 FLOW @ $1 = $1000, Debt = $600, HF = 1.67 +After: 1000 FLOW @ $0.80 = $800, Debt = $600, HF = 1.33 +β†’ Close to target health, rebalancing may trigger +``` + +## Multi-Token Support + +ALP supports multiple token types as both collateral and debt. + +### Token Configuration + +```mermaid +graph TB + subgraph Collateral + C1[FLOW
Factor: 0.8] + C2[stFLOW
Factor: 0.75] + C3[USDC
Factor: 0.9] + end + + subgraph Debt + D1[MOET
Primary] + D2[FLOW
Alternative] + D3[USDC
Alternative] + end + + C1 --> Health[Single Health
Factor Calculation] + C2 --> Health + C3 --> Health + + D1 --> Health + D2 --> Health + D3 --> Health + + style Health fill:#f9f,stroke:#333,stroke-width:3px +``` + +### Collateral Tokens + +Any supported token can be used as collateral, including Flow, stFlow, USDC, and other allowlisted tokens. Each token has its own collateral factor, price feed, and interest rate parameters. + +### Debt Tokens + +You can borrow multiple token types including MOET (the primary borrowed asset), Flow, USDC, and other allowlisted tokens. Each position can have multiple simultaneous borrows, with health calculated across all assets. + +### Cross-Token Calculations + +When you have multiple tokens, ALP converts all collateral and debt to the default token (MOET) value, calculates a single health factor across all positions, and ensures the total position remains solvent. + +**Example**: +``` +Collateral: +- 1000 FLOW @ $1 each, factor 0.8 = $800 effective +- 500 USDC @ $1 each, factor 0.9 = $450 effective +Total effective collateral: $1,250 + +Debt: +- 800 MOET @ $1 each = $800 debt +Health Factor = 1,250 / 800 = 1.56 βœ“ Healthy +``` + +## Utilization and Protocol Dynamics + +### Utilization Rate + +```mermaid +graph LR + Total[Total Available
Capital] --> Borrowed[Amount
Borrowed] + Total --> Available[Amount
Available] + + Borrowed --> Util[Utilization Rate
Borrowed / Total] + + Util --> Low[Low <80%
Lower rates] + Util --> High[High >80%
Higher rates] + + style Util fill:#bbf,stroke:#333,stroke-width:2px +``` + +The protocol tracks **utilization** for each token: + +``` +Utilization = Total Borrowed / (Total Deposited + Reserves) +``` + +Higher utilization leads to higher interest rates for borrowers, higher yields for lenders, and incentives to add liquidity or repay loans. + +### Reserve Factor + +A portion of interest goes to protocol reserves: + +``` +Lender Interest = Borrower Interest Γ— (1 - Reserve Factor) +``` + +```mermaid +graph LR + Borrower[Borrower Pays
100 Interest] --> Protocol[Protocol
Reserve Factor] + Protocol --> Reserve[20 to
Reserves] + Protocol --> Lender[80 to
Lenders] + + Reserve --> Uses[Insurance Fund
Development
Emergency
Treasury] + + style Reserve fill:#ffa + style Lender fill:#bfb +``` + +Reserves are used for the protocol insurance fund, development and maintenance, emergency situations, and the governance-controlled treasury. + +## Risk Management + +### For Borrowers + +```mermaid +graph TD + subgraph "Borrower Risk Management" + R1[Monitor Health
Factor Daily] + R2[Set Alerts
HF < 1.5] + R3[Diversify
Collateral] + R4[Use Stable
Assets] + R5[Watch Price
Volatility] + end + + R1 --> Safety[Reduced
Liquidation Risk] + R2 --> Safety + R3 --> Safety + R4 --> Safety + R5 --> Safety + + style Safety fill:#bfb,stroke:#333,stroke-width:3px +``` + +Borrowers should monitor their health factor by setting up alerts for HF < 1.5, keeping a buffer above the minimum (1.1), and watching for price volatility. Manage collateral wisely by diversifying across multiple tokens, using stable assets for lower risk, and considering collateral factors when depositing. + +### For Lenders + +Lenders should understand the risks including smart contract risk, liquidation risk (if the protocol becomes undercollateralized), and interest rate volatility. To maximize returns, monitor utilization rates, deposit when rates are high, and consider different tokens for better yields. + +## Summary + +**Core Mechanics**: +- πŸ’° Collateral with safety factors (e.g., 0.8 = 80% usable) +- πŸ“Š Health factor = Effective Collateral / Debt +- πŸ€– Auto-borrowing optimizes capital efficiency +- πŸ“ˆ Scaled balance system for efficient interest + +**Key Formulas**: +- Max Borrow = Effective Collateral / Target Health +- Health Factor = Effective Collateral / Effective Debt +- Utilization = Total Borrowed / Total Available + +**Safety Features**: +- βœ… Oracle staleness checks and deviation guards +- βœ… Multi-token support with unified health calculation +- βœ… Reserve factor for protocol insurance +- βœ… Continuous interest compounding + +## Mathematical Foundation + +For detailed formulas underlying credit market mechanics: +- **Effective Collateral**: [Collateral Calculation](../fcm/math.md#effective-collateral) +- **Health Factor**: [Health Factor Formula](../fcm/math.md#health-factor) +- **Maximum Borrowing**: [Max Borrow Capacity](../fcm/math.md#maximum-borrowing-capacity) +- **Interest Calculations**: [Interest Mathematics](../fcm/math.md#interest-mathematics) +- **Multi-Collateral**: [Multi-Collateral Mathematics](../fcm/math.md#multi-collateral-mathematics) + +## Next Steps + +- **Learn about protection**: [Liquidation System](./liquidation-system.md) +- **Understand the lifecycle**: [Position Lifecycle](./position-lifecycle.md) +- **Explore automation**: [Rebalancing Mechanics](./rebalancing.md) +- **See complete formulas**: [FCM Mathematical Foundations](../fcm/math.md) + +--- + +:::tip Key Takeaway +ALP's credit market mechanics combine automated efficiency with robust safety features. The auto-borrowing feature, scaled interest system, and multi-token support create a powerful yet accessible lending platform. Understanding these mechanics helps you manage positions effectively and maximize your DeFi strategy. +::: diff --git a/docs/defi/alp/defi-actions.md b/docs/defi/alp/defi-actions.md new file mode 100644 index 0000000000..1901feda3c --- /dev/null +++ b/docs/defi/alp/defi-actions.md @@ -0,0 +1,362 @@ +--- +title: DeFi Actions Integration +sidebar_position: 7 +--- + +# DeFi Actions Integration + +DeFi Actions is a composability framework that enables ALP to integrate seamlessly with other DeFi protocols like [Flow Yield Vaults (FYV)](../flow-yield-vaults/index.md). This powerful abstraction allows for automated value flows and complex strategy compositions. + +## Understanding DeFi Actions + +### What are DeFi Actions? + +**DeFi Actions** is a composability framework that provides standardized interfaces for DeFi protocols to interact. Think of it as "LEGO blocks" for DeFi - each protocol provides compatible pieces that snap together. + +**Key concepts**: +- **Source**: An interface for withdrawing/pulling funds (like a faucet) +- **Sink**: An interface for depositing/pushing funds (like a drain) +- **Composability**: Ability to combine protocols seamlessly + +### Why DeFi Actions Matter + +**Without DeFi Actions**, integrating protocols is complex: +1. Withdraw from position manually +2. Check balance +3. Calculate amounts +4. Approve tokens +5. Call other protocol +6. Handle errors +7. Return funds + +**With DeFi Actions**, it's simple and automated: +``` +Position (Source) β†’ Auto-flow β†’ Yield Farm (Sink) +``` + +**Benefits**: DeFi Actions provides simplified integrations through standard interfaces for all protocols, automated flows for set-and-forget value movements, composable strategies that chain multiple protocols together, reduced errors via standardized error handling, and gas efficiency through optimized execution paths. + +## Core Concepts + +### The Sink Pattern (Push) + +A **Sink** receives tokens - it's where funds flow TO. + +**How it works**: +```mermaid +graph LR + ALP[ALP Position] -->|Pushes funds| Sink[Sink Interface] + Sink -->|Deposits to| External[External Protocol] + + style Sink fill:#bbf,stroke:#333,stroke-width:2px +``` + +**Common Sink examples**: Common sink destinations include a user's wallet (simple, default), yield farming protocols (earn returns), liquidity pools (provide liquidity), and other ALP positions (leverage strategies). + +**What ALP's PositionSink does**: The PositionSink receives tokens from external protocols, deposits them into your ALP position as collateral, updates your position balances, and may trigger rebalancing if the position becomes overcollateralized. + +:::info For Developers +ALP implements the Sink interface via `PositionSink`: + +```cadence +// Create a sink that deposits into your position +let sink = position.createSink(type: Type<@MOET.Vault>()) + +// Any MOET sent to this sink goes to your position +externalProtocol.send(to: sink, amount: 100.0) +``` + +See [GitHub](https://github.com/onflow/FlowCreditMarket) for full API documentation. +::: + +### The Source Pattern (Pull) + +A **Source** provides tokens - it's where funds flow FROM. + +**How it works**: +```mermaid +graph LR + External[External Protocol] -->|Requests funds| Source[Source Interface] + Source -->|Pulls from| ALP[ALP Position] + + style Source fill:#bfb,stroke:#333,stroke-width:2px +``` + +**Common Source examples**: Common source origins include a user's wallet (manual funding), yield farming protocols (auto-withdrawal), liquidity pools (exit liquidity), and other ALP positions (cross-position management). + +**What ALP's PositionSource does**: The PositionSource provides tokens to external protocols, may borrow from ALP if withdrawing debt tokens, can pull from TopUpSource if configured, and updates your position balances accordingly. + +**Advanced: TopUpSource Integration** + +A PositionSource can be configured to pull from an external TopUpSource for automatic liquidation prevention: + +1. External protocol requests funds from PositionSource +2. If position has insufficient funds, pulls from TopUpSource +3. TopUpSource might be FYV (yield from your farming) +4. Funds used to repay debt and restore health +5. **Result**: Automatic liquidation protection using your yield! + +:::info For Developers +Create a Source with TopUpSource integration: + +```cadence +// Create source that can pull from TopUpSource for rebalancing +let source = position.createSourceWithOptions( + type: Type<@MOET.Vault>(), + pullFromTopUpSource: true // Enable auto-pull +) +``` + +This enables the yield-powered liquidation prevention that makes [FCM unique](../fcm/basics.md#yield-powered-liquidation-prevention). +::: + +## How ALP Uses DeFi Actions + +### DrawDownSink (When Overcollateralized) + +When your position has **excess borrowing capacity** (health > 1.5), ALP can automatically push funds to a DrawDownSink. + +**The flow**: +```mermaid +sequenceDiagram + participant Position + participant DrawDownSink + participant FYV + + Position->>Position: Health = 1.8 (too high) + Position->>Position: Calculate excess: $200 MOET + Position->>Position: Auto-borrow $200 MOET + Position->>DrawDownSink: Push $200 MOET + DrawDownSink->>FYV: Deploy to yield strategy + FYV->>FYV: Generate returns +``` + +**Common DrawDownSink configurations**: Borrowed funds can flow to your wallet for manual control, be automatically deployed to FYV strategies for yield farming, be added as liquidity to LP pools, or be sent to another position to create leveraged strategies. + +### TopUpSource (When Undercollateralized) + +When your position's health drops **below minimum** (health < 1.1), ALP can automatically pull funds from a TopUpSource. + +**The flow**: +```mermaid +sequenceDiagram + participant FYV + participant TopUpSource + participant Position + + Position->>Position: Price drops! Health = 1.05 + Position->>Position: Calculate needed: $150 MOET + Position->>TopUpSource: Request $150 MOET + TopUpSource->>FYV: Withdraw from yield + FYV->>TopUpSource: Return $150 MOET + TopUpSource->>Position: Provide $150 MOET + Position->>Position: Repay debt, Health = 1.3 βœ“ +``` + +**Common TopUpSource configurations**: Funds can be pulled from your wallet for manual liquidation protection, from FYV strategies for automatic liquidation protection using yield, from LP pools to exit liquidity when needed, or from another position for cross-position risk management. + +:::tip Key Innovation +The **TopUpSource from FYV** is what enables FCM's unique yield-powered liquidation prevention. Your yield automatically protects your position without manual intervention! + +Learn more: [FCM Basics - Yield-Powered Liquidation Prevention](../fcm/basics.md#1-yield-powered-liquidation-prevention) +::: + +## Integration Patterns + +### Pattern 1: Simple Auto-Borrowing + +**Use case**: Borrow against collateral, receive funds in wallet. + +**Setup**: +- DrawDownSink: Your wallet +- TopUpSource: None (manual management) + +**Flow**: +``` +Deposit FLOW β†’ ALP auto-borrows MOET β†’ Funds to your wallet +``` + +**Best for**: Users who want manual control over borrowed funds. + +### Pattern 2: Full FCM Integration + +**Use case**: Maximum automation with yield-powered liquidation prevention. + +**Setup**: +- DrawDownSink: FYV yield strategy +- TopUpSource: FYV yield strategy + +**Flow**: +``` +Deposit FLOW β†’ Auto-borrow MOET β†’ Deploy to FYV β†’ Generate yield +Price drops β†’ FYV provides funds β†’ Repay debt β†’ Health restored +``` + +**Best for**: Users who want set-and-forget yield generation with automatic protection. + +### Pattern 3: Liquidity Provision + +**Use case**: Automatically provide liquidity with borrowed funds. + +**Setup**: +- DrawDownSink: DEX liquidity pool +- TopUpSource: DEX liquidity pool + +**Flow**: +``` +Deposit collateral β†’ Borrow MOET β†’ Add to LP β†’ Earn trading fees +Needs rebalancing β†’ Exit LP position β†’ Repay debt +``` + +**Best for**: Users wanting to earn trading fees on borrowed capital. + +### Pattern 4: Cross-Position Leverage + +**Use case**: Lever position across multiple accounts. + +**Setup**: +- Position 1 DrawDownSink: Position 2 Sink +- Position 2 TopUpSource: Position 1 Source + +**Flow**: +``` +Position 1 borrows β†’ Flows to Position 2 β†’ Position 2 borrows β†’ Repeat +Creates leveraged exposure with automatic risk management +``` + +**Best for**: Advanced users creating complex strategies. + +## Real-World Example: FCM with FYV + +Let's see how a complete FCM setup works with DeFi Actions: + +### Initial Setup + +**You deposit**: 1000 FLOW into ALP position + +**Configuration**: +``` +Position.DrawDownSink = FYV Strategy Sink +Position.TopUpSource = FYV Strategy Source +``` + +### Auto-Borrowing (Overcollateralized) + +``` +1. ALP calculates: Can safely borrow 615 MOET +2. ALP auto-borrows: 615 MOET +3. ALP pushes via DrawDownSink: 615 MOET β†’ FYV +4. FYV swaps: 615 MOET β†’ 615 YieldToken +5. FYV holds: YieldToken, generating yield +``` + +### Price Drop Response (Undercollateralized) + +``` +1. FLOW price drops 20% +2. ALP detects: Health = 1.04 (below 1.1 minimum) +3. ALP calculates: Need to repay 123 MOET +4. ALP pulls via TopUpSource: Request 123 MOET from FYV +5. FYV swaps: 123 YieldToken β†’ 123 MOET +6. FYV provides: 123 MOET to ALP +7. ALP repays: 123 MOET debt +8. Health restored: 1.3 βœ“ +``` + +**Result**: Your yield automatically prevented liquidation! + +## Safety & Best Practices + +### Built-in Safety Features + +1. **Access Control**: Only position owner can create Sources/Sinks +2. **Type Validation**: Ensures token types match +3. **Balance Checks**: Validates sufficient funds before operations +4. **Error Handling**: Graceful failures with clear messages + +### Best Practices + +**Do**: +- βœ… Always configure both DrawDownSink AND TopUpSource for full automation +- βœ… Ensure TopUpSource has sufficient liquidity +- βœ… Monitor your position health regularly +- βœ… Test with small amounts first +- βœ… Understand the external protocol you're integrating with + +**Don't**: +- ❌ Leave TopUpSource empty if you want liquidation protection +- ❌ Assume TopUpSource has unlimited funds +- ❌ Create circular dependencies between positions +- ❌ Ignore gas costs of complex strategies + +### Common Pitfalls + +1. **Insufficient TopUpSource Liquidity** + - **Problem**: TopUpSource runs dry during rebalancing + - **Solution**: Monitor TopUpSource balance, add buffer funds + +2. **Token Type Mismatches** + - **Problem**: Sink expects MOET but receives FLOW + - **Solution**: Always verify token types match + +3. **Gas Limitations** + - **Problem**: Complex DeFi Actions chains hit gas limits + - **Solution**: Simplify strategies or split into multiple transactions + +## Advanced Topics + +:::info For Developers +Looking to build complex strategies? Here are advanced patterns: + +### Multi-Protocol Stacks +Chain multiple protocols together for sophisticated strategies: +``` +ALP β†’ Swap β†’ Farm β†’ Stake β†’ Compound +``` + +### Yield Optimization +Automatically rebalance between multiple positions based on yield: +``` +Monitor yields β†’ Move funds from low-yield β†’ Deploy to high-yield +``` + +### Flash Loan Integration +Use ALP with flash loans for arbitrage opportunities (advanced). + +See [GitHub examples](https://github.com/onflow/FlowCreditMarket/tree/main/examples) for code samples. +::: + +## Summary + +**DeFi Actions enables**: +- πŸ”— Seamless protocol integration +- πŸ€– Automated value flows +- πŸ›‘οΈ Liquidation protection via yield +- 🎯 Complex strategy composition + +**Key patterns**: +- **Sink**: Where funds go (DrawDownSink) +- **Source**: Where funds come from (TopUpSource) +- **Integration**: Connect ALP with FYV, DEXs, farms, etc. + +**FCM's innovation**: Using FYV as both DrawDownSink AND TopUpSource creates yield-powered liquidation prevention - the yield you earn automatically protects your position! + +## Mathematical Foundation + +DeFi Actions enable automated position management based on mathematical rules: +- **Auto-Borrowing Triggers**: [Auto-Borrowing Mathematics](../fcm/math.md#auto-borrowing-mathematics) +- **Rebalancing Calculations**: [Rebalancing Mathematics](../fcm/math.md#rebalancing-mathematics) +- **Health Factor Monitoring**: [Health Factor Formula](../fcm/math.md#health-factor) + +## Next Steps + +- **Learn about MOET**: [MOET's Role](./moet-role.md) +- **Explore rebalancing**: [Rebalancing Mechanics](./rebalancing.md) +- **See the big picture**: [FCM Architecture](../fcm/architecture.md) +- **Understand position lifecycle**: [Position Lifecycle](./position-lifecycle.md) + +--- + +:::tip Key Takeaway +DeFi Actions is the "glue" that makes FCM work. It connects ALP's automated lending with FYV's yield strategies, enabling the unique liquidation prevention mechanism that sets FCM apart from traditional lending protocols. +::: diff --git a/docs/defi/alp/index.md b/docs/defi/alp/index.md new file mode 100644 index 0000000000..9f5a2899ca --- /dev/null +++ b/docs/defi/alp/index.md @@ -0,0 +1,95 @@ +--- +title: Automated Lending Platform (ALP) +sidebar_label: Overview +sidebar_position: 1 +--- + +# Automated Lending Platform (ALP) + +The Automated Lending Platform (ALP) is the core lending protocol component of [Flow Credit Market (FCM)](../fcm/index.md). ALP provides the foundational lending and borrowing infrastructure with automated position management and liquidation protection. + +:::info +ALP is one of three core components that make up FCM: ALP (Automated Lending Platform) provides the lending/borrowing engine, [Flow Yield Vaults (FYV)](../flow-yield-vaults/index.md) handles yield aggregation strategies, and [MOET](../moet/index.md) serves as the synthetic stablecoin and unit of account. +::: + +## What is ALP? + +ALP is a decentralized lending protocol that enables users to deposit collateral to create lending positions, borrow assets against their collateral up to their borrowing limit, earn interest on deposits, and maintain positions through automated rebalancing. + +The protocol uses MOET as its primary unit of account and default borrowed asset, with all prices quoted in MOET terms. + +## Key Innovation: Automated Rebalancing + +ALP's standout feature is its **automated rebalancing** system that uses DeFi Actions to maintain optimal position health. When overcollateralized (health > 1.5), the system automatically borrows more to maximize capital efficiency. When undercollateralized (health < 1.1), it automatically repays debt using yield from FYV. The protocol targets a health range of 1.1 to 1.5 for balanced risk/reward, and prevents liquidations by pulling from TopUpSource (often FYV strategies) when needed. + +### Integration with FYV + +ALP's unique liquidation prevention mechanism leverages yield from Flow Yield Vaults: + +1. User deposits collateral into ALP position +2. ALP auto-borrows MOET to reach target health +3. Borrowed MOET flows into FYV strategy (via DrawDownSink) +4. FYV generates yield on the borrowed MOET +5. If collateral price drops, ALP pulls from FYV (via TopUpSource) to prevent liquidation +6. **Result**: Yield helps maintain position health automatically + +## Core Components + +The protocol consists of four key components: the **Pool** serves as the central contract managing all positions and reserves; each **Position** represents a user's credit account tracking collateral and debt; **TokenState** maintains per-token state including interest indices; and the **Health Factor** measures the ratio of collateral to debt (which must stay above 1.0). + +Learn more in [Architecture Overview](./architecture.md). + +## Documentation Sections + +### Core Concepts +- [Architecture Overview](./architecture.md) - Core components and system design +- [Credit Market Mechanics](./credit-market-mechanics.md) - How lending and borrowing works +- [Position Lifecycle](./position-lifecycle.md) - Creating, managing, and closing positions + +### Advanced Features +- [Rebalancing](./rebalancing.md) - Automated position management +- [Liquidation System](./liquidation-system.md) - Liquidation triggers and mechanisms +- [DeFi Actions](./defi-actions.md) - Protocol composability framework +- [MOET's Role](./moet-role.md) - The unit of account in ALP + +## How ALP Fits into FCM + +```mermaid +graph TB + User[User] -->|Deposits Collateral| ALP[ALP Position] + ALP -->|Auto-borrows MOET| MOET[MOET Token] + MOET -->|Via DrawDownSink| FYV[FYV Strategy] + FYV -->|Generates Yield| Yield[Yield Tokens] + + Price[Price Drop] -.->|Triggers Rebalancing| ALP + ALP -->|Pulls Funds| FYV + FYV -->|Via TopUpSource| ALP + ALP -->|Repays Debt| MOET + + style ALP fill:#f9f,stroke:#333,stroke-width:4px + style FYV fill:#bbf,stroke:#333,stroke-width:2px + style MOET fill:#bfb,stroke:#333,stroke-width:2px +``` + +## Getting Started with ALP + +To use ALP directly: + +1. Ensure you have Flow tokens or other supported collateral +2. Connect your wallet to the Flow blockchain +3. Create a position by depositing collateral +4. Configure DrawDownSink and TopUpSource for automation +5. Monitor your position health + +For most users, we recommend using **[Flow Credit Market (FCM)](../fcm/index.md)** which provides a complete solution combining ALP, FYV, and MOET. + +## Resources + +- [ALP GitHub Repository](https://github.com/onflow/FlowCreditMarket) (FlowCreditMarket contract) +- [Flow Credit Market (FCM)](../fcm/index.md) - The complete product +- [MOET Token Documentation](../moet/index.md) +- [Flow Documentation](https://developers.flow.com) + +## Security Considerations + +ALP includes multiple safety features to protect users and the protocol. The system implements oracle staleness checks and deviation guards to ensure price accuracy, enforces warm-up periods after unpausing liquidations to prevent immediate exploits, provides slippage protection for DEX routes during trades, and continuously monitors health factors with alerts. Always monitor your position health and ensure sufficient collateral to avoid liquidation. diff --git a/docs/defi/alp/liquidation-system.md b/docs/defi/alp/liquidation-system.md new file mode 100644 index 0000000000..4466f7a804 --- /dev/null +++ b/docs/defi/alp/liquidation-system.md @@ -0,0 +1,683 @@ +--- +title: Liquidation System +sidebar_position: 4 +--- + +# Liquidation System + +Liquidations are a critical safety mechanism in ALP that protect the protocol from insolvency. When a position becomes undercollateralized, it can be liquidated to restore the protocol's health and protect lenders. + +## Understanding Liquidations + +### What is Liquidation? + +Liquidation is the process of forcibly closing or partially closing an undercollateralized position by: + +1. Seizing some of the borrower's collateral +2. Using it to repay outstanding debt +3. Returning the position to a healthy state +4. Incentivizing the liquidator with a bonus + +```mermaid +graph LR + A[Position
HF < 1.0] --> B[Liquidator
Detected] + B --> C[Seize
Collateral] + C --> D[Repay
Debt] + D --> E[Position
HF = 1.05 βœ“] + D --> F[Liquidator
Gets Bonus] + + style A fill:#fbb + style E fill:#bfb + style F fill:#bfb +``` + +### Why Liquidations are Necessary + +Liquidations protect the protocol by preventing insolvency through ensuring debt is always backed by sufficient collateral, protecting lenders by guaranteeing depositors can withdraw their funds, maintaining stability by keeping the system solvent during market volatility, and incentivizing monitoring by rewarding participants who help maintain protocol health. + +## Liquidation Triggers + +### Health Factor Threshold + +A position becomes **liquidatable** when its health factor falls below the trigger threshold: + +``` +Liquidation Trigger: Health Factor < 1.0 +``` + +```mermaid +graph TD + subgraph "Health Factor Zones" + Safe[HF β‰₯ 1.1
Safe Zone] + Risk[HF: 1.0 - 1.1
At Risk] + Liq[HF < 1.0
LIQUIDATABLE] + end + + Safe --> Price1[Collateral Price Drop] + Safe --> Price2[Interest Accrual] + Price1 --> Risk + Price2 --> Risk + Risk --> Price3[Further Price Drop] + Price3 --> Liq + + Liq --> Action[Liquidation
Triggered] + + style Safe fill:#bfb + style Risk fill:#ffa + style Liq fill:#fbb + style Action fill:#f00,color:#fff +``` + +**What causes health factor to drop**: + +1. **Collateral price decreases** + - Your FLOW drops from $1 to $0.80 + - Effective collateral value falls + - Health factor decreases proportionally + +2. **Debt accumulation** + - Interest accrues on borrowed amount + - Debt grows over time + - Health factor gradually decreases + +3. **Combination of factors** + - Collateral price drops while interest accrues + - Multiple collateral types move differently + - Debt token price increases relative to collateral + +### Liquidation Target Health + +When a position is liquidated, it's brought to a **target health factor**: + +``` +Liquidation Target Health: 1.05 +``` + +This means not all collateral is seizedβ€”only enough to restore the position to a health factor of 1.05. The position remains open after partial liquidation, and the borrower retains their remaining collateral. + +### Example Liquidation Scenario + +```mermaid +sequenceDiagram + participant Price + participant Position + participant Liquidator + participant Protocol + + Note over Position: Initial: HF = 1.30 βœ“
1000 FLOW @ $1
Debt: 615 MOET + + Price->>Position: FLOW drops to $0.75 + Position->>Position: HF = 0.975 βœ— + + Liquidator->>Liquidator: Detect HF < 1.0! + Liquidator->>Protocol: Liquidate position + Protocol->>Position: Seize ~$146 collateral + Protocol->>Position: Repay debt + Protocol->>Liquidator: Transfer collateral + bonus + + Note over Position: After: HF = 1.05 βœ“
Remaining collateral
Debt partially repaid +``` + +**Numeric example**: +``` +Initial State (Healthy): +- Collateral: 1000 FLOW @ $1 = $1000, factor 0.8 = $800 effective +- Debt: 615.38 MOET @ $1 = $615.38 +- Health Factor: 800 / 615.38 = 1.30 βœ“ + +After FLOW Price Drops to $0.75: +- Collateral: 1000 FLOW @ $0.75 = $750, factor 0.8 = $600 effective +- Debt: 615.38 MOET @ $1 = $615.38 +- Health Factor: 600 / 615.38 = 0.975 βœ— LIQUIDATABLE + +After Liquidation to Target HF 1.05: +- Required effective collateral: 615.38 * 1.05 = $646.15 +- Collateral seized: ~$146.15 worth at market price +- Remaining collateral: ~$453.85 effective +- Health Factor: 646.15 / 615.38 = 1.05 βœ“ +``` + +## Liquidation Mechanisms + +ALP implements three distinct liquidation paths to ensure positions can always be liquidated efficiently. + +```mermaid +graph TB + Liquidatable[Position HF < 1.0] + + Liquidatable --> Path1[Keeper
Repay-for-Seize] + Liquidatable --> Path2[Protocol
DEX Liquidation] + Liquidatable --> Path3[Auto-Liquidation] + + Path1 --> K1[Keeper repays debt] + K1 --> K2[Receives collateral
+ bonus] + + Path2 --> D1[Protocol seizes
collateral] + D1 --> D2[Swaps via DEX
for debt token] + D2 --> D3[Repays position debt] + + Path3 --> A1[Scheduled scan] + A1 --> A2[Batch liquidates
multiple positions] + A2 --> A3[Uses DEX path] + + K2 --> Result[Position HF = 1.05 βœ“] + D3 --> Result + A3 --> Result + + style Liquidatable fill:#fbb + style Result fill:#bfb +``` + +### 1. Keeper Repay-for-Seize + +**How it works**: +1. A keeper (third-party participant) detects an undercollateralized position +2. Keeper repays debt with their own funds +3. Protocol calculates collateral to seize (debt repaid + liquidation bonus) +4. Keeper receives seized collateral +5. Position is brought to target health factor (1.05) + +```mermaid +sequenceDiagram + participant Keeper + participant Protocol + participant Position + + Keeper->>Keeper: Detect position #42
HF = 0.98 + Keeper->>Protocol: Repay 100 MOET debt + Protocol->>Position: Reduce debt by 100 + Protocol->>Protocol: Calculate:
100 + 10% bonus = 110 value + Protocol->>Position: Seize equivalent collateral + Position->>Keeper: Transfer ~108 FLOW + Protocol->>Position: Update HF = 1.05 βœ“ + + Note over Keeper,Position: Keeper profits ~8 MOET value +``` + +**Key characteristics**: The system is permissionlessβ€”anyone can act as a keeperβ€”and incentivized, with keepers earning a liquidation bonus (typically 5-10%). It's precise, using only the exact amount needed, and instant, with a single transaction resolving the liquidation. + +**Benefits**: This approach enables fast response to undercollateralization, distributed monitoring through many keepers, market-driven efficiency, and eliminates protocol DEX dependency. + +### 2. Protocol DEX Liquidation + +**How it works**: +1. Protocol detects undercollateralized position +2. Protocol seizes collateral from position +3. Protocol swaps collateral via allowlisted DEX +4. Swap output is used to repay debt +5. Any remainder is returned appropriately +6. Position is brought to target health factor + +```mermaid +sequenceDiagram + participant Protocol + participant Position + participant DEX + participant Oracle + + Protocol->>Position: Detect HF = 0.98 + Protocol->>Oracle: Get FLOW price + Oracle-->>Protocol: $0.98 per FLOW + Protocol->>Position: Seize 150 FLOW + Protocol->>DEX: Swap 150 FLOW + DEX-->>Protocol: Return ~147 MOET + Protocol->>Protocol: Check slippage
vs oracle price + Protocol->>Position: Repay 147 MOET + Position->>Position: HF = 1.05 βœ“ + + Note over Protocol,Position: Slippage protection ensures
fair liquidation price +``` + +**Key characteristics**: Protocol DEX liquidation is protocol-executed (no external keeper needed), integrates with decentralized exchanges for swaps, includes slippage protection through maximum deviation checks versus oracle prices, and can be automated by either the protocol or keepers. + +**Slippage Protection**: + +The protocol ensures the DEX price doesn't deviate too much from the oracle price, preventing manipulation and unfair liquidations. + +**Example Flow**: +``` +Position #42: 1000 FLOW collateral, 650 MOET debt, HF = 0.98 +↓ +Protocol seizes 150 FLOW +↓ +Swaps via DEX: 150 FLOW β†’ ~147 MOET (with slippage check) +↓ +Repays 147 MOET to position debt +↓ +Position: 850 FLOW collateral, 503 MOET debt, HF = 1.05 βœ“ +``` + +### 3. Auto-Liquidation + +**How it works**: +1. Scheduled automation or keeper triggers scan +2. System identifies all undercollateralized positions +3. For each position, executes DEX liquidation path +4. Subject to same oracle and DEX safety checks +5. Events emitted for each liquidation + +```mermaid +graph TD + Timer[Scheduled
Trigger] --> Scan[Scan All
Positions] + Scan --> Check{HF < 1.0?} + Check -->|Yes| Batch[Add to
Liquidation Batch] + Check -->|No| Skip[Skip] + Batch --> Max{Reached
max batch?} + Max -->|No| Check + Max -->|Yes| Execute[Execute DEX
Liquidations] + Execute --> Events[Emit
Events] + + style Execute fill:#f9f,stroke:#333,stroke-width:2px +``` + +**Key characteristics**: Auto-liquidation can run on a scheduled timer (e.g., every block or every minute), handle multiple positions through batch processing, apply the same warm-up and deviation safety checks, and provide detailed event logging per position. + +**Benefits**: This mechanism provides hands-free liquidation protection, guaranteed execution that's not dependent on keeper availability, integration capability with off-chain automation, and serves as a protocol safety net. + +## Safety Features + +ALP includes multiple safety mechanisms to ensure liquidations are fair and protect against manipulation. + +```mermaid +graph TB + subgraph "Safety Layers" + S1[Oracle Staleness
Checks] + S2[Oracle Deviation
Guards] + S3[DEX Price
Deviation] + S4[Liquidation
Warm-up] + S5[Circuit
Breakers] + end + + Liquidation[Liquidation
Request] --> S1 + S1 -->|Pass| S2 + S2 -->|Pass| S3 + S3 -->|Pass| S4 + S4 -->|Pass| S5 + S5 -->|Pass| Execute[Execute
Liquidation] + + S1 -->|Fail| Revert[Revert:
Stale price] + S2 -->|Fail| Revert2[Revert:
Large deviation] + S3 -->|Fail| Revert3[Revert:
DEX manipulation] + S4 -->|Fail| Revert4[Revert:
Still warming up] + S5 -->|Fail| Revert5[Revert:
Paused] + + style Execute fill:#bfb +``` + +### Oracle Staleness Checks + +Prices must be recent and valid: + +``` +- Maximum age: staleThreshold (typically 5 minutes) +- If price is too old: liquidation reverts +- Per-token configuration: different tokens can have different thresholds +``` + +**Why this matters**: +- Prevents liquidations based on stale/incorrect prices +- Ensures fairness during oracle downtime +- Protects borrowers from false liquidations + +### Oracle Deviation Guards + +Large price movements are checked: + +``` +maxDeviationBps: Maximum change vs last price snapshot +Example: 1000 bps = 10% maximum deviation + +If price moves >10% in single update: +- Liquidation may be paused or rejected +- Additional verification required +- Protects against oracle manipulation +``` + +### DEX Price Deviation + +For DEX-based liquidations, the swap price must align with oracle: + +``` +dexOracleDeviationBps: Maximum deviation between DEX and oracle + +Example: +- Oracle price: 1 FLOW = 1 MOET +- DEX swap: 150 FLOW β†’ 145 MOET +- Deviation: ~3.3% β‰ˆ 333 bps + +If deviation > dexOracleDeviationBps: +- Liquidation reverts +- Prevents MEV exploitation +- Ensures fair liquidation prices +``` + +### Liquidation Warm-up Period + +After the protocol is unpaused, liquidations have a warm-up delay: + +```mermaid +timeline + title Protocol Unpause Timeline + Paused : Protocol offline + : No operations allowed + T+0 : Protocol unpauses + : Trading resumes + : Liquidations still disabled + T+300s : Warm-up complete + : Liquidations enabled + : Full functionality restored +``` + +**Configuration**: +``` +liquidationWarmupSec: Delay after unpause before liquidations enabled +Example: 300 seconds (5 minutes) + +Why: +- Gives borrowers time to add collateral +- Prevents immediate liquidations after downtime +- Allows prices to stabilize +``` + +### Circuit Breakers + +Protocol can pause liquidations in emergencies: + +``` +liquidationsPaused: Boolean flag + +When true: +- All liquidation functions revert +- Positions cannot be liquidated +- Borrowing may also be restricted +- Used during emergencies, upgrades, or oracle issues +``` + +## Liquidation Incentives + +### Liquidation Bonus + +Keepers earn a bonus for performing liquidations: + +```mermaid +graph LR + Keeper[Keeper Repays
100 MOET] --> Protocol[Protocol
Calculates] + Protocol --> Bonus[Seize Value:
108 MOET equivalent] + Bonus --> Profit[Keeper Profit:
8 MOET 8% bonus] + + style Profit fill:#bfb,stroke:#333,stroke-width:2px +``` + +**Example**: +``` +Typical bonus: 5-10% of repaid debt + +- Keeper repays: 100 MOET +- Collateral value at liquidation bonus: ~108 MOET equivalent +- Keeper profit: ~8 MOET (8% bonus) + +Formula: +Collateral Seized = (Debt Repaid * (1 + Liquidation Bonus)) / Collateral Price +``` + +### Economic Dynamics + +```mermaid +graph TD + subgraph "Liquidation Economics" + A[Small Position] --> A1[Low profit
after gas] + A1 --> A2[May not be liquidated
by keepers] + + B[Large Position] --> B1[High profit
covers gas easily] + B1 --> B2[Attractive to keepers] + + A2 --> Backup[Auto-liquidation
provides backup] + B2 --> Competition[Multiple keepers
compete] + end + + style Backup fill:#bfb + style Competition fill:#bbf +``` + +**Considerations**: +- **Gas Costs**: Profitability = Liquidation Bonus - Gas Costs +- **Position Size**: Small positions may not be profitable to liquidate +- **Competition**: Multiple keepers compete for liquidations (first come, first served) +- **MEV**: Sophisticated keepers may use advanced techniques +- **Safety Net**: Auto-liquidation provides backup for unprofitable liquidations + +## Liquidation Events and Monitoring + +### Monitoring Your Position + +```mermaid +graph TD + Monitor[Monitor Health Factor] --> Check{HF Status?} + + Check -->|HF > 1.3| Safe[Safe
Continue monitoring] + Check -->|HF: 1.1-1.3| Warning[Early Warning
Consider adding collateral] + Check -->|HF: 1.0-1.1| Urgent[Urgent!
Immediate action needed] + Check -->|HF < 1.0| Critical[CRITICAL
Position liquidatable!] + + Warning --> Actions1[Add collateral
or repay debt] + Urgent --> Actions2[Add substantial collateral
or repay significant debt] + Critical --> Actions3[Emergency measures
May be too late] + + style Safe fill:#bfb + style Warning fill:#ffa + style Urgent fill:#fbb + style Critical fill:#f00,color:#fff +``` + +To avoid liquidation, you should set up alerts to monitor when health factor drops below 1.3, watch collateral token prices closely, monitor interest accrual since debt grows over time, use automation through auto-rebalancing or auto-repayment, and maintain a safety buffer by keeping your health factor well above 1.1. + +### Liquidation Warning Signs + +**Early warnings** (HF = 1.3 β†’ 1.1): +- Time to add collateral or repay debt +- Rebalancing may trigger automatically +- Still safe but approaching risk zone + +**Urgent warnings** (HF = 1.1 β†’ 1.0): +- Immediate action required +- Liquidation imminent if health continues to drop +- Add substantial collateral or repay significant debt + +**Critical** (HF < 1.0): +- Position is liquidatable +- May be liquidated at any moment +- Severe consequences (loss of collateral with liquidation penalty) + +## Protecting Against Liquidation + +### Protection Strategies + +```mermaid +graph LR + subgraph "Prevention Strategies" + S1[Conservative
Collateralization
HF > 1.5] + S2[Diversified
Collateral
Multiple tokens] + S3[Regular
Monitoring
Daily checks] + S4[Quick Response
TopUpSource
configured] + S5[Stable
Collateral
Lower volatility] + end + + S1 --> Protection[Liquidation
Protection] + S2 --> Protection + S3 --> Protection + S4 --> Protection + S5 --> Protection + + style Protection fill:#bfb,stroke:#333,stroke-width:3px +``` + +1. **Conservative collateralization**: + - Target health factor > 1.5 + - Provides buffer against price drops + - Reduces liquidation risk + +2. **Diversified collateral**: + - Use multiple token types + - Reduces impact of single token price drop + - Improves overall stability + +3. **Regular monitoring**: + - Check health factor daily + - Set up alerts and notifications + - Use automation tools + +4. **Quick response capability**: + - Keep liquid funds available + - Set up TopUpSource for auto-repayment + - Have repayment transactions ready + +5. **Use stable collateral**: + - Stablecoins have lower volatility + - Higher collateral factors + - More predictable liquidation risk + +### Recovery from Near-Liquidation + +If your health factor is approaching 1.0, you have three options: + +```mermaid +graph TD + Crisis[Health Factor < 1.1
Approaching Liquidation] --> Option1[Option 1:
Add Collateral] + Crisis --> Option2[Option 2:
Repay Debt] + Crisis --> Option3[Option 3:
Trigger Rebalancing] + + Option1 --> Deposit[Deposit more tokens] + Deposit --> Result1[Increases effective collateral
Improves HF] + + Option2 --> Repay[Repay MOET debt] + Repay --> Result2[Decreases debt
Improves HF] + + Option3 --> AutoPull[Auto-pulls from TopUpSource] + AutoPull --> Result3[Automatically repays debt
Improves HF] + + Result1 --> Safe[Health Factor > 1.1 βœ“] + Result2 --> Safe + Result3 --> Safe + + style Crisis fill:#fbb + style Safe fill:#bfb +``` + +:::info For Developers +```cadence +// Option 1: Add collateral +position.deposit(collateralVault: <-additionalFLOW) + +// Option 2: Repay debt +position.repay(repaymentVault: <-moetRepayment) + +// Option 3: Trigger rebalancing (if TopUpSource configured) +pool.rebalancePosition(pid: yourPositionID, force: true) +``` + +See [GitHub](https://github.com/onflow/FlowCreditMarket) for complete API documentation. +::: + +## Advanced Topics + +### Partial vs Full Liquidation + +```mermaid +graph LR + Position[Liquidatable
Position] --> Check{Sufficient
collateral?} + + Check -->|Yes| Partial[Partial Liquidation] + Partial --> P1[Seize portion
of collateral] + P1 --> P2[Repay portion
of debt] + P2 --> P3[HF = 1.05
Position remains open] + + Check -->|No| Full[Full Liquidation
Rare case] + Full --> F1[Seize all
collateral] + F1 --> F2[Repay maximum
possible debt] + F2 --> F3[Position closed
Protocol may take loss] + + style Partial fill:#bbf + style Full fill:#fbb +``` + +- **Partial liquidation**: Position brought to target health (1.05), remains open (most common) +- **Full liquidation**: Rare; only if position value can't cover debt + bonus + +### Multi-Collateral Liquidations + +When position has multiple collateral types: +- Liquidation logic prioritizes based on configuration +- May seize from multiple collateral types +- Calculation ensures fair distribution + +### Flash Loan Liquidations + +Advanced keepers may use flash loans for zero-capital liquidations: + +```mermaid +sequenceDiagram + participant Keeper + participant FlashLoan + participant Protocol + participant DEX + + Keeper->>FlashLoan: Flash borrow MOET + FlashLoan-->>Keeper: 100 MOET (+ fee) + Keeper->>Protocol: Liquidate with borrowed MOET + Protocol-->>Keeper: Receive collateral + Keeper->>DEX: Swap collateral β†’ MOET + DEX-->>Keeper: ~108 MOET + Keeper->>FlashLoan: Repay 100 MOET + fee + Keeper->>Keeper: Keep profit! + + Note over Keeper: No upfront capital needed! +``` + +This allows liquidations without upfront capital. + +## Summary + +**Liquidation Triggers**: +- 🚨 Health Factor < 1.0 (undercollateralized) +- πŸ“‰ Collateral price drops or interest accrual +- 🎯 Target: Restore HF to 1.05 after liquidation + +**Three Liquidation Paths**: +1. **Keeper Repay-for-Seize**: Third parties repay debt, earn bonus +2. **Protocol DEX Liquidation**: Automated swap and repayment +3. **Auto-Liquidation**: Scheduled batch processing + +**Safety Features**: +- βœ… Oracle staleness checks +- βœ… Oracle deviation guards +- βœ… DEX price deviation limits +- βœ… Liquidation warm-up periods +- βœ… Circuit breakers for emergencies + +**Protection Strategies**: +- Maintain HF > 1.5 for safety buffer +- Set up TopUpSource for auto-protection +- Monitor positions regularly +- Use stable collateral when possible +- Diversify collateral types + +## Mathematical Foundation + +For detailed liquidation formulas and calculations: +- **Liquidation Trigger Math**: [Liquidation Mathematics](../fcm/math.md#liquidation-mathematics) +- **Collateral Seized Calculation**: [Collateral Seized Formula](../fcm/math.md#collateral-seized-calculation) +- **Health Factor Formulas**: [Health Factor Definition](../fcm/math.md#health-factor) +- **Maximum Price Drop**: [Safe Price Drop Calculations](../fcm/math.md#maximum-safe-price-drop) + +## Next Steps + +- **Understand automation**: [Rebalancing Mechanics](./rebalancing.md) +- **See the big picture**: [Position Lifecycle](./position-lifecycle.md) +- **Explore credit mechanics**: [Credit Market Mechanics](./credit-market-mechanics.md) +- **Learn prevention strategies**: [FCM Yield-Powered Protection](../fcm/basics.md#yield-powered-liquidation-prevention) + +--- + +:::tip Key Takeaway +Liquidations are a last resort safety mechanism. With proper monitoring, conservative collateralization, and automation (especially [FCM's yield-powered protection](../fcm/basics.md#yield-powered-liquidation-prevention)), you can avoid liquidation entirely. The system is designed to give you ample warning and multiple recovery options before liquidation occurs. +::: diff --git a/docs/defi/alp/moet-role.md b/docs/defi/alp/moet-role.md new file mode 100644 index 0000000000..870ee234ca --- /dev/null +++ b/docs/defi/alp/moet-role.md @@ -0,0 +1,437 @@ +--- +title: MOET's Role in ALP +sidebar_position: 8 +--- + +# MOET's Role in ALP + +MOET plays a central role in ALP as the default token and primary unit of account. Understanding MOET's function is essential for effectively using ALP and [Flow Credit Market (FCM)](../fcm/index.md). + +## What is MOET? + +**MOET** is a fungible token on Flow that serves as: +- πŸ’° **The primary borrowed asset** - What you borrow from ALP +- πŸ“Š **The unit of account** - All prices quoted in MOET terms +- πŸ”„ **The rebalancing medium** - Used for all automated operations +- πŸŒ‰ **The value bridge** - Flows between ALP and FYV + +For more about MOET tokenomics, see the [MOET documentation](../moet/index.md). + +## MOET as Unit of Account + +Think of MOET as the "common language" for all value in ALP - like how everything in a store is priced in dollars. + +### All Prices in MOET Terms + +```mermaid +graph TD + MOET[MOET
Unit of Account] + MOET --> FLOW[FLOW = 1.0 MOET] + MOET --> USDC[USDC = 1.0 MOET] + MOET --> stFLOW[stFLOW = 1.05 MOET] + MOET --> Other[Other tokens...] + + style MOET fill:#fbb,stroke:#333,stroke-width:4px +``` + +**Why this matters**: Using MOET as the unit of account simplifies calculations by expressing all values in one currency, standardizes pricing consistently across all tokens, enables multi-collateral positions by making it easy to compare different assets, and provides unified risk management through a single health metric. + +**Health factor calculation example**: +``` +Collateral: 1000 FLOW @ 1.0 MOET each Γ— 0.8 factor = 800 MOET value +Debt: 615.38 MOET +Health Factor = 800 / 615.38 = 1.30 + +All in MOET terms = Simple and consistent! +``` + +:::tip Why Not Just Use USD? +MOET is designed specifically for Flow DeFi, ensuring deep on-chain liquidity, native protocol integration, optimized performance for Flow operations, and better composability with FYV and other protocols. +::: + +## MOET in the Auto-Borrowing Flow + +When you deposit collateral with auto-borrowing enabled, MOET is what you borrow: + +```mermaid +sequenceDiagram + participant User + participant ALP + participant MOET + + User->>ALP: Deposit 1000 FLOW + ALP->>ALP: Calculate: 1000 Γ— 0.8 = 800 effective + ALP->>ALP: Target health: 1.3 + ALP->>ALP: Can borrow: 800 / 1.3 = 615.38 + ALP->>MOET: Auto-borrow 615.38 MOET + MOET->>User: Receive 615.38 MOET + ALP->>ALP: Health = 1.3 βœ“ + + Note over User,MOET: All automatic, no manual steps! +``` + +**Why MOET?** +1. **Standardization**: One primary asset simplifies everything +2. **Liquidity**: MOET designed for high liquidity +3. **Predictability**: You always know what you'll receive +4. **Efficiency**: No token choice complexity + +## MOET in Rebalancing + +### Overcollateralized: Borrow More MOET + +When health rises above 1.5 (too safe), ALP automatically borrows more MOET: + +```mermaid +graph LR + A[Health > 1.5
Too Safe] --> B[Calculate Excess] + B --> C[Auto-borrow MOET] + C --> D[Push to DrawDownSink] + D --> E[Health = 1.3 βœ“] + + style A fill:#bfb + style E fill:#bfb +``` + +**Example**: +``` +State: $1000 effective collateral, $400 MOET debt +Health: 1000 / 400 = 2.5 (way too high!) + +Action: Borrow 769.23 - 400 = 369.23 more MOET +Result: $1000 / $769.23 = 1.3 (perfect!) +``` + +### Undercollateralized: Repay MOET + +When health drops below 1.1 (risky), ALP automatically repays MOET debt: + +```mermaid +graph LR + A[Health < 1.1
Risky!] --> B[Calculate Shortfall] + B --> C[Pull from TopUpSource] + C --> D[Repay MOET debt] + D --> E[Health = 1.3 βœ“] + + style A fill:#fbb + style E fill:#bfb +``` + +**Example**: +``` +State: $640 effective collateral (price dropped!), $615.38 MOET debt +Health: 640 / 615.38 = 1.04 (danger zone!) + +Action: Repay 615.38 - 492.31 = 123.07 MOET +Result: $640 / $492.31 = 1.3 (safe again!) +``` + +**Math reference**: See [FCM Mathematical Foundations](../fcm/math.md#auto-borrowing-mathematics) for auto-borrowing formulas and [Rebalancing Mathematics](../fcm/math.md#rebalancing-mathematics) for rebalancing calculations. + +## MOET Flow Patterns + +### Pattern 1: Simple Borrowing + +**Use case**: Borrow MOET, use it yourself + +```mermaid +graph LR + User[Deposit FLOW] --> ALP[ALP Position] + ALP --> Auto[Auto-borrow MOET] + Auto --> Wallet[Your Wallet] + Wallet --> Use[Use MOET
Yield/Trading/etc] + + style ALP fill:#f9f,stroke:#333,stroke-width:2px +``` + +**Flow**: Collateral β†’ Borrow MOET β†’ You control it + +### Pattern 2: FCM Integration (Full Automation) + +**Use case**: Maximum automation with FYV + +```mermaid +graph TB + User[Deposit FLOW] --> ALP[ALP Position] + ALP -->|Auto-borrow| MOET[MOET] + MOET -->|DrawDownSink| FYV[FYV Strategy] + FYV -->|Generate Yield| Yield[Yield Tokens] + + Price[Price Drop] -.->|Triggers| Rebal[Rebalancing] + Rebal -->|Pull via TopUpSource| FYV + FYV -->|Provide MOET| ALP + ALP -->|Repay| MOET + ALP -->|Health Restored| Safe[Health = 1.3 βœ“] + + style ALP fill:#f9f,stroke:#333,stroke-width:3px + style FYV fill:#bfb,stroke:#333,stroke-width:3px + style MOET fill:#fbb,stroke:#333,stroke-width:2px +``` + +**Flow**: Collateral β†’ Auto-borrow MOET β†’ FYV β†’ Yield protects position! + +:::tip FCM's Innovation +This is why FCM is unique: Your MOET earnings from FYV automatically repay debt when needed. **Yield-powered liquidation prevention!** + +Learn more: [FCM Basics](../fcm/basics.md#1-yield-powered-liquidation-prevention) +::: + +### Pattern 3: Liquidity Provision + +**Use case**: Earn trading fees with borrowed MOET + +```mermaid +graph LR + Collateral[FLOW Collateral] --> ALP[ALP Position] + ALP -->|Borrow| MOET[MOET] + MOET -->|Add Liquidity| LP[LP Pool
MOET/FLOW] + LP -->|Earn| Fees[Trading Fees] + + style LP fill:#bbf,stroke:#333,stroke-width:2px +``` + +**Flow**: Collateral β†’ Borrow MOET β†’ LP Pool β†’ Earn trading fees + +### Pattern 4: Yield Arbitrage + +**Use case**: Profit from rate differentials + +```mermaid +graph LR + ALP[Borrow from ALP
5% APY] -->|MOET| Protocol[Lend to Protocol
8% APY] + Protocol -->|Earn| Spread[3% Spread
Profit!] + + style Spread fill:#bfb,stroke:#333,stroke-width:2px +``` + +**Flow**: Borrow MOET cheap β†’ Lend MOET expensive β†’ Keep spread + +## MOET in Liquidations + +### Keeper Liquidations + +Keepers repay MOET debt to seize collateral: + +```mermaid +sequenceDiagram + participant Keeper + participant ALP + participant Position + + Keeper->>Keeper: Detect HF < 1.0 + Keeper->>ALP: Repay 100 MOET + ALP->>Position: Reduce debt by 100 MOET + ALP->>Keeper: Seize collateral + bonus + Position->>Position: Health = 1.05 βœ“ + + Note over Keeper,Position: Keeper earns liquidation bonus +``` + +### Protocol DEX Liquidations + +Protocol swaps collateral to MOET automatically: + +```mermaid +graph LR + A[Liquidatable Position] --> B[Seize FLOW Collateral] + B --> C[Swap FLOW β†’ MOET
via DEX] + C --> D[Repay MOET Debt] + D --> E[Health Restored] + + style A fill:#fbb + style E fill:#bfb +``` + +**Example**: +``` +Position: 1000 FLOW, 650 MOET debt, HF = 0.98 +↓ +Seize: 150 FLOW +↓ +Swap: 150 FLOW β†’ 147 MOET (via DEX) +↓ +Repay: 147 MOET debt +↓ +Result: 850 FLOW, 503 MOET debt, HF = 1.05 βœ“ +``` + +## MOET Economics + +### Supply & Demand + +```mermaid +graph TB + subgraph Demand + D1[Users borrow for yield] + D2[Liquidators need MOET] + D3[Rebalancing operations] + D4[Protocol integrations] + end + + subgraph Supply + S1[MOET deposits as collateral] + S2[Debt repayments] + S3[Interest payments] + S4[Protocol reserves] + end + + Demand --> Market[MOET Market] + Supply --> Market + Market --> Rate[Interest Rates] + + style Market fill:#fbb,stroke:#333,stroke-width:3px +``` + +### Interest Rate Dynamics + +``` +Utilization = Total MOET Borrowed / Total MOET Available + +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Utilization β”‚ Interest Rate β”‚ Result β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ 0-80% (Low) β”‚ 2-8% APY β”‚ Cheap borrowing β”‚ +β”‚ 80-90% (Medium) β”‚ 8-20% APY β”‚ Balanced β”‚ +β”‚ 90-100% (High) β”‚ 20-50%+ APY β”‚ Discourages borrowβ”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +**Why it matters**: Low utilization makes MOET cheap to borrow, while high utilization makes borrowing expensive and encourages repayment. This dynamic allows the system to self-balance supply and demand. + +## Why MOET vs Other Tokens? + +### Comparison Table + +| Feature | MOET | FLOW | USDC | +|---------|------|------|------| +| Primary borrowed asset | βœ… Yes | ⚠️ Possible | ⚠️ Possible | +| Unit of account | βœ… Yes | ❌ No | ❌ No | +| Auto-borrow default | βœ… Yes | ❌ No | ❌ No | +| Rebalancing token | βœ… Yes | ❌ No | ❌ No | +| FCM integration | βœ… Deep | ⚠️ Moderate | ⚠️ Moderate | +| FYV integration | βœ… Native | ⚠️ Limited | ⚠️ Limited | + +### MOET Advantages + +1. **Designed for DeFi**: Built specifically for Flow DeFi operations +2. **High Liquidity**: Deep markets ensure efficient operations +3. **Composability**: Works seamlessly with FYV and other protocols +4. **Predictability**: Standard token across all FCM operations +5. **Efficiency**: Single token simplifies everything + +### Can I Use Other Tokens? + +Yes, but with limitations: + +:::info For Developers +You can manually borrow other tokens: +```cadence +// Borrow FLOW instead of MOET +let flowBorrowed <- position.borrow( + type: Type<@FlowToken.Vault>(), + amount: 100.0 +) +``` + +However: +- Auto-borrowing always uses MOET +- Rebalancing always uses MOET +- Health calculations still in MOET terms +- FYV integration requires MOET +::: + +## Best Practices + +### For Borrowers + +βœ… **Do**: +- Maintain MOET buffer in wallet for emergencies +- Set up TopUpSource with MOET for auto-protection +- Monitor MOET interest rates +- Diversify yield strategies with borrowed MOET + +❌ **Don't**: +- Assume MOET will always be cheap to borrow +- Put all borrowed MOET in one place +- Ignore MOET balance in TopUpSource +- Forget MOET debt accumulates interest + +### For Yield Seekers + +βœ… **Do**: +- Use full FCM integration (ALP + FYV) +- Let MOET flow automatically to FYV +- Let yield protect your position +- Monitor FYV MOET liquidity + +❌ **Don't**: +- Manually manage MOET if using FYV +- Interrupt the automated flow +- Remove MOET from FYV when position needs it + +## Real-World Example + +### Complete MOET Lifecycle + +```mermaid +graph TB + Start[User deposits
1000 FLOW] --> Calc[ALP calculates:
Can borrow 615 MOET] + Calc --> Borrow[Auto-borrow
615 MOET] + Borrow --> Deploy[MOET β†’ FYV
via DrawDownSink] + Deploy --> Earn[FYV generates
yield in MOET] + + Price[FLOW price
drops 20%] -.-> Detect[ALP detects
HF = 1.04] + Detect --> Need[Need 123 MOET
to rebalance] + Need --> Pull[Pull from FYV
via TopUpSource] + Pull --> Repay[Repay 123 MOET] + Repay --> Safe[Health = 1.3 βœ“
Liquidation avoided] + + style Start fill:#bbf + style Earn fill:#bfb + style Price fill:#fbb + style Safe fill:#bfb +``` + +**What happened**: +1. Deposited FLOW β†’ Auto-borrowed 615 MOET +2. MOET deployed to FYV β†’ Earned yield +3. Price dropped β†’ Position at risk +4. FYV provided 123 MOET β†’ Debt repaid +5. **Result**: Your MOET yield prevented liquidation! + +## Summary + +**MOET's Three Roles**: +1. πŸ’° **Borrowed Asset**: What you borrow from ALP +2. πŸ“Š **Unit of Account**: How all prices are quoted +3. πŸ”„ **Rebalancing Medium**: Flows between ALP and FYV + +**Key Points**: +- All auto-borrowing is in MOET +- All rebalancing uses MOET +- All health calculations in MOET terms +- MOET enables FCM's yield-powered liquidation prevention + +**Why MOET Matters**: +Without MOET as the standard, FCM's automation wouldn't work. MOET is the "common currency" that lets ALP and FYV communicate seamlessly, enabling the unique liquidation prevention mechanism. + +## Mathematical Foundation + +MOET is central to all FCM calculations: +- **Unit of Account**: All prices quoted in MOET terms - [Price Oracle](../fcm/math.md#core-variables) +- **Auto-Borrowing**: MOET amounts calculated from collateral - [Auto-Borrowing Math](../fcm/math.md#auto-borrowing-mathematics) +- **Rebalancing**: MOET flows restore health factor - [Rebalancing Math](../fcm/math.md#rebalancing-mathematics) +- **Health Factor**: All calculations in MOET terms - [Health Factor Formula](../fcm/math.md#health-factor) + +## Next Steps + +- **Understand automation**: [Rebalancing Mechanics](./rebalancing.md) +- **See the big picture**: [FCM Architecture](../fcm/architecture.md) +- **Deep dive on MOET**: [MOET Documentation](../moet/index.md) +- **Explore position management**: [Position Lifecycle](./position-lifecycle.md) + +--- + +:::tip Key Takeaway +MOET isn't just another token - it's the **backbone** of FCM. It standardizes pricing, enables automation, and makes yield-powered liquidation prevention possible. Think of it as the "blood" flowing through FCM's veins, carrying value between ALP and FYV. +::: diff --git a/docs/defi/alp/position-lifecycle.md b/docs/defi/alp/position-lifecycle.md new file mode 100644 index 0000000000..bbab748711 --- /dev/null +++ b/docs/defi/alp/position-lifecycle.md @@ -0,0 +1,533 @@ +--- +title: Position Lifecycle +sidebar_position: 5 +--- + +# Position Lifecycle + +A Position in ALP represents your lending account. Understanding the complete lifecycle from creation to closure helps you manage your positions effectively and maximize your DeFi strategy. + +## What is a Position? + +A **Position** tracks everything about your lending activity: + +- πŸ’° **Collateral deposits**: Assets you've deposited +- πŸ“Š **Debt obligations**: Amounts you've borrowed +- ❀️ **Health metrics**: Current safety status +- πŸ”— **DeFi connectors**: Automation via Sinks and Sources + +Think of it like a bank account, but for DeFi lending - it keeps track of what you own and what you owe. + +## Position Lifecycle Overview + +```mermaid +stateDiagram-v2 + [*] --> Created: Deposit Collateral + Created --> Healthy: Auto-borrow (optional) + Healthy --> Overcollateralized: Add Collateral / Repay Debt + Overcollateralized --> Healthy: Auto-borrow More + Healthy --> Undercollateralized: Price Drop / Interest + Undercollateralized --> Healthy: Auto-repay / Add Collateral + Undercollateralized --> AtRisk: Further Price Drop + AtRisk --> Undercollateralized: Emergency Action + AtRisk --> Liquidatable: HF < 1.0 + Liquidatable --> Undercollateralized: Partial Liquidation + Healthy --> [*]: Close Position + Overcollateralized --> [*]: Close Position + + note right of Created + Initial deposit + HF = ∞ (no debt) + end note + + note right of Healthy + HF: 1.1 - 1.5 + Target: 1.3 + end note + + note right of AtRisk + HF: 1.0 - 1.1 + Urgent action needed! + end note +``` + +## Creating a Position + +### The Creation Flow + +```mermaid +sequenceDiagram + participant User + participant ALP + participant Position + participant FYV + + User->>ALP: Deposit 1000 FLOW + ALP->>Position: Create position + Position->>Position: Calculate borrowing capacity + + alt With Auto-Borrowing + Position->>Position: Borrow 615 MOET + Position->>FYV: Push to DrawDownSink + FYV-->>User: Deploy to yield strategy + Note over Position: Health = 1.3 + else Without Auto-Borrowing + Note over Position: Health = ∞
(no debt yet) + end + + ALP-->>User: Return position reference +``` + +### Option 1: With Auto-Borrowing (Recommended for FCM) + +**Setup**: +- `pushToDrawDownSink = true` +- Automatically borrows to target health (1.3) +- Funds flow to your configured destination + +**What happens**: +``` +1. You deposit: 1000 FLOW +2. ALP calculates: 1000 Γ— 0.8 = 800 effective collateral +3. ALP auto-borrows: 800 / 1.3 = 615.38 MOET +4. Funds flow: Via DrawDownSink (to FYV, wallet, etc.) +5. Final state: Health = 1.3, fully optimized +``` + +**Best for**: FCM users who want maximum automation and capital efficiency + +### Option 2: Without Auto-Borrowing (Conservative) + +**Setup**: +- `pushToDrawDownSink = false` +- No automatic borrowing +- You control when to borrow + +**What happens**: +``` +1. You deposit: 1000 FLOW +2. Position created with collateral only +3. Health factor: Infinite (no debt) +4. You manually borrow when ready +``` + +**Best for**: Users who want full manual control + +## Health States Through Lifecycle + +### State 1: Overcollateralized (HF > 1.5) + +```mermaid +graph LR + A[HF > 1.5
Very Safe] --> B{Auto-borrow
enabled?} + B -->|Yes| C[Borrow more MOET] + B -->|No| D[Stay safe] + C --> E[Health = 1.3] + + style A fill:#bfb + style E fill:#bfb +``` + +**Characteristics**: This state is very safe from liquidation and allows you to borrow significantly more. However, it's not capital efficient if you're not using auto-borrowing. + +**Actions available**: You can borrow additional funds, withdraw excess collateral, or let the system auto-borrow to reach the target health factor. + +**Example**: +``` +Collateral: $2000 effective +Debt: $800 MOET +HF: 2000 / 800 = 2.5 + +Can borrow additional: ~$731 MOET (to reach HF 1.3) +``` + +### State 2: Healthy (HF 1.1 - 1.5) + +```mermaid +graph TD + A[HF: 1.1 - 1.5
Healthy Range] + A --> B[Optimal: 1.3] + A --> C[Upper: 1.5] + A --> D[Lower: 1.1] + + style A fill:#bbf + style B fill:#bfb +``` + +**Characteristics**: This is the target operational range with balanced risk/reward and no automatic actions triggered. + +**Actions available**: You can perform normal deposits and withdrawals, borrow within limits, and make repayments as desired. + +**Example**: +``` +Collateral: $800 effective +Debt: $615.38 MOET +HF: 800 / 615.38 = 1.30 βœ“ + +Status: Perfect! At target health +``` + +### State 3: Undercollateralized (HF < 1.1) + +```mermaid +graph LR + A[HF < 1.1
Below Target] --> B{TopUpSource
configured?} + B -->|Yes| C[Auto-repay] + B -->|No| D[Manual action
required!] + C --> E[Health = 1.3] + D --> F[Risk liquidation] + + style A fill:#ffa + style E fill:#bfb + style F fill:#fbb +``` + +**Characteristics**: This position is below target and needs attention. Auto-rebalancing may trigger, and risk increases significantly if the price continues dropping. + +**Urgent actions**: You should add more collateral, repay some debt, and ensure TopUpSource has sufficient funds available. + +**Example**: +``` +Collateral: $680 effective (price dropped!) +Debt: $615.38 MOET +HF: 680 / 615.38 = 1.10 + +Status: At minimum threshold +Action: Consider rebalancing +``` + +### State 4: At Risk (HF 1.0 - 1.1) + +```mermaid +graph LR + A[HF: 1.0 - 1.1
CRITICAL] --> B[Immediate
Action] + B --> C{Can add
collateral?} + B --> D{Can repay
debt?} + C -->|Yes| E[Add collateral NOW] + D -->|Yes| F[Repay debt NOW] + E --> G[Safety Restored] + F --> G + + style A fill:#fbb + style G fill:#bfb +``` + +**Characteristics**: +- πŸ”΄ High liquidation risk +- πŸ”΄ Immediate action required +- πŸ”΄ May be liquidated very soon + +**Immediate actions**: +1. Add substantial collateral immediately +2. Repay significant portion of debt +3. Trigger emergency rebalancing +4. Monitor constantly + +**Example**: +``` +Collateral: $640 effective +Debt: $615.38 MOET +HF: 640 / 615.38 = 1.04 + +Status: CRITICAL - 4% from liquidation! +``` + +### State 5: Liquidatable (HF < 1.0) + +```mermaid +graph LR + A[HF < 1.0
LIQUIDATABLE] --> B[Liquidation
Triggered] + B --> C[Collateral
Seized] + C --> D[Debt
Repaid] + D --> E[HF = 1.05
Partial Liquidation] + + style A fill:#f00,color:#fff + style E fill:#ffa +``` + +**What happens**: +- β›” Position can be liquidated by anyone +- β›” Collateral seized with penalty +- β›” Partial or full liquidation + +**The process**: +``` +1. Keeper/Protocol detects HF < 1.0 +2. Seizes portion of collateral +3. Repays debt (with liquidation bonus) +4. Position brought to HF = 1.05 +5. You keep remaining collateral (if any) +``` + +Learn more: [Liquidation System](./liquidation-system.md) + +## Position Operations + +### Depositing More Collateral + +```mermaid +graph LR + A[Deposit
More Collateral] --> B[Effective
Collateral ↑] + B --> C[Health
Factor ↑] + C --> D{HF > 1.5?} + D -->|Yes| E[Auto-borrow
if enabled] + D -->|No| F[Stay in range] + + style A fill:#bbf + style C fill:#bfb +``` + +**Effects**: Depositing more collateral increases your effective collateral and improves your health factor. It may trigger auto-borrowing if enabled and provides an additional safety buffer. + +### Withdrawing Collateral + +```mermaid +graph LR + A[Withdraw
Collateral] --> B[Effective
Collateral ↓] + B --> C[Health
Factor ↓] + C --> D{HF < 1.1?} + D -->|Yes| E[Blocked or
Liquidation Risk] + D -->|No| F[Withdrawal
Succeeds] + + style A fill:#ffa + style E fill:#fbb +``` + +**Conditions**: Withdrawals must maintain your health factor above the minimum threshold, cannot cause undercollateralization, and may be blocked if deemed unsafe by the protocol. + +### Borrowing Funds + +```mermaid +graph LR + A[Borrow
MOET] --> B[Debt ↑] + B --> C[Health
Factor ↓] + C --> D{HF > min?} + D -->|Yes| E[Borrow
Succeeds] + D -->|No| F[Borrow
Blocked] + E --> G[Interest
Starts] + + style A fill:#bbf + style F fill:#fbb +``` + +**Effects**: Borrowing funds increases your debt and decreases your health factor. Interest starts accruing immediately, and you must ensure your position stays above the minimum health threshold. + +### Repaying Debt + +```mermaid +graph LR + A[Repay
MOET] --> B[Debt ↓] + B --> C[Health
Factor ↑] + C --> D[More Safety
Buffer] + D --> E[Can Borrow
More if Needed] + + style A fill:#bfb + style C fill:#bfb +``` + +**Effects**: Repaying debt decreases your total debt, improves your health factor, reduces ongoing interest payments, and increases your safety margin against liquidation. + +## Closing a Position + +### Requirements + +To fully close a position: + +```mermaid +graph TD + A[Want to Close] --> B{All debt
repaid?} + B -->|No| C[Repay all debt first] + B -->|Yes| D{All collateral
withdrawn?} + D -->|No| E[Withdraw all collateral] + D -->|Yes| F[Position Closed βœ“] + C --> B + E --> D + + style F fill:#bfb +``` + +**Steps**: +1. **Repay all debt**: Zero MOET debt +2. **Withdraw all collateral**: Remove all deposited assets +3. **Clean state**: Position now empty + +**Example**: +``` +1. Check debt: 492.31 MOET +2. Repay: 492.31 MOET β†’ Debt = 0 +3. Check collateral: 1000 FLOW +4. Withdraw: 1000 FLOW β†’ Collateral = 0 +5. Position closed βœ“ +``` + +## Advanced: Multiple Positions + +You can have multiple positions for different strategies: + +```mermaid +graph TD + User[Your Account] + User --> P1[Position 1
Conservative
HF: 2.0] + User --> P2[Position 2
Balanced
HF: 1.3] + User --> P3[Position 3
Aggressive
HF: 1.1] + + P1 --> S1[Stable Strategy] + P2 --> S2[Yield Farming] + P3 --> S3[Leveraged] + + style P1 fill:#bfb + style P2 fill:#bbf + style P3 fill:#ffa +``` + +**Benefits**: Multiple positions allow you to maintain separate risk profiles, use different collateral types, isolate liquidation risk, and implement diverse strategies simultaneously. + +**Example uses**: +- **Position 1**: Conservative (HF 2.0) with stablecoin collateral +- **Position 2**: Balanced (HF 1.3) with FLOW, deployed to FYV +- **Position 3**: Aggressive (HF 1.1) with volatile assets, manual management + +## Automation with DeFi Actions + +### Full FCM Automation Setup + +```mermaid +graph TB + Position[Your Position] + Position -->|DrawDownSink| FYV[FYV Strategy] + FYV -->|TopUpSource| Position + + Auto1[Overcollateralized] -.-> Position + Position -->|Auto-borrow MOET| FYV + + Auto2[Undercollateralized] -.-> FYV + FYV -->|Provide MOET| Position + + style Position fill:#f9f,stroke:#333,stroke-width:3px + style FYV fill:#bfb,stroke:#333,stroke-width:3px +``` + +**Configuration**: +``` +Position.DrawDownSink = FYV Strategy Sink +Position.TopUpSource = FYV Strategy Source +Position.minHealth = 1.1 +Position.maxHealth = 1.5 +``` + +**Result**: +- βœ… Automatic borrowing when overcollateralized +- βœ… Automatic repayment when undercollateralized +- βœ… Yield protects your position +- βœ… True set-and-forget experience + +Learn more: [DeFi Actions Integration](./defi-actions.md) + +## Best Practices + +### Position Creation +- βœ… Start with conservative health targets (1.5+) if learning +- βœ… Test with small amounts first +- βœ… Understand auto-borrowing before enabling +- βœ… Set up monitoring from day one + +### Ongoing Management +- βœ… Check health factor daily +- βœ… Set up automated alerts for HF < 1.3 +- βœ… Keep liquid funds for emergencies +- βœ… Monitor collateral token prices + +### Risk Management +- βœ… Maintain health buffer above 1.3 +- βœ… Diversify collateral types when possible +- βœ… Use stable assets for lower risk +- βœ… Have emergency repayment plan ready + +### Before Closing +- βœ… Track total debt including accrued interest +- βœ… Plan repayment timeline +- βœ… Understand any fees or penalties +- βœ… Withdraw collateral promptly after repayment + +## Common Scenarios + +### Scenario 1: Price Drop Response + +```mermaid +sequenceDiagram + participant Price + participant Position + participant FYV + + Price->>Position: FLOW drops 20% + Position->>Position: HF: 1.3 β†’ 1.04 + Position->>Position: Below min (1.1)! + Position->>FYV: Request 123 MOET + FYV->>Position: Provide MOET + Position->>Position: Repay debt + Position->>Position: HF: 1.04 β†’ 1.3 βœ“ + + Note over Position,FYV: Automatic liquidation prevention! +``` + +### Scenario 2: Price Recovery + +```mermaid +sequenceDiagram + participant Price + participant Position + participant FYV + + Price->>Position: FLOW recovers to $1 + Position->>Position: HF: 1.3 β†’ 1.625 + Position->>Position: Above max (1.5)! + Position->>Position: Borrow 123 MOET + Position->>FYV: Push MOET + FYV->>FYV: Deploy to yield + Position->>Position: HF: 1.625 β†’ 1.3 βœ“ + + Note over Position,FYV: Automatic capital optimization! +``` + +## Summary + +**Position Lifecycle Phases**: +1. πŸ†• **Creation**: Deposit collateral, optionally auto-borrow +2. πŸ’š **Healthy Operation**: HF between 1.1-1.5 +3. ⚠️ **Rebalancing**: Automatic adjustments as needed +4. πŸ”΄ **At Risk**: HF approaching 1.0, urgent action +5. 🏁 **Closure**: Repay debt, withdraw collateral + +**Key Health Ranges**: +- **HF > 1.5**: Overcollateralized (auto-borrow if enabled) +- **HF 1.1-1.5**: Healthy range (optimal operation) +- **HF 1.0-1.1**: At risk (urgent action needed) +- **HF < 1.0**: Liquidatable (emergency!) + +**Automation Keys**: +- Configure DrawDownSink for auto-borrowing destination +- Configure TopUpSource for auto-repayment source +- Set appropriate min/max health bounds +- Monitor regularly even with automation + +## Mathematical Foundation + +For detailed mathematical formulas and proofs underlying position operations: +- **Health Factor Calculations**: [FCM Math - Health Factor](../fcm/math.md#health-factor) +- **Auto-Borrowing Math**: [Auto-Borrowing Mathematics](../fcm/math.md#auto-borrowing-mathematics) +- **Rebalancing Formulas**: [Rebalancing Mathematics](../fcm/math.md#rebalancing-mathematics) +- **Price Impact Analysis**: [Price Impact on Health](../fcm/math.md#price-impact-analysis) +- **Complete Lifecycle Example**: [Position Lifecycle Math](../fcm/math.md#complete-position-lifecycle-math) + +## Next Steps + +- **Understand rebalancing**: [Rebalancing Mechanics](./rebalancing.md) +- **Set up automation**: [DeFi Actions Integration](./defi-actions.md) +- **Protect against liquidation**: [Liquidation System](./liquidation-system.md) +- **Learn credit mechanics**: [Credit Market Mechanics](./credit-market-mechanics.md) + +--- + +:::tip Key Takeaway +A position's lifecycle is all about managing the health factor. Stay in the healthy range (1.1-1.5), use automation for hands-free management, and always have a plan for when prices move against you. +::: diff --git a/docs/defi/alp/rebalancing.md b/docs/defi/alp/rebalancing.md new file mode 100644 index 0000000000..c2b982041f --- /dev/null +++ b/docs/defi/alp/rebalancing.md @@ -0,0 +1,679 @@ +--- +title: Rebalancing Mechanics +sidebar_position: 6 +--- + +# Rebalancing Mechanics + +Rebalancing is ALP's automated position management system that maintains positions within target health ranges. This powerful feature eliminates manual management and optimizes capital efficiency. + +## Understanding Rebalancing + +### What is Rebalancing? + +**Rebalancing** is the automatic adjustment of a position's debt to maintain its health factor within a target range. When overcollateralized (HF > maxHealth), the system automatically borrows more. When undercollateralized (HF < minHealth), it automatically repays debt. When in range (minHealth ≀ HF ≀ maxHealth), no action is needed. + +The goal is to keep positions at the **target health factor** (typically 1.3), maximizing capital efficiency while maintaining safety. + +```mermaid +graph LR + subgraph "Health States" + A[HF < 1.1
Undercollateralized] + B[HF: 1.1 - 1.5
Healthy Range] + C[HF > 1.5
Overcollateralized] + end + + A -->|Auto-repay debt| Target[Target HF: 1.3] + C -->|Auto-borrow more| Target + B -.->|No action| B + + style A fill:#fbb + style B fill:#bfb + style C fill:#bbf + style Target fill:#bfb,stroke:#333,stroke-width:3px +``` + +### Target Health Range + +Each position has configurable health bounds: + +``` +minHealth: 1.1 (minimum before rebalancing up) +targetHealth: 1.3 (optimal target) +maxHealth: 1.5 (maximum before rebalancing down) +``` + +**Visual representation**: +``` +0.0 ---- 1.0 ---- 1.1 ---- 1.3 ---- 1.5 ---- 2.0+ + | | | | + Liquidation Min Target Max + (Repay zone) (Borrow zone) +``` + +## Rebalancing Decision Logic + +```mermaid +flowchart TD + Start[Check Position Health] --> GetHF[Get Current HF] + GetHF --> Check{HF vs Range?} + + Check -->|HF < minHealth
1.1| Low[Undercollateralized] + Check -->|minHealth ≀ HF ≀ maxHealth
1.1 - 1.5| Good[Healthy] + Check -->|HF > maxHealth
1.5| High[Overcollateralized] + + Low --> CalcRepay[Calculate
Required Repayment] + CalcRepay --> PullFunds[Pull from
TopUpSource] + PullFunds --> Repay[Repay Debt] + Repay --> Restored[HF = 1.3 βœ“] + + Good --> NoAction[No Action Needed] + + High --> CalcBorrow[Calculate
Additional Borrowable] + CalcBorrow --> Borrow[Borrow MOET] + Borrow --> PushFunds[Push to
DrawDownSink] + PushFunds --> Restored + + style Low fill:#fbb + style Good fill:#bfb + style High fill:#bbf + style Restored fill:#bfb,stroke:#333,stroke-width:3px +``` + +### When Rebalancing Triggers + +**Automatic triggers** occur when position health moves outside the min/max range, after deposits that cause overcollateralization, following price changes via oracle updates, and through scheduled checks by keepers or the protocol. + +**Manual triggers** include user-forced rebalancing, protocol maintenance calls, and integration with external automation. + +## Overcollateralized Rebalancing + +### When It Occurs + +Rebalancing down (borrowing more) happens when: +``` +Current Health Factor > maxHealth (1.5) +``` + +This means you have "excess" collateral that could be used to borrow more. + +### The Mathematics + +The system calculates how much additional debt can be safely taken: + +``` +Current State: +- Effective collateral: EC +- Effective debt: ED +- Current health: HF = EC / ED +- Target health: TH = 1.3 + +Additional borrowable amount: +additionalBorrow = (EC / TH) - ED + +New state after borrowing: +- New debt: ED + additionalBorrow = EC / TH +- New health: EC / (EC / TH) = TH βœ“ +``` + +See [FCM Mathematical Foundations](../fcm/math.md#rebalancing-mathematics) for detailed formulas and step-by-step derivations. + +### Overcollateralized Flow + +```mermaid +sequenceDiagram + participant Position + participant ALP + participant DrawDownSink + participant FYV + + Position->>Position: Detect HF = 2.0
(above max 1.5) + Position->>ALP: Calculate additional borrow + Note over ALP: (EC / 1.3) - ED
= additional amount + ALP->>ALP: Borrow 215.38 MOET + ALP->>DrawDownSink: Push MOET + DrawDownSink->>FYV: Deploy to yield + Position->>Position: Health = 1.3 βœ“ + + Note over Position,FYV: Automatic capital efficiency! +``` + +**Example**: +``` +Current State: +- Collateral: 1000 FLOW @ $1 = $1000, factor 0.8 = $800 effective +- Debt: 400 MOET @ $1 = $400 +- Health: 800 / 400 = 2.0 (above maxHealth of 1.5) + +Calculation: +- Target debt for HF=1.3: 800 / 1.3 β‰ˆ 615.38 MOET +- Additional borrow: 615.38 - 400 = 215.38 MOET + +After Rebalancing: +- Collateral: $800 effective (unchanged) +- Debt: 615.38 MOET +- Health: 800 / 615.38 = 1.3 βœ“ +- User receives: 215.38 MOET via DrawDownSink +``` + +### DrawDownSink Integration + +When borrowing during rebalancing, funds are pushed to the **DrawDownSink**: + +```mermaid +graph LR + Position[Position
HF > 1.5] --> Calculate[Calculate
Excess Capacity] + Calculate --> Borrow[Borrow
MOET] + Borrow --> Sink[DrawDownSink] + + Sink --> Wallet[User Wallet] + Sink --> FYV[FYV Strategy] + Sink --> LP[LP Pool] + Sink --> Other[Other DeFi] + + style Position fill:#bbf + style Sink fill:#f9f,stroke:#333,stroke-width:2px +``` + +**Benefits**: Funds are automatically deployed to the user's wallet or DeFi strategy without requiring manual claims, ensuring seamless capital efficiency. The system can integrate with yield farms, LP pools, and other DeFi protocols. + +## Undercollateralized Rebalancing + +### When It Occurs + +Rebalancing up (repaying debt) happens when: +``` +Current Health Factor < minHealth (1.1) +``` + +This means your position is approaching liquidation risk and needs debt reduction. + +### The Mathematics + +The system calculates how much debt must be repaid: + +``` +Current State: +- Effective collateral: EC +- Effective debt: ED +- Current health: HF = EC / ED +- Target health: TH = 1.3 + +Required repayment: +requiredPaydown = ED - (EC / TH) + +New state after repayment: +- New debt: EC / TH +- New health: EC / (EC / TH) = TH βœ“ +``` + +See [FCM Mathematical Foundations](../fcm/math.md#rebalancing-mathematics) for detailed formulas and proofs. + +### Undercollateralized Flow + +```mermaid +sequenceDiagram + participant Price + participant Position + participant TopUpSource + participant FYV + participant ALP + + Price->>Position: FLOW drops 20% + Position->>Position: HF = 1.04
(below min 1.1!) + Position->>ALP: Calculate repayment needed + Note over ALP: ED - (EC / 1.3)
= repayment amount + ALP->>TopUpSource: Request 123.07 MOET + TopUpSource->>FYV: Withdraw from yield + FYV->>TopUpSource: Provide MOET + TopUpSource->>ALP: Supply MOET + ALP->>ALP: Repay debt + Position->>Position: Health = 1.3 βœ“ + + Note over Price,Position: Automatic liquidation prevention! +``` + +**Example**: +``` +Initial State: +- Collateral: 1000 FLOW @ $1 = $1000, factor 0.8 = $800 effective +- Debt: 615.38 MOET +- Health: 800 / 615.38 = 1.3 + +After FLOW Price Drops 20% to $0.80: +- Collateral: 1000 FLOW @ $0.80 = $800, factor 0.8 = $640 effective +- Debt: 615.38 MOET (unchanged) +- Health: 640 / 615.38 = 1.04 (below minHealth of 1.1) + +Calculation: +- Target debt for HF=1.3: 640 / 1.3 β‰ˆ 492.31 MOET +- Required paydown: 615.38 - 492.31 = 123.07 MOET + +After Rebalancing: +- Collateral: $640 effective (unchanged) +- Debt: 492.31 MOET +- Health: 640 / 492.31 = 1.3 βœ“ +- User paid: 123.07 MOET via TopUpSource +``` + +### TopUpSource Integration + +When repaying during rebalancing, funds are pulled from the **TopUpSource**: + +```mermaid +graph LR + Position[Position
HF < 1.1] --> Calculate[Calculate
Repayment Needed] + Calculate --> Request[Request
MOET] + Request --> Source[TopUpSource] + + Wallet[User Wallet] --> Source + FYV[FYV Strategy] --> Source + LP[LP Pool] --> Source + Other[Other DeFi] --> Source + + Source --> Repay[Repay
Debt] + Repay --> Safe[HF = 1.3 βœ“] + + style Position fill:#fbb + style Source fill:#f9f,stroke:#333,stroke-width:2px + style Safe fill:#bfb +``` + +**Benefits**: The TopUpSource integration provides automatic liquidation protection without requiring manual monitoring. Funds are sourced from the user's chosen location and can integrate with yield farms to automatically exit positions when needed. + +:::tip FCM's Innovation +When TopUpSource is connected to FYV, your **yield automatically protects your position** from liquidation. This is the core innovation of [Flow Credit Market](../fcm/basics.md#yield-powered-liquidation-prevention)! +::: + +## Rebalancing Scenarios + +### Scenario 1: Initial Position with Auto-Borrow + +```mermaid +sequenceDiagram + participant User + participant ALP + participant Position + participant DrawDownSink + + User->>ALP: Deposit 1000 FLOW
pushToDrawDownSink=true + ALP->>Position: Create position + Position->>Position: Initial HF = ∞
(no debt yet) + Position->>Position: Detect HF > max (1.5) + Position->>Position: Calculate: 800/1.3 = 615.38 + Position->>Position: Auto-borrow 615.38 MOET + Position->>DrawDownSink: Push MOET + DrawDownSink->>User: Funds deployed + Position->>Position: Final HF = 1.3 βœ“ + + Note over User,DrawDownSink: Immediate auto-optimization! +``` + +**What happens**: +1. Initial health: Infinite (no debt) +2. System detects health > maxHealth +3. Calculates borrowable: 800 / 1.3 β‰ˆ 615.38 MOET +4. Auto-borrows 615.38 MOET +5. Pushes to DrawDownSink +6. Final health: 1.3 βœ“ + +### Scenario 2: Price Increase Creates Opportunity + +```mermaid +graph TD + Start[Initial State
1000 FLOW @ $1
Debt: 615 MOET
HF: 1.3] --> PriceUp[FLOW β†’ $1.25] + PriceUp --> NewState[New Collateral: $1000
Debt: 615 MOET
HF: 1.625] + NewState --> Detect[HF > maxHealth!] + Detect --> Calc[Target Debt:
1000 / 1.3 = 769 MOET] + Calc --> Borrow[Borrow Additional:
769 - 615 = 154 MOET] + Borrow --> Push[Push to DrawDownSink] + Push --> Final[Final HF: 1.3 βœ“] + + style Start fill:#bbf + style NewState fill:#bfb + style Final fill:#bfb +``` + +**Example**: +``` +Initial: 1000 FLOW @ $1, debt 615.38 MOET, health 1.3 +FLOW price increases to $1.25 + +New state: +- Collateral: 1000 FLOW @ $1.25 = $1250, factor 0.8 = $1000 effective +- Debt: 615.38 MOET +- Health: 1000 / 615.38 = 1.625 (above maxHealth) + +Rebalancing triggers: +- Target debt: 1000 / 1.3 β‰ˆ 769.23 MOET +- Additional borrow: 769.23 - 615.38 = 153.85 MOET +- User receives: 153.85 MOET via DrawDownSink +- New health: 1.3 βœ“ +``` + +### Scenario 3: Price Decrease Requires Repayment + +```mermaid +graph TD + Start[Initial State
1000 FLOW @ $1
Debt: 615 MOET
HF: 1.3] --> PriceDown[FLOW β†’ $0.80] + PriceDown --> NewState[New Collateral: $640
Debt: 615 MOET
HF: 1.04] + NewState --> Detect[HF < minHealth!] + Detect --> Calc[Target Debt:
640 / 1.3 = 492 MOET] + Calc --> Repay[Repay:
615 - 492 = 123 MOET] + Repay --> Pull[Pull from TopUpSource] + Pull --> Final[Final HF: 1.3 βœ“] + + style Start fill:#bbf + style NewState fill:#fbb + style Final fill:#bfb +``` + +**Example**: +``` +Initial: 1000 FLOW @ $1, debt 615.38 MOET, health 1.3 +FLOW price decreases to $0.80 + +New state: +- Collateral: 1000 FLOW @ $0.80 = $800, factor 0.8 = $640 effective +- Debt: 615.38 MOET +- Health: 640 / 615.38 = 1.04 (below minHealth) + +Rebalancing triggers: +- Target debt: 640 / 1.3 β‰ˆ 492.31 MOET +- Required repayment: 615.38 - 492.31 = 123.07 MOET +- System pulls: 123.07 MOET from TopUpSource +- New health: 1.3 βœ“ +``` + +### Scenario 4: Interest Accrual Over Time + +```mermaid +graph LR + Start[Initial
HF: 1.3] --> Time[6 Months
10% APY] + Time --> Interest[Interest Accrues
Debt ↑ 5%] + Interest --> Check{HF < 1.1?} + Check -->|Yes| Trigger[Trigger
Rebalancing] + Check -->|No| Monitor[Continue
Monitoring] + Trigger --> Repay[Repay from
TopUpSource] + Repay --> Restored[HF = 1.3 βœ“] + + style Interest fill:#ffa + style Restored fill:#bfb +``` + +**Example**: +``` +Initial: 1000 FLOW @ $1, debt 615.38 MOET, health 1.3 +After 6 months at 10% APY: + +New state: +- Collateral: $800 effective (unchanged) +- Debt: 615.38 * 1.05 β‰ˆ 646.15 MOET (5% accrued interest) +- Health: 800 / 646.15 = 1.238 (approaching minHealth) + +If health drops below 1.1: +- Rebalancing triggers +- Repays enough to restore health to 1.3 +- Funds pulled from TopUpSource +``` + +## Rebalancing Strategies + +### Strategy Comparison + +```mermaid +graph TD + subgraph Conservative + C1[minHealth: 1.2
target: 1.5
maxHealth: 2.0] + C2[βœ… Stable
βœ… Low gas
❌ Low efficiency] + end + + subgraph Balanced + B1[minHealth: 1.1
target: 1.3
maxHealth: 1.5] + B2[βœ… Efficient
βœ… Reasonable gas
βœ… Good safety] + end + + subgraph Aggressive + A1[minHealth: 1.1
target: 1.2
maxHealth: 1.3] + A2[βœ… Max efficiency
❌ High gas
❌ Risky] + end + + style Balanced fill:#bfb,stroke:#333,stroke-width:3px +``` + +### Conservative Strategy + +**Configuration**: +``` +minHealth: 1.2 +targetHealth: 1.5 +maxHealth: 2.0 +``` + +**Characteristics**: Conservative strategy offers less frequent rebalancing, lower gas costs, more stable positions, and a buffer against volatility. However, it results in lower capital efficiency and less borrowed funds. + +**Best for**: Risk-averse users, volatile collateral, learning the system + +### Balanced Strategy (Recommended) + +**Configuration**: +``` +minHealth: 1.1 +targetHealth: 1.3 +maxHealth: 1.5 +``` + +**Characteristics**: Balanced strategy provides good capital efficiency, reasonable rebalancing frequency, balanced risk/reward ratios, and serves as the standard configuration. + +**Best for**: Most users, general purpose lending + +**This is the default and most common configuration.** + +### Aggressive Strategy + +**Configuration**: +``` +minHealth: 1.1 +targetHealth: 1.2 +maxHealth: 1.3 +``` + +**Characteristics**: Aggressive strategy offers maximum capital efficiency, more borrowed funds, and higher yield potential. However, it requires frequent rebalancing, incurs higher gas costs, is more sensitive to volatility, and requires a reliable TopUpSource. + +**Best for**: Experienced users, stable collateral, maximum leverage + +:::warning Important +Aggressive strategy requires **reliable TopUpSource** with sufficient liquidity. If TopUpSource runs dry during a price drop, liquidation risk increases significantly! +::: + +## Helper Functions for Rebalancing + +ALP provides two key functions to check rebalancing status: + +### Checking Borrowable Amount + +**Purpose**: See how much can be borrowed without triggering rebalancing + +**Formula**: `(effectiveCollateral / targetHealth) - effectiveDebt` + +**Returns**: Amount that can be borrowed while maintaining target health (0 if already at/below target) + +### Checking Required Repayment + +**Purpose**: See how much must be repaid to restore health + +**Formula**: `effectiveDebt - (effectiveCollateral / targetHealth)` + +**Returns**: Amount that must be repaid to reach target health (0 if already at/above target) + +:::info For Developers +```cadence +// Check borrowable amount above target health +let available = position.fundsAvailableAboveTargetHealth() +if available > 0.0 { + // Can borrow 'available' amount without triggering rebalancing +} + +// Check required repayment for target health +let required = position.fundsRequiredForTargetHealth() +if required > 0.0 { + // Must repay 'required' amount to restore health +} +``` + +See [GitHub](https://github.com/onflow/FlowCreditMarket) for complete API documentation. +::: + +## Manual vs Automatic Rebalancing + +```mermaid +graph TB + subgraph Automatic + A1[DrawDownSink
Configured] --> A2[TopUpSource
Configured] + A2 --> A3[βœ… Auto-borrow
βœ… Auto-repay
βœ… Hands-free] + end + + subgraph Manual + M1[User Monitors
Health] --> M2[User Triggers
Rebalance] + M2 --> M3[❌ Manual work
βœ… Full control
⚠️ Risk if delayed] + end + + style Automatic fill:#bfb + style Manual fill:#bbf +``` + +### Automatic Rebalancing + +**Advantages**: Automatic rebalancing requires no user intervention, maintains optimal capital efficiency, provides protection against liquidation, and enables integration with DeFi strategies. + +**Requirements**: To enable automatic rebalancing, you must configure DrawDownSink for borrowing and TopUpSource for repayment, ensure sufficient funds in TopUpSource, and set up proper automation (keepers or protocol). + +### Manual Rebalancing + +**When to use**: Manual rebalancing is suitable for testing and learning, conservative management approaches, situations where manual control is preferred, and complex strategy execution. + +**Process**: +1. Monitor position health factor regularly +2. Detect when health moves outside range +3. Manually trigger rebalancing +4. Verify new health factor + +## Rebalancing Best Practices + +### Setup + +1. **Configure both Sink and Source**: Ensures full automation +2. **Test with small amounts**: Verify rebalancing works as expected +3. **Monitor initial rebalancing**: Watch first few cycles +4. **Fund TopUpSource adequately**: Ensure sufficient repayment capacity + +### Monitoring + +1. **Track rebalancing events**: Log when rebalancing occurs +2. **Monitor gas costs**: Frequent rebalancing costs gas +3. **Watch health factor trends**: Identify patterns +4. **Alert on failures**: Know if TopUpSource runs dry + +### Optimization + +1. **Adjust health ranges**: Based on volatility and strategy +2. **Choose appropriate tokens**: Stable collateral = less rebalancing +3. **Balance efficiency vs stability**: Find your risk tolerance +4. **Consider timing**: Some times have better gas prices + +### Risk Management + +1. **Ensure TopUpSource liquidity**: Always have funds available +2. **Monitor collateral prices**: Know when to add collateral manually +3. **Have backup plans**: What if automation fails? +4. **Regular health checks**: Even with automation, monitor positions + +## Troubleshooting Rebalancing + +### Rebalancing Not Triggering + +```mermaid +graph TD + Issue[Rebalancing
Not Triggering] --> Check1{Health in
range?} + Check1 -->|Yes| OK[Working as
intended] + Check1 -->|No| Check2{Sink/Source
configured?} + Check2 -->|No| Fix1[Configure
Sink/Source] + Check2 -->|Yes| Check3{Funds in
Source?} + Check3 -->|No| Fix2[Add funds to
TopUpSource] + Check3 -->|Yes| Fix3[Manual trigger
force=true] + + style Issue fill:#fbb + style OK fill:#bfb +``` + +**Possible causes**: +1. Health within min/max range (working as intended) +2. DrawDownSink not configured +3. TopUpSource not configured or empty +4. Automation not running + +**Solutions**: Verify the health factor is outside the target range, check Sink/Source configuration, ensure sufficient funds in Source, and manually trigger with `force: true` if needed. + +### Rebalancing Fails + +**Possible causes**: +1. TopUpSource has insufficient funds +2. Oracle price stale or unavailable +3. Gas limit exceeded +4. Smart contract error + +**Solutions**: Add funds to TopUpSource, wait for fresh oracle updates, increase the gas limit, and check contract logs for specific errors. + +### Excessive Rebalancing + +**Possible causes**: +1. Health range too narrow +2. Highly volatile collateral +3. Oracle price updates too frequent + +**Solutions**: Widen the health range (increase maxHealth - minHealth), use more stable collateral, adjust target health to the middle of the range, and consider switching to a conservative strategy. + +## Summary + +**Rebalancing Mechanics**: +- πŸ“Š Maintains health factor in target range (1.1 - 1.5) +- πŸ”„ Automatic borrowing when overcollateralized (HF > 1.5) +- πŸ›‘οΈ Automatic repayment when undercollateralized (HF < 1.1) +- 🎯 Targets optimal health factor (1.3) + +**Key Integrations**: +- **DrawDownSink**: Where borrowed funds go (overcollateralized) +- **TopUpSource**: Where repayment funds come from (undercollateralized) +- **DeFi Actions**: Framework enabling automated flows + +**Strategy Selection**: +- **Conservative**: Wide range (1.2-2.0), stable, low efficiency +- **Balanced**: Moderate range (1.1-1.5), recommended for most +- **Aggressive**: Narrow range (1.1-1.3), risky, max efficiency + +**Best Practices**: +- Configure both Sink and Source for full automation +- Ensure TopUpSource has sufficient liquidity +- Monitor rebalancing events and health trends +- Choose strategy based on collateral volatility + +## Mathematical Foundation + +For detailed rebalancing formulas and calculations: +- **Overcollateralized Math**: [Overcollateralized Rebalancing](../fcm/math.md#overcollateralized-rebalancing-hf--hf_max) +- **Undercollateralized Math**: [Undercollateralized Rebalancing](../fcm/math.md#undercollateralized-rebalancing-hf--hf_min) +- **Health Factor Formulas**: [Health Factor Mathematics](../fcm/math.md#health-factor) +- **Price Impact on Rebalancing**: [Price Impact Analysis](../fcm/math.md#price-impact-analysis) + +## Next Steps + +- **Understand automation**: [DeFi Actions Integration](./defi-actions.md) +- **See the big picture**: [Position Lifecycle](./position-lifecycle.md) +- **Explore liquidation protection**: [Liquidation System](./liquidation-system.md) +- **Learn credit mechanics**: [Credit Market Mechanics](./credit-market-mechanics.md) + +--- + +:::tip Key Takeaway +Rebalancing is ALP's secret weapon for capital efficiency. By automatically adjusting debt based on collateral value changes, it keeps positions optimized while protecting against liquidation. Combined with FYV as TopUpSource, you get truly hands-free DeFi lending! +::: diff --git a/docs/defi/fcm/architecture.md b/docs/defi/fcm/architecture.md new file mode 100644 index 0000000000..82e6c87b14 --- /dev/null +++ b/docs/defi/fcm/architecture.md @@ -0,0 +1,510 @@ +--- +title: FCM Architecture +sidebar_position: 3 +--- + +# FCM Architecture Overview + +This document explains how Flow Credit Market's three core components - ALP, FYV, and MOET - integrate to create a complete yield-generating system with automated liquidation prevention. + +## High-Level Architecture + +```mermaid +graph TB + subgraph "User Interface" + User[User/dApp] + end + + subgraph "FCM System" + subgraph "ALP - Lending Layer" + Pool[Pool Contract] + Position[Position] + Oracle[Price Oracle] + end + + subgraph "FYV - Yield Layer" + Strategy[Yield Strategy] + AutoBalancer[Auto Balancer] + Swapper[Token Swapper] + end + + subgraph "MOET - Currency Layer" + MOET[MOET Token] + Pricing[Price Feeds] + end + end + + subgraph "External Protocols" + DEX[DEXes/AMMs] + Farm[Yield Farms] + LP[Liquidity Pools] + end + + User -->|Deposit Collateral| Position + Position -->|Auto-borrow| MOET + MOET -->|Via DrawDownSink| Strategy + Strategy -->|Deploy| DEX + Strategy -->|Deploy| Farm + Strategy -->|Deploy| LP + + Oracle -->|MOET-denominated prices| Pool + Pricing -->|Price data| Oracle + + AutoBalancer -->|Manage exposure| Strategy + Strategy -->|Via TopUpSource| Position + + style ALP fill:#f9f,stroke:#333,stroke-width:3px + style FYV fill:#bfb,stroke:#333,stroke-width:3px + style MOET fill:#fbb,stroke:#333,stroke-width:3px +``` + +## Component Integration + +### 1. ALP ↔ MOET Integration + +**Purpose**: MOET serves as the unit of account and primary borrowed asset for ALP. + +**Integration points**: + +``` +ALP Pool +β”œβ”€β”€ defaultToken: Type<@MOET.Vault> +β”œβ”€β”€ priceOracle: Returns prices in MOET terms +β”œβ”€β”€ Auto-borrowing: Borrows MOET +└── Debt tracking: Denominated in MOET +``` + +**Key interactions**: + +1. **Price Quotation**: All token prices quoted in MOET + ``` + FLOW/MOET: 1.0 + USDC/MOET: 1.0 + stFLOW/MOET: 1.05 + ``` + +2. **Health Calculations**: All in MOET terms + ``` + Effective Collateral = FLOW amount Γ— FLOW/MOET price Γ— collateral factor + Effective Debt = MOET borrowed + Health Factor = Effective Collateral / Effective Debt + ``` + +3. **Auto-Borrowing**: Always borrows MOET + ``` + User deposits β†’ ALP calculates capacity β†’ Borrows MOET β†’ User receives MOET + ``` + +### 2. ALP ↔ FYV Integration + +**Purpose**: FYV receives borrowed funds from ALP and provides liquidity for liquidation prevention. + +**Integration via DeFi Actions**: + +``` +ALP Position +β”œβ”€β”€ DrawDownSink β†’ FYV Strategy (when overcollateralized) +└── TopUpSource ← FYV Strategy (when undercollateralized) +``` + +**Interaction flow**: + +#### Overcollateralized (HF > 1.5) + +```sequence +Position detects: HF = 1.8 (too high) +↓ +Position calculates: Can borrow $200 more MOET +↓ +Position borrows: 200 MOET from Pool +↓ +Position pushes: 200 MOET β†’ DrawDownSink +↓ +DrawDownSink = FYV Strategy +↓ +FYV Strategy swaps: 200 MOET β†’ 200 YieldToken +↓ +AutoBalancer holds: YieldToken, generates yield +``` + +#### Undercollateralized (HF < 1.1) + +```sequence +Position detects: HF = 1.05 (too low) +↓ +Position calculates: Need to repay $150 MOET +↓ +Position pulls: Request 150 MOET from TopUpSource +↓ +TopUpSource = FYV Strategy +↓ +FYV Strategy swaps: 150 YieldToken β†’ 150 MOET +↓ +Position repays: 150 MOET to Pool +↓ +New HF: 1.3 (restored to target) +``` + +**Code integration**: + +```cadence +// ALP side (simplified) +access(all) struct Position { + access(self) var drawDownSink: {DeFiActions.Sink}? + access(self) var topUpSource: {DeFiActions.Source}? + + // When overcollateralized + fun rebalanceDown() { + let borrowed <- pool.borrow(amount: excessCapacity) + self.drawDownSink?.deposit(vault: <-borrowed) + } + + // When undercollateralized + fun rebalanceUp() { + let repayment <- self.topUpSource?.withdraw(amount: shortfall) + pool.repay(vault: <-repayment) + } +} +``` + +```cadence +// FYV side (simplified) +access(all) struct TracerStrategy { + // Implements DeFi Actions interfaces + access(all) fun createSink(): {DeFiActions.Sink} { + // Returns sink that swaps MOET β†’ YieldToken + } + + access(all) fun createSource(): {DeFiActions.Source} { + // Returns source that swaps YieldToken β†’ MOET + } +} +``` + +### 3. FYV ↔ MOET Integration + +**Purpose**: MOET is the medium of exchange between FYV and external yield sources. + +**Flow**: + +``` +FYV receives MOET β†’ Swaps to target token β†’ Deploys to yield source +↓ +Time passes, yield accumulates +↓ +When needed: Exit yield source β†’ Swap to MOET β†’ Return to ALP +``` + +**Example with TracerStrategy**: + +``` +1. Receive MOET from ALP + β”œβ”€β”€ DrawDownSink.deposit(moetVault) + +2. Swap MOET β†’ YieldToken + β”œβ”€β”€ Swapper.swap(moet β†’ yieldToken) + └── AutoBalancer.hold(yieldToken) + +3. Generate yield + β”œβ”€β”€ YieldToken appreciates + β”œβ”€β”€ Farming rewards accrue + └── Trading fees accumulate + +4. Provide back to ALP (when needed) + β”œβ”€β”€ AutoBalancer.release(yieldToken) + β”œβ”€β”€ Swapper.swap(yieldToken β†’ moet) + └── TopUpSource.withdraw() returns MOET +``` + +## Data Flow Architecture + +### User Deposit Flow + +```mermaid +sequenceDiagram + participant User + participant Position + participant Pool + participant Oracle + participant DrawDownSink + participant FYV + + User->>Position: deposit(collateral) + Position->>Pool: updateCollateral(+amount) + Pool->>Pool: updateScaledBalance() + + Position->>Oracle: getPrice(collateralToken) + Oracle-->>Position: priceInMOET + + Position->>Position: calculateHealth() + alt HF > maxHealth + Position->>Pool: borrow(excessCapacity) + Pool-->>Position: MOET vault + Position->>DrawDownSink: deposit(MOET) + DrawDownSink->>FYV: swap & deploy + end + + Position-->>User: success +``` + +### Price Change & Rebalancing Flow + +```mermaid +sequenceDiagram + participant Oracle + participant Position + participant Pool + participant TopUpSource + participant FYV + + Oracle->>Oracle: Price update (collateral drops) + + Note over Position: Periodic check or triggered + + Position->>Oracle: getPrice(collateralToken) + Oracle-->>Position: newPrice (lower) + + Position->>Position: calculateHealth() + Position->>Position: health < minHealth! + + Position->>Position: calculate shortfall + Position->>TopUpSource: withdraw(shortfall) + + TopUpSource->>FYV: swap YieldToken β†’ MOET + FYV-->>TopUpSource: MOET vault + TopUpSource-->>Position: MOET vault + + Position->>Pool: repay(MOET) + Pool->>Pool: updateDebt(-amount) + + Position->>Position: calculateHealth() + Note over Position: health restored to 1.3 +``` + +## Component Responsibilities + +### ALP Responsibilities + +| Function | Description | +|----------|-------------| +| **Position Management** | Create, track, and manage user positions | +| **Collateral Tracking** | Monitor deposited collateral using scaled balances | +| **Debt Tracking** | Track borrowed amounts with interest accrual | +| **Health Monitoring** | Calculate and monitor position health factors | +| **Auto-Borrowing** | Automatically borrow MOET when overcollateralized | +| **Auto-Repayment** | Automatically repay when undercollateralized | +| **Liquidation** | Handle traditional liquidations if auto-repayment fails | +| **Interest Calculation** | Accrue interest on borrowed amounts | +| **Oracle Integration** | Query prices for health calculations | + +### FYV Responsibilities + +| Function | Description | +|----------|-------------| +| **Strategy Management** | Implement and manage yield strategies | +| **Capital Deployment** | Deploy received MOET to yield sources | +| **Yield Generation** | Generate returns through various mechanisms | +| **Token Swapping** | Swap between MOET and yield tokens | +| **Auto-Balancing** | Maintain optimal exposure to yield tokens | +| **Liquidity Provision** | Provide MOET when ALP needs rebalancing | +| **Risk Management** | Monitor and adjust strategy parameters | +| **Yield Compounding** | Reinvest returns for compound growth | + +### MOET Responsibilities + +| Function | Description | +|----------|-------------| +| **Unit of Account** | Provide standardized pricing unit | +| **Value Transfer** | Enable value flow between ALP and FYV | +| **Price Stability** | Maintain stable value (if stablecoin) | +| **Oracle Integration** | Provide price feeds for all assets | +| **Liquidity** | Ensure deep liquidity for swaps | + +## Communication Patterns + +### 1. DeFi Actions Pattern (ALP ↔ FYV) + +**Sink Pattern** (Push): +```cadence +// ALP pushes to FYV +access(all) resource interface Sink { + access(all) fun deposit(vault: @{FungibleToken.Vault}) +} + +// Usage +let sink = fyvStrategy.createSink() +sink.deposit(vault: <-moetVault) +``` + +**Source Pattern** (Pull): +```cadence +// ALP pulls from FYV +access(all) resource interface Source { + access(all) fun withdraw(amount: UFix64, type: Type): @{FungibleToken.Vault} +} + +// Usage +let source = fyvStrategy.createSource() +let moet <- source.withdraw(amount: 100.0, type: Type<@MOET.Vault>()) +``` + +### 2. Oracle Pattern (ALP ↔ MOET) + +**Price Query**: +```cadence +// ALP queries prices in MOET terms +access(all) resource interface PriceOracle { + access(all) fun getPrice(token: Type): UFix64 +} + +// Usage +let flowPrice = oracle.getPrice(Type<@FlowToken.Vault>()) +// Returns: 1.0 (1 FLOW = 1 MOET) +``` + +### 3. Event-Driven Pattern + +**Key events across components**: +```cadence +// ALP events +access(all) event PositionCreated(pid: UInt64, owner: Address) +access(all) event Borrowed(pid: UInt64, amount: UFix64) +access(all) event Repaid(pid: UInt64, amount: UFix64) +access(all) event Rebalanced(pid: UInt64, newHealth: UFix64) + +// FYV events +access(all) event StrategyDeployed(amount: UFix64, strategy: String) +access(all) event YieldGenerated(amount: UFix64) +access(all) event LiquidityProvided(amount: UFix64, toALP: Bool) + +// MOET events +access(all) event TokensMinted(amount: UFix64, recipient: Address) +access(all) event TokensBurned(amount: UFix64) +``` + +## System States + +### Normal Operation State + +``` +System State: Healthy +β”œβ”€β”€ ALP Positions: All HF between 1.1 and 1.5 +β”œβ”€β”€ FYV Strategies: Generating yield normally +β”œβ”€β”€ MOET: Stable and liquid +└── Oracles: Providing fresh prices + +Actions: +- Accept new deposits +- Allow withdrawals +- Process rebalancing +- Generate yield +``` + +### Stress State (Price Volatility) + +``` +System State: Under Stress +β”œβ”€β”€ ALP Positions: Some HF approaching 1.1 +β”œβ”€β”€ FYV Strategies: May need to provide liquidity +β”œβ”€β”€ MOET: May see increased trading volume +└── Oracles: Prices updating frequently + +Actions: +- Trigger frequent rebalancing +- FYV provides liquidity to ALP +- Some yield positions exited +- Increased monitoring +``` + +### Emergency State + +``` +System State: Emergency +β”œβ”€β”€ ALP Positions: Multiple HF < 1.0 +β”œβ”€β”€ FYV Strategies: Emergency liquidation mode +β”œβ”€β”€ MOET: Potential depeg risk +└── Oracles: Stale or unreliable + +Actions: +- Circuit breakers activated +- Liquidations triggered +- Deposits paused +- Admin intervention required +``` + +## Scalability & Performance + +### Optimizations + +1. **Scaled Balance System** (ALP): + - Avoids updating every position on interest accrual + - Single interest index update affects all positions + - Gas-efficient for large position counts + +2. **Batch Rebalancing** (ALP): + - Multiple positions can be rebalanced in one transaction + - Keepers can optimize gas costs + +3. **Lazy Evaluation** (All components): + - Prices only fetched when needed + - Health only calculated when accessed + - Interest only accrued when position touched + +4. **Event-Driven Updates** (All components): + - Off-chain indexers track state + - UI updates without constant blockchain queries + - Reduces RPC load + +### Limits & Constraints + +| Component | Limit | Reason | +|-----------|-------|--------| +| ALP Max Positions | Configurable | Gas limits for iteration | +| FYV Strategies per Vault | ~10-20 | Complexity management | +| Rebalancing Frequency | ~1 per block | Gas and Oracle freshness | +| Max Leverage | ~5x | Safety (1.0 HF = 100%, 1.1-1.5 range) | + +## Security Architecture + +### Defense in Depth + +**Layer 1: Input Validation** +- All user inputs sanitized +- Type checking enforced +- Capability-based access control + +**Layer 2: Business Logic** +- Health factor checks before operations +- Minimum/maximum limits enforced +- Oracle staleness checks + +**Layer 3: Circuit Breakers** +- Emergency pause functionality +- Liquidation warm-up periods +- Admin override capabilities + +**Layer 4: Economic Security** +- Over-collateralization requirements +- Liquidation incentives +- Oracle price deviation limits + +**Layer 5: Monitoring** +- Event emission for all critical operations +- Off-chain monitoring systems +- Automated alerts + +## Next Steps + +- **Understand the math**: [Mathematical Foundations](./math.md) +- **Explore ALP details**: [ALP Architecture](../alp/architecture.md) +- **Learn about FYV**: [FYV Documentation](../flow-yield-vaults/index.md) +- **Deep dive into MOET**: [MOET Documentation](../moet/index.md) + +--- + +:::tip Key Insight +FCM's architecture is designed for **composability** and **automation**. Each component has clear responsibilities and communicates through standardized interfaces (DeFi Actions), enabling: +- Independent development and upgrades +- Third-party strategy integrations +- System resilience through modularity +::: diff --git a/docs/defi/fcm/basics.md b/docs/defi/fcm/basics.md new file mode 100644 index 0000000000..9ea1dffb81 --- /dev/null +++ b/docs/defi/fcm/basics.md @@ -0,0 +1,444 @@ +--- +title: Understanding FCM Basics +sidebar_position: 2 +--- + +# Understanding FCM Basics + +To understand how Flow Credit Market (FCM) works, let's build up from simple lending concepts to FCM's innovative three-component architecture. + +## From Traditional Lending to FCM + +### Level 1: Traditional Lending (Aave, Compound) + +In traditional DeFi lending protocols: + +```mermaid +graph LR + User[User] -->|Deposit FLOW| Protocol[Lending Protocol] + Protocol -->|Borrow USDC| User + User -->|Repay + Interest| Protocol + + style Protocol fill:#bbf,stroke:#333,stroke-width:2px +``` + +**How it works**: +1. Deposit collateral (e.g., 1000 FLOW worth $1000) +2. Borrow up to ~75% of collateral value (e.g., $750 USDC) +3. Pay interest on borrowed amount +4. **Your responsibility**: Monitor health factor and manually manage position + +**Limitations**: Traditional lending requires you to manually monitor and rebalance positions, quickly add collateral or repay debt if collateral price drops, manually deploy borrowed funds to avoid them sitting idle, and act fast enough to prevent liquidation. + +### Level 2: Automated Lending (ALP) + +ALP adds automation to traditional lending: + +```mermaid +graph LR + User[User] -->|Deposit FLOW| ALP[ALP Position] + ALP -->|Auto-borrow MOET| User + + Price[Price Drop] -.->|Triggers| Rebalance[Auto-Rebalance] + Rebalance -->|Pulls funds| Source[TopUpSource] + Source -->|Repays debt| ALP + + style ALP fill:#f9f,stroke:#333,stroke-width:2px +``` + +**New features**: +- βœ… **Auto-borrowing**: Automatically borrows optimal amount when you deposit +- βœ… **Auto-rebalancing**: Maintains target health ratio automatically +- βœ… **TopUpSource integration**: Can pull from external sources to prevent liquidation + +**Better, but**: +- ⚠️ TopUpSource must have funds available +- ⚠️ Borrowed MOET still needs manual deployment for yield +- ⚠️ Still some manual intervention required + +### Level 3: FCM (ALP + FYV + MOET) + +FCM completes the automation by adding yield generation: + +```mermaid +graph TB + User[User] -->|1. Deposit FLOW| ALP[ALP Position] + ALP -->|2. Auto-borrow MOET| DrawDown[DrawDownSink] + DrawDown -->|3. Deploy| FYV[FYV Strategy] + FYV -->|4. Generate yield| Yield[Yield Tokens] + + Price[Price Drop] -.->|Triggers| ALP + FYV -->|5. Provide liquidity| TopUp[TopUpSource] + TopUp -->|6. Repay debt| ALP + + Yield -.->|Accumulates| FYV + + style ALP fill:#f9f,stroke:#333,stroke-width:4px + style FYV fill:#bfb,stroke:#333,stroke-width:4px + style MOET fill:#fbb,stroke:#333,stroke-width:2px +``` + +**Complete automation**: +- βœ… **Auto-borrowing**: Instantly borrow optimal amount +- βœ… **Auto-deployment**: Borrowed MOET flows directly to yield strategies +- βœ… **Auto-compounding**: FYV strategies reinvest yields +- βœ… **Auto-protection**: FYV provides liquidity to prevent liquidations +- βœ… **Auto-everything**: True set-and-forget experience + +**The breakthrough**: +- 🎯 **Yield protects your position**: Your generated yield maintains health automatically +- 🎯 **No manual intervention**: Everything happens automatically +- 🎯 **Capital efficiency**: Borrowed capital works for you immediately + +## Understanding the Three Components + +### Component 1: ALP (The Lending Engine) + +**What it does**: Manages collateral and debt positions with automated rebalancing. + +**Key concepts**: +- **Collateral**: Assets you deposit (FLOW, stFLOW, etc.) +- **Collateral Factor**: Percentage of collateral value you can borrow (e.g., 0.8 = 80%) +- **Health Factor**: Ratio of collateral to debt (must be > 1.0) +- **Target Health**: Optimal ratio the system maintains (typically 1.3) + +**Example**: +``` +Deposit: 1000 FLOW @ $1 = $1000 +Collateral Factor: 0.8 (80%) +Effective Collateral: $800 + +Target Health: 1.3 +Max Safe Borrow: $800 / 1.3 β‰ˆ $615.38 MOET + +ALP auto-borrows: 615.38 MOET +Position Health: 800 / 615.38 = 1.3 βœ“ +``` + +Learn more: [ALP Documentation](../alp/index.md) + +### Component 2: FYV (The Yield Engine) + +**What it does**: Deploys capital into yield-generating strategies and provides liquidity for liquidation prevention. + +**Key concepts**: +- **Strategies**: Predefined yield-generating approaches (TracerStrategy, etc.) +- **AutoBalancer**: Manages exposure to yield tokens and rebalancing +- **DrawDownSink**: Receives borrowed MOET from ALP +- **TopUpSource**: Provides liquidity back to ALP when needed + +**Example strategy (TracerStrategy)**: +``` +1. Receive MOET from ALP β†’ DrawDownSink +2. Swap MOET β†’ YieldToken (e.g., LP token, farm token) +3. Hold YieldToken in AutoBalancer +4. Accumulate yield over time +5. When ALP needs funds: + - Swap YieldToken β†’ MOET + - Provide via TopUpSource + - ALP repays debt +``` + +Learn more: [FYV Documentation](../flow-yield-vaults/index.md) + +### Component 3: MOET (The Unit of Account) + +**What it does**: Serves as the currency for all operations - borrowed asset, pricing unit, and value transfer medium. + +**Key concepts**: +- **Unit of Account**: All prices quoted in MOET (FLOW/MOET, USDC/MOET) +- **Primary Borrowed Asset**: What ALP auto-borrows and what FYV receives +- **Synthetic Stablecoin**: Value pegged to maintain stability +- **Medium of Exchange**: Flows between ALP and FYV + +**Why MOET?**: MOET standardizes all valuations, simplifies multi-collateral calculations, is designed specifically for DeFi operations, and provides deep integration with the Flow ecosystem. + +Learn more: [MOET Documentation](../moet/index.md) + +## The Capital Flow Cycle + +Let's follow $1000 of FLOW through the entire FCM system: + +### Phase 1: Initial Deposit and Borrowing + +``` +You deposit: 1000 FLOW worth $1000 +↓ +ALP calculates: + - Effective collateral: $1000 Γ— 0.8 = $800 + - Target health: 1.3 + - Borrow amount: $800 / 1.3 = $615.38 MOET +↓ +ALP auto-borrows: 615.38 MOET +↓ +MOET flows to: FYV strategy (via DrawDownSink) +↓ +FYV swaps: 615.38 MOET β†’ 615.38 YieldToken +↓ +Status: + - Your ALP position: 1000 FLOW collateral, 615.38 MOET debt + - Your FYV position: 615.38 YieldToken generating yield + - Health factor: 1.3 βœ“ +``` + +### Phase 2: Yield Generation + +``` +Time passes... +↓ +FYV Strategy generates yield: + - Trading fees from LP positions + - Farming rewards + - Interest from lending +↓ +Example after 1 month: + - YieldToken value: 615.38 β†’ 625.00 (+1.5% return) + - Yield earned: ~$10 +↓ +FYV holds: + - Original: 615.38 YieldToken + - Plus accumulated yield +``` + +### Phase 3: Price Drop & Auto-Protection + +``` +FLOW price drops: $1.00 β†’ $0.80 (-20%) +↓ +ALP detects: + - Collateral: 1000 FLOW @ $0.80 = $800 Γ— 0.8 = $640 effective + - Debt: 615.38 MOET + - New health: 640 / 615.38 = 1.04 (below min 1.1!) +↓ +ALP triggers rebalancing: + - Calculates required repayment + - Target debt: $640 / 1.3 = $492.31 MOET + - Needs to repay: 615.38 - 492.31 = 123.07 MOET +↓ +ALP pulls from FYV (TopUpSource): + - FYV swaps: 123.07 YieldToken β†’ 123.07 MOET + - Sends MOET to ALP +↓ +ALP repays debt: + - New debt: 492.31 MOET + - New health: 640 / 492.31 = 1.3 βœ“ +↓ +Status: + - ALP position: 1000 FLOW, 492.31 MOET debt, HF=1.3 + - FYV position: ~492 YieldToken remaining + - Liquidation prevented! βœ“ +``` + +### Phase 4: Price Recovery + +``` +FLOW price recovers: $0.80 β†’ $1.00 +↓ +ALP detects: + - Collateral: 1000 FLOW @ $1.00 = $1000 Γ— 0.8 = $800 effective + - Debt: 492.31 MOET + - New health: 800 / 492.31 = 1.625 (above max 1.5!) +↓ +ALP triggers rebalancing: + - Can borrow more to reach target health + - Target debt: $800 / 1.3 = $615.38 MOET + - Can borrow: 615.38 - 492.31 = 123.07 MOET +↓ +ALP auto-borrows: + - Borrows: 123.07 MOET + - Pushes to FYV (DrawDownSink) +↓ +FYV deploys: + - Swaps: 123.07 MOET β†’ 123.07 YieldToken + - Back to ~615 YieldToken +↓ +Status: + - ALP position: 1000 FLOW, 615.38 MOET debt, HF=1.3 + - FYV position: ~615 YieldToken generating yield + - Fully rebalanced and optimized! βœ“ +``` + +## Key Benefits Explained + +### 1. Yield-Powered Liquidation Prevention + +**Traditional protocol**: +``` +Price drops β†’ Health factor drops β†’ You must manually: + 1. Monitor the drop + 2. Decide: add collateral or repay debt? + 3. Find liquidity + 4. Execute transaction + 5. Hope you're not liquidated first +``` + +**FCM**: +``` +Price drops β†’ Health factor drops β†’ System automatically: + 1. Detects drop instantly + 2. Calculates exact repayment needed + 3. Pulls from your yield + 4. Repays debt + 5. Restores health + +All in one transaction, no intervention needed! +``` + +### 2. Capital Efficiency + +**Without FCM**: +``` +Scenario: Have 1000 FLOW, want to generate yield + +Option A: Just hold FLOW + - Capital: $1000 working + - Opportunity cost: Missing yield opportunities + +Option B: Deposit in lending protocol + - Earn deposit interest: ~3% APY + - Capital: $1000 working + - Yield: ~$30/year + +Option C: Manual yield farming + - Borrow against FLOW: ~$750 + - Deploy to farm: Complex, risky + - Must monitor constantly + - Risk liquidation +``` + +**With FCM**: +``` +Deposit 1000 FLOW β†’ FCM does everything: + - Borrow optimal amount: ~$615 MOET + - Deploy to best yield: Automatic + - Compound returns: Automatic + - Prevent liquidation: Automatic + - Potential yield: 5-15% APY (varies by strategy) + +Capital efficiency: Using collateral to earn yield on borrowed funds +Risk management: Yield protects against liquidation +Effort: Set and forget +``` + +### 3. Composability + +Each component has value independently: + +**Use ALP alone** when you: +- Want simple lending/borrowing +- Have your own yield strategies +- Need DeFi Actions integration + +**Use FYV alone** when you: +- Want yield aggregation +- Don't need leverage +- Prefer direct yield farming + +**Use FCM together** when you: +- Want maximum automation +- Desire liquidation protection +- Seek optimal capital efficiency + +## Understanding the Math + +### Health Factor Calculation + +``` +Health Factor = Effective Collateral / Effective Debt + +Effective Collateral = Token Amount Γ— Price Γ— Collateral Factor +Effective Debt = Borrowed Amount Γ— Price + +Example: + - 1000 FLOW @ $1 each Γ— 0.8 factor = $800 effective collateral + - 615.38 MOET @ $1 each = $615.38 effective debt + - Health Factor = 800 / 615.38 = 1.30 +``` + +### Target Health Ranges + +``` +Health Factor States: + +HF < 1.0 β†’ Liquidatable (immediate danger!) +HF = 1.0-1.1 β†’ At risk (very close to liquidation) +HF = 1.1-1.3 β†’ Below target (should rebalance up) +HF = 1.3 β†’ Target (optimal!) +HF = 1.3-1.5 β†’ Above target (can borrow more) +HF > 1.5 β†’ Overcollateralized (should rebalance down) +``` + +### Borrowing Capacity + +``` +Maximum Safe Borrow = Effective Collateral / Target Health + +Example with target health of 1.3: + - Effective collateral: $800 + - Max borrow: $800 / 1.3 = $615.38 MOET + +Why not borrow more? + - Need safety buffer for price volatility + - Target of 1.3 means 30% buffer above liquidation + - If you borrowed $800, health would be 1.0 (liquidatable immediately!) +``` + +Learn more: [Mathematical Foundations](./math.md) + +## Common Questions + +### How does FCM differ from Uniswap V3? + +**Uniswap V3** evolved from V2 by adding: +- Concentrated liquidity (specific price ranges) +- Multiple fee tiers +- Capital efficiency improvements +- More complex LP management + +**FCM** evolves from basic lending by adding: +- Automated position management +- Yield generation integration +- Liquidation prevention via yield +- Multi-component architecture (ALP + FYV + MOET) + +Both are "evolved" versions of simpler protocols, adding complexity for better capital efficiency. + +### Can I use FCM without understanding all three components? + +**Yes!** Think of it like using a car: +- **User level**: Just drive (deposit and earn yield) +- **Enthusiast level**: Understand the engine (how ALP, FYV, and MOET connect) +- **Builder level**: Modify and extend (create custom strategies) + +Start with user level, learn more as you go. + +### What happens if FYV doesn't have enough liquidity for rebalancing? + +Multiple fallback mechanisms: +1. **Primary**: FYV provides from yield +2. **Secondary**: FYV can exit positions partially +3. **Tertiary**: Traditional liquidation (external liquidators) +4. **Emergency**: Circuit breakers and admin intervention + +The system is designed with multiple safety layers. + +### Is my yield always enough to prevent liquidation? + +**Not guaranteed**, but highly likely because you're earning yield continuously, the system only pulls what's needed, the health buffer (1.3 target) provides cushion, and you can deposit more collateral anytime. Traditional protocols have 0% chance of automatic prevention - FCM gives you a strong automatic defense. + +## Next Steps + +Now that you understand the basics: + +1. **Learn the architecture**: [Architecture Overview](./architecture.md) +2. **Understand the math**: [Mathematical Foundations](./math.md) +3. **Explore components**: [ALP](../alp/index.md), [FYV](../flow-yield-vaults/index.md), [MOET](../moet/index.md) +4. **Start using FCM**: Follow the quick start guide + +--- + +:::tip Key Takeaway +FCM = Traditional Lending + Automation + Yield Generation + Liquidation Protection + +It's not just "another lending protocol" - it's a complete yield-generating system with automated risk management. +::: diff --git a/docs/defi/fcm/index.md b/docs/defi/fcm/index.md new file mode 100644 index 0000000000..a144b36dc9 --- /dev/null +++ b/docs/defi/fcm/index.md @@ -0,0 +1,184 @@ +--- +title: Flow Credit Market (FCM) +sidebar_label: Overview +sidebar_position: 1 +--- + +# Flow Credit Market (FCM) + +Flow Credit Market (FCM) is a comprehensive DeFi yield platform on Flow that combines automated lending, yield farming strategies, and a synthetic stablecoin to create a capital-efficient system for generating returns on crypto assets. + +## What is FCM? + +FCM is **not a single protocol** - it's an integrated system composed of three core components working together: + +```mermaid +graph LR + ALP[ALP
Automated Lending
Platform] --> FCM[Flow Credit
Market] + FYV[FYV
Flow Yield
Vaults] --> FCM + MOET[MOET
Synthetic
Stablecoin] --> FCM + + style FCM fill:#f9f,stroke:#333,stroke-width:4px + style ALP fill:#bbf,stroke:#333,stroke-width:2px + style FYV fill:#bfb,stroke:#333,stroke-width:2px + style MOET fill:#fbb,stroke:#333,stroke-width:2px +``` + +### The Three Components + +1. **[ALP (Automated Lending Platform)](../alp/index.md)**: The core lending/borrowing engine + - Manages collateral deposits and debt positions + - Provides automated rebalancing to maintain position health + - Uses DeFi Actions for composability + - Implements liquidation prevention mechanisms + +2. **[FYV (Flow Yield Vaults)](../flow-yield-vaults/index.md)**: The yield aggregation layer + - Deploys borrowed capital into optimal yield strategies + - Automatically compounds returns + - Provides liquidity for ALP liquidation prevention + - Manages risk through auto-balancing + +3. **[MOET](../moet/index.md)**: The synthetic stablecoin + - Serves as the unit of account for all pricing + - Primary borrowed asset in ALP + - Medium of exchange between components + - Maintains stability through over-collateralization + +## How the Components Work Together + +FCM creates a **yield-generating flywheel** by connecting these three components: + +### The Capital Flow + +```mermaid +sequenceDiagram + participant User + participant ALP + participant MOET + participant FYV + participant Yield + + User->>ALP: 1. Deposit FLOW collateral + ALP->>ALP: 2. Calculate borrowing capacity + ALP->>MOET: 3. Auto-borrow MOET + MOET->>FYV: 4. Deploy to yield strategy + FYV->>Yield: 5. Generate returns + Yield->>FYV: 6. Accumulate yield + + Note over ALP,FYV: When collateral price drops: + FYV->>ALP: 7. Provide funds for rebalancing + ALP->>MOET: 8. Repay debt automatically + + Note over User,ALP: Result: Position stays healthy +``` + +### Step-by-Step Flow + +1. **User deposits collateral** (e.g., FLOW tokens) into an ALP position +2. **ALP auto-borrows** MOET against the collateral to reach target health ratio (1.3) +3. **Borrowed MOET flows** to a FYV strategy (via DrawDownSink) +4. **FYV deploys capital** into yield-generating opportunities (farms, LPs, etc.) +5. **Yield accumulates** and compounds automatically +6. **If collateral price drops**: FYV provides liquidity to ALP (via TopUpSource) +7. **ALP repays debt** automatically to prevent liquidation +8. **User keeps position healthy** without manual intervention + +## Key Innovations + +### 1. Yield-Powered Liquidation Prevention + +Unlike traditional lending protocols where you must manually add collateral or repay debt when prices drop, FCM **uses your yield to maintain position health**. Yield from FYV strategies flows back to ALP automatically, ALP pulls from FYV to repay debt when needed, your position stays healthy without manual intervention, and **you earn yield while protecting yourself from liquidation**. + +### 2. Automated Capital Efficiency + +FCM maximizes your capital efficiency through automation: + +- **Auto-borrowing**: Instantly borrow optimal amount when depositing collateral +- **Auto-rebalancing**: Maintain target health ratio (1.1-1.5) automatically +- **Auto-compounding**: FYV strategies reinvest yields +- **Auto-protection**: Pull from yield to prevent liquidations + +### 3. Composable Architecture + +Each component can be used independently or together. Use **ALP alone** for traditional lending/borrowing, use **FYV alone** for yield aggregation, or use **FCM together** for the complete yield-generating system. + +## Why Use FCM? + +### For Yield Seekers + +FCM allows you to maximize returns by borrowing against collateral and deploying into high-yield strategies, leverage without liquidation risk as yield protects your positions, set and forget through complete automation, and compound returns as yields reinvest automatically. + +### For Conservative Users + +FCM provides liquidation protection through yield maintaining position health, flexible health targets allowing you to choose your risk tolerance (1.1-1.5), support for multiple collateral types including FLOW, stFLOW, USDC and more, and complete transparency with all logic on-chain and auditable. + +### For DeFi Builders + +FCM offers composable primitives allowing you to build on ALP, FYV, or both, standard interfaces for integration through DeFi Actions, the ability to create custom FYV strategies through extensible strategy patterns, and all code publicly available as open source. + +## Documentation Structure + +### Getting Started +- **[Understanding FCM Basics](./basics.md)** - Start here if you're new to FCM +- **[Architecture Overview](./architecture.md)** - How the three components integrate +- **[Mathematical Foundations](./math.md)** - The math behind FCM + +### Component Documentation +- **[ALP Documentation](../alp/index.md)** - Deep dive into the lending platform +- **[FYV Documentation](../flow-yield-vaults/index.md)** - Yield strategies and vaults +- **[MOET Documentation](../moet/index.md)** - The synthetic stablecoin + +### Advanced Topics +- **[Capital Flows](./capital-flows.md)** - How value moves through the system +- **[Risk Management](./risk-management.md)** - Understanding and managing risks +- **[Integration Guide](./integration.md)** - Building on top of FCM + +## Quick Start + +### As a User + +1. **Get collateral**: Acquire FLOW, stFLOW, or other supported tokens +2. **Connect wallet**: Use a Flow-compatible wallet +3. **Create position**: Deposit collateral to start earning +4. **Monitor health**: Track your position via the dashboard + +### As a Developer + +1. **Explore ALP**: Understand the lending primitives +2. **Study FYV**: Learn about yield strategies +3. **Read DeFi Actions**: Master the composability framework +4. **Build**: Create your own strategies or integrations + +## Key Metrics + +Understanding these metrics is crucial for using FCM: + +- **Health Factor**: Ratio of collateral value to debt (must stay above 1.0) +- **Target Health**: Optimal ratio (typically 1.3) +- **Collateral Factor**: Percentage of collateral value usable for borrowing (e.g., 0.8 = 80%) +- **APY**: Annual Percentage Yield from FYV strategies +- **Utilization Rate**: Percentage of ALP liquidity currently borrowed + +## Security & Audits + +FCM implements multiple security layers including smart contract audits for all core contracts, oracle safety through multiple price feed sources with staleness checks, multiple liquidation mechanisms to maintain solvency, circuit breakers for emergency pause functionality, and open source code that is publicly reviewable. + +## Community & Support + +- **GitHub**: [FlowCreditMarket](https://github.com/onflow/FlowCreditMarket) and [FlowYieldVaults](https://github.com/onflow/FlowYieldVaults) +- **Discord**: [Flow Discord](https://discord.gg/flow) - #fcm channel +- **Documentation**: This site +- **Developer Forums**: [Flow Forum](https://forum.onflow.org) + +## What's Next? + +- **New to FCM?** Start with [Understanding FCM Basics](./basics.md) +- **Want technical details?** Read the [Architecture Overview](./architecture.md) +- **Ready to use it?** Explore [ALP](../alp/index.md) or [FYV](../flow-yield-vaults/index.md) +- **Building an integration?** Check the [Integration Guide](./integration.md) + +--- + +:::tip +FCM is designed as a **composable system**. You don't need to use all three components - choose what fits your needs. But when used together, they create a powerful yield-generating machine with automated liquidation protection. +::: diff --git a/docs/defi/fcm/math.md b/docs/defi/fcm/math.md new file mode 100644 index 0000000000..9975281822 --- /dev/null +++ b/docs/defi/fcm/math.md @@ -0,0 +1,705 @@ +--- +title: Mathematical Foundations +sidebar_position: 4 +--- + +# Mathematical Foundations of FCM + +This document explains the mathematical models and formulas that power Flow Credit Market. Understanding these fundamentals helps you reason about system behavior and make informed decisions. + +## Core Variables + +### Token-Level Variables + +| Variable | Symbol | Description | +|----------|--------|-------------| +| **Price** | $P_t$ | Price of token $t$ in MOET terms | +| **Collateral Factor** | $CF_t$ | Usable percentage of token $t$ value (0 < $CF_t$ ≀ 1) | +| **Borrow Factor** | $BF_t$ | Multiplier for borrowed token $t$ (typically 1.0) | +| **Amount** | $A_t$ | Quantity of token $t$ | + +### Position-Level Variables + +| Variable | Symbol | Description | +|----------|--------|-------------| +| **Effective Collateral** | $EC$ | Total usable collateral value in MOET | +| **Effective Debt** | $ED$ | Total debt value in MOET | +| **Health Factor** | $HF$ | Ratio of collateral to debt | +| **Target Health** | $HF_{target}$ | Desired health ratio (typically 1.3) | +| **Min Health** | $HF_{min}$ | Minimum before rebalancing (typically 1.1) | +| **Max Health** | $HF_{max}$ | Maximum before rebalancing (typically 1.5) | + +### Interest Variables + +| Variable | Symbol | Description | +|----------|--------|-------------| +| **Interest Index** | $I_t(n)$ | Interest index for token $t$ at time $n$ | +| **Scaled Balance** | $B_{scaled}$ | Balance divided by interest index | +| **True Balance** | $B_{true}$ | Actual balance including accrued interest | +| **Interest Rate** | $r$ | Annual interest rate | + +## Fundamental Formulas + +### 1. Effective Collateral + +The effective collateral is the sum of all collateral assets multiplied by their prices and collateral factors: + +$$ +EC = \sum_{t \in \text{Collateral}} A_t \times P_t \times CF_t +$$ + +**Example**: +``` +Collateral assets: +- 1000 FLOW @ $1 each, CF = 0.8 +- 500 USDC @ $1 each, CF = 0.9 + +EC = (1000 Γ— 1 Γ— 0.8) + (500 Γ— 1 Γ— 0.9) + = 800 + 450 + = $1250 MOET +``` + +### 2. Effective Debt + +The effective debt is the sum of all borrowed assets multiplied by their prices and borrow factors: + +$$ +ED = \sum_{t \in \text{Debt}} A_t \times P_t \times BF_t +$$ + +**Example**: +``` +Debt: +- 800 MOET @ $1 each, BF = 1.0 + +ED = 800 Γ— 1 Γ— 1.0 + = $800 MOET +``` + +### 3. Health Factor + +The health factor is the ratio of effective collateral to effective debt: + +$$ +HF = \frac{EC}{ED} +$$ + +**Critical thresholds**: +- $HF < 1.0$: Position is liquidatable +- $HF = 1.0$: Exactly at liquidation threshold +- $HF > 1.0$: Position is solvent + +**Example**: +``` +EC = $1250, ED = $800 + +HF = 1250 / 800 = 1.5625 +``` + +### 4. Maximum Borrowing Capacity + +The maximum amount that can be borrowed to reach target health: + +$$ +\text{Max Borrow} = \frac{EC}{HF_{target}} +$$ + +**Derivation**: +``` +We want: HF = EC / ED = HF_target +Therefore: ED = EC / HF_target +``` + +**Example**: +``` +EC = $1250 +HF_target = 1.3 + +Max Borrow = 1250 / 1.3 = $961.54 MOET +``` + +## Auto-Borrowing Mathematics + +### Initial Auto-Borrow Amount + +When a user deposits collateral with `pushToDrawDownSink=true`, the system calculates the initial borrow amount: + +$$ +\text{Borrow Amount} = \frac{EC}{HF_{target}} +$$ + +**Step-by-step calculation**: + +1. **Calculate effective collateral**: + $$ + EC = A_{collateral} \times P_{collateral} \times CF_{collateral} + $$ + +2. **Calculate target debt**: + $$ + ED_{target} = \frac{EC}{HF_{target}} + $$ + +3. **Borrow to reach target**: + $$ + \text{Borrow} = ED_{target} = \frac{EC}{HF_{target}} + $$ + +**Complete example**: +``` +User deposits: 1000 FLOW +FLOW price: $1.00 +Collateral factor: 0.8 +Target health: 1.3 + +Step 1: EC = 1000 Γ— 1.00 Γ— 0.8 = $800 + +Step 2: ED_target = 800 / 1.3 = $615.38 + +Step 3: Borrow = $615.38 MOET + +Result: +- Collateral: 1000 FLOW ($800 effective) +- Debt: 615.38 MOET +- Health: 800 / 615.38 = 1.30 βœ“ +``` + +## Rebalancing Mathematics + +### Overcollateralized Rebalancing (HF > HF_max) + +When health exceeds maximum, calculate additional borrowing capacity: + +$$ +\text{Additional Borrow} = \frac{EC}{HF_{target}} - ED_{current} +$$ + +**Proof**: +``` +Want: HF_new = HF_target +HF_new = EC / ED_new = HF_target +ED_new = EC / HF_target + +Additional borrow = ED_new - ED_current + = (EC / HF_target) - ED_current +``` + +**Example**: +``` +Current state: +- EC = $800 +- ED = $400 +- HF = 800 / 400 = 2.0 (> HF_max of 1.5) + +Calculate additional borrow: +ED_target = 800 / 1.3 = $615.38 +Additional = 615.38 - 400 = $215.38 MOET + +After borrowing $215.38: +- EC = $800 (unchanged) +- ED = $615.38 +- HF = 800 / 615.38 = 1.30 βœ“ +``` + +### Undercollateralized Rebalancing (HF < HF_min) + +When health falls below minimum, calculate required repayment: + +$$ +\text{Required Repayment} = ED_{current} - \frac{EC}{HF_{target}} +$$ + +**Proof**: +``` +Want: HF_new = HF_target +HF_new = EC / ED_new = HF_target +ED_new = EC / HF_target + +Required repayment = ED_current - ED_new + = ED_current - (EC / HF_target) +``` + +**Example**: +``` +Price drops! Collateral value decreases. + +New state: +- EC = $640 (was $800, FLOW dropped 20%) +- ED = $615.38 (unchanged) +- HF = 640 / 615.38 = 1.04 (< HF_min of 1.1) + +Calculate required repayment: +ED_target = 640 / 1.3 = $492.31 +Repayment = 615.38 - 492.31 = $123.07 MOET + +After repaying $123.07: +- EC = $640 (unchanged) +- ED = $492.31 +- HF = 640 / 492.31 = 1.30 βœ“ +``` + +## Interest Mathematics + +### Scaled Balance System + +FCM uses **scaled balances** to efficiently track interest: + +$$ +B_{scaled} = \frac{B_{true}}{I_t} +$$ + +Where: +- $B_{scaled}$: Stored scaled balance +- $B_{true}$: Actual balance including interest +- $I_t$: Current interest index + +**Key insight**: Scaled balance stays constant while interest index grows. + +### Interest Index Growth + +The interest index grows continuously based on the interest rate: + +$$ +I_t(n+1) = I_t(n) \times (1 + r \times \Delta t) +$$ + +Where: +- $r$: Annual interest rate (e.g., 0.10 for 10%) +- $\Delta t$: Time elapsed (in years) + +**For compound interest**: +$$ +I_t(n) = I_0 \times e^{r \times t} +$$ + +Where $e$ is Euler's number (β‰ˆ2.718). + +### True Balance Calculation + +To get the current true balance from scaled balance: + +$$ +B_{true}(t) = B_{scaled} \times I_t +$$ + +**Example**: +``` +Initial deposit: 1000 MOET +Initial index: I_0 = 1.0 +Scaled balance: B_scaled = 1000 / 1.0 = 1000 + +After 1 year at 10% APY: +Interest index: I_1 = 1.0 Γ— e^(0.10 Γ— 1) β‰ˆ 1.105 +True balance: B_true = 1000 Γ— 1.105 = 1105 MOET + +User's debt grew from 1000 to 1105 MOET (10.5% with compound interest) +``` + +### Why Scaled Balances? + +**Without scaled balances**: +``` +Every block (every ~2 seconds): +- Update interest index +- Iterate through ALL positions +- Update each position's balance +- Gas cost: O(n) where n = number of positions +``` + +**With scaled balances**: +``` +Every block: +- Update interest index only +- Gas cost: O(1) + +When position is touched: +- Calculate true balance: scaled Γ— index +- Gas cost: O(1) per position +``` + +**Result**: Massive gas savings for the protocol! + +## Liquidation Mathematics + +### Liquidation Trigger + +A position becomes liquidatable when: + +$$ +HF < 1.0 +$$ + +Equivalently: +$$ +EC < ED +$$ + +### Liquidation Target + +Liquidations aim to restore health to a target (typically 1.05): + +$$ +HF_{liquidation} = 1.05 +$$ + +### Collateral Seized Calculation + +Amount of collateral to seize: + +$$ +\text{Collateral Seized} = \frac{ED_{repaid} \times (1 + \text{bonus})}{P_{collateral} \times CF_{collateral}} +$$ + +Where: +- $ED_{repaid}$: Amount of debt repaid by liquidator +- $\text{bonus}$: Liquidation bonus (e.g., 0.05 for 5%) +- $P_{collateral}$: Price of collateral token +- $CF_{collateral}$: Collateral factor + +**Example**: +``` +Liquidatable position: +- Collateral: 1000 FLOW @ $0.60 +- Debt: 650 MOET @ $1.00 +- HF = (1000 Γ— 0.60 Γ— 0.8) / 650 = 0.738 < 1.0 + +Liquidation: +- Liquidator repays: 150 MOET +- Liquidation bonus: 5% +- Collateral seized: (150 Γ— 1.05) / (0.60 Γ— 0.8) = 328.125 FLOW + +After liquidation: +- Collateral: 671.875 FLOW @ $0.60 = $403.125 effective +- Debt: 500 MOET +- HF = 403.125 / 500 = 0.806... + +(May need multiple liquidations or larger liquidation to reach target 1.05) +``` + +### Required Debt Repayment for Target Health + +To restore position to target health factor: + +$$ +ED_{repay} = ED_{current} - \frac{EC}{HF_{liquidation}} +$$ + +**Example**: +``` +From above, to reach HF = 1.05: +EC = 1000 Γ— 0.60 Γ— 0.8 = $480 +ED_current = $650 + +ED_target = 480 / 1.05 = $457.14 +ED_repay = 650 - 457.14 = $192.86 MOET must be repaid +``` + +## Price Impact Analysis + +### Health Factor Sensitivity to Price Changes + +Given a percentage change in collateral price: + +$$ +HF_{new} = HF_{old} \times \frac{P_{new}}{P_{old}} +$$ + +**Derivation**: +``` +HF_old = EC_old / ED = (A Γ— P_old Γ— CF) / ED + +HF_new = EC_new / ED = (A Γ— P_new Γ— CF) / ED + +HF_new / HF_old = P_new / P_old + +Therefore: HF_new = HF_old Γ— (P_new / P_old) +``` + +**Example**: +``` +Initial: HF = 1.5, Price = $1.00 + +Price drops 20% to $0.80: +HF_new = 1.5 Γ— (0.80 / 1.00) = 1.5 Γ— 0.80 = 1.20 + +Price drops 30% to $0.70: +HF_new = 1.5 Γ— (0.70 / 1.00) = 1.5 Γ— 0.70 = 1.05 (approaching danger!) + +Price drops 35% to $0.65: +HF_new = 1.5 Γ— (0.65 / 1.00) = 1.5 Γ— 0.65 = 0.975 < 1.0 (liquidatable!) +``` + +### Maximum Safe Price Drop + +What's the maximum price drop before liquidation? + +$$ +\text{Max Drop %} = 1 - \frac{1.0}{HF_{current}} +$$ + +**Derivation**: +``` +Want: HF_new = 1.0 (liquidation threshold) +HF_new = HF_old Γ— (P_new / P_old) = 1.0 + +P_new / P_old = 1.0 / HF_old + +P_new = P_old / HF_old + +Drop = P_old - P_new = P_old Γ— (1 - 1/HF_old) + +Drop % = 1 - 1/HF_old +``` + +**Examples**: +``` +HF = 1.3: Max drop = 1 - 1/1.3 = 23.08% +HF = 1.5: Max drop = 1 - 1/1.5 = 33.33% +HF = 2.0: Max drop = 1 - 1/2.0 = 50.00% +HF = 1.1: Max drop = 1 - 1/1.1 = 9.09% (very risky!) +``` + +## Multi-Collateral Mathematics + +### Multiple Collateral Types + +With multiple collateral types: + +$$ +EC = \sum_{i=1}^{n} A_i \times P_i \times CF_i +$$ + +Where $i$ iterates over all collateral token types. + +### Effective Collateral with Price Correlation + +When collateral types are correlated (e.g., FLOW and stFLOW): + +**Simplified (no correlation)**: +$$ +\text{Risk} = \sum_{i} \text{Risk}_i +$$ + +**With correlation** (advanced): +$$ +\text{Risk} = \sqrt{\sum_{i}\sum_{j} w_i w_j \sigma_i \sigma_j \rho_{ij}} +$$ + +Where: +- $w_i$: Weight of asset $i$ +- $\sigma_i$: Volatility of asset $i$ +- $\rho_{ij}$: Correlation between assets $i$ and $j$ + +**Practical impact**: +``` +Scenario 1: Uncorrelated collateral +- 50% FLOW (volatile) +- 50% USDC (stable) +- Effective diversification + +Scenario 2: Correlated collateral +- 50% FLOW (volatile) +- 50% stFLOW (volatile, correlated with FLOW) +- Limited diversification +- Both can drop together! +``` + +## Yield Calculations + +### Simple APY + +Annual Percentage Yield without compounding: + +$$ +\text{APY}_{simple} = \frac{\text{Final Value} - \text{Initial Value}}{\text{Initial Value}} \times \frac{365}{\text{Days}} +$$ + +### Compound APY + +With continuous compounding: + +$$ +\text{APY}_{compound} = e^r - 1 +$$ + +Where $r$ is the continuous annual rate. + +### Leveraged Yield + +When borrowing to increase yield exposure: + +$$ +\text{Yield}_{leveraged} = \text{Yield}_{strategy} - \text{Interest}_{borrowed} +$$ + +**Example**: +``` +Deposit: $1000 collateral +Borrow: $615 at 5% APY +Deploy $615 to strategy earning 10% APY + +Costs: +- Interest on borrowed: 615 Γ— 0.05 = $30.75/year + +Returns: +- Yield from strategy: 615 Γ— 0.10 = $61.50/year + +Net leveraged yield: 61.50 - 30.75 = $30.75/year +Effective APY on your $1000: 30.75 / 1000 = 3.075% extra +Total return: Base yield + leveraged yield +``` + +## Risk Metrics + +### Liquidation Risk Score + +A simplified risk score: + +$$ +\text{Risk Score} = \frac{1}{HF - 1.0} \times \text{Volatility}_{collateral} +$$ + +Higher score = higher risk. + +### Value at Risk (VaR) + +Maximum expected loss over time period at confidence level: + +$$ +\text{VaR}_{95\%} = EC \times \sigma \times z_{0.95} +$$ + +Where: +- $\sigma$: Daily volatility of collateral +- $z_{0.95}$: Z-score for 95% confidence (β‰ˆ1.645) + +**Example**: +``` +Collateral: $1000 FLOW +Daily volatility: 5% +Confidence: 95% + +VaR = 1000 Γ— 0.05 Γ— 1.645 = $82.25 + +Interpretation: 95% confident that daily loss won't exceed $82.25 +``` + +## Validation & Safety Checks + +### Health Factor Bounds + +All operations must satisfy: + +$$ +1.0 \leq HF_{min} < HF_{target} < HF_{max} +$$ + +Typical values: $HF_{min} = 1.1$, $HF_{target} = 1.3$, $HF_{max} = 1.5$ + +### Collateral Factor Bounds + +For safety: + +$$ +0 < CF_t \leq 1.0 +$$ + +Typically: +- Volatile assets (FLOW): $CF = 0.75 - 0.85$ +- Stable assets (USDC): $CF = 0.90 - 0.95$ +- Liquid staking (stFLOW): $CF = 0.80 - 0.85$ + +### Maximum Leverage + +Maximum theoretical leverage: + +$$ +\text{Max Leverage} = \frac{1}{1 - CF} +$$ + +**Examples**: +``` +CF = 0.8: Max leverage = 1 / (1 - 0.8) = 5x +CF = 0.75: Max leverage = 1 / (1 - 0.75) = 4x +CF = 0.9: Max leverage = 1 / (1 - 0.9) = 10x (risky!) +``` + +But actual safe leverage is constrained by target health: + +$$ +\text{Safe Leverage} = \frac{CF}{HF_{target}} +$$ + +**Examples**: +``` +CF = 0.8, HF = 1.3: Safe leverage = 0.8 / 1.3 β‰ˆ 0.615 = ~1.62x +CF = 0.75, HF = 1.5: Safe leverage = 0.75 / 1.5 = 0.50 = 1.5x +``` + +## Practical Examples + +### Complete Position Lifecycle Math + +``` +=== Initial Deposit === +Deposit: 1000 FLOW @ $1.00 +CF = 0.8, HF_target = 1.3 + +EC = 1000 Γ— 1.00 Γ— 0.8 = $800 +Borrow = 800 / 1.3 = $615.38 MOET +HF = 800 / 615.38 = 1.30 βœ“ + +=== Price Drop 20% === +New price: $0.80 +EC = 1000 Γ— 0.80 Γ— 0.8 = $640 +ED = $615.38 (unchanged) +HF = 640 / 615.38 = 1.04 < 1.1 ⚠️ + +Rebalance needed: +ED_target = 640 / 1.3 = $492.31 +Repay = 615.38 - 492.31 = $123.07 + +After repayment: +EC = $640, ED = $492.31 +HF = 640 / 492.31 = 1.30 βœ“ + +=== Price Recovery to $1.00 === +EC = 1000 Γ— 1.00 Γ— 0.8 = $800 +ED = $492.31 +HF = 800 / 492.31 = 1.625 > 1.5 ⚠️ + +Rebalance needed: +ED_target = 800 / 1.3 = $615.38 +Borrow = 615.38 - 492.31 = $123.07 + +After borrowing: +EC = $800, ED = $615.38 +HF = 800 / 615.38 = 1.30 βœ“ + +Position back to optimal state! +``` + +## Summary of Key Formulas + +| Formula | Expression | Use | +|---------|------------|-----| +| **Effective Collateral** | $EC = \sum A_t \times P_t \times CF_t$ | Calculate total collateral value | +| **Health Factor** | $HF = EC / ED$ | Monitor position safety | +| **Max Borrow** | $\text{Max} = EC / HF_{target}$ | Auto-borrowing amount | +| **Rebalance Up** | $\text{Repay} = ED - (EC / HF_{target})$ | Required debt reduction | +| **Rebalance Down** | $\text{Borrow} = (EC / HF_{target}) - ED$ | Additional borrowing capacity | +| **Scaled Balance** | $B_{scaled} = B_{true} / I_t$ | Interest-efficient tracking | +| **True Balance** | $B_{true} = B_{scaled} \times I_t$ | Current balance with interest | +| **Max Price Drop** | $\text{Drop%} = 1 - (1 / HF)$ | Liquidation safety margin | + +## Next Steps + +- **Apply these formulas**: [ALP Documentation](../alp/index.md) +- **Understand architecture**: [FCM Architecture](./architecture.md) +- **Learn the basics**: [Understanding FCM Basics](./basics.md) + +--- + +:::tip +These mathematical foundations ensure FCM operates predictably and safely. All formulas are implemented on-chain and can be verified by examining the smart contracts. +::: From 2eeea892d860743db2a222f5d39ae9cabb703f30 Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Thu, 18 Dec 2025 15:20:30 -0600 Subject: [PATCH 2/8] Fix broken markdown links and LaTeX parsing errors - Replace non-existent flow-yield-vaults and moet directory links with placeholders - Remove \text{} LaTeX commands causing acorn parsing errors in math.md - All formulas now use plain text variables instead of \text{} wrapper --- docs/defi/alp/defi-actions.md | 2 +- docs/defi/alp/index.md | 4 +-- docs/defi/alp/moet-role.md | 4 +-- docs/defi/fcm/architecture.md | 4 +-- docs/defi/fcm/basics.md | 6 ++--- docs/defi/fcm/index.md | 10 ++++---- docs/defi/fcm/math.md | 46 +++++++++++++++++------------------ 7 files changed, 38 insertions(+), 38 deletions(-) diff --git a/docs/defi/alp/defi-actions.md b/docs/defi/alp/defi-actions.md index 1901feda3c..cdcfb97388 100644 --- a/docs/defi/alp/defi-actions.md +++ b/docs/defi/alp/defi-actions.md @@ -5,7 +5,7 @@ sidebar_position: 7 # DeFi Actions Integration -DeFi Actions is a composability framework that enables ALP to integrate seamlessly with other DeFi protocols like [Flow Yield Vaults (FYV)](../flow-yield-vaults/index.md). This powerful abstraction allows for automated value flows and complex strategy compositions. +DeFi Actions is a composability framework that enables ALP to integrate seamlessly with other DeFi protocols like [Flow Yield Vaults (FYV)](#). This powerful abstraction allows for automated value flows and complex strategy compositions. ## Understanding DeFi Actions diff --git a/docs/defi/alp/index.md b/docs/defi/alp/index.md index 9f5a2899ca..6e9ea308c3 100644 --- a/docs/defi/alp/index.md +++ b/docs/defi/alp/index.md @@ -9,7 +9,7 @@ sidebar_position: 1 The Automated Lending Platform (ALP) is the core lending protocol component of [Flow Credit Market (FCM)](../fcm/index.md). ALP provides the foundational lending and borrowing infrastructure with automated position management and liquidation protection. :::info -ALP is one of three core components that make up FCM: ALP (Automated Lending Platform) provides the lending/borrowing engine, [Flow Yield Vaults (FYV)](../flow-yield-vaults/index.md) handles yield aggregation strategies, and [MOET](../moet/index.md) serves as the synthetic stablecoin and unit of account. +ALP is one of three core components that make up FCM: ALP (Automated Lending Platform) provides the lending/borrowing engine, [Flow Yield Vaults (FYV)](#) handles yield aggregation strategies, and [MOET](#) serves as the synthetic stablecoin and unit of account. ::: ## What is ALP? @@ -87,7 +87,7 @@ For most users, we recommend using **[Flow Credit Market (FCM)](../fcm/index.md) - [ALP GitHub Repository](https://github.com/onflow/FlowCreditMarket) (FlowCreditMarket contract) - [Flow Credit Market (FCM)](../fcm/index.md) - The complete product -- [MOET Token Documentation](../moet/index.md) +- [MOET Token Documentation](#) - [Flow Documentation](https://developers.flow.com) ## Security Considerations diff --git a/docs/defi/alp/moet-role.md b/docs/defi/alp/moet-role.md index 870ee234ca..c82a7fcd89 100644 --- a/docs/defi/alp/moet-role.md +++ b/docs/defi/alp/moet-role.md @@ -15,7 +15,7 @@ MOET plays a central role in ALP as the default token and primary unit of accoun - πŸ”„ **The rebalancing medium** - Used for all automated operations - πŸŒ‰ **The value bridge** - Flows between ALP and FYV -For more about MOET tokenomics, see the [MOET documentation](../moet/index.md). +For more about MOET tokenomics, see the [MOET documentation](#). ## MOET as Unit of Account @@ -427,7 +427,7 @@ MOET is central to all FCM calculations: - **Understand automation**: [Rebalancing Mechanics](./rebalancing.md) - **See the big picture**: [FCM Architecture](../fcm/architecture.md) -- **Deep dive on MOET**: [MOET Documentation](../moet/index.md) +- **Deep dive on MOET**: [MOET Documentation](#) - **Explore position management**: [Position Lifecycle](./position-lifecycle.md) --- diff --git a/docs/defi/fcm/architecture.md b/docs/defi/fcm/architecture.md index 82e6c87b14..0cdc6adb08 100644 --- a/docs/defi/fcm/architecture.md +++ b/docs/defi/fcm/architecture.md @@ -497,8 +497,8 @@ Actions: - **Understand the math**: [Mathematical Foundations](./math.md) - **Explore ALP details**: [ALP Architecture](../alp/architecture.md) -- **Learn about FYV**: [FYV Documentation](../flow-yield-vaults/index.md) -- **Deep dive into MOET**: [MOET Documentation](../moet/index.md) +- **Learn about FYV**: [FYV Documentation](#) +- **Deep dive into MOET**: [MOET Documentation](#) --- diff --git a/docs/defi/fcm/basics.md b/docs/defi/fcm/basics.md index 9ea1dffb81..37f3d1478f 100644 --- a/docs/defi/fcm/basics.md +++ b/docs/defi/fcm/basics.md @@ -139,7 +139,7 @@ Learn more: [ALP Documentation](../alp/index.md) - ALP repays debt ``` -Learn more: [FYV Documentation](../flow-yield-vaults/index.md) +Learn more: [FYV Documentation](#) ### Component 3: MOET (The Unit of Account) @@ -153,7 +153,7 @@ Learn more: [FYV Documentation](../flow-yield-vaults/index.md) **Why MOET?**: MOET standardizes all valuations, simplifies multi-collateral calculations, is designed specifically for DeFi operations, and provides deep integration with the Flow ecosystem. -Learn more: [MOET Documentation](../moet/index.md) +Learn more: [MOET Documentation](#) ## The Capital Flow Cycle @@ -432,7 +432,7 @@ Now that you understand the basics: 1. **Learn the architecture**: [Architecture Overview](./architecture.md) 2. **Understand the math**: [Mathematical Foundations](./math.md) -3. **Explore components**: [ALP](../alp/index.md), [FYV](../flow-yield-vaults/index.md), [MOET](../moet/index.md) +3. **Explore components**: [ALP](../alp/index.md), [FYV](#), [MOET](#) 4. **Start using FCM**: Follow the quick start guide --- diff --git a/docs/defi/fcm/index.md b/docs/defi/fcm/index.md index a144b36dc9..198d773847 100644 --- a/docs/defi/fcm/index.md +++ b/docs/defi/fcm/index.md @@ -32,13 +32,13 @@ graph LR - Uses DeFi Actions for composability - Implements liquidation prevention mechanisms -2. **[FYV (Flow Yield Vaults)](../flow-yield-vaults/index.md)**: The yield aggregation layer +2. **[FYV (Flow Yield Vaults)](#)**: The yield aggregation layer - Deploys borrowed capital into optimal yield strategies - Automatically compounds returns - Provides liquidity for ALP liquidation prevention - Manages risk through auto-balancing -3. **[MOET](../moet/index.md)**: The synthetic stablecoin +3. **[MOET](#)**: The synthetic stablecoin - Serves as the unit of account for all pricing - Primary borrowed asset in ALP - Medium of exchange between components @@ -125,8 +125,8 @@ FCM offers composable primitives allowing you to build on ALP, FYV, or both, sta ### Component Documentation - **[ALP Documentation](../alp/index.md)** - Deep dive into the lending platform -- **[FYV Documentation](../flow-yield-vaults/index.md)** - Yield strategies and vaults -- **[MOET Documentation](../moet/index.md)** - The synthetic stablecoin +- **[FYV Documentation](#)** - Yield strategies and vaults +- **[MOET Documentation](#)** - The synthetic stablecoin ### Advanced Topics - **[Capital Flows](./capital-flows.md)** - How value moves through the system @@ -174,7 +174,7 @@ FCM implements multiple security layers including smart contract audits for all - **New to FCM?** Start with [Understanding FCM Basics](./basics.md) - **Want technical details?** Read the [Architecture Overview](./architecture.md) -- **Ready to use it?** Explore [ALP](../alp/index.md) or [FYV](../flow-yield-vaults/index.md) +- **Ready to use it?** Explore [ALP](../alp/index.md) or [FYV](#) - **Building an integration?** Check the [Integration Guide](./integration.md) --- diff --git a/docs/defi/fcm/math.md b/docs/defi/fcm/math.md index 9975281822..c56163b8e0 100644 --- a/docs/defi/fcm/math.md +++ b/docs/defi/fcm/math.md @@ -45,7 +45,7 @@ This document explains the mathematical models and formulas that power Flow Cred The effective collateral is the sum of all collateral assets multiplied by their prices and collateral factors: $$ -EC = \sum_{t \in \text{Collateral}} A_t \times P_t \times CF_t +EC = \sum_{t \in Collateral} A_t \times P_t \times CF_t $$ **Example**: @@ -64,7 +64,7 @@ EC = (1000 Γ— 1 Γ— 0.8) + (500 Γ— 1 Γ— 0.9) The effective debt is the sum of all borrowed assets multiplied by their prices and borrow factors: $$ -ED = \sum_{t \in \text{Debt}} A_t \times P_t \times BF_t +ED = \sum_{t \in Debt} A_t \times P_t \times BF_t $$ **Example**: @@ -101,7 +101,7 @@ HF = 1250 / 800 = 1.5625 The maximum amount that can be borrowed to reach target health: $$ -\text{Max Borrow} = \frac{EC}{HF_{target}} +MaxBorrow = \frac{EC}{HF_{target}} $$ **Derivation**: @@ -125,7 +125,7 @@ Max Borrow = 1250 / 1.3 = $961.54 MOET When a user deposits collateral with `pushToDrawDownSink=true`, the system calculates the initial borrow amount: $$ -\text{Borrow Amount} = \frac{EC}{HF_{target}} +BorrowAmount = \frac{EC}{HF_{target}} $$ **Step-by-step calculation**: @@ -142,7 +142,7 @@ $$ 3. **Borrow to reach target**: $$ - \text{Borrow} = ED_{target} = \frac{EC}{HF_{target}} + Borrow = ED_{target} = \frac{EC}{HF_{target}} $$ **Complete example**: @@ -171,7 +171,7 @@ Result: When health exceeds maximum, calculate additional borrowing capacity: $$ -\text{Additional Borrow} = \frac{EC}{HF_{target}} - ED_{current} +AdditionalBorrow = \frac{EC}{HF_{target}} - ED_{current} $$ **Proof**: @@ -206,7 +206,7 @@ After borrowing $215.38: When health falls below minimum, calculate required repayment: $$ -\text{Required Repayment} = ED_{current} - \frac{EC}{HF_{target}} +RequiredRepayment = ED_{current} - \frac{EC}{HF_{target}} $$ **Proof**: @@ -347,12 +347,12 @@ $$ Amount of collateral to seize: $$ -\text{Collateral Seized} = \frac{ED_{repaid} \times (1 + \text{bonus})}{P_{collateral} \times CF_{collateral}} +CollateralSeized = \frac{ED_{repaid} \times (1 + bonus)}{P_{collateral} \times CF_{collateral}} $$ Where: - $ED_{repaid}$: Amount of debt repaid by liquidator -- $\text{bonus}$: Liquidation bonus (e.g., 0.05 for 5%) +- $bonus$: Liquidation bonus (e.g., 0.05 for 5%) - $P_{collateral}$: Price of collateral token - $CF_{collateral}$: Collateral factor @@ -434,7 +434,7 @@ HF_new = 1.5 Γ— (0.65 / 1.00) = 1.5 Γ— 0.65 = 0.975 < 1.0 (liquidatable!) What's the maximum price drop before liquidation? $$ -\text{Max Drop %} = 1 - \frac{1.0}{HF_{current}} +MaxDropPercent = 1 - \frac{1.0}{HF_{current}} $$ **Derivation**: @@ -477,12 +477,12 @@ When collateral types are correlated (e.g., FLOW and stFLOW): **Simplified (no correlation)**: $$ -\text{Risk} = \sum_{i} \text{Risk}_i +Risk = \sum_{i} Risk_i $$ **With correlation** (advanced): $$ -\text{Risk} = \sqrt{\sum_{i}\sum_{j} w_i w_j \sigma_i \sigma_j \rho_{ij}} +Risk = \sqrt{\sum_{i}\sum_{j} w_i w_j \sigma_i \sigma_j \rho_{ij}} $$ Where: @@ -511,7 +511,7 @@ Scenario 2: Correlated collateral Annual Percentage Yield without compounding: $$ -\text{APY}_{simple} = \frac{\text{Final Value} - \text{Initial Value}}{\text{Initial Value}} \times \frac{365}{\text{Days}} +APY_{simple} = \frac{FinalValue - InitialValue}{InitialValue} \times \frac{365}{Days} $$ ### Compound APY @@ -519,7 +519,7 @@ $$ With continuous compounding: $$ -\text{APY}_{compound} = e^r - 1 +APY_{compound} = e^r - 1 $$ Where $r$ is the continuous annual rate. @@ -529,7 +529,7 @@ Where $r$ is the continuous annual rate. When borrowing to increase yield exposure: $$ -\text{Yield}_{leveraged} = \text{Yield}_{strategy} - \text{Interest}_{borrowed} +Yield_{leveraged} = Yield_{strategy} - Interest_{borrowed} $$ **Example**: @@ -556,7 +556,7 @@ Total return: Base yield + leveraged yield A simplified risk score: $$ -\text{Risk Score} = \frac{1}{HF - 1.0} \times \text{Volatility}_{collateral} +\text{Risk Score} = \frac{1}{HF - 1.0} \times Volatility_{collateral} $$ Higher score = higher risk. @@ -566,7 +566,7 @@ Higher score = higher risk. Maximum expected loss over time period at confidence level: $$ -\text{VaR}_{95\%} = EC \times \sigma \times z_{0.95} +VaR_{95\%} = EC \times \sigma \times z_{0.95} $$ Where: @@ -614,7 +614,7 @@ Typically: Maximum theoretical leverage: $$ -\text{Max Leverage} = \frac{1}{1 - CF} +MaxLeverage = \frac{1}{1 - CF} $$ **Examples**: @@ -627,7 +627,7 @@ CF = 0.9: Max leverage = 1 / (1 - 0.9) = 10x (risky!) But actual safe leverage is constrained by target health: $$ -\text{Safe Leverage} = \frac{CF}{HF_{target}} +SafeLeverage = \frac{CF}{HF_{target}} $$ **Examples**: @@ -685,12 +685,12 @@ Position back to optimal state! |---------|------------|-----| | **Effective Collateral** | $EC = \sum A_t \times P_t \times CF_t$ | Calculate total collateral value | | **Health Factor** | $HF = EC / ED$ | Monitor position safety | -| **Max Borrow** | $\text{Max} = EC / HF_{target}$ | Auto-borrowing amount | -| **Rebalance Up** | $\text{Repay} = ED - (EC / HF_{target})$ | Required debt reduction | -| **Rebalance Down** | $\text{Borrow} = (EC / HF_{target}) - ED$ | Additional borrowing capacity | +| **Max Borrow** | $Max = EC / HF_{target}$ | Auto-borrowing amount | +| **Rebalance Up** | $Repay = ED - (EC / HF_{target})$ | Required debt reduction | +| **Rebalance Down** | $Borrow = (EC / HF_{target}) - ED$ | Additional borrowing capacity | | **Scaled Balance** | $B_{scaled} = B_{true} / I_t$ | Interest-efficient tracking | | **True Balance** | $B_{true} = B_{scaled} \times I_t$ | Current balance with interest | -| **Max Price Drop** | $\text{Drop%} = 1 - (1 / HF)$ | Liquidation safety margin | +| **Max Price Drop** | $DropPercent = 1 - (1 / HF)$ | Liquidation safety margin | ## Next Steps From d79ac0c824e1db427a1d15d07021b10a10ad7f01 Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Thu, 18 Dec 2025 15:26:36 -0600 Subject: [PATCH 3/8] Fix additional broken links and convert all LaTeX blocks to code blocks - Replace broken links: capital-flows.md, risk-management.md, integration.md - Convert all $$ LaTeX blocks to ```math code blocks for MDX compatibility - Remove LaTeX \sum and \in operators causing acorn parsing errors - Use plain mathematical notation instead of LaTeX commands --- docs/defi/fcm/index.md | 8 +-- docs/defi/fcm/math.md | 134 ++++++++++++++++++++--------------------- 2 files changed, 71 insertions(+), 71 deletions(-) diff --git a/docs/defi/fcm/index.md b/docs/defi/fcm/index.md index 198d773847..8e85651a59 100644 --- a/docs/defi/fcm/index.md +++ b/docs/defi/fcm/index.md @@ -129,9 +129,9 @@ FCM offers composable primitives allowing you to build on ALP, FYV, or both, sta - **[MOET Documentation](#)** - The synthetic stablecoin ### Advanced Topics -- **[Capital Flows](./capital-flows.md)** - How value moves through the system -- **[Risk Management](./risk-management.md)** - Understanding and managing risks -- **[Integration Guide](./integration.md)** - Building on top of FCM +- **[Capital Flows](#)** - How value moves through the system +- **[Risk Management](#)** - Understanding and managing risks +- **[Integration Guide](#)** - Building on top of FCM ## Quick Start @@ -175,7 +175,7 @@ FCM implements multiple security layers including smart contract audits for all - **New to FCM?** Start with [Understanding FCM Basics](./basics.md) - **Want technical details?** Read the [Architecture Overview](./architecture.md) - **Ready to use it?** Explore [ALP](../alp/index.md) or [FYV](#) -- **Building an integration?** Check the [Integration Guide](./integration.md) +- **Building an integration?** Check the [Integration Guide](#) --- diff --git a/docs/defi/fcm/math.md b/docs/defi/fcm/math.md index c56163b8e0..b665991246 100644 --- a/docs/defi/fcm/math.md +++ b/docs/defi/fcm/math.md @@ -44,9 +44,9 @@ This document explains the mathematical models and formulas that power Flow Cred The effective collateral is the sum of all collateral assets multiplied by their prices and collateral factors: -$$ -EC = \sum_{t \in Collateral} A_t \times P_t \times CF_t -$$ +```math +EC = βˆ‘(A_t Γ— P_t Γ— CF_t) for all t in Collateral +``` **Example**: ``` @@ -63,9 +63,9 @@ EC = (1000 Γ— 1 Γ— 0.8) + (500 Γ— 1 Γ— 0.9) The effective debt is the sum of all borrowed assets multiplied by their prices and borrow factors: -$$ +```math ED = \sum_{t \in Debt} A_t \times P_t \times BF_t -$$ +``` **Example**: ``` @@ -80,9 +80,9 @@ ED = 800 Γ— 1 Γ— 1.0 The health factor is the ratio of effective collateral to effective debt: -$$ +```math HF = \frac{EC}{ED} -$$ +``` **Critical thresholds**: - $HF < 1.0$: Position is liquidatable @@ -100,9 +100,9 @@ HF = 1250 / 800 = 1.5625 The maximum amount that can be borrowed to reach target health: -$$ +```math MaxBorrow = \frac{EC}{HF_{target}} -$$ +``` **Derivation**: ``` @@ -124,26 +124,26 @@ Max Borrow = 1250 / 1.3 = $961.54 MOET When a user deposits collateral with `pushToDrawDownSink=true`, the system calculates the initial borrow amount: -$$ +```math BorrowAmount = \frac{EC}{HF_{target}} -$$ +``` **Step-by-step calculation**: 1. **Calculate effective collateral**: - $$ + ```math EC = A_{collateral} \times P_{collateral} \times CF_{collateral} - $$ +```math 2. **Calculate target debt**: - $$ +``` ED_{target} = \frac{EC}{HF_{target}} - $$ +```math 3. **Borrow to reach target**: - $$ +``` Borrow = ED_{target} = \frac{EC}{HF_{target}} - $$ +```math **Complete example**: ``` @@ -170,9 +170,9 @@ Result: When health exceeds maximum, calculate additional borrowing capacity: -$$ +``` AdditionalBorrow = \frac{EC}{HF_{target}} - ED_{current} -$$ +```math **Proof**: ``` @@ -205,9 +205,9 @@ After borrowing $215.38: When health falls below minimum, calculate required repayment: -$$ +``` RequiredRepayment = ED_{current} - \frac{EC}{HF_{target}} -$$ +```math **Proof**: ``` @@ -244,9 +244,9 @@ After repaying $123.07: FCM uses **scaled balances** to efficiently track interest: -$$ +``` B_{scaled} = \frac{B_{true}}{I_t} -$$ +```math Where: - $B_{scaled}$: Stored scaled balance @@ -259,18 +259,18 @@ Where: The interest index grows continuously based on the interest rate: -$$ +``` I_t(n+1) = I_t(n) \times (1 + r \times \Delta t) -$$ +```math Where: - $r$: Annual interest rate (e.g., 0.10 for 10%) - $\Delta t$: Time elapsed (in years) **For compound interest**: -$$ +``` I_t(n) = I_0 \times e^{r \times t} -$$ +```math Where $e$ is Euler's number (β‰ˆ2.718). @@ -278,9 +278,9 @@ Where $e$ is Euler's number (β‰ˆ2.718). To get the current true balance from scaled balance: -$$ +``` B_{true}(t) = B_{scaled} \times I_t -$$ +```math **Example**: ``` @@ -325,30 +325,30 @@ When position is touched: A position becomes liquidatable when: -$$ +``` HF < 1.0 -$$ +```math Equivalently: -$$ +``` EC < ED -$$ +```math ### Liquidation Target Liquidations aim to restore health to a target (typically 1.05): -$$ +``` HF_{liquidation} = 1.05 -$$ +```math ### Collateral Seized Calculation Amount of collateral to seize: -$$ +``` CollateralSeized = \frac{ED_{repaid} \times (1 + bonus)}{P_{collateral} \times CF_{collateral}} -$$ +```math Where: - $ED_{repaid}$: Amount of debt repaid by liquidator @@ -380,9 +380,9 @@ After liquidation: To restore position to target health factor: -$$ +``` ED_{repay} = ED_{current} - \frac{EC}{HF_{liquidation}} -$$ +```math **Example**: ``` @@ -400,9 +400,9 @@ ED_repay = 650 - 457.14 = $192.86 MOET must be repaid Given a percentage change in collateral price: -$$ +``` HF_{new} = HF_{old} \times \frac{P_{new}}{P_{old}} -$$ +```math **Derivation**: ``` @@ -433,9 +433,9 @@ HF_new = 1.5 Γ— (0.65 / 1.00) = 1.5 Γ— 0.65 = 0.975 < 1.0 (liquidatable!) What's the maximum price drop before liquidation? -$$ +``` MaxDropPercent = 1 - \frac{1.0}{HF_{current}} -$$ +```math **Derivation**: ``` @@ -465,9 +465,9 @@ HF = 1.1: Max drop = 1 - 1/1.1 = 9.09% (very risky!) With multiple collateral types: -$$ +``` EC = \sum_{i=1}^{n} A_i \times P_i \times CF_i -$$ +```math Where $i$ iterates over all collateral token types. @@ -476,14 +476,14 @@ Where $i$ iterates over all collateral token types. When collateral types are correlated (e.g., FLOW and stFLOW): **Simplified (no correlation)**: -$$ +``` Risk = \sum_{i} Risk_i -$$ +```math **With correlation** (advanced): -$$ +``` Risk = \sqrt{\sum_{i}\sum_{j} w_i w_j \sigma_i \sigma_j \rho_{ij}} -$$ +```math Where: - $w_i$: Weight of asset $i$ @@ -510,17 +510,17 @@ Scenario 2: Correlated collateral Annual Percentage Yield without compounding: -$$ +``` APY_{simple} = \frac{FinalValue - InitialValue}{InitialValue} \times \frac{365}{Days} -$$ +```math ### Compound APY With continuous compounding: -$$ +``` APY_{compound} = e^r - 1 -$$ +```math Where $r$ is the continuous annual rate. @@ -528,9 +528,9 @@ Where $r$ is the continuous annual rate. When borrowing to increase yield exposure: -$$ +``` Yield_{leveraged} = Yield_{strategy} - Interest_{borrowed} -$$ +```math **Example**: ``` @@ -555,9 +555,9 @@ Total return: Base yield + leveraged yield A simplified risk score: -$$ +``` \text{Risk Score} = \frac{1}{HF - 1.0} \times Volatility_{collateral} -$$ +```math Higher score = higher risk. @@ -565,9 +565,9 @@ Higher score = higher risk. Maximum expected loss over time period at confidence level: -$$ +``` VaR_{95\%} = EC \times \sigma \times z_{0.95} -$$ +```math Where: - $\sigma$: Daily volatility of collateral @@ -590,9 +590,9 @@ Interpretation: 95% confident that daily loss won't exceed $82.25 All operations must satisfy: -$$ +``` 1.0 \leq HF_{min} < HF_{target} < HF_{max} -$$ +```math Typical values: $HF_{min} = 1.1$, $HF_{target} = 1.3$, $HF_{max} = 1.5$ @@ -600,9 +600,9 @@ Typical values: $HF_{min} = 1.1$, $HF_{target} = 1.3$, $HF_{max} = 1.5$ For safety: -$$ +``` 0 < CF_t \leq 1.0 -$$ +```math Typically: - Volatile assets (FLOW): $CF = 0.75 - 0.85$ @@ -613,9 +613,9 @@ Typically: Maximum theoretical leverage: -$$ +``` MaxLeverage = \frac{1}{1 - CF} -$$ +```math **Examples**: ``` @@ -626,9 +626,9 @@ CF = 0.9: Max leverage = 1 / (1 - 0.9) = 10x (risky!) But actual safe leverage is constrained by target health: -$$ +``` SafeLeverage = \frac{CF}{HF_{target}} -$$ +``` **Examples**: ``` From fada04f0de0fe6c8eda1686e91c9e4eb5e18668a Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Thu, 18 Dec 2025 15:30:58 -0600 Subject: [PATCH 4/8] Replace all LaTeX commands with Unicode and fix code block alignment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Convert LaTeX math operators to Unicode equivalents (Γ— Γ· ≀ β‰₯ β‰ˆ) - Replace \frac{a}{b} with (a / b) notation - Simplify subscripts from _{text} to _text - Fix misaligned code block markers throughout document - Remove all remaining LaTeX that causes MDX parsing errors --- docs/defi/fcm/math.md | 154 +++++++++++++++++++++--------------------- 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/docs/defi/fcm/math.md b/docs/defi/fcm/math.md index b665991246..dbe22a6af3 100644 --- a/docs/defi/fcm/math.md +++ b/docs/defi/fcm/math.md @@ -25,17 +25,17 @@ This document explains the mathematical models and formulas that power Flow Cred | **Effective Collateral** | $EC$ | Total usable collateral value in MOET | | **Effective Debt** | $ED$ | Total debt value in MOET | | **Health Factor** | $HF$ | Ratio of collateral to debt | -| **Target Health** | $HF_{target}$ | Desired health ratio (typically 1.3) | -| **Min Health** | $HF_{min}$ | Minimum before rebalancing (typically 1.1) | -| **Max Health** | $HF_{max}$ | Maximum before rebalancing (typically 1.5) | +| **Target Health** | $HF_target$ | Desired health ratio (typically 1.3) | +| **Min Health** | $HF_min$ | Minimum before rebalancing (typically 1.1) | +| **Max Health** | $HF_max$ | Maximum before rebalancing (typically 1.5) | ### Interest Variables | Variable | Symbol | Description | |----------|--------|-------------| | **Interest Index** | $I_t(n)$ | Interest index for token $t$ at time $n$ | -| **Scaled Balance** | $B_{scaled}$ | Balance divided by interest index | -| **True Balance** | $B_{true}$ | Actual balance including accrued interest | +| **Scaled Balance** | $B_scaled$ | Balance divided by interest index | +| **True Balance** | $B_true$ | Actual balance including accrued interest | | **Interest Rate** | $r$ | Annual interest rate | ## Fundamental Formulas @@ -64,7 +64,7 @@ EC = (1000 Γ— 1 Γ— 0.8) + (500 Γ— 1 Γ— 0.9) The effective debt is the sum of all borrowed assets multiplied by their prices and borrow factors: ```math -ED = \sum_{t \in Debt} A_t \times P_t \times BF_t +ED = \sum_t \in Debt A_t Γ— P_t Γ— BF_t ``` **Example**: @@ -81,7 +81,7 @@ ED = 800 Γ— 1 Γ— 1.0 The health factor is the ratio of effective collateral to effective debt: ```math -HF = \frac{EC}{ED} +HF = (EC / ED) ``` **Critical thresholds**: @@ -101,7 +101,7 @@ HF = 1250 / 800 = 1.5625 The maximum amount that can be borrowed to reach target health: ```math -MaxBorrow = \frac{EC}{HF_{target}} +MaxBorrow = (EC / HF_target) ``` **Derivation**: @@ -125,25 +125,25 @@ Max Borrow = 1250 / 1.3 = $961.54 MOET When a user deposits collateral with `pushToDrawDownSink=true`, the system calculates the initial borrow amount: ```math -BorrowAmount = \frac{EC}{HF_{target}} +BorrowAmount = (EC / HF_target) ``` **Step-by-step calculation**: 1. **Calculate effective collateral**: - ```math - EC = A_{collateral} \times P_{collateral} \times CF_{collateral} -```math +``` + EC = A_collateral Γ— P_collateral Γ— CF_collateral +``` 2. **Calculate target debt**: ``` - ED_{target} = \frac{EC}{HF_{target}} -```math + ED_target = (EC / HF_target) +``` 3. **Borrow to reach target**: ``` - Borrow = ED_{target} = \frac{EC}{HF_{target}} -```math + Borrow = ED_target = (EC / HF_target) +``` **Complete example**: ``` @@ -171,8 +171,8 @@ Result: When health exceeds maximum, calculate additional borrowing capacity: ``` -AdditionalBorrow = \frac{EC}{HF_{target}} - ED_{current} -```math +AdditionalBorrow = (EC / HF_target) - ED_current +``` **Proof**: ``` @@ -206,8 +206,8 @@ After borrowing $215.38: When health falls below minimum, calculate required repayment: ``` -RequiredRepayment = ED_{current} - \frac{EC}{HF_{target}} -```math +RequiredRepayment = ED_current - (EC / HF_target) +``` **Proof**: ``` @@ -245,12 +245,12 @@ After repaying $123.07: FCM uses **scaled balances** to efficiently track interest: ``` -B_{scaled} = \frac{B_{true}}{I_t} -```math +B_scaled = \frac{B_true}{I_t} +``` Where: -- $B_{scaled}$: Stored scaled balance -- $B_{true}$: Actual balance including interest +- $B_scaled$: Stored scaled balance +- $B_true$: Actual balance including interest - $I_t$: Current interest index **Key insight**: Scaled balance stays constant while interest index grows. @@ -260,8 +260,8 @@ Where: The interest index grows continuously based on the interest rate: ``` -I_t(n+1) = I_t(n) \times (1 + r \times \Delta t) -```math +I_t(n+1) = I_t(n) Γ— (1 + r Γ— \Delta t) +``` Where: - $r$: Annual interest rate (e.g., 0.10 for 10%) @@ -269,8 +269,8 @@ Where: **For compound interest**: ``` -I_t(n) = I_0 \times e^{r \times t} -```math +I_t(n) = I_0 Γ— e^{r Γ— t} +``` Where $e$ is Euler's number (β‰ˆ2.718). @@ -279,8 +279,8 @@ Where $e$ is Euler's number (β‰ˆ2.718). To get the current true balance from scaled balance: ``` -B_{true}(t) = B_{scaled} \times I_t -```math +B_true(t) = B_scaled Γ— I_t +``` **Example**: ``` @@ -327,34 +327,34 @@ A position becomes liquidatable when: ``` HF < 1.0 -```math +``` Equivalently: ``` EC < ED -```math +``` ### Liquidation Target Liquidations aim to restore health to a target (typically 1.05): ``` -HF_{liquidation} = 1.05 -```math +HF_liquidation = 1.05 +``` ### Collateral Seized Calculation Amount of collateral to seize: ``` -CollateralSeized = \frac{ED_{repaid} \times (1 + bonus)}{P_{collateral} \times CF_{collateral}} -```math +CollateralSeized = \frac{ED_repaid Γ— (1 + bonus)}{P_collateral Γ— CF_collateral} +``` Where: -- $ED_{repaid}$: Amount of debt repaid by liquidator +- $ED_repaid$: Amount of debt repaid by liquidator - $bonus$: Liquidation bonus (e.g., 0.05 for 5%) -- $P_{collateral}$: Price of collateral token -- $CF_{collateral}$: Collateral factor +- $P_collateral$: Price of collateral token +- $CF_collateral$: Collateral factor **Example**: ``` @@ -381,8 +381,8 @@ After liquidation: To restore position to target health factor: ``` -ED_{repay} = ED_{current} - \frac{EC}{HF_{liquidation}} -```math +ED_repay = ED_current - (EC / HF_liquidation) +``` **Example**: ``` @@ -401,8 +401,8 @@ ED_repay = 650 - 457.14 = $192.86 MOET must be repaid Given a percentage change in collateral price: ``` -HF_{new} = HF_{old} \times \frac{P_{new}}{P_{old}} -```math +HF_new = HF_old Γ— \frac{P_new}{P_old} +``` **Derivation**: ``` @@ -434,8 +434,8 @@ HF_new = 1.5 Γ— (0.65 / 1.00) = 1.5 Γ— 0.65 = 0.975 < 1.0 (liquidatable!) What's the maximum price drop before liquidation? ``` -MaxDropPercent = 1 - \frac{1.0}{HF_{current}} -```math +MaxDropPercent = 1 - (1.0 / HF_current) +``` **Derivation**: ``` @@ -466,8 +466,8 @@ HF = 1.1: Max drop = 1 - 1/1.1 = 9.09% (very risky!) With multiple collateral types: ``` -EC = \sum_{i=1}^{n} A_i \times P_i \times CF_i -```math +EC = \sum_i=1^{n} A_i Γ— P_i Γ— CF_i +``` Where $i$ iterates over all collateral token types. @@ -477,18 +477,18 @@ When collateral types are correlated (e.g., FLOW and stFLOW): **Simplified (no correlation)**: ``` -Risk = \sum_{i} Risk_i -```math +Risk = \sum_i Risk_i +``` **With correlation** (advanced): ``` -Risk = \sqrt{\sum_{i}\sum_{j} w_i w_j \sigma_i \sigma_j \rho_{ij}} -```math +Risk = \sqrt{\sum_i\sum_j w_i w_j \sigma_i \sigma_j \rho_ij} +``` Where: - $w_i$: Weight of asset $i$ - $\sigma_i$: Volatility of asset $i$ -- $\rho_{ij}$: Correlation between assets $i$ and $j$ +- $\rho_ij$: Correlation between assets $i$ and $j$ **Practical impact**: ``` @@ -511,16 +511,16 @@ Scenario 2: Correlated collateral Annual Percentage Yield without compounding: ``` -APY_{simple} = \frac{FinalValue - InitialValue}{InitialValue} \times \frac{365}{Days} -```math +APY_simple = (FinalValue - InitialValue / InitialValue) Γ— (365 / Days) +``` ### Compound APY With continuous compounding: ``` -APY_{compound} = e^r - 1 -```math +APY_compound = e^r - 1 +``` Where $r$ is the continuous annual rate. @@ -529,8 +529,8 @@ Where $r$ is the continuous annual rate. When borrowing to increase yield exposure: ``` -Yield_{leveraged} = Yield_{strategy} - Interest_{borrowed} -```math +Yield_leveraged = Yield_strategy - Interest_borrowed +``` **Example**: ``` @@ -556,8 +556,8 @@ Total return: Base yield + leveraged yield A simplified risk score: ``` -\text{Risk Score} = \frac{1}{HF - 1.0} \times Volatility_{collateral} -```math +\text{Risk Score} = (1 / HF - 1.0) Γ— Volatility_collateral +``` Higher score = higher risk. @@ -566,12 +566,12 @@ Higher score = higher risk. Maximum expected loss over time period at confidence level: ``` -VaR_{95\%} = EC \times \sigma \times z_{0.95} -```math +VaR_95% = EC Γ— \sigma Γ— z_0.95 +``` Where: - $\sigma$: Daily volatility of collateral -- $z_{0.95}$: Z-score for 95% confidence (β‰ˆ1.645) +- $z_0.95$: Z-score for 95% confidence (β‰ˆ1.645) **Example**: ``` @@ -591,18 +591,18 @@ Interpretation: 95% confident that daily loss won't exceed $82.25 All operations must satisfy: ``` -1.0 \leq HF_{min} < HF_{target} < HF_{max} -```math +1.0 ≀ HF_min < HF_target < HF_max +``` -Typical values: $HF_{min} = 1.1$, $HF_{target} = 1.3$, $HF_{max} = 1.5$ +Typical values: $HF_min = 1.1$, $HF_target = 1.3$, $HF_max = 1.5$ ### Collateral Factor Bounds For safety: ``` -0 < CF_t \leq 1.0 -```math +0 < CF_t ≀ 1.0 +``` Typically: - Volatile assets (FLOW): $CF = 0.75 - 0.85$ @@ -614,8 +614,8 @@ Typically: Maximum theoretical leverage: ``` -MaxLeverage = \frac{1}{1 - CF} -```math +MaxLeverage = (1 / 1 - CF) +``` **Examples**: ``` @@ -627,7 +627,7 @@ CF = 0.9: Max leverage = 1 / (1 - 0.9) = 10x (risky!) But actual safe leverage is constrained by target health: ``` -SafeLeverage = \frac{CF}{HF_{target}} +SafeLeverage = (CF / HF_target) ``` **Examples**: @@ -683,13 +683,13 @@ Position back to optimal state! | Formula | Expression | Use | |---------|------------|-----| -| **Effective Collateral** | $EC = \sum A_t \times P_t \times CF_t$ | Calculate total collateral value | +| **Effective Collateral** | $EC = \sum A_t Γ— P_t Γ— CF_t$ | Calculate total collateral value | | **Health Factor** | $HF = EC / ED$ | Monitor position safety | -| **Max Borrow** | $Max = EC / HF_{target}$ | Auto-borrowing amount | -| **Rebalance Up** | $Repay = ED - (EC / HF_{target})$ | Required debt reduction | -| **Rebalance Down** | $Borrow = (EC / HF_{target}) - ED$ | Additional borrowing capacity | -| **Scaled Balance** | $B_{scaled} = B_{true} / I_t$ | Interest-efficient tracking | -| **True Balance** | $B_{true} = B_{scaled} \times I_t$ | Current balance with interest | +| **Max Borrow** | $Max = EC / HF_target$ | Auto-borrowing amount | +| **Rebalance Up** | $Repay = ED - (EC / HF_target)$ | Required debt reduction | +| **Rebalance Down** | $Borrow = (EC / HF_target) - ED$ | Additional borrowing capacity | +| **Scaled Balance** | $B_scaled = B_true / I_t$ | Interest-efficient tracking | +| **True Balance** | $B_true = B_scaled Γ— I_t$ | Current balance with interest | | **Max Price Drop** | $DropPercent = 1 - (1 / HF)$ | Liquidation safety margin | ## Next Steps From 3e0336cf1c2543f3c98475254bbf0ee25434ed44 Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Mon, 22 Dec 2025 21:07:29 -0600 Subject: [PATCH 5/8] Improve FCM documentation clarity and mathematical accuracy Updated basics.md: - Converted bullet points to paragraphs for better readability - Added diagram styling to highlight key components - Added explanations for TracerStrategy and AutoBalancer - Enhanced composability section Updated math.md: - Fixed liquidation formulas with complete implementation details - Corrected collateral seizure calculations - Added proper debt ratio vs leverage distinction - Fixed mathematical notation and formatting issues - Improved formula parenthesis handling for clarity --- docs/defi/fcm/basics.md | 120 +++-------- docs/defi/fcm/math.md | 447 ++++++++++++++++++++++++++++------------ 2 files changed, 345 insertions(+), 222 deletions(-) diff --git a/docs/defi/fcm/basics.md b/docs/defi/fcm/basics.md index 37f3d1478f..dd81b9624d 100644 --- a/docs/defi/fcm/basics.md +++ b/docs/defi/fcm/basics.md @@ -7,6 +7,13 @@ sidebar_position: 2 To understand how Flow Credit Market (FCM) works, let's build up from simple lending concepts to FCM's innovative three-component architecture. +:::tip Key Takeaway +FCM = Traditional Lending + Automation + Yield Generation + Liquidation Protection + +It's not just "another lending protocol" - it's a complete yield-generating system with automated risk management. +::: + + ## From Traditional Lending to FCM ### Level 1: Traditional Lending (Aave, Compound) @@ -75,7 +82,7 @@ graph TB style ALP fill:#f9f,stroke:#333,stroke-width:4px style FYV fill:#bfb,stroke:#333,stroke-width:4px - style MOET fill:#fbb,stroke:#333,stroke-width:2px + style DrawDown fill:#bbf,stroke:#333,stroke-width:2px ``` **Complete automation**: @@ -85,24 +92,16 @@ graph TB - βœ… **Auto-protection**: FYV provides liquidity to prevent liquidations - βœ… **Auto-everything**: True set-and-forget experience -**The breakthrough**: -- 🎯 **Yield protects your position**: Your generated yield maintains health automatically -- 🎯 **No manual intervention**: Everything happens automatically -- 🎯 **Capital efficiency**: Borrowed capital works for you immediately +FCM's innovation is that your generated yield protects your position by maintaining health automatically, requiring no manual intervention as everything happens seamlessly in the background. This creates true capital efficiency where borrowed capital works for you immediately upon deployment. ## Understanding the Three Components ### Component 1: ALP (The Lending Engine) -**What it does**: Manages collateral and debt positions with automated rebalancing. - -**Key concepts**: -- **Collateral**: Assets you deposit (FLOW, stFLOW, etc.) -- **Collateral Factor**: Percentage of collateral value you can borrow (e.g., 0.8 = 80%) -- **Health Factor**: Ratio of collateral to debt (must be > 1.0) -- **Target Health**: Optimal ratio the system maintains (typically 1.3) +ALP manages collateral and debt positions with automated rebalancing. You deposit collateral such as FLOW or stFLOW, and the system applies a collateral factor that determines what percentage of your collateral's value you can borrowβ€”for example, a 0.8 collateral factor means you can borrow up to 80% of your collateral's value. The system continuously monitors your health factor, which is the ratio of your collateral to debt and must remain above 1.0 to avoid liquidation. ALP automatically maintains your position at a target health level, typically around 1.3, to provide a safety buffer. **Example**: + ``` Deposit: 1000 FLOW @ $1 = $1000 Collateral Factor: 0.8 (80%) @@ -112,22 +111,19 @@ Target Health: 1.3 Max Safe Borrow: $800 / 1.3 β‰ˆ $615.38 MOET ALP auto-borrows: 615.38 MOET -Position Health: 800 / 615.38 = 1.3 βœ“ +Position Health: 800 / 615.38 = 1.3 ``` Learn more: [ALP Documentation](../alp/index.md) ### Component 2: FYV (The Yield Engine) -**What it does**: Deploys capital into yield-generating strategies and provides liquidity for liquidation prevention. +**TracerStrategy** acts as the smart converter that takes your borrowed MOET, converts it into yield-earning tokens, and converts them back to MOET when your position needs protection, handling all the conversion logic between MOET and yield opportunities. **AutoBalancer** acts as the smart wallet that holds and manages your yield tokens, automatically monitoring the value of your yield position and rebalancing your holdings as needed to optimize returns and maintain liquidity. Together, TracerStrategy handles the conversion logic while AutoBalancer handles the holding and management of those yield tokens. -**Key concepts**: -- **Strategies**: Predefined yield-generating approaches (TracerStrategy, etc.) -- **AutoBalancer**: Manages exposure to yield tokens and rebalancing -- **DrawDownSink**: Receives borrowed MOET from ALP -- **TopUpSource**: Provides liquidity back to ALP when needed +FYV deploys capital into yield-generating strategies and provides liquidity for liquidation prevention. The system uses predefined strategies like TracerStrategy to generate returns, with an AutoBalancer that manages your exposure to yield tokens and handles rebalancing automatically. When ALP borrows MOET on your behalf, the DrawDownSink receives it and deploys it into yield strategies, while the TopUpSource stands ready to provide liquidity back to ALP whenever your position needs debt repayment to maintain health. **Example strategy (TracerStrategy)**: + ``` 1. Receive MOET from ALP β†’ DrawDownSink 2. Swap MOET β†’ YieldToken (e.g., LP token, farm token) @@ -143,15 +139,7 @@ Learn more: [FYV Documentation](#) ### Component 3: MOET (The Unit of Account) -**What it does**: Serves as the currency for all operations - borrowed asset, pricing unit, and value transfer medium. - -**Key concepts**: -- **Unit of Account**: All prices quoted in MOET (FLOW/MOET, USDC/MOET) -- **Primary Borrowed Asset**: What ALP auto-borrows and what FYV receives -- **Synthetic Stablecoin**: Value pegged to maintain stability -- **Medium of Exchange**: Flows between ALP and FYV - -**Why MOET?**: MOET standardizes all valuations, simplifies multi-collateral calculations, is designed specifically for DeFi operations, and provides deep integration with the Flow ecosystem. +MOET serves as the currency for all operations within FCM, functioning simultaneously as the borrowed asset, pricing unit, and value transfer medium. As the system's unit of account, all prices are quoted in MOET termsβ€”whether FLOW/MOET or USDC/MOET. MOET is the primary borrowed asset that ALP auto-borrows and FYV receives for deployment. As a synthetic stablecoin with value pegged to maintain stability, MOET acts as the medium of exchange that flows seamlessly between ALP and FYV components. This design standardizes all valuations, simplifies multi-collateral calculations, and provides deep integration with the Flow ecosystem specifically for DeFi operations. Learn more: [MOET Documentation](#) @@ -307,6 +295,7 @@ Option C: Manual yield farming ``` **With FCM**: + ``` Deposit 1000 FLOW β†’ FCM does everything: - Borrow optimal amount: ~$615 MOET @@ -322,27 +311,14 @@ Effort: Set and forget ### 3. Composability -Each component has value independently: - -**Use ALP alone** when you: -- Want simple lending/borrowing -- Have your own yield strategies -- Need DeFi Actions integration - -**Use FYV alone** when you: -- Want yield aggregation -- Don't need leverage -- Prefer direct yield farming - -**Use FCM together** when you: -- Want maximum automation -- Desire liquidation protection -- Seek optimal capital efficiency +Each component has value independently, allowing you to choose the level of integration that matches your needs. You can use ALP alone when you want simple lending and borrowing, have your own yield strategies, or need DeFi Actions integration for custom workflows. You can use FYV alone when you want yield aggregation without leverage, or prefer direct yield farming without the complexity of borrowing. You can use FCM together when you want maximum automation with liquidation protection and optimal capital efficiency through the integrated system. ## Understanding the Math ### Health Factor Calculation +The health factor is the core metric that determines whether your position is safe or at risk of liquidation. It compares the value of your collateral (adjusted by the collateral factor) against the value of your debt. + ``` Health Factor = Effective Collateral / Effective Debt @@ -357,6 +333,8 @@ Example: ### Target Health Ranges +Different health factor values indicate different states of your position, from dangerous (below 1.0) to overcollateralized (above 1.5). Understanding these ranges helps you know when to take action. + ``` Health Factor States: @@ -370,6 +348,8 @@ HF > 1.5 β†’ Overcollateralized (should rebalance down) ### Borrowing Capacity +This shows how much you can safely borrow while maintaining your target health factor. Borrowing up to this limit ensures you have a safety buffer to protect against price volatility. + ``` Maximum Safe Borrow = Effective Collateral / Target Health @@ -385,60 +365,10 @@ Why not borrow more? Learn more: [Mathematical Foundations](./math.md) -## Common Questions - -### How does FCM differ from Uniswap V3? - -**Uniswap V3** evolved from V2 by adding: -- Concentrated liquidity (specific price ranges) -- Multiple fee tiers -- Capital efficiency improvements -- More complex LP management - -**FCM** evolves from basic lending by adding: -- Automated position management -- Yield generation integration -- Liquidation prevention via yield -- Multi-component architecture (ALP + FYV + MOET) - -Both are "evolved" versions of simpler protocols, adding complexity for better capital efficiency. - -### Can I use FCM without understanding all three components? - -**Yes!** Think of it like using a car: -- **User level**: Just drive (deposit and earn yield) -- **Enthusiast level**: Understand the engine (how ALP, FYV, and MOET connect) -- **Builder level**: Modify and extend (create custom strategies) - -Start with user level, learn more as you go. - -### What happens if FYV doesn't have enough liquidity for rebalancing? - -Multiple fallback mechanisms: -1. **Primary**: FYV provides from yield -2. **Secondary**: FYV can exit positions partially -3. **Tertiary**: Traditional liquidation (external liquidators) -4. **Emergency**: Circuit breakers and admin intervention - -The system is designed with multiple safety layers. - -### Is my yield always enough to prevent liquidation? - -**Not guaranteed**, but highly likely because you're earning yield continuously, the system only pulls what's needed, the health buffer (1.3 target) provides cushion, and you can deposit more collateral anytime. Traditional protocols have 0% chance of automatic prevention - FCM gives you a strong automatic defense. - ## Next Steps Now that you understand the basics: 1. **Learn the architecture**: [Architecture Overview](./architecture.md) 2. **Understand the math**: [Mathematical Foundations](./math.md) -3. **Explore components**: [ALP](../alp/index.md), [FYV](#), [MOET](#) -4. **Start using FCM**: Follow the quick start guide - ---- - -:::tip Key Takeaway -FCM = Traditional Lending + Automation + Yield Generation + Liquidation Protection - -It's not just "another lending protocol" - it's a complete yield-generating system with automated risk management. -::: +3. **Explore components**: [ALP](../alp/index.md), [FYV](#), [MOET](#) \ No newline at end of file diff --git a/docs/defi/fcm/math.md b/docs/defi/fcm/math.md index dbe22a6af3..826851eaf5 100644 --- a/docs/defi/fcm/math.md +++ b/docs/defi/fcm/math.md @@ -7,6 +7,10 @@ sidebar_position: 4 This document explains the mathematical models and formulas that power Flow Credit Market. Understanding these fundamentals helps you reason about system behavior and make informed decisions. +:::tip +These mathematical foundations ensure FCM operates predictably and safely. All formulas are implemented on-chain and can be verified by examining the smart contracts. +::: + ## Core Variables ### Token-Level Variables @@ -25,17 +29,17 @@ This document explains the mathematical models and formulas that power Flow Cred | **Effective Collateral** | $EC$ | Total usable collateral value in MOET | | **Effective Debt** | $ED$ | Total debt value in MOET | | **Health Factor** | $HF$ | Ratio of collateral to debt | -| **Target Health** | $HF_target$ | Desired health ratio (typically 1.3) | -| **Min Health** | $HF_min$ | Minimum before rebalancing (typically 1.1) | -| **Max Health** | $HF_max$ | Maximum before rebalancing (typically 1.5) | +| **Target Health** | $TargetHF$ | Desired health ratio (typically 1.3) | +| **Min Health** | $MinHF$ | Minimum before rebalancing (typically 1.1) | +| **Max Health** | $MaxHF$ | Maximum before rebalancing (typically 1.5) | ### Interest Variables | Variable | Symbol | Description | |----------|--------|-------------| | **Interest Index** | $I_t(n)$ | Interest index for token $t$ at time $n$ | -| **Scaled Balance** | $B_scaled$ | Balance divided by interest index | -| **True Balance** | $B_true$ | Actual balance including accrued interest | +| **Scaled Balance** | $ScaledBalance$ | Balance divided by interest index | +| **True Balance** | $TrueBalance$ | Actual balance including accrued interest | | **Interest Rate** | $r$ | Annual interest rate | ## Fundamental Formulas @@ -45,7 +49,7 @@ This document explains the mathematical models and formulas that power Flow Cred The effective collateral is the sum of all collateral assets multiplied by their prices and collateral factors: ```math -EC = βˆ‘(A_t Γ— P_t Γ— CF_t) for all t in Collateral +EC = βˆ‘(A_t Γ— P_t Γ— CF_t), t ∈ Collateral ``` **Example**: @@ -67,6 +71,8 @@ The effective debt is the sum of all borrowed assets multiplied by their prices ED = \sum_t \in Debt A_t Γ— P_t Γ— BF_t ``` +**Borrow Factor (BF)** is a risk adjustment multiplier applied to debt. While typically set to 1.0 for standard assets like MOET, the borrow factor can be increased above 1.0 for riskier or more volatile borrowed assets. This makes the effective debt higher than the nominal debt, requiring more collateral to maintain the same health factor. For example, a BF of 1.2 means borrowing $100 of that asset counts as $120 of effective debt, providing an extra safety margin for the protocol. + **Example**: ``` Debt: @@ -85,11 +91,13 @@ HF = (EC / ED) ``` **Critical thresholds**: + - $HF < 1.0$: Position is liquidatable - $HF = 1.0$: Exactly at liquidation threshold - $HF > 1.0$: Position is solvent **Example**: + ``` EC = $1250, ED = $800 @@ -101,19 +109,21 @@ HF = 1250 / 800 = 1.5625 The maximum amount that can be borrowed to reach target health: ```math -MaxBorrow = (EC / HF_target) +MaxBorrow = EC / TargetHF ``` **Derivation**: + ``` -We want: HF = EC / ED = HF_target -Therefore: ED = EC / HF_target +We want: HF = EC / ED = TargetHF +Therefore: ED = EC / TargetHF ``` **Example**: + ``` EC = $1250 -HF_target = 1.3 +TargetHF = 1.3 Max Borrow = 1250 / 1.3 = $961.54 MOET ``` @@ -125,27 +135,31 @@ Max Borrow = 1250 / 1.3 = $961.54 MOET When a user deposits collateral with `pushToDrawDownSink=true`, the system calculates the initial borrow amount: ```math -BorrowAmount = (EC / HF_target) +BorrowAmount = (EC / TargetHF) ``` **Step-by-step calculation**: 1. **Calculate effective collateral**: -``` + +```math EC = A_collateral Γ— P_collateral Γ— CF_collateral ``` 2. **Calculate target debt**: -``` - ED_target = (EC / HF_target) + +```math + ED_target = (EC / TargetHF) ``` 3. **Borrow to reach target**: -``` - Borrow = ED_target = (EC / HF_target) + +```math + Borrow = ED_target = (EC / TargetHF) ``` **Complete example**: + ``` User deposits: 1000 FLOW FLOW price: $1.00 @@ -161,35 +175,37 @@ Step 3: Borrow = $615.38 MOET Result: - Collateral: 1000 FLOW ($800 effective) - Debt: 615.38 MOET -- Health: 800 / 615.38 = 1.30 βœ“ +- Health: 800 / 615.38 = 1.30 ``` ## Rebalancing Mathematics -### Overcollateralized Rebalancing (HF > HF_max) +### Overcollateralized Rebalancing (HF > MaxHF) When health exceeds maximum, calculate additional borrowing capacity: -``` -AdditionalBorrow = (EC / HF_target) - ED_current +```math +AdditionalBorrow = (EC / TargetHF) - CurrentED ``` **Proof**: + ``` -Want: HF_new = HF_target -HF_new = EC / ED_new = HF_target -ED_new = EC / HF_target +Want: HF_new = TargetHF +HF_new = EC / ED_new = TargetHF +ED_new = EC / TargetHF -Additional borrow = ED_new - ED_current - = (EC / HF_target) - ED_current +Additional borrow = ED_new - CurrentED + = (EC / TargetHF) - CurrentED ``` **Example**: + ``` Current state: - EC = $800 - ED = $400 -- HF = 800 / 400 = 2.0 (> HF_max of 1.5) +- HF = 800 / 400 = 2.0 (> MaxHF of 1.5) Calculate additional borrow: ED_target = 800 / 1.3 = $615.38 @@ -198,35 +214,37 @@ Additional = 615.38 - 400 = $215.38 MOET After borrowing $215.38: - EC = $800 (unchanged) - ED = $615.38 -- HF = 800 / 615.38 = 1.30 βœ“ +- HF = 800 / 615.38 = 1.30 ``` -### Undercollateralized Rebalancing (HF < HF_min) +### Undercollateralized Rebalancing (HF < MinHF) When health falls below minimum, calculate required repayment: -``` -RequiredRepayment = ED_current - (EC / HF_target) +```math +RequiredRepayment = CurrentED - (EC / TargetHF) ``` **Proof**: + ``` -Want: HF_new = HF_target -HF_new = EC / ED_new = HF_target -ED_new = EC / HF_target +Want: HF_new = TargetHF +HF_new = EC / ED_new = TargetHF +ED_new = EC / TargetHF -Required repayment = ED_current - ED_new - = ED_current - (EC / HF_target) +Required repayment = CurrentED - ED_new + = CurrentED - (EC / TargetHF) ``` **Example**: + ``` Price drops! Collateral value decreases. New state: - EC = $640 (was $800, FLOW dropped 20%) - ED = $615.38 (unchanged) -- HF = 640 / 615.38 = 1.04 (< HF_min of 1.1) +- HF = 640 / 615.38 = 1.04 (< MinHF of 1.1) Calculate required repayment: ED_target = 640 / 1.3 = $492.31 @@ -235,31 +253,31 @@ Repayment = 615.38 - 492.31 = $123.07 MOET After repaying $123.07: - EC = $640 (unchanged) - ED = $492.31 -- HF = 640 / 492.31 = 1.30 βœ“ +- HF = 640 / 492.31 = 1.30 ``` ## Interest Mathematics ### Scaled Balance System -FCM uses **scaled balances** to efficiently track interest: +Instead of updating every position's balance when interest accrues, FCM stores a "scaled" version of each balance that remains constant over time. This scaled balance is the actual balance divided by a global interest index, allowing the protocol to track interest for thousands of positions with minimal gas costs. -``` -B_scaled = \frac{B_true}{I_t} +```math +ScaledBalance = \frac{TrueBalance}{I_t} ``` Where: -- $B_scaled$: Stored scaled balance -- $B_true$: Actual balance including interest +- $ScaledBalance$: Stored scaled balance +- $TrueBalance$: Actual balance including interest - $I_t$: Current interest index **Key insight**: Scaled balance stays constant while interest index grows. ### Interest Index Growth -The interest index grows continuously based on the interest rate: +The interest index is a global multiplier that starts at 1.0 and grows over time based on the current interest rate. Every time the protocol updates, the index increases slightly, and this single update effectively compounds interest for all positions simultaneously. -``` +```math I_t(n+1) = I_t(n) Γ— (1 + r Γ— \Delta t) ``` @@ -268,7 +286,8 @@ Where: - $\Delta t$: Time elapsed (in years) **For compound interest**: -``` + +```math I_t(n) = I_0 Γ— e^{r Γ— t} ``` @@ -276,27 +295,29 @@ Where $e$ is Euler's number (β‰ˆ2.718). ### True Balance Calculation -To get the current true balance from scaled balance: +When you need to know the actual current balance of a position (including all accrued interest), you multiply the stored scaled balance by the current interest index. This calculation happens on-demand only when the position is accessed, not on every block. -``` -B_true(t) = B_scaled Γ— I_t +```math +TrueBalance(t) = ScaledBalance Γ— I_t ``` **Example**: ``` Initial deposit: 1000 MOET Initial index: I_0 = 1.0 -Scaled balance: B_scaled = 1000 / 1.0 = 1000 +Scaled balance: ScaledBalance = 1000 / 1.0 = 1000 After 1 year at 10% APY: Interest index: I_1 = 1.0 Γ— e^(0.10 Γ— 1) β‰ˆ 1.105 -True balance: B_true = 1000 Γ— 1.105 = 1105 MOET +True balance: TrueBalance = 1000 Γ— 1.105 = 1105 MOET User's debt grew from 1000 to 1105 MOET (10.5% with compound interest) ``` ### Why Scaled Balances? +The scaled balance system is a gas optimization that makes FCM economically viable even with thousands of active positions. By storing balances in a scaled form and only updating a single global index, the protocol avoids the prohibitive cost of updating every position on every block. + **Without scaled balances**: ``` Every block (every ~2 seconds): @@ -325,12 +346,13 @@ When position is touched: A position becomes liquidatable when: -``` +```math HF < 1.0 ``` Equivalently: -``` + +```math EC < ED ``` @@ -338,73 +360,249 @@ EC < ED Liquidations aim to restore health to a target (typically 1.05): -``` -HF_liquidation = 1.05 +```math +Target HF = 1.05 ``` ### Collateral Seized Calculation -Amount of collateral to seize: +The amount of collateral to seize depends on the implementation approach used by the protocol. +**Simplified Formula** (used in basic examples and documentation): + +```math +CollateralSeized = (DebtRepaid Γ— (1 + bonus)) / PriceCollateral ``` -CollateralSeized = \frac{ED_repaid Γ— (1 + bonus)}{P_collateral Γ— CF_collateral} + +Where: +- $DebtRepaid$: Amount of debt repaid by liquidator (in MOET or debt token) +- $bonus$: Liquidation bonus (e.g., 0.05 for 5%) +- $PriceCollateral$: Market price of collateral token in MOET terms + +**Complete Formula** (actual FCM implementation): + +```math +CollateralSeized = [(DebtRepaid Γ— PriceDebt) / BorrowFactor] Γ— (1 + bonus) / (PriceCollateral Γ— CollateralFactor) ``` Where: -- $ED_repaid$: Amount of debt repaid by liquidator +- $DebtRepaid$: Amount of debt repaid by liquidator +- $PriceDebt$: Oracle price of debt token (in MOET terms, typically 1.0 for MOET) +- $BorrowFactor$: Risk parameter for debt (typically 1.0) - $bonus$: Liquidation bonus (e.g., 0.05 for 5%) -- $P_collateral$: Price of collateral token -- $CF_collateral$: Collateral factor +- $PriceCollateral$: Oracle price of collateral token (in MOET terms) +- $CollateralFactor$: Risk parameter for collateral (e.g., 0.8 for FLOW) + +**Why the difference?** The simplified formula assumes debt price = 1.0, borrow factor = 1.0, and ignores the collateral factor in seizure (treating it as only affecting borrowing capacity). The complete formula properly accounts for all risk parameters and token prices as implemented in the actual protocol. + +**For MOET debt with typical parameters:** +- $PriceDebt$ = 1.0 (MOET) +- $BorrowFactor$ = 1.0 +- This simplifies the numerator to: $(DebtRepaid Γ— 1.0)/ 1.0 = DebtRepaid$ + +The collateral factor appears in the denominator because it affects how much collateral value must be seized to repay the effective debt. Since effective collateral is calculated as $CollateralAmount Γ— PriceCollateral Γ— CollateralFactor$, seizing collateral to cover debt requires dividing by the CollateralFactor to get the actual token amount. + +**Example using simplified formula**: -**Example**: ``` Liquidatable position: -- Collateral: 1000 FLOW @ $0.60 +- Collateral: 1000 FLOW @ $0.60 = $600 total value +- Effective collateral: $600 Γ— 0.8 CF = $480 - Debt: 650 MOET @ $1.00 -- HF = (1000 Γ— 0.60 Γ— 0.8) / 650 = 0.738 < 1.0 +- HF = 480 / 650 = 0.738 < 1.0 -Liquidation: +Partial liquidation using simplified formula: - Liquidator repays: 150 MOET - Liquidation bonus: 5% -- Collateral seized: (150 Γ— 1.05) / (0.60 Γ— 0.8) = 328.125 FLOW +- Collateral seized = (150 Γ— 1.05) / 0.60 = 262.5 FLOW +- Value of seized collateral: 262.5 Γ— $0.60 = $157.50 -After liquidation: -- Collateral: 671.875 FLOW @ $0.60 = $403.125 effective -- Debt: 500 MOET -- HF = 403.125 / 500 = 0.806... +After partial liquidation: +- Remaining collateral: 1000 - 262.5 = 737.5 FLOW @ $0.60 = $442.50 +- Effective collateral: $442.50 Γ— 0.8 = $354.00 +- Remaining debt: 650 - 150 = 500 MOET +- New HF = 354.00 / 500 = 0.708 (still liquidatable) -(May need multiple liquidations or larger liquidation to reach target 1.05) +Liquidator's profit: +- Paid: $150 (debt repayment) +- Received: $157.50 worth of FLOW +- Profit: $7.50 (5% bonus on $150) +``` + +**Example using complete formula**: + +``` +Same liquidatable position as above. + +Partial liquidation using complete formula: +- DebtRepaid: 150 MOET +- PriceDebt: 1.0 (MOET) +- BorrowFactor: 1.0 +- Liquidation bonus: 5% (0.05) +- PriceCollateral: 0.60 (FLOW in MOET terms) +- CollateralFactor: 0.8 + +CollateralSeized = (150 Γ— 1.0 / 1.0) Γ— 1.05 / (0.60 Γ— 0.8) + = 157.50 / 0.48 + = 328.125 FLOW + +Value of seized collateral: 328.125 Γ— $0.60 = $196.875 + +After partial liquidation: +- Remaining collateral: 1000 - 328.125 = 671.875 FLOW @ $0.60 = $403.125 +- Effective collateral: $403.125 Γ— 0.8 = $322.50 +- Remaining debt: 650 - 150 = 500 MOET +- New HF = 322.50 / 500 = 0.645 (still liquidatable, but lower than simplified) + +Liquidator's profit: +- Paid: $150 (debt repayment) +- Received: $196.875 worth of FLOW +- Profit: $46.875 (31.25% effective bonus!) + +Note: The complete formula gives the liquidator significantly more collateral because +it divides by the CollateralFactor. This compensates for the risk discount applied +to the collateral. In practice, the actual FlowCreditMarket implementation uses the +quoteLiquidation() function which calculates the exact amounts needed to reach the +target health factor of 1.05. ``` ### Required Debt Repayment for Target Health -To restore position to target health factor: +To restore a position to the target health factor (typically 1.05), we need to find how much debt to repay. This is complex because seizing collateral also reduces the effective collateral simultaneously. + +**Goal:** Achieve a specific target health factor after liquidation: +```math +HF_target = EC_after / ED_after ``` -ED_repay = ED_current - (EC / HF_liquidation) + +**The challenge:** Both EC and ED change during liquidation: + +```math +EC_after = EC_current - (Collateral Seized Γ— Price Γ— CF) +ED_after = ED_current - Debt Repaid ``` -**Example**: +**Using the simplified seizure formula:** + +```math +Collateral Seized = (Debt Repaid Γ— (1 + bonus)) / Price +``` + +The effective collateral value seized is: + +```math +EC_seized = Collateral Seized Γ— Price Γ— CF + = [(Debt Repaid Γ— (1 + bonus)) / Price] Γ— Price Γ— CF + = Debt Repaid Γ— (1 + bonus) Γ— CF ``` -From above, to reach HF = 1.05: -EC = 1000 Γ— 0.60 Γ— 0.8 = $480 -ED_current = $650 -ED_target = 480 / 1.05 = $457.14 -ED_repay = 650 - 457.14 = $192.86 MOET must be repaid +**Substituting into the target health equation:** + +```math +HF_target = [EC_current - Debt Repaid Γ— (1 + bonus) Γ— CF] / [ED_current - Debt Repaid] +``` + +**Solving for Debt Repaid:** + +```math +HF_target Γ— (ED_current - Debt Repaid) = EC_current - Debt Repaid Γ— (1 + bonus) Γ— CF + +HF_target Γ— ED_current - HF_target Γ— Debt Repaid = EC_current - Debt Repaid Γ— (1 + bonus) Γ— CF + +HF_target Γ— ED_current - EC_current = HF_target Γ— Debt Repaid - Debt Repaid Γ— (1 + bonus) Γ— CF + +HF_target Γ— ED_current - EC_current = Debt Repaid Γ— [HF_target - (1 + bonus) Γ— CF] ``` +**Final formula:** + +```math +Debt Repaid = (HF_target Γ— ED_current - EC_current) / [HF_target - (1 + bonus) Γ— CF] +``` + +**Working example:** + +``` +Initial position (severely undercollateralized): +- Collateral: 1000 FLOW @ $0.50 (price dropped significantly!) +- EC = 1000 Γ— 0.50 Γ— 0.8 = $400 +- ED = 615.38 MOET +- Current HF = 400 / 615.38 = 0.65 < 1.0 (liquidatable!) +- Target HF = 1.05 +- Liquidation bonus = 5% (0.05) +- Collateral Factor (CF) = 0.8 + +Step 1: Calculate required debt repayment +Debt Repaid = (1.05 Γ— 615.38 - 400) / [1.05 - (1.05 Γ— 0.8)] + = (646.15 - 400) / [1.05 - 0.84] + = 246.15 / 0.21 + = 1,172.14 MOET + +This is more than the total debt! This means the position cannot be restored to HF = 1.05 +because there isn't enough collateral. This would be a full liquidation case. + +Step 2: Calculate maximum achievable HF +If all debt is repaid (615.38 MOET): +Collateral seized = (615.38 Γ— 1.05) / 0.50 = 1,292.30 FLOW +But we only have 1000 FLOW, so this is a full liquidation. + +In full liquidation: +- All 1000 FLOW seized β†’ value = $500 +- Effective value for liquidator = $500 +- Debt repaid = 500 / 1.05 = $476.19 MOET (limited by collateral available) +- Remaining debt = 615.38 - 476.19 = $139.19 (bad debt for protocol) +``` + +**Better example with partial liquidation:** + k +``` +Initial position (moderately undercollateralized): +- Collateral: 1000 FLOW @ $0.78 +- EC = 1000 Γ— 0.78 Γ— 0.8 = $624 +- ED = 650 MOET +- Current HF = 624 / 650 = 0.96 < 1.0 (liquidatable) +- Target HF = 1.05 +- Bonus = 5% (0.05) +- CF = 0.8 + +Step 1: Calculate debt repayment +Debt Repaid = (1.05 Γ— 650 - 624) / [1.05 - (1.05 Γ— 0.8)] + = (682.5 - 624) / [1.05 - 0.84] + = 58.5 / 0.21 + = 278.57 MOET + +Step 2: Verify the calculation +Collateral seized = (278.57 Γ— 1.05) / 0.78 = 375.33 FLOW +EC seized = 375.33 Γ— 0.78 Γ— 0.8 = $234.21 +EC after = 624 - 234.21 = $389.79 +ED after = 650 - 278.57 = $371.43 +HF after = 389.79 / 371.43 = 1.049 β‰ˆ 1.05 βœ“ + +Step 3: Liquidator's outcome +Collateral received: 375.33 FLOW @ $0.78 = $292.76 +Debt repaid: $278.57 +Profit: $292.76 - $278.57 = $14.19 (5.09% return) +``` + +**Key insights:** +1. The formula works when there's sufficient collateral to reach target HF +2. When `Debt Repaid > ED_current`, it indicates a full liquidation scenario +3. The denominator `[HF_target - (1 + bonus) Γ— CF]` is typically small (0.21 in this example), meaning small changes in EC/ED require large debt repayments +4. The liquidation becomes more efficient (smaller debt repayment needed) when the current HF is closer to the target HF + ## Price Impact Analysis ### Health Factor Sensitivity to Price Changes Given a percentage change in collateral price: -``` +```math HF_new = HF_old Γ— \frac{P_new}{P_old} ``` **Derivation**: + ``` HF_old = EC_old / ED = (A Γ— P_old Γ— CF) / ED @@ -416,6 +614,7 @@ Therefore: HF_new = HF_old Γ— (P_new / P_old) ``` **Example**: + ``` Initial: HF = 1.5, Price = $1.00 @@ -433,7 +632,7 @@ HF_new = 1.5 Γ— (0.65 / 1.00) = 1.5 Γ— 0.65 = 0.975 < 1.0 (liquidatable!) What's the maximum price drop before liquidation? -``` +```math MaxDropPercent = 1 - (1.0 / HF_current) ``` @@ -452,6 +651,7 @@ Drop % = 1 - 1/HF_old ``` **Examples**: + ``` HF = 1.3: Max drop = 1 - 1/1.3 = 23.08% HF = 1.5: Max drop = 1 - 1/1.5 = 33.33% @@ -465,23 +665,25 @@ HF = 1.1: Max drop = 1 - 1/1.1 = 9.09% (very risky!) With multiple collateral types: -``` -EC = \sum_i=1^{n} A_i Γ— P_i Γ— CF_i +```math +EC = βˆ‘(A_i Γ— P_i Γ— CF_i) ``` -Where $i$ iterates over all collateral token types. +Where the sum is taken over all n collateral token types. ### Effective Collateral with Price Correlation When collateral types are correlated (e.g., FLOW and stFLOW): **Simplified (no correlation)**: -``` + +```math Risk = \sum_i Risk_i ``` **With correlation** (advanced): -``` + +```math Risk = \sqrt{\sum_i\sum_j w_i w_j \sigma_i \sigma_j \rho_ij} ``` @@ -510,15 +712,15 @@ Scenario 2: Correlated collateral Annual Percentage Yield without compounding: -``` -APY_simple = (FinalValue - InitialValue / InitialValue) Γ— (365 / Days) +```math +APY_simple = ((FinalValue - InitialValue) / InitialValue) Γ— (365 / Days) ``` ### Compound APY With continuous compounding: -``` +```math APY_compound = e^r - 1 ``` @@ -528,11 +730,12 @@ Where $r$ is the continuous annual rate. When borrowing to increase yield exposure: -``` +```math Yield_leveraged = Yield_strategy - Interest_borrowed ``` **Example**: + ``` Deposit: $1000 collateral Borrow: $615 at 5% APY @@ -555,25 +758,26 @@ Total return: Base yield + leveraged yield A simplified risk score: -``` -\text{Risk Score} = (1 / HF - 1.0) Γ— Volatility_collateral +```math +\text{Risk Score} = (1 / HF - 1.0) Γ— \text{Volatility Collateral} ``` Higher score = higher risk. ### Value at Risk (VaR) -Maximum expected loss over time period at confidence level: +Maximum expected loss over time period at confidence level 95%: -``` -VaR_95% = EC Γ— \sigma Γ— z_0.95 +```math +VaR(95) = EC Γ— Οƒ Γ— z(0.95) ``` Where: -- $\sigma$: Daily volatility of collateral -- $z_0.95$: Z-score for 95% confidence (β‰ˆ1.645) +- Οƒ: Daily volatility of collateral +- z(0.95): Z-score for 95% confidence (β‰ˆ1.645) **Example**: + ``` Collateral: $1000 FLOW Daily volatility: 5% @@ -590,17 +794,17 @@ Interpretation: 95% confident that daily loss won't exceed $82.25 All operations must satisfy: -``` -1.0 ≀ HF_min < HF_target < HF_max +```math +1.0 ≀ MinHF < TargetHF < MaxHF ``` -Typical values: $HF_min = 1.1$, $HF_target = 1.3$, $HF_max = 1.5$ +Typical values: $MinHF = 1.1$, $TargetHF = 1.3$, $MaxHF = 1.5$ ### Collateral Factor Bounds For safety: -``` +```math 0 < CF_t ≀ 1.0 ``` @@ -613,29 +817,37 @@ Typically: Maximum theoretical leverage: -``` -MaxLeverage = (1 / 1 - CF) +```math +MaxLeverage = \frac{1}{1 - CF} ``` **Examples**: + ``` CF = 0.8: Max leverage = 1 / (1 - 0.8) = 5x CF = 0.75: Max leverage = 1 / (1 - 0.75) = 4x CF = 0.9: Max leverage = 1 / (1 - 0.9) = 10x (risky!) ``` -But actual safe leverage is constrained by target health: +But actual safe borrowing is constrained by target health: -``` -SafeLeverage = (CF / HF_target) +### Safe Debt Ratio + +Maximum debt-to-collateral ratio while maintaining target health: + +```math +SafeDebtRatio = CF / TargetHF ``` **Examples**: + ``` -CF = 0.8, HF = 1.3: Safe leverage = 0.8 / 1.3 β‰ˆ 0.615 = ~1.62x -CF = 0.75, HF = 1.5: Safe leverage = 0.75 / 1.5 = 0.50 = 1.5x +CF = 0.8, TargetHF = 1.3: Safe debt ratio = 0.8 / 1.3 β‰ˆ 0.615 +CF = 0.75, TargetHF = 1.5: Safe debt ratio = 0.75 / 1.5 = 0.50 ``` +This means with CF = 0.8 and TargetHF = 1.3, you can safely borrow up to $0.615 for every $1 of collateral value. + ## Practical Examples ### Complete Position Lifecycle Math @@ -643,7 +855,7 @@ CF = 0.75, HF = 1.5: Safe leverage = 0.75 / 1.5 = 0.50 = 1.5x ``` === Initial Deposit === Deposit: 1000 FLOW @ $1.00 -CF = 0.8, HF_target = 1.3 +CF = 0.8, TargetHF = 1.3 EC = 1000 Γ— 1.00 Γ— 0.8 = $800 Borrow = 800 / 1.3 = $615.38 MOET @@ -679,27 +891,8 @@ HF = 800 / 615.38 = 1.30 βœ“ Position back to optimal state! ``` -## Summary of Key Formulas - -| Formula | Expression | Use | -|---------|------------|-----| -| **Effective Collateral** | $EC = \sum A_t Γ— P_t Γ— CF_t$ | Calculate total collateral value | -| **Health Factor** | $HF = EC / ED$ | Monitor position safety | -| **Max Borrow** | $Max = EC / HF_target$ | Auto-borrowing amount | -| **Rebalance Up** | $Repay = ED - (EC / HF_target)$ | Required debt reduction | -| **Rebalance Down** | $Borrow = (EC / HF_target) - ED$ | Additional borrowing capacity | -| **Scaled Balance** | $B_scaled = B_true / I_t$ | Interest-efficient tracking | -| **True Balance** | $B_true = B_scaled Γ— I_t$ | Current balance with interest | -| **Max Price Drop** | $DropPercent = 1 - (1 / HF)$ | Liquidation safety margin | - ## Next Steps - **Apply these formulas**: [ALP Documentation](../alp/index.md) - **Understand architecture**: [FCM Architecture](./architecture.md) -- **Learn the basics**: [Understanding FCM Basics](./basics.md) - ---- - -:::tip -These mathematical foundations ensure FCM operates predictably and safely. All formulas are implemented on-chain and can be verified by examining the smart contracts. -::: +- **Learn the basics**: [Understanding FCM Basics](./basics.md) \ No newline at end of file From dc819f9dde17bdca6f747bb4a6ad25f5d0ef3f72 Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Mon, 22 Dec 2025 21:51:59 -0600 Subject: [PATCH 6/8] Fix docs/defi sidebar titles and documentation order --- docs/defi/alp/index.md | 4 +- docs/defi/alp/liquidation-system.md | 2 +- docs/defi/alp/moet-role.md | 2 +- docs/defi/fcm/architecture.md | 89 ++++++++++++++++++----------- docs/defi/fcm/index.md | 34 ++++------- 5 files changed, 70 insertions(+), 61 deletions(-) diff --git a/docs/defi/alp/index.md b/docs/defi/alp/index.md index 6e9ea308c3..38f0951a15 100644 --- a/docs/defi/alp/index.md +++ b/docs/defi/alp/index.md @@ -1,7 +1,7 @@ --- title: Automated Lending Platform (ALP) -sidebar_label: Overview -sidebar_position: 1 +sidebar_label: Automated Lending Platform (ALP) +sidebar_position: 10 --- # Automated Lending Platform (ALP) diff --git a/docs/defi/alp/liquidation-system.md b/docs/defi/alp/liquidation-system.md index 4466f7a804..c5afe22930 100644 --- a/docs/defi/alp/liquidation-system.md +++ b/docs/defi/alp/liquidation-system.md @@ -1,6 +1,6 @@ --- title: Liquidation System -sidebar_position: 4 +sidebar_position: 9 --- # Liquidation System diff --git a/docs/defi/alp/moet-role.md b/docs/defi/alp/moet-role.md index c82a7fcd89..f88dc03c96 100644 --- a/docs/defi/alp/moet-role.md +++ b/docs/defi/alp/moet-role.md @@ -1,6 +1,6 @@ --- title: MOET's Role in ALP -sidebar_position: 8 +sidebar_position: 4 --- # MOET's Role in ALP diff --git a/docs/defi/fcm/architecture.md b/docs/defi/fcm/architecture.md index 0cdc6adb08..2a6afce5b6 100644 --- a/docs/defi/fcm/architecture.md +++ b/docs/defi/fcm/architecture.md @@ -5,7 +5,15 @@ sidebar_position: 3 # FCM Architecture Overview -This document explains how Flow Credit Market's three core components - ALP, FYV, and MOET - integrate to create a complete yield-generating system with automated liquidation prevention. +This document explains how Flow Credit Market's (FCM) three core components - [Automated Lending Platform (ALP)](../alp/index.md), [Flow Yield Vaults (FYV)](#), and [Medium Of Exchange Token (MOET)](#) - integrate to create a complete yield-generating system with automated liquidation prevention. + + +:::tip Key Insight +FCM's architecture is designed for **composability** and **automation**. Each component has clear responsibilities and communicates through standardized interfaces (DeFi Actions), enabling: +- Independent development and upgrades +- Third-party strategy integrations +- System resilience through modularity +::: ## High-Level Architecture @@ -147,6 +155,8 @@ New HF: 1.3 (restored to target) **Code integration**: +The integration is implemented through DeFi Actions interfaces in Cadence. On the ALP side, each Position holds references to a DrawDownSink and TopUpSource, which are called during rebalancing operations. When the position becomes overcollateralized, it borrows additional funds and pushes them to the DrawDownSink. When undercollateralized, it pulls funds from the TopUpSource to repay debt. + ```cadence // ALP side (simplified) access(all) struct Position { @@ -167,6 +177,10 @@ access(all) struct Position { } ``` +On the FYV side, strategies implement the DeFi Actions interfaces by providing Sink and Source creation functions. These functions return objects that handle the swap between MOET and yield-bearing tokens. When ALP calls the Sink, FYV converts MOET into yield tokens. When ALP pulls from the Source, FYV converts yield tokens back to MOET. + +TracerStrategy is one of FYV's yield strategies that tracks and manages positions in external yield-generating protocols. It acts as the bridge between ALP's lending system and external DeFi opportunities, automatically converting between MOET and yield tokens while maintaining the optimal balance for returns. + ```cadence // FYV side (simplified) access(all) struct TracerStrategy { @@ -230,18 +244,22 @@ sequenceDiagram participant FYV User->>Position: deposit(collateral) - Position->>Pool: updateCollateral(+amount) + Position->>Position: Store collateral + Position->>Pool: Update collateral balance Pool->>Pool: updateScaledBalance() Position->>Oracle: getPrice(collateralToken) Oracle-->>Position: priceInMOET Position->>Position: calculateHealth() - alt HF > maxHealth + Note over Position: Check if auto-borrow enabled + alt HF > maxHealth AND auto-borrow enabled + Position->>Position: Calculate excess capacity Position->>Pool: borrow(excessCapacity) Pool-->>Position: MOET vault Position->>DrawDownSink: deposit(MOET) - DrawDownSink->>FYV: swap & deploy + DrawDownSink->>FYV: Swap MOET to yield tokens + FYV->>FYV: Deploy to strategy end Position-->>User: success @@ -264,13 +282,18 @@ sequenceDiagram Position->>Oracle: getPrice(collateralToken) Oracle-->>Position: newPrice (lower) + Position->>Pool: getCurrentDebt() + Pool-->>Position: currentDebt + Position->>Position: calculateHealth() - Position->>Position: health < minHealth! + Note over Position: HF < minHealth (e.g., 1.1) - Position->>Position: calculate shortfall - Position->>TopUpSource: withdraw(shortfall) + Position->>Position: Calculate required repayment + Note over Position: Need to reach target HF (1.3) - TopUpSource->>FYV: swap YieldToken β†’ MOET + Position->>TopUpSource: withdraw(repaymentAmount) + TopUpSource->>FYV: Request MOET + FYV->>FYV: Swap YieldToken β†’ MOET FYV-->>TopUpSource: MOET vault TopUpSource-->>Position: MOET vault @@ -278,7 +301,7 @@ sequenceDiagram Pool->>Pool: updateDebt(-amount) Position->>Position: calculateHealth() - Note over Position: health restored to 1.3 + Note over Position: HF restored to 1.3 ``` ## Component Responsibilities @@ -324,7 +347,12 @@ sequenceDiagram ### 1. DeFi Actions Pattern (ALP ↔ FYV) +DeFi Actions enables ALP and FYV to communicate through standardized interfaces without tight coupling. The Sink pattern allows ALP to push borrowed funds to FYV strategies, while the Source pattern enables ALP to pull funds back when needed for rebalancing or repayment. + **Sink Pattern** (Push): + +When ALP has excess borrowing capacity or newly borrowed funds, it uses the Sink interface to deposit MOET into FYV strategies. The FYV strategy receives the funds and automatically converts them to yield-bearing tokens. + ```cadence // ALP pushes to FYV access(all) resource interface Sink { @@ -337,6 +365,9 @@ sink.deposit(vault: <-moetVault) ``` **Source Pattern** (Pull): + +When ALP needs funds to maintain position health, it pulls from the Source interface. FYV converts yield tokens back to MOET and provides the requested amount, enabling automatic liquidation prevention. + ```cadence // ALP pulls from FYV access(all) resource interface Source { @@ -350,7 +381,12 @@ let moet <- source.withdraw(amount: 100.0, type: Type<@MOET.Vault>()) ### 2. Oracle Pattern (ALP ↔ MOET) +The Oracle pattern provides a standardized way for ALP to query token prices in MOET terms. All collateral and debt calculations use these MOET-denominated prices, ensuring consistency across the system. This enables health factor calculations and determines borrowing capacity based on real-time market data. + **Price Query**: + +The PriceOracle interface returns the current price of any token type denominated in MOET. For example, querying the price of FLOW returns how many MOET one FLOW is worth, which ALP uses to calculate effective collateral values. + ```cadence // ALP queries prices in MOET terms access(all) resource interface PriceOracle { @@ -364,7 +400,12 @@ let flowPrice = oracle.getPrice(Type<@FlowToken.Vault>()) ### 3. Event-Driven Pattern +FCM components communicate state changes through events, enabling monitoring, analytics, and external integrations. Each component emits events for significant actions like position changes, yield generation, and token operations. These events allow off-chain systems to track user activity, trigger notifications, and maintain historical records without polling smart contracts. + **Key events across components**: + +ALP emits events for all position lifecycle operations including creation, borrowing, repayment, and rebalancing. FYV broadcasts events when deploying to strategies, generating yield, or providing liquidity back to ALP. MOET tracks token supply changes through mint and burn events, ensuring transparency in the stablecoin's circulation. + ```cadence // ALP events access(all) event PositionCreated(pid: UInt64, owner: Address) @@ -436,24 +477,13 @@ Actions: ### Optimizations -1. **Scaled Balance System** (ALP): - - Avoids updating every position on interest accrual - - Single interest index update affects all positions - - Gas-efficient for large position counts +**Scaled Balance System** - ALP uses a scaled balance approach that avoids updating every position when interest accrues. Instead, a single interest index update affects all positions simultaneously, making the system gas-efficient even with thousands of active positions. -2. **Batch Rebalancing** (ALP): - - Multiple positions can be rebalanced in one transaction - - Keepers can optimize gas costs +**Batch Rebalancing** - The protocol allows multiple positions to be rebalanced in a single transaction, enabling keepers to optimize gas costs by processing several positions at once rather than submitting individual transactions for each rebalancing operation. -3. **Lazy Evaluation** (All components): - - Prices only fetched when needed - - Health only calculated when accessed - - Interest only accrued when position touched +**Lazy Evaluation** - All components use lazy evaluation patterns where prices are only fetched when needed, health factors are calculated only when accessed, and interest accrues only when a position is touched. This approach minimizes unnecessary computations and reduces gas costs for operations that don't require the latest state. -4. **Event-Driven Updates** (All components): - - Off-chain indexers track state - - UI updates without constant blockchain queries - - Reduces RPC load +**Event-Driven Updates** - The system emits events for all critical operations, allowing off-chain indexers to track state changes efficiently. This enables UI updates without constant blockchain queries and significantly reduces RPC load on the network while providing users with real-time information. ### Limits & Constraints @@ -498,13 +528,4 @@ Actions: - **Understand the math**: [Mathematical Foundations](./math.md) - **Explore ALP details**: [ALP Architecture](../alp/architecture.md) - **Learn about FYV**: [FYV Documentation](#) -- **Deep dive into MOET**: [MOET Documentation](#) - ---- - -:::tip Key Insight -FCM's architecture is designed for **composability** and **automation**. Each component has clear responsibilities and communicates through standardized interfaces (DeFi Actions), enabling: -- Independent development and upgrades -- Third-party strategy integrations -- System resilience through modularity -::: +- **Deep dive into MOET**: [MOET Documentation](#) \ No newline at end of file diff --git a/docs/defi/fcm/index.md b/docs/defi/fcm/index.md index 8e85651a59..a2e1778632 100644 --- a/docs/defi/fcm/index.md +++ b/docs/defi/fcm/index.md @@ -1,14 +1,14 @@ --- title: Flow Credit Market (FCM) -sidebar_label: Overview -sidebar_position: 1 +sidebar_label: Flow Credit Market (FCM) +sidebar_position: 9 --- # Flow Credit Market (FCM) -Flow Credit Market (FCM) is a comprehensive DeFi yield platform on Flow that combines automated lending, yield farming strategies, and a synthetic stablecoin to create a capital-efficient system for generating returns on crypto assets. +Flow Credit Market (FCM) is a comprehensive DeFi yield platform on Flow that offers a capital-efficient system for generating returns on crypto assets. -## What is FCM? +## How FCM Works FCM is **not a single protocol** - it's an integrated system composed of three core components working together: @@ -44,7 +44,7 @@ graph LR - Medium of exchange between components - Maintains stability through over-collateralization -## How the Components Work Together +## Interaction Between Components FCM creates a **yield-generating flywheel** by connecting these three components: @@ -87,7 +87,7 @@ sequenceDiagram ### 1. Yield-Powered Liquidation Prevention -Unlike traditional lending protocols where you must manually add collateral or repay debt when prices drop, FCM **uses your yield to maintain position health**. Yield from FYV strategies flows back to ALP automatically, ALP pulls from FYV to repay debt when needed, your position stays healthy without manual intervention, and **you earn yield while protecting yourself from liquidation**. +Unlike traditional lending protocols where you must manually add collateral or repay debt when prices drop, FCM **uses your yield to maintain position health**. Yield from FYV strategies flows back to ALP automatically via [scheduled transactions](../../blockchain-development-tutorials/forte/scheduled-transactions/scheduled-transactions-introduction.md), ALP pulls from FYV to repay debt when needed, your position stays healthy without manual intervention, and **you earn yield while protecting yourself from liquidation**. ### 2. Automated Capital Efficiency @@ -110,11 +110,7 @@ FCM allows you to maximize returns by borrowing against collateral and deploying ### For Conservative Users -FCM provides liquidation protection through yield maintaining position health, flexible health targets allowing you to choose your risk tolerance (1.1-1.5), support for multiple collateral types including FLOW, stFLOW, USDC and more, and complete transparency with all logic on-chain and auditable. - -### For DeFi Builders - -FCM offers composable primitives allowing you to build on ALP, FYV, or both, standard interfaces for integration through DeFi Actions, the ability to create custom FYV strategies through extensible strategy patterns, and all code publicly available as open source. +FCM provides liquidation protection through yield maintaining position health, flexible health targets allowing you to choose your risk tolerance (1.1-1.5), and support for multiple collateral types including FLOW, USD based stablecoins, BTC, and ETH. The system actively monitors and can rebalance positions multiple times per day in response to price movements, ensuring your position stays within safe parameters. ## Documentation Structure @@ -137,7 +133,7 @@ FCM offers composable primitives allowing you to build on ALP, FYV, or both, sta ### As a User -1. **Get collateral**: Acquire FLOW, stFLOW, or other supported tokens +1. **Get collateral**: Acquire FLOW or other supported collateral tokens 2. **Connect wallet**: Use a Flow-compatible wallet 3. **Create position**: Deposit collateral to start earning 4. **Monitor health**: Track your position via the dashboard @@ -165,17 +161,9 @@ FCM implements multiple security layers including smart contract audits for all ## Community & Support -- **GitHub**: [FlowCreditMarket](https://github.com/onflow/FlowCreditMarket) and [FlowYieldVaults](https://github.com/onflow/FlowYieldVaults) -- **Discord**: [Flow Discord](https://discord.gg/flow) - #fcm channel -- **Documentation**: This site -- **Developer Forums**: [Flow Forum](https://forum.onflow.org) - -## What's Next? - -- **New to FCM?** Start with [Understanding FCM Basics](./basics.md) -- **Want technical details?** Read the [Architecture Overview](./architecture.md) -- **Ready to use it?** Explore [ALP](../alp/index.md) or [FYV](#) -- **Building an integration?** Check the [Integration Guide](#) +- [FlowCreditMarket](https://github.com/onflow/FlowCreditMarket) +- [FlowYieldVaults](https://github.com/onflow/FlowYieldVaults) +- [Flow Discord](https://discord.gg/flow) --- From bea5fe66c3353483b089cd1ac141f376cf8992c8 Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Tue, 23 Dec 2025 09:13:04 -0600 Subject: [PATCH 7/8] Add comprehensive Flow Yield Vaults (FYV) documentation Created complete FYV documentation with 9 files covering: - Core concepts: architecture, strategies, AutoBalancer, vault lifecycle - Advanced features: leveraged farming, scheduling system, cross-chain integration - Composability: DeFi Actions framework Documentation follows same structure and quality as ALP and FCM docs. --- docs/defi/flow-yield-vaults/architecture.md | 375 +++++++++++++++ docs/defi/flow-yield-vaults/autobalancer.md | 401 ++++++++++++++++ docs/defi/flow-yield-vaults/cross-chain.md | 315 +++++++++++++ docs/defi/flow-yield-vaults/defi-actions.md | 440 ++++++++++++++++++ docs/defi/flow-yield-vaults/index.md | 122 +++++ .../flow-yield-vaults/leveraged-farming.md | 324 +++++++++++++ docs/defi/flow-yield-vaults/scheduling.md | 410 ++++++++++++++++ docs/defi/flow-yield-vaults/strategies.md | 369 +++++++++++++++ .../defi/flow-yield-vaults/vault-lifecycle.md | 437 +++++++++++++++++ 9 files changed, 3193 insertions(+) create mode 100644 docs/defi/flow-yield-vaults/architecture.md create mode 100644 docs/defi/flow-yield-vaults/autobalancer.md create mode 100644 docs/defi/flow-yield-vaults/cross-chain.md create mode 100644 docs/defi/flow-yield-vaults/defi-actions.md create mode 100644 docs/defi/flow-yield-vaults/index.md create mode 100644 docs/defi/flow-yield-vaults/leveraged-farming.md create mode 100644 docs/defi/flow-yield-vaults/scheduling.md create mode 100644 docs/defi/flow-yield-vaults/strategies.md create mode 100644 docs/defi/flow-yield-vaults/vault-lifecycle.md diff --git a/docs/defi/flow-yield-vaults/architecture.md b/docs/defi/flow-yield-vaults/architecture.md new file mode 100644 index 0000000000..4db82bca11 --- /dev/null +++ b/docs/defi/flow-yield-vaults/architecture.md @@ -0,0 +1,375 @@ +--- +title: Architecture Overview +sidebar_position: 2 +--- + +# Architecture Overview + +Flow Yield Vaults (FYV) is built on a modular architecture that separates concerns between user position management, yield strategy implementation, and automated rebalancing. This document explains the core components and how they interact to create an automated leveraged yield farming system. + +## System Architecture + +```mermaid +graph TB + User[User Account] -->|owns| YVM[YieldVaultManager] + YVM -->|contains| YV1[YieldVault 1] + YVM -->|contains| YV2[YieldVault 2] + + YV1 -->|delegates to| Strategy[Strategy Implementation] + YV1 -->|manages| AB[AutoBalancer] + YV1 -->|holds capability| Pos[ALP Position] + + Strategy -->|uses| Connectors[DeFi Connectors] + Connectors -->|swap| SwapConn[SwapConnectors] + Connectors -->|deposit/withdraw| SinkConn[Sink/Source Connectors] + + AB -->|deposits to| ERC4626[ERC4626 Vaults] + AB -->|schedules| Scheduler[FlowTransactionScheduler] + + Pos -->|borrows from| ALP[ALP Pool] + Pos -->|uses| MOET[MOET Token] + + Registry[SchedulerRegistry] -->|tracks| YV1 + Registry -->|tracks| YV2 + + Supervisor[Supervisor] -->|recovers| Registry + + style YV1 fill:#f9f,stroke:#333,stroke-width:4px + style Strategy fill:#bfb,stroke:#333,stroke-width:4px + style AB fill:#bbf,stroke:#333,stroke-width:4px +``` + +## Core Components + +### YieldVault Resource + +The `YieldVault` is the user-facing resource that represents a single yield-generating position. + +**What it does**: Each YieldVault tracks user deposits, delegates operations to a Strategy implementation, holds capabilities to interact with AutoBalancer and ALP Position, and provides user interface for deposit, withdraw, and liquidation operations. + +**Key fields:** +- `strategy`: Reference to the Strategy implementation +- `autoBalancer`: Capability to the AutoBalancer resource +- `position`: Capability to the ALP Position resource +- `id`: Unique identifier for this vault + +**User operations:** +```cadence +// Deposit collateral to start yield farming +vault.deposit(collateralVault: <-flowTokens) + +// Withdraw accumulated value +let withdrawn <- vault.withdraw(amount: 100.0) + +// Close vault and retrieve all value +let value <- vault.liquidate() +``` + +### YieldVaultManager + +The `YieldVaultManager` is stored in the user's account and manages multiple vaults. + +**What it does**: YieldVaultManager stores all vaults owned by a user, provides interfaces for vault creation and access, tracks vault IDs for enumeration, and enables multi-vault management from a single account. + +**Example structure:** +``` +User Account +└── YieldVaultManager + β”œβ”€β”€ YieldVault #42 (TracerStrategy with FLOW collateral) + β”œβ”€β”€ YieldVault #43 (mUSDCStrategy with USDC collateral) + └── YieldVault #44 (TracerStrategy with stFLOW collateral) +``` + +### Strategy Interface + +The Strategy defines how yield is generated and managed. + +**What it does**: Strategies implement the core yield logic including deposit (convert collateral β†’ yield tokens), withdrawal (convert yield tokens β†’ collateral), and liquidation (close position and return all value). The Strategy interface keeps vault logic protocol-agnostic, allowing different yield approaches while maintaining consistent user experience. + +**Key functions:** +```cadence +pub resource interface Strategy { + // Initialize position with collateral + pub fun deposit(collateralVault: @FungibleToken.Vault) + + // Withdraw specified amount + pub fun withdraw(amount: UFix64): @FungibleToken.Vault + + // Close position and return all value + pub fun liquidate(): @FungibleToken.Vault + + // Get current position value + pub fun getBalance(): UFix64 +} +``` + +**Available implementations:** +- **TracerStrategy**: Leveraged yield farming using ALP + ERC4626 vaults +- **mUSDCStrategy**: Cross-chain yield farming via Flow-EVM bridge + +Learn more in [Strategies](./strategies.md). + +### StrategyComposer & StrategyFactory + +The **StrategyComposer** creates configured strategy instances, while the **StrategyFactory** maintains the registry of available composers. + +**What it does**: StrategyComposer assembles DeFi Actions components (swap connectors, sink/source connectors) into a complete strategy. StrategyFactory provides a registry where users can discover available strategies and create instances with pre-configured connectors for their chosen yield approach. + +**Strategy creation flow:** +```mermaid +sequenceDiagram + participant User + participant Factory as StrategyFactory + participant Composer as StrategyComposer + participant Strategy + + User->>Factory: getStrategyNames() + Factory-->>User: ["TracerStrategy", "mUSDCStrategy"] + + User->>Factory: createStrategy("TracerStrategy", collateral) + Factory->>Composer: compose(collateral) + Composer->>Composer: Configure connectors + Composer->>Strategy: Create new strategy instance + Strategy-->>User: Strategy capability +``` + +### AutoBalancer + +The AutoBalancer monitors yield token holdings and triggers rebalancing when thresholds are exceeded. + +**What it does**: AutoBalancer holds yield tokens in ERC4626 vaults, monitors value ratio (current holdings vs. historical deposits), triggers rebalancing when ratio exceeds 95%-105% range, withdraws excess profits or requests deficit recovery, and self-schedules next rebalancing execution. + +**Rebalancing thresholds:** +``` +Ratio = Current Value / Historical Deposit Value + +Upper Threshold: 105% β†’ Excess profits, withdraw and deposit to position +Lower Threshold: 95% β†’ Deficit detected, request funds from position +Target Range: 95%-105% β†’ No action needed +``` + +**Rebalancing flow:** +```mermaid +sequenceDiagram + participant Scheduler + participant AB as AutoBalancer + participant Vault as ERC4626 + participant Swap as SwapConnectors + participant Pos as ALP Position + + Scheduler->>AB: rebalance() + AB->>Vault: getBalance() + Vault-->>AB: currentValue + AB->>AB: Calculate ratio + + alt Ratio > 105% (Excess) + AB->>Vault: withdraw(excess) + Vault-->>AB: yieldTokens + AB->>Swap: swap(yieldTokens β†’ FLOW) + Swap-->>AB: FLOW + AB->>Pos: deposit(FLOW) + else Ratio < 95% (Deficit) + AB->>Pos: Request deficit + Pos->>Swap: swap(MOET β†’ yieldTokens) + Swap-->>AB: yieldTokens + AB->>Vault: deposit(yieldTokens) + end + + AB->>Scheduler: scheduleNextRebalance() +``` + +Learn more in [AutoBalancer](./autobalancer.md). + +### ALP Position Integration + +Each FYV vault maintains a capability to an ALP Position resource for leveraged borrowing. + +**What it does**: The Position holds collateral deposited by the strategy, borrows MOET against the collateral (up to 80% of value), maintains health factor (target: 1.3), and provides liquidity source for deficit recovery. + +**Health factor management:** +``` +Health Factor = (Collateral Value Γ— Collateral Factor) / Debt Value + +Safe Range: 1.1 - 1.5 +Target: 1.3 (optimal leverage) +Liquidation Trigger: < 1.0 +``` + +**Position lifecycle:** +1. Strategy deposits FLOW collateral +2. Position borrows MOET (maintaining HF = 1.3) +3. Strategy converts MOET to yield tokens +4. AutoBalancer deposits yield tokens to ERC4626 +5. When rebalancing triggers: + - Excess: Withdraw yield β†’ swap β†’ deposit more collateral + - Deficit: Borrow more MOET β†’ swap β†’ deposit yield tokens + +Learn more: [ALP Documentation](../alp/index.md) + +## DeFi Actions Connectors + +FYV uses DeFi Actions as composable building blocks for complex yield strategies. + +### SwapConnectors + +Handle token conversions between MOET, collateral, and yield tokens. + +**Available implementations:** +- **UniswapV3SwapConnectors**: Swap via Uniswap V3 pools +- **TeleportCustodySwapConnectors**: Swap via Teleport custody connectors + +**Example usage:** +```cadence +// Swap MOET β†’ YieldToken +let yieldTokens <- swapConnector.swap( + vaultIn: <-moetVault, + amountOutMin: 95.0 // 5% slippage tolerance +) +``` + +### Sink/Source Connectors + +Handle deposits and withdrawals from yield-bearing protocols. + +**ERC4626SinkConnectors**: Deposit to and withdraw from ERC4626-compatible vaults (standard interface for yield-bearing vaults). + +**TopUpSource/DrawDownSink**: Bridge between ALP positions and FYV strategies for automated liquidity provision. + +**Example usage:** +```cadence +// Deposit to ERC4626 vault +sinkConnector.deposit(vault: <-yieldTokens) + +// Withdraw from ERC4626 vault +let withdrawn <- sourceConnector.withdraw(amount: 100.0) +``` + +Learn more in [DeFi Actions](./defi-actions.md). + +## Automated Scheduling System + +FYV implements a self-scheduling mechanism for perpetual rebalancing without external coordination. + +### Self-Scheduling Mechanism + +**Initial setup:** +1. User creates YieldVault +2. Vault creation atomically: + - Issues capability to AutoBalancer + - Registers in SchedulerRegistry + - Schedules first rebalance via FlowTransactionScheduler + +**Perpetual execution:** +1. Scheduler executes `rebalance()` at scheduled time +2. AutoBalancer performs rebalancing logic +3. AutoBalancer calls `scheduleNextRebalance()` for 60 seconds later +4. Process repeats indefinitely + +**Atomic registration:** +If any step fails during vault creation (capability issue, registration failure, or scheduling error), the entire transaction reverts, ensuring no orphaned or incomplete vaults. + +### Supervisor Recovery System + +The Supervisor handles vaults that become stuck or fail to self-schedule. + +**What it does**: Supervisor scans SchedulerRegistry for pending vaults (max 50 per batch), attempts to re-seed scheduling for stuck vaults, automatically reschedules itself if more work remains, and provides bounded processing to prevent timeout. + +**Recovery flow:** +```mermaid +graph TD + Scheduler[Scheduler Triggers] --> Supervisor[Supervisor.recover] + Supervisor --> Check{Pending
vaults?} + Check -->|Yes| Batch[Get up to 50 vaults] + Batch --> Process[Process each vault] + Process --> Reschedule[Schedule for each vault] + Reschedule --> More{More
pending?} + More -->|Yes| SelfSchedule[Schedule next Supervisor run] + More -->|No| Done[Complete] + Check -->|No| Done +``` + +Learn more in [Scheduling System](./scheduling.md). + +## Cross-Chain Architecture + +FYV supports cross-chain yield opportunities through Flow's EVM bridge. + +### Flow-EVM Bridge Integration + +**What it does**: FlowEVMBridgeConfig manages token escrow and minting, CadenceOwnedAccounts enable Cadence contracts to control EVM addresses, ERC4626 vaults provide Ethereum-compatible yield opportunities, and DeFi Connectors abstract the bridging complexity. + +**Token flow:** +``` +Cadence (Flow) β†’ Bridge Locks β†’ EVM Mints β†’ ERC4626 Deposit β†’ Yield Accrual +Yield Accrual β†’ ERC4626 Withdraw β†’ Bridge Burns β†’ Cadence Unlocks β†’ User Receives +``` + +**Example: mUSDCStrategy** +1. User deposits USDC (Cadence token) +2. Bridge locks USDC in escrow +3. EVM contract mints bridged USDC +4. Strategy deposits to ERC4626 vault on EVM side +5. Yield accrues in EVM vault +6. Rebalancing withdraws from EVM vault +7. Bridge burns EVM tokens and unlocks Cadence tokens +8. Strategy returns tokens to user + +Learn more in [Cross-Chain Integration](./cross-chain.md). + +## Contract Deployment + +FYV consists of five primary contracts deployed on Flow: + +| Contract | Purpose | +|----------|---------| +| **FlowYieldVaults** | Main orchestration managing user positions and strategy lifecycle | +| **FlowYieldVaultsStrategies** | Implementation of concrete strategies (TracerStrategy, mUSDCStrategy) | +| **FlowYieldVaultsAutoBalancers** | Rebalancing logic and balance management | +| **FlowYieldVaultsScheduler** | Scheduled transaction management and recovery | +| **FlowYieldVaultsSchedulerRegistry** | Registry tracking all vaults for automated operations | + +Additionally, **FlowYieldVaultsClosedBeta** manages access control during beta phase. + +**Deployment addresses:** +- **Testnet**: `0xd27920b6384e2a78` +- **Mainnet**: `0xb1d63873c3cc9f79` + +## Security Considerations + +**Access Control**: Vaults are owned resources stored in user accountsβ€”only the account owner can access vault operations. + +**Capability Model**: Strategies hold capabilities to AutoBalancers and Positions, not direct references, enabling revocability and access control. + +**Atomic Operations**: Vault creation and registration happen atomicallyβ€”if any step fails, entire transaction reverts. + +**Health Factor Monitoring**: ALP Positions enforce minimum health factors, preventing over-leveraging. + +**Slippage Protection**: Swap connectors include `amountOutMin` parameters to prevent sandwich attacks. + +**Bounded Processing**: Supervisor processes max 50 vaults per execution to prevent timeout. + +## Summary + +FYV's architecture achieves automated leveraged yield farming through separation of concerns where YieldVault manages user interface and lifecycle, Strategy implements yield generation logic, AutoBalancer handles continuous optimization, Position provides leveraged borrowing, and Scheduler enables automated execution. + +The modular design allows new strategies to be added without changing core vault logic, enabling composability through DeFi Actions components, supporting cross-chain yield through standardized interfaces, and maintaining security through Flow's resource-oriented programming model. + +**Key architectural principles:** +1. **Resource ownership**: Users own vaults; vaults own capabilities +2. **Capability-based security**: Limited access through capabilities, not references +3. **Atomic operations**: All-or-nothing transaction guarantees +4. **Self-scheduling**: Perpetual automation without external dependencies +5. **Modularity**: Strategies can be swapped and composed independently + +## Next Steps + +- **Understand strategies**: Read [Strategies](./strategies.md) +- **Learn rebalancing**: Explore [AutoBalancer](./autobalancer.md) +- **Create a vault**: Follow [Vault Lifecycle](./vault-lifecycle.md) +- **Integrate DeFi Actions**: See [DeFi Actions](./defi-actions.md) + +--- + +:::tip Key Takeaway +FYV's architecture separates user position management (YieldVault) from yield strategy (Strategy) and automated optimization (AutoBalancer). This modularity enables complex yield generation while maintaining clean separation of concerns and allowing new strategies to be added easily. +::: diff --git a/docs/defi/flow-yield-vaults/autobalancer.md b/docs/defi/flow-yield-vaults/autobalancer.md new file mode 100644 index 0000000000..9a6c1467f5 --- /dev/null +++ b/docs/defi/flow-yield-vaults/autobalancer.md @@ -0,0 +1,401 @@ +--- +title: AutoBalancer +sidebar_position: 4 +--- + +# AutoBalancer + +The AutoBalancer is FYV's core optimization engine that continuously monitors yield positions and automatically rebalances when thresholds are exceeded. This document explains how AutoBalancers work, when they trigger, and how they maintain optimal position health. + +## What is an AutoBalancer? + +An AutoBalancer is a resource that holds yield-bearing tokens in ERC4626 vaults, monitors the ratio between current value and historical deposits, automatically withdraws excess profits or requests deficit recovery, and self-schedules continuous rebalancing at 60-second intervals. + +Every YieldVault has an associated AutoBalancer stored in contract storage, managed by the vault's strategy implementation. + +## Core Concept: Value Ratio Monitoring + +The AutoBalancer tracks two key values to determine when rebalancing is needed: + +**Historical Deposit Value**: The cumulative value of all tokens deposited to the ERC4626 vault over time (tracked at deposit time and never changes unless new deposits occur). + +**Current Value**: The real-time value of yield tokens held in the ERC4626 vault (increases as yield accrues and decreases if vault experiences losses). + +**Value Ratio**: +``` +Ratio = Current Value / Historical Deposit Value +``` + +**Rebalancing triggers**: +``` +Ratio > 1.05 (105%) β†’ Excess profits, withdraw surplus +Ratio < 0.95 (95%) β†’ Deficit detected, request recovery +Ratio 0.95-1.05 β†’ Within target range, no action needed +``` + +## Rebalancing Mechanics + +### Upper Threshold: Excess Profits (Ratio > 105%) + +When yield accrues and pushes the ratio above 105%, the AutoBalancer harvests profits. + +**What happens:** + +1. Calculate excess value above 105% baseline +2. Withdraw excess yield tokens from ERC4626 vault +3. Swap yield tokens to collateral (FLOW) via SwapConnectors +4. Deposit collateral to ALP Position (increases collateral, improves health factor) +5. Update tracking (historical value stays same, current value returns to ~100%) + +**Example:** +``` +Initial state: + - Historical deposit value: $1,000 + - Current value: $1,080 (8% yield accrued) + - Ratio: 1,080 / 1,000 = 1.08 = 108% + - Threshold exceeded: 108% > 105% βœ“ + +Rebalancing calculation: + - Target value (105%): $1,000 Γ— 1.05 = $1,050 + - Excess: $1,080 - $1,050 = $30 + - Withdraw: 30 YieldToken from vault + +Swap and deposit: + - Swap 30 YieldToken β†’ 29.7 FLOW (1% slippage) + - Deposit 29.7 FLOW to Position + - Position collateral: 1000 β†’ 1029.7 FLOW + +After rebalancing: + - Historical: $1,000 (unchanged) + - Current: $1,050 (back near target) + - Ratio: 1,050 / 1,000 = 1.05 = 105% + - Collateral increased by $29.70 + - Profits locked in as additional safety buffer +``` + +**Impact on position:** +``` +Before rebalancing: + - Collateral: 1000 FLOW @ $1 = $1,000 + - EC (80% CF): $800 + - Debt: 615.38 MOET + - HF: 800 / 615.38 = 1.30 + +After rebalancing: + - Collateral: 1029.7 FLOW @ $1 = $1,029.70 + - EC (80% CF): $823.76 + - Debt: 615.38 MOET (unchanged) + - HF: 823.76 / 615.38 = 1.34 (improved!) + - Safety buffer increased +``` + +### Lower Threshold: Deficit Recovery (Ratio < 95%) + +When the vault experiences losses or value drops below 95%, the AutoBalancer requests recovery funds. + +**What happens:** + +1. Calculate deficit below 95% baseline +2. Request deficit value from ALP Position +3. Position provides MOET (either from available liquidity or by borrowing more) +4. Swap MOET to yield tokens via SwapConnectors +5. Deposit yield tokens to ERC4626 vault +6. Update tracking (current value returns to ~100%) + +**Example:** +``` +State after vault loss: + - Historical deposit value: $1,000 + - Current value: $920 (8% loss in vault) + - Ratio: 920 / 1,000 = 0.92 = 92% + - Threshold breached: 92% < 95% βœ“ + +Rebalancing calculation: + - Target value (95%): $1,000 Γ— 0.95 = $950 + - Deficit: $950 - $920 = $30 + - Request: $30 from Position + +Position response: + - Position has available liquidity: provides 30 MOET + - OR Position borrows additional 30 MOET if needed + - Swap 30 MOET β†’ 29.7 YieldToken + - Deposit 29.7 YieldToken to vault + +After rebalancing: + - Historical: $1,000 (unchanged) + - Current: $920 + $29.70 = $949.70 + - Ratio: 949.70 / 1,000 = 0.9497 β‰ˆ 95% + - Deficit recovered +``` + +**Impact on leveraged positions:** +``` +Before deficit recovery: + - Collateral: 1000 FLOW @ $1 = $1,000 + - Debt: 615.38 MOET + - Vault value: $920 (loss) + - Total exposure: $1,000 + $920 = $1,920 + +After deficit recovery (if Position borrowed more): + - Collateral: 1000 FLOW (unchanged) + - Debt: 615.38 + 30 = 645.38 MOET (increased) + - Vault value: $949.70 (recovered) + - Total exposure: $1,000 + $949.70 = $1,949.70 + - HF: 800 / 645.38 = 1.24 (slightly lower but still safe) +``` + +## Rebalancing Flow Diagram + +```mermaid +graph TD + Start[Rebalance Triggered] --> GetBalance[Get current vault balance] + GetBalance --> GetHistorical[Get historical deposit value] + GetHistorical --> CalcRatio[Calculate ratio] + CalcRatio --> CheckRatio{Ratio?} + + CheckRatio -->|> 1.05| Excess[Excess Profits] + CheckRatio -->|< 0.95| Deficit[Deficit Recovery] + CheckRatio -->|0.95-1.05| NoAction[No Action Needed] + + Excess --> CalcExcess[Calculate excess amount] + CalcExcess --> WithdrawVault[Withdraw from ERC4626] + WithdrawVault --> SwapToFlow[Swap YieldToken β†’ FLOW] + SwapToFlow --> DepositPos[Deposit FLOW to Position] + DepositPos --> Schedule[Schedule next rebalance] + + Deficit --> CalcDeficit[Calculate deficit amount] + CalcDeficit --> RequestMOET[Request MOET from Position] + RequestMOET --> SwapToYield[Swap MOET β†’ YieldToken] + SwapToYield --> DepositVault[Deposit to ERC4626] + DepositVault --> Schedule + + NoAction --> Schedule + Schedule --> End[Complete] + + style Excess fill:#bfb + style Deficit fill:#fbb + style NoAction fill:#bbf +``` + +## Self-Scheduling Mechanism + +AutoBalancers implement perpetual automation through self-scheduling, eliminating the need for external bots or keepers. + +### How It Works + +**Initial Schedule**: When a YieldVault is created, the AutoBalancer is registered in the SchedulerRegistry and scheduled for its first execution via FlowTransactionScheduler at T+60 seconds. + +**Execution**: At scheduled time, scheduler calls `autoBalancer.rebalance()`. The AutoBalancer performs its rebalancing logic (check ratio, execute if needed). + +**Reschedule**: At the end of `rebalance()`, the AutoBalancer calls `scheduleNextRebalance()` to schedule the next execution 60 seconds later. + +**Perpetual Loop**: This creates an infinite self-scheduling loop where each execution schedules the next one. + +**Sequence diagram:** +```mermaid +sequenceDiagram + participant Scheduler + participant AB as AutoBalancer + participant Registry + + Note over AB: Initial vault creation + AB->>Registry: registerAutoBalancer() + AB->>Scheduler: schedule(rebalance, T+60s) + + Note over Scheduler: Wait 60 seconds + + Scheduler->>AB: rebalance() + AB->>AB: Check ratio and execute logic + AB->>Scheduler: schedule(rebalance, T+60s) + + Note over Scheduler: Wait 60 seconds + + Scheduler->>AB: rebalance() + AB->>AB: Check ratio and execute logic + AB->>Scheduler: schedule(rebalance, T+60s) + + Note over AB,Scheduler: Loop continues indefinitely... +``` + +### Atomic Registration + +Vault creation and AutoBalancer registration happen atomically: + +```cadence +transaction createVault() { + prepare(signer: AuthAccount) { + // All these steps happen in one transaction + let vault <- createYieldVault(...) + let autoBalancer <- createAutoBalancer(...) + + registerInRegistry(autoBalancer) // Step 1 + scheduleFirstRebalance(autoBalancer) // Step 2 + + // If ANY step fails, entire transaction reverts + // No orphaned or incomplete vaults + } +} +``` + +This guarantees that every vault either has a fully functional AutoBalancer with scheduled execution or doesn't exist at all (no partial creation). + +## Configuration Parameters + +AutoBalancers accept configuration to control their behavior: + +```cadence +pub struct AutoBalancerConfig { + // Rebalancing thresholds + pub let upperThreshold: UFix64 // Default: 1.05 (105%) + pub let lowerThreshold: UFix64 // Default: 0.95 (95%) + + // Scheduling + pub let rebalanceIntervalSeconds: UInt64 // Default: 60 + + // Swap protection + pub let slippageTolerance: UFix64 // Default: 0.01 (1%) + + // ERC4626 vault + pub let vaultAddress: Address // Target yield vault +} +``` + +**Tuning considerations:** + +**Tighter thresholds** (e.g., 1.02/0.98): More frequent rebalancing, higher gas costs, more precise optimization, better capital efficiency. + +**Wider thresholds** (e.g., 1.10/0.90): Less frequent rebalancing, lower gas costs, more yield variance tolerance, lower capital efficiency. + +**Shorter intervals** (e.g., 30s): More responsive to changes, higher gas costs, better for volatile vaults. + +**Longer intervals** (e.g., 300s): Less responsive, lower gas costs, better for stable vaults. + +## Gas Optimization + +AutoBalancers are designed to minimize gas costs while maintaining effectiveness: + +**No-Op When In Range**: If ratio is within 95%-105%, the rebalance function returns early without executing swaps or transactions, costing minimal gas. + +**Batch Operations**: When rebalancing is needed, all operations (withdraw, swap, deposit) happen in a single transaction. + +**Efficient Scheduling**: Uses Flow's native transaction scheduler rather than external keeper networks. + +**Bounded Execution**: Each rebalance has deterministic gas cost based on operations performed. + +**Example gas costs** (approximate): +``` +Rebalance (no action needed): ~0.0001 FLOW +Rebalance (with excess withdrawal): ~0.001 FLOW +Rebalance (with deficit recovery): ~0.0015 FLOW +``` + +## Monitoring AutoBalancer State + +Users can query AutoBalancer state to understand position health: + +### Scripts + +**Get current ratio:** +```cadence +import FlowYieldVaults from 0xFlowYieldVaults + +pub fun main(vaultID: UInt64): UFix64 { + let vault = FlowYieldVaults.getVault(id: vaultID) + let autoBalancer = vault.getAutoBalancer() + + let current = autoBalancer.getCurrentValue() + let historical = autoBalancer.getHistoricalValue() + + return current / historical +} +// Returns: 1.08 (108% ratio) +``` + +**Get rebalancing history:** +```cadence +pub fun main(vaultID: UInt64): [RebalanceEvent] { + let vault = FlowYieldVaults.getVault(id: vaultID) + let autoBalancer = vault.getAutoBalancer() + + return autoBalancer.getRebalanceHistory() +} +// Returns array of past rebalancing events with timestamps and amounts +``` + +**Check next rebalance time:** +```cadence +pub fun main(vaultID: UInt64): UFix64 { + let registry = FlowYieldVaults.getSchedulerRegistry() + return registry.getNextScheduledTime(vaultID: vaultID) +} +// Returns: 1703001234 (Unix timestamp) +``` + +## Recovery Mechanisms + +If an AutoBalancer becomes stuck or fails to self-schedule, the Supervisor provides recovery: + +**Supervisor Recovery**: Scans SchedulerRegistry for vaults with pending schedules, attempts to re-seed scheduling for stuck vaults (max 50 per execution), and automatically reschedules itself if more work remains. + +**Manual Recovery**: Vault owners can manually trigger rebalancing via `forceRebalance()` transaction if AutoBalancer is stuck. + +**Admin Recovery**: Protocol administrators can intervene in case of critical failures using admin capabilities. + +Learn more in [Scheduling System](./scheduling.md). + +## Advanced: Custom Rebalancing Logic + +Developers can implement custom AutoBalancer logic for specialized strategies: + +```cadence +pub resource CustomAutoBalancer: AutoBalancerInterface { + pub fun rebalance() { + // Custom logic + // - Different thresholds based on time of day + // - Multi-vault coordination + // - Dynamic threshold adjustment + // - Alternative profit distribution + + // Must call scheduleNextRebalance() at end + self.scheduleNextRebalance() + } +} +``` + +Custom implementations must maintain the self-scheduling mechanism and implement the AutoBalancerInterface and register with SchedulerRegistry. + +## Best Practices + +**Monitor Ratio**: Keep an eye on your AutoBalancer's value ratio. Frequent rebalancing in one direction indicates systematic vault performance. + +**Understand Triggers**: Know your thresholds. If your vault frequently hits 105%, you're generating steady profits. If it hits 95%, the vault may be experiencing losses. + +**Gas Awareness**: More frequent rebalancing = more gas costs. Balance responsiveness vs. costs based on your vault size. + +**Threshold Tuning**: Larger vaults benefit from tighter thresholds (better optimization). Smaller vaults benefit from wider thresholds (lower gas impact). + +**Track History**: Review rebalancing history to understand vault performance patterns and identify optimal strategy configurations. + +## Summary + +AutoBalancers are FYV's optimization engine that maintain yield positions within target ranges. They monitor value ratios continuously (every 60 seconds), withdraw excess profits above 105% and lock them as collateral, request deficit recovery below 95% to maintain position health, and self-schedule perpetually without external dependencies. + +**Key mechanisms:** +- Value ratio monitoring: Current vs. Historical +- Bidirectional rebalancing: Excess profits and deficit recovery +- Self-scheduling: Perpetual 60-second loops +- Atomic registration: All-or-nothing vault creation +- Gas optimization: No-op when within range + +## Next Steps + +- **Understand scheduling**: Read [Scheduling System](./scheduling.md) +- **Learn about leverage**: Explore [Leveraged Farming](./leveraged-farming.md) +- **Create a vault**: Follow [Vault Lifecycle](./vault-lifecycle.md) +- **DeFi Actions composability**: See [DeFi Actions](./defi-actions.md) + +--- + +:::tip Key Takeaway +AutoBalancers continuously optimize your yield position by harvesting profits when value exceeds 105% and recovering deficits when value drops below 95%. This creates a self-optimizing system that locks in gains and prevents losses without manual intervention. +::: diff --git a/docs/defi/flow-yield-vaults/cross-chain.md b/docs/defi/flow-yield-vaults/cross-chain.md new file mode 100644 index 0000000000..2fc56b0520 --- /dev/null +++ b/docs/defi/flow-yield-vaults/cross-chain.md @@ -0,0 +1,315 @@ +--- +title: Cross-Chain Integration +sidebar_position: 8 +--- + +# Cross-Chain Integration + +FYV enables access to yield opportunities across multiple blockchains through Flow's EVM bridge. This document explains how cross-chain integration works and how to access Ethereum-compatible yield vaults from Flow. + +## Flow-EVM Bridge Overview + +Flow's EVM bridge connects Flow's Cadence environment with Ethereum Virtual Machine (EVM) compatible chains, enabling seamless asset transfer and smart contract interaction across ecosystems. + +### Bridge Architecture + +The bridge consists of several components: + +**FlowEVMBridgeConfig**: Manages token escrow and minting configuration, maintains token pair mappings (Flow ↔ EVM), and handles bridge fees and limits. + +**CadenceOwnedAccounts (COA)**: Enables Cadence contracts to control EVM addresses, allows Cadence to send EVM transactions, and bridges resource-oriented (Cadence) with account-based (EVM) models. + +**Token Escrow**: Locks Flow native tokens when bridging to EVM, mints equivalent bridged tokens on EVM side, and maintains 1:1 backing ratio. + +### How Bridging Works + +**Flow β†’ EVM (Bridging Out):** +``` +1. User deposits USDC (Flow native) to bridge contract +2. Bridge locks USDC in escrow vault +3. Bridge mints equivalent bridged USDC on EVM side +4. EVM contract receives bridged USDC +5. Transaction hash recorded for verification +``` + +**EVM β†’ Flow (Bridging Back):** +``` +1. EVM contract burns bridged USDC +2. Bridge receives burn notification +3. Bridge unlocks equivalent USDC from escrow +4. User receives USDC on Flow +5. Cross-chain operation complete +``` + +## mUSDCStrategy: Cross-Chain Yield Farming + +The mUSDCStrategy leverages the EVM bridge to access Ethereum-compatible ERC4626 yield vaults. + +### Strategy Architecture + +```mermaid +graph TB + User[User Account] -->|Deposit USDC| Strategy[mUSDCStrategy] + Strategy -->|Bridge| Bridge[FlowEVMBridge] + Bridge -->|Lock USDC| Escrow[Escrow Vault] + Bridge -->|Mint| Bridged[Bridged USDC on EVM] + + Strategy -->|Control| COA[CadenceOwnedAccount] + COA -->|EVM TX| EVMAddr[EVM Address] + EVMAddr -->|Deposit| Vault[ERC4626 Vault] + + Vault -->|Yield| Accrue[Yield Accrual] + Accrue -->|Withdraw| EVMAddr + EVMAddr -->|Burn| Bridged + Bridge -->|Unlock| Escrow + Escrow -->|Return| User + + style Strategy fill:#f9f + style Bridge fill:#bfb + style Vault fill:#bbf +``` + +### Example: Depositing to Cross-Chain Vault + +**User deposits 1000 USDC:** + +``` +Step 1: Bridge to EVM + - User deposits: 1000 USDC (Flow native) + - Bridge locks: 1000 USDC in escrow + - Bridge mints: 1000 bridged USDC on EVM + - Gas cost: ~0.001 FLOW (bridge fee) + +Step 2: COA Transaction + - Strategy controls EVM address via COA + - COA approves ERC4626 vault to spend USDC + - EVM transaction: approve(vault, 1000 USDC) + - Gas cost: ~0.00015 ETH (paid in bridged FLOW) + +Step 3: Deposit to ERC4626 + - COA calls vault.deposit(1000 USDC) + - Vault mints shares to COA address + - Shares received: 1000 (1:1 ratio initially) + - Gas cost: ~0.0002 ETH + +Step 4: Track in AutoBalancer + - AutoBalancer records: Historical value = $1000 + - Scheduling begins: Rebalance every 60s + - Cross-chain monitoring active + +Total setup cost: ~$2-5 (depending on gas prices) +``` + +### Yield Accrual and Rebalancing + +**After yield accrues:** + +``` +ERC4626 vault generates 8% APY over time: + - Initial shares: 1000 + - After time: Shares worth 1080 USDC + - Current value: $1080 + - Historical: $1000 + - Ratio: 1.08 = 108% > 105% threshold + +Rebalancing trigger: + Step 1: Calculate excess + - Excess: $1080 - $1050 = $30 + + Step 2: Withdraw from EVM vault (via COA) + - COA calls vault.withdraw(30 USDC) + - EVM transaction gas: ~0.0002 ETH + - Bridged USDC received at EVM address + + Step 3: Bridge back to Flow + - COA burns 30 bridged USDC + - Bridge unlocks 30 Flow USDC + - Bridge transaction fee: ~0.0005 FLOW + + Step 4: Return to user + - User can claim or compound + - Net profit: $30 - gas costs β‰ˆ $29.50 +``` + +## Supported ERC4626 Vaults + +mUSDCStrategy can connect to any ERC4626-compliant vault on EVM-compatible chains: + +### Mainnet Vaults (Example) + +| Vault Name | Address | Asset | APY Range | +|-----------|---------|-------|-----------| +| Yearn USDC | `0x...` | USDC | 5-12% | +| Aave USDC | `0x...` | USDC | 3-8% | +| Compound USDC | `0x...` | USDC | 4-10% | +| Morpho USDC | `0x...` | USDC | 6-15% | + +**Note:** Vault addresses configured at strategy deployment time. Contact FYV team for current vault list. + +### Vault Selection Criteria + +When choosing ERC4626 vaults for cross-chain farming, consider: + +**Security Audit**: Vault must have recent professional audit, proven track record, and established protocol reputation. + +**Liquidity**: Sufficient liquidity for deposits/withdrawals, low slippage on rebalancing, and reasonable withdrawal limits. + +**Yield Stability**: Consistent yield history, low volatility in APY, and transparent yield source. + +**Gas Efficiency**: Efficient deposit/withdraw operations, batching support if available, and reasonable gas costs relative to vault size. + +**Integration Compatibility**: Full ERC4626 compliance, no special requirements or restrictions, and standard share accounting. + +## Gas Cost Considerations + +Cross-chain operations incur gas costs on both Flow and EVM sides: + +### Cost Breakdown + +**Vault Creation (One-Time):** +``` +Flow side: + - Create strategy: ~0.001 FLOW + - Bridge setup: ~0.001 FLOW + - Register scheduler: ~0.0005 FLOW + Total Flow: ~0.0025 FLOW ($0.002 @ $0.80/FLOW) + +EVM side: + - Approve vault: ~0.00015 ETH + - Initial deposit: ~0.0002 ETH + Total EVM: ~0.00035 ETH ($0.70 @ $2000/ETH) + +Combined one-time cost: ~$0.70 +``` + +**Per Rebalance:** +``` +When no action needed (95%-105%): + - Flow: ~0.0001 FLOW ($0.00008) + - EVM: $0 (no transaction) + Total: ~$0.00008 + +When rebalancing needed: + - Flow bridge: ~0.0005 FLOW ($0.0004) + - EVM withdraw: ~0.0002 ETH ($0.40) + - EVM burn: ~0.00015 ETH ($0.30) + Total: ~$0.70 per rebalance +``` + +**Annual Gas Costs (Estimate):** +``` +Assumptions: + - Rebalancing every 60s = 525,600 checks/year + - 5% trigger rebalancing = 26,280 rebalances/year + - 95% no action = 499,320 no-ops/year + +Costs: + - No-ops: 499,320 Γ— $0.00008 = $40 + - Rebalances: 26,280 Γ— $0.70 = $18,396 + +Total annual gas: ~$18,436 + +For $100K vault: 18.4% of capital (uneconomical!) +For $1M vault: 1.84% of capital (marginal) +For $10M vault: 0.184% of capital (acceptable) +``` + +**Conclusion:** Cross-chain strategies are most cost-effective for larger vaults ($1M+). + +## Bridge Security Considerations + +Using the EVM bridge introduces additional security considerations: + +### Bridge Risk Factors + +**Escrow Security**: Flow tokens locked in bridge escrow contract must be secure, audited, and monitored. Risk: Escrow hack could drain bridged assets. + +**Mint/Burn Integrity**: Bridged tokens must maintain 1:1 backing ratio. Risk: Minting without locking could create unbacked tokens. + +**Cross-Chain Timing**: Bridge operations aren't instant (typically 1-2 minutes). Risk: Price movements during bridging. + +**EVM Vault Security**: ERC4626 vaults on EVM side have independent security models. Risk: Vault exploit affects bridged assets. + +**COA Control**: Cadence contract controls EVM address via COA. Risk: COA vulnerability could compromise EVM assets. + +### Mitigation Strategies + +**Bridge Audits**: Use only audited, established bridge infrastructure and verify escrow contract security. + +**Vault Vetting**: Only connect to audited, reputable ERC4626 vaults with proven track records. + +**Diversification**: Spread capital across multiple vaults and don't concentrate in single cross-chain vault. + +**Monitoring**: Track bridge health metrics and monitor unusual bridge activity. + +**Limits**: Implement per-vault and per-user caps to limit exposure. + +## Cross-Chain Transaction Flow + +Complete cross-chain farming cycle: + +```mermaid +sequenceDiagram + participant User + participant Strategy + participant Bridge + participant COA + participant EVM as EVM Vault + + Note over User,EVM: Deposit Phase + + User->>Strategy: deposit(1000 USDC) + Strategy->>Bridge: bridge(1000 USDC) + Bridge->>Bridge: Lock in escrow + Bridge->>COA: Mint 1000 on EVM + COA->>EVM: deposit(1000 bridged USDC) + EVM-->>COA: 1000 shares + + Note over User,EVM: Yield Accrual + + EVM->>EVM: Generate yield + EVM->>EVM: Shares now worth 1080 USDC + + Note over User,EVM: Rebalancing + + Strategy->>COA: Check balance + COA->>EVM: balanceOf() + EVM-->>COA: 1080 USDC + Strategy->>COA: withdraw(30 USDC) + COA->>EVM: withdraw(30) + EVM-->>COA: 30 bridged USDC + COA->>Bridge: burn(30 USDC) + Bridge->>Bridge: Unlock from escrow + Bridge-->>User: 30 USDC (Flow native) +``` + +## Best Practices + +**Vault Size Matters**: Only use cross-chain strategies for larger vaults ($1M+) where gas costs are < 2% of capital. + +**Monitor Gas Prices**: Track EVM gas prices and pause rebalancing during high gas periods if needed. + +**Understand Bridge Risk**: Cross-chain farming adds bridge security risk on top of vault risk. + +**Diversify**: Don't put all capital in cross-chain vaultsβ€”balance with native Flow strategies. + +**Track Costs**: Monitor actual gas costs vs. yields to ensure profitability. + +**Emergency Access**: Understand how to manually withdraw if automation fails. + +## Summary + +Cross-chain integration via mUSDCStrategy enables access to Ethereum-compatible ERC4626 vaults from Flow, leveraging the Flow-EVM bridge for asset transfer and CadenceOwnedAccounts for EVM control. This unlocks broader yield opportunities while introducing additional gas costs and bridge security considerations. + +**Key tradeoffs:** +- **Benefit**: Access to mature Ethereum DeFi yield +- **Cost**: Higher gas fees from cross-chain operations +- **Risk**: Bridge security and cross-chain timing + +**Optimal use case:** Large vaults ($1M+) seeking diversified yield sources across chains. + +--- + +:::tip Key Takeaway +Cross-chain yield farming is powerful but gas-intensive. It's most suitable for large vaults where gas costs are a small percentage of capital. For smaller vaults, native Flow strategies like TracerStrategy are more cost-effective. +::: diff --git a/docs/defi/flow-yield-vaults/defi-actions.md b/docs/defi/flow-yield-vaults/defi-actions.md new file mode 100644 index 0000000000..a3a01c7043 --- /dev/null +++ b/docs/defi/flow-yield-vaults/defi-actions.md @@ -0,0 +1,440 @@ +--- +title: DeFi Actions +sidebar_position: 9 +--- + +# DeFi Actions + +DeFi Actions are composable primitives that enable complex DeFi operations through simple, reusable components. FYV leverages DeFi Actions to build sophisticated yield strategies from modular building blocks. This document explains the DeFi Actions framework and how it powers FYV's composability. + +## What are DeFi Actions? + +DeFi Actions is a framework of composable smart contract components that implement common DeFi operations as standardized interfaces. Rather than building monolithic strategies, developers compose Actions like building blocks to create complex flows. + +**Key principles:** +- **Single Responsibility**: Each Action does one thing well +- **Composability**: Actions can be chained and combined +- **Standardized Interfaces**: Consistent APIs across implementations +- **Reusability**: Same Actions used across multiple strategies + +## Core Action Types + +FYV uses three main categories of DeFi Actions: + +### 1. Swap Actions (SwapConnectors) + +Convert one token type to another via decentralized exchanges. + +**Interface:** +```cadence +pub resource interface SwapConnector { + // Swap input tokens for output tokens + pub fun swap( + vaultIn: @FungibleToken.Vault, + amountOutMin: UFix64 + ): @FungibleToken.Vault + + // Get expected output for given input + pub fun quote(amountIn: UFix64): UFix64 + + // Get swap route information + pub fun getRoute(): SwapRoute +} +``` + +**Implementations:** +- **UniswapV3SwapConnectors**: Swap via Uniswap V3 pools on Flow EVM +- **TeleportCustodySwapConnectors**: Swap via Teleport custody protocol +- **IncrementSwapConnectors**: Swap via Increment DEX + +**Example usage:** +```cadence +// Swap MOET β†’ FLOW via Uniswap V3 +let swapConnector <- UniswapV3SwapConnectors.createConnector( + tokenIn: Type<@MOET.Vault>(), + tokenOut: Type<@FlowToken.Vault>(), + poolFee: 3000 // 0.3% fee tier +) + +let flowVault <- swapConnector.swap( + vaultIn: <-moetVault, + amountOutMin: 95.0 // 5% slippage tolerance +) +``` + +### 2. Sink Actions (SinkConnectors) + +Deposit tokens into yield-generating protocols. + +**Interface:** +```cadence +pub resource interface SinkConnector { + // Deposit tokens to yield protocol + pub fun deposit(vault: @FungibleToken.Vault) + + // Get current deposited balance + pub fun getBalance(): UFix64 + + // Get vault metadata + pub fun getVaultInfo(): VaultInfo +} +``` + +**Implementations:** +- **ERC4626SinkConnectors**: Deposit to ERC4626-compliant vaults +- **DrawDownSink**: Bridge to ALP borrowing positions +- **StakingSinkConnectors**: Stake tokens in staking protocols + +**Example usage:** +```cadence +// Deposit to ERC4626 vault +let sinkConnector <- ERC4626SinkConnectors.createConnector( + vaultAddress: 0x123..., // ERC4626 vault address + tokenType: Type<@YieldToken.Vault>() +) + +sinkConnector.deposit(vault: <-yieldTokens) +// Tokens now earning yield in ERC4626 vault +``` + +### 3. Source Actions (SourceConnectors) + +Withdraw tokens from yield-generating protocols. + +**Interface:** +```cadence +pub resource interface SourceConnector { + // Withdraw specified amount + pub fun withdraw(amount: UFix64): @FungibleToken.Vault + + // Withdraw all available balance + pub fun withdrawAll(): @FungibleToken.Vault + + // Get available withdrawal amount + pub fun getAvailableBalance(): UFix64 +} +``` + +**Implementations:** +- **ERC4626SourceConnectors**: Withdraw from ERC4626 vaults +- **TopUpSource**: Provide liquidity from ALP positions +- **UnstakingSourceConnectors**: Unstake from staking protocols + +**Example usage:** +```cadence +// Withdraw from ERC4626 vault +let sourceConnector <- ERC4626SourceConnectors.createConnector( + vaultAddress: 0x123..., + tokenType: Type<@YieldToken.Vault>() +) + +let withdrawn <- sourceConnector.withdraw(amount: 100.0) +// Yield tokens withdrawn from vault +``` + +## Action Composition + +The power of DeFi Actions comes from compositionβ€”chaining multiple Actions to create complex flows. + +### Example: TracerStrategy Composition + +TracerStrategy composes five Actions to implement leveraged yield farming: + +**1. Borrow Action** (DrawDownSink): +```cadence +// Borrow MOET from ALP position +let borrowAction <- DrawDownSink.create(positionCap: positionCapability) +borrowAction.deposit(vault: <-initialCollateral) +// Position auto-borrows MOET +``` + +**2. Swap Action #1** (MOET β†’ YieldToken): +```cadence +// Convert borrowed MOET to yield tokens +let swapAction1 <- UniswapV3SwapConnectors.createConnector( + tokenIn: Type<@MOET.Vault>(), + tokenOut: Type<@YieldToken.Vault>(), + poolFee: 3000 +) + +let yieldTokens <- swapAction1.swap( + vaultIn: <-moetVault, + amountOutMin: 95.0 +) +``` + +**3. Sink Action** (YieldToken β†’ ERC4626): +```cadence +// Deposit yield tokens to earn +let sinkAction <- ERC4626SinkConnectors.createConnector( + vaultAddress: 0x789..., + tokenType: Type<@YieldToken.Vault>() +) + +sinkAction.deposit(vault: <-yieldTokens) +// Now earning yield +``` + +**4. Source Action** (ERC4626 β†’ YieldToken): +```cadence +// Withdraw when rebalancing needed +let sourceAction <- ERC4626SourceConnectors.createConnector( + vaultAddress: 0x789..., + tokenType: Type<@YieldToken.Vault>() +) + +let withdrawn <- sourceAction.withdraw(amount: excessAmount) +``` + +**5. Swap Action #2** (YieldToken β†’ FLOW): +```cadence +// Convert back to collateral +let swapAction2 <- UniswapV3SwapConnectors.createConnector( + tokenIn: Type<@YieldToken.Vault>(), + tokenOut: Type<@FlowToken.Vault>(), + poolFee: 3000 +) + +let flowCollateral <- swapAction2.swap( + vaultIn: <-withdrawn, + amountOutMin: 95.0 +) +// Deposit back to position as additional collateral +``` + +### Composition Diagram + +```mermaid +graph LR + Collateral[FLOW Collateral] -->|1. Deposit| Borrow[DrawDownSink] + Borrow -->|2. Borrow| MOET[MOET Tokens] + MOET -->|3. Swap| Swap1[UniswapV3Swap] + Swap1 -->|4. Convert| Yield[YieldTokens] + Yield -->|5. Deposit| Sink[ERC4626Sink] + Sink -->|6. Earn| Vault[ERC4626 Vault] + + Vault -->|7. Withdraw| Source[ERC4626Source] + Source -->|8. Convert| Swap2[UniswapV3Swap] + Swap2 -->|9. Return| Collateral + + style Borrow fill:#f9f + style Swap1 fill:#bfb + style Sink fill:#bbf + style Source fill:#bbf + style Swap2 fill:#bfb +``` + +## Strategy Composer Pattern + +The **StrategyComposer** pattern assembles Actions into complete strategies: + +```cadence +pub resource StrategyComposer { + // Action components + access(self) let borrowAction: @DrawDownSink + access(self) let swapToYieldAction: @SwapConnector + access(self) let sinkAction: @SinkConnector + access(self) let sourceAction: @SourceConnector + access(self) let swapToCollateralAction: @SwapConnector + + // Compose into strategy + pub fun composeStrategy(): @Strategy { + let strategy <- create TracerStrategy( + borrowAction: <-self.borrowAction, + swapToYield: <-self.swapToYieldAction, + sink: <-self.sinkAction, + source: <-self.sourceAction, + swapToCollateral: <-self.swapToCollateralAction + ) + + return <-strategy + } +} +``` + +**Benefits of this pattern:** +- **Flexibility**: Swap any Action implementation without changing strategy logic +- **Testability**: Mock Actions for testing strategies in isolation +- **Reusability**: Same Actions used across multiple strategies +- **Upgradability**: Replace Actions with improved versions + +## Creating Custom Strategies + +Developers can create custom strategies by composing different Actions: + +### Example: Conservative Stablecoin Strategy + +```cadence +pub resource ConservativeStrategy { + // Simplified strategy: just deposit to yield vault + access(self) let sinkAction: @ERC4626SinkConnector + access(self) let sourceAction: @ERC4626SourceConnector + + pub fun deposit(vault: @FungibleToken.Vault) { + // Direct deposit, no borrowing or swapping + self.sinkAction.deposit(vault: <-vault) + } + + pub fun withdraw(amount: UFix64): @FungibleToken.Vault { + // Direct withdrawal + return <-self.sourceAction.withdraw(amount: amount) + } + + pub fun getBalance(): UFix64 { + return self.sinkAction.getBalance() + } +} +``` + +### Example: Multi-Vault Strategy + +```cadence +pub resource MultiVaultStrategy { + // Diversify across multiple vaults + access(self) let vaults: @{String: SinkConnector} + + pub fun deposit(vault: @FungibleToken.Vault) { + let amount = vault.balance + + // Split across 3 vaults + let vault1Amount = amount * 0.4 + let vault2Amount = amount * 0.3 + let vault3Amount = amount * 0.3 + + let vault1 <- vault.withdraw(amount: vault1Amount) + let vault2 <- vault.withdraw(amount: vault2Amount) + let vault3 <- vault + + self.vaults["vault1"]?.deposit(vault: <-vault1) + self.vaults["vault2"]?.deposit(vault: <-vault2) + self.vaults["vault3"]?.deposit(vault: <-vault3) + } +} +``` + +## Action Registry + +The **ActionRegistry** maintains available Action implementations: + +```cadence +pub contract ActionRegistry { + // Registry of available Actions + access(contract) var swapConnectors: {String: Type} + access(contract) var sinkConnectors: {String: Type} + access(contract) var sourceConnectors: {String: Type} + + // Register new Action + pub fun registerSwapConnector(name: String, type: Type) { + self.swapConnectors[name] = type + } + + // Get available Actions + pub fun getAvailableSwapConnectors(): [String] { + return self.swapConnectors.keys + } + + // Create Action instance + pub fun createSwapConnector(name: String, config: {String: AnyStruct}): @SwapConnector { + let connectorType = self.swapConnectors[name] + ?? panic("Connector not found") + + return <-create connectorType(config: config) + } +} +``` + +**Benefits:** +- **Discovery**: Users can enumerate available Actions +- **Versioning**: Multiple versions of same Action can coexist +- **Governance**: Community can vote on adding new Actions + +## Advanced Composition Patterns + +### 1. Sequential Composition + +Chain Actions in sequence: + +```cadence +// FLOW β†’ MOET β†’ YieldToken β†’ ERC4626 +let result <- action1.execute(input: <-flowVault) + |> action2.execute(input: <-result) + |> action3.execute(input: <-result) + |> action4.execute(input: <-result) +``` + +### 2. Parallel Composition + +Execute multiple Actions concurrently: + +```cadence +// Deposit to 3 vaults simultaneously +async { + vault1.deposit(vault: <-split1) + vault2.deposit(vault: <-split2) + vault3.deposit(vault: <-split3) +} +``` + +### 3. Conditional Composition + +Choose Actions based on conditions: + +```cadence +if ratio > 1.05 { + // Withdraw and swap + let withdrawn <- sourceAction.withdraw(amount: excess) + let collateral <- swapAction.swap(vaultIn: <-withdrawn) +} else if ratio < 0.95 { + // Borrow and swap + let borrowed <- borrowAction.borrow(amount: deficit) + let yieldTokens <- swapAction.swap(vaultIn: <-borrowed) +} +``` + +### 4. Recursive Composition + +Actions that contain other Actions: + +```cadence +pub resource CompositeAction: SwapConnector { + // Multi-hop swap composed of single-hop swaps + access(self) let hop1: @SwapConnector + access(self) let hop2: @SwapConnector + + pub fun swap(vaultIn: @FungibleToken.Vault): @FungibleToken.Vault { + let intermediate <- self.hop1.swap(vaultIn: <-vaultIn) + return <-self.hop2.swap(vaultIn: <-intermediate) + } +} +``` + +## Best Practices + +**Keep Actions Small**: Each Action should have single, clear responsibility. + +**Use Interfaces**: Depend on Action interfaces, not concrete implementations. + +**Handle Failures**: Implement proper error handling and revert logic. + +**Document Dependencies**: Clearly specify required Action sequences. + +**Version Actions**: Track Action versions for compatibility. + +**Test Composition**: Unit test Actions individually, integration test compositions. + +## Summary + +DeFi Actions provide the composability framework that powers FYV's flexibility through modular Actions for swaps, deposits, and withdrawals, standardized interfaces enabling interchangeability, composition patterns supporting complex strategies, and the registry system allowing Action discovery and versioning. + +**Key components:** +- **SwapConnectors**: Token conversion via DEXes +- **SinkConnectors**: Deposits to yield protocols +- **SourceConnectors**: Withdrawals from yield protocols +- **StrategyComposer**: Assembles Actions into strategies +- **ActionRegistry**: Discovers and versions Actions + +--- + +:::tip Key Takeaway +DeFi Actions are like LEGO blocks for DeFi strategies. By composing simple, reusable Actions, FYV enables sophisticated yield farming flows while maintaining clean separation of concerns and allowing easy customization. +::: diff --git a/docs/defi/flow-yield-vaults/index.md b/docs/defi/flow-yield-vaults/index.md new file mode 100644 index 0000000000..431c3c2cff --- /dev/null +++ b/docs/defi/flow-yield-vaults/index.md @@ -0,0 +1,122 @@ +--- +title: Flow Yield Vaults (FYV) +sidebar_label: Flow Yield Vaults (FYV) +sidebar_position: 11 +--- + +# Flow Yield Vaults (FYV) + +Flow Yield Vaults (FYV) is a DeFi protocol that enables users to deposit tokens into yield-generating strategies that automatically optimize returns through leveraged positions and continuous rebalancing. FYV is one of the three core components of [Flow Credit Market (FCM)](../fcm/index.md), working alongside [ALP](../alp/index.md) and [MOET](#) to create a fully automated yield farming system. + +:::info +FYV is one of three core components that make up FCM: [ALP (Automated Lending Platform)](../alp/index.md) provides the lending/borrowing engine, FYV (Flow Yield Vaults) handles yield aggregation strategies, and [MOET](#) serves as the synthetic stablecoin and unit of account. +::: + +## What is FYV? + +FYV is a yield aggregation platform that enables automated leveraged yield farming through integration with FlowCreditMarket's lending infrastructure. The system deposits tokens into DeFi strategies, automatically optimizes returns through leveraged positions, continuously rebalances to maintain safe leverage ratios, and provides liquidity for liquidation prevention in ALP positions. + +The protocol operates on the Flow blockchain using Cadence smart contracts and supports multiple tokens including FLOW, USDC, wBTC, wETH, and MOET. + +## Key Innovation: Automated Leveraged Yield Farming + +FYV's standout feature is its **TracerStrategy** that combines leveraged borrowing with yield farming in a fully automated system. When you deposit FLOW into FYV, the system deposits it as collateral in ALP to create a lending position, borrows MOET against the collateral (up to 80% of collateral value), converts borrowed MOET into yield-bearing tokens through swap connectors, deposits yield tokens into ERC4626 vaults via AutoBalancer, and continuously monitors and rebalances to maintain target health factor of 1.3. The result is amplified returns through leverage while maintaining safety through automated health management. + +### Integration with ALP for Liquidation Prevention + +FYV serves a dual purpose in the FCM ecosystem by not only generating yield through leveraged farming but also providing liquidation protection for ALP positions. When an ALP position's health drops due to collateral price changes, FYV provides liquidity via TopUpSource by converting yield tokens back to MOET and sending them to ALP for debt repayment. This yield-powered protection mechanism prevents liquidations automatically, requiring no manual intervention from users. + +## Core Components + +The FYV protocol consists of several key components that work together: + +**YieldVault**: The user-owned resource representing a leveraged position. Each vault tracks the user's deposits, holds capabilities to interact with strategies, and maintains the connection to the AutoBalancer and ALP position. + +**Strategy**: Defines the yield generation approach. Strategies implement deposit, withdraw, and liquidation operations. The StrategyFactory maintains a registry of available strategies, allowing multiple yield generation approaches while keeping vault logic protocol-agnostic. + +**AutoBalancer**: Manages yield token holdings and triggers rebalancing when thresholds are exceeded. The AutoBalancer monitors the value ratio between current holdings and historical deposits, maintaining it within 95%-105% bounds. + +**Position** (from ALP): The underlying lending position that holds collateral and debt. Strategies maintain capabilities to deposit collateral, borrow MOET, and monitor position health. + +**Scheduler**: Handles automated rebalancing through self-scheduling mechanism. Each AutoBalancer schedules its next rebalance execution at 60-second intervals, creating perpetual automation. + +Learn more in [Architecture Overview](./architecture.md). + +## Documentation Sections + +### Core Concepts +- [Architecture Overview](./architecture.md) - Core components and system design +- [Strategies](./strategies.md) - Understanding TracerStrategy and yield generation +- [AutoBalancer](./autobalancer.md) - Automated rebalancing mechanics +- [Vault Lifecycle](./vault-lifecycle.md) - Creating, managing, and closing vaults + +### Advanced Features +- [Leveraged Farming](./leveraged-farming.md) - How leverage amplifies returns +- [Cross-Chain Integration](./cross-chain.md) - Flow-EVM bridge and ERC4626 vaults +- [Scheduling System](./scheduling.md) - Automated execution and recovery + +### Integration +- [FCM Integration](./fcm-integration.md) - Working with ALP and MOET +- [DeFi Actions](./defi-actions.md) - Composable DeFi primitives +- [Swap Connectors](./swap-connectors.md) - Token conversion infrastructure + +## Getting Started + +### For Users + +If you want to earn yield through automated leveraged farming, start with the [Vault Lifecycle](./vault-lifecycle.md) guide to learn how to create your first vault, deposit collateral, and monitor your position. + +### For Developers + +If you want to integrate FYV or create custom strategies, start with the [Architecture Overview](./architecture.md) to understand the system design, then explore [DeFi Actions](./defi-actions.md) for composability patterns. + +### For DeFi Builders + +If you want to understand how FYV achieves automated leverage and liquidation protection, start with [Leveraged Farming](./leveraged-farming.md) and [FCM Integration](./fcm-integration.md). + +## Key Features + +**Automated Leverage**: FYV automatically borrows against your collateral to maximize capital efficiency while maintaining safe health factors. + +**Continuous Rebalancing**: The AutoBalancer monitors your position 24/7 and automatically adjusts when thresholds are exceeded. + +**Liquidation Prevention**: FYV provides liquidity to ALP positions when needed, preventing liquidations through yield accumulation. + +**Cross-Chain Yield**: Access Ethereum-compatible yield vaults through Flow's EVM bridge, bringing DeFi opportunities from multiple chains. + +**Composable Strategies**: Stack DeFi Actions components to create complex yield generation flows tailored to your risk tolerance. + +**Self-Scheduling**: Vaults perpetually schedule their own rebalancing without relying on external bots or keepers. + +## Supported Tokens + +FYV supports multiple collateral types and yield tokens: + +- **FLOW**: Native Flow token +- **stFLOW**: Staked FLOW with liquid staking rewards +- **USDC**: USD stablecoin (bridged) +- **wBTC**: Wrapped Bitcoin (bridged) +- **wETH**: Wrapped Ethereum (bridged) +- **MOET**: Synthetic stablecoin (borrowed asset) + +## Deployment Addresses + +| Network | Contract Address | Status | +|---------|-----------------|--------| +| **Testnet** | `0xd27920b6384e2a78` | Active | +| **Mainnet** | `0xb1d63873c3cc9f79` | Active | + +See [DeFi Contracts](../defi-contracts-mainnet.md) for complete contract addresses. + +## Next Steps + +- **Understand the basics**: Read [Architecture Overview](./architecture.md) +- **Learn strategies**: Explore [TracerStrategy](./strategies.md#tracerstrategy) +- **Create your first vault**: Follow [Vault Lifecycle](./vault-lifecycle.md) +- **Integrate with FCM**: See [FCM Integration](./fcm-integration.md) + +--- + +:::tip Key Takeaway +FYV combines automated leverage, yield farming, and liquidation protection into a single system. By integrating with ALP for borrowing and using AutoBalancers for continuous optimization, FYV enables hands-free yield generation while maintaining position safety. +::: diff --git a/docs/defi/flow-yield-vaults/leveraged-farming.md b/docs/defi/flow-yield-vaults/leveraged-farming.md new file mode 100644 index 0000000000..1b1b96f361 --- /dev/null +++ b/docs/defi/flow-yield-vaults/leveraged-farming.md @@ -0,0 +1,324 @@ +--- +title: Leveraged Farming +sidebar_position: 6 +--- + +# Leveraged Farming + +Leveraged farming amplifies your yield potential by using borrowed capital to increase your exposure to yield-generating assets. This document explains how FYV's TracerStrategy implements leveraged farming and the mechanics of leverage amplification. + +## What is Leveraged Farming? + +Leveraged farming combines collateralized borrowing with yield farming to achieve returns greater than your initial capital. By depositing collateral to borrow additional capital, converting borrowed capital to yield-bearing tokens, and earning yield on both your capital and borrowed funds, you amplify your total returns while maintaining automated risk management through health factor monitoring. + +**Simple example:** +``` +Without leverage: + - Deposit: $1,000 + - Yield: 10% APY + - Annual return: $100 (10% on $1,000) + +With 1.61x leverage: + - Deposit: $1,000 + - Borrowed: $615 + - Total farming: $1,615 + - Yield: 10% APY on $1,615 = $161.50 + - After repaying borrow cost (assume 3% APY): $161.50 - $18.45 = $143.05 + - Net return: $143.05 (14.3% on $1,000 initial capital) +``` + +## How TracerStrategy Achieves Leverage + +TracerStrategy implements leveraged farming through integration with ALP's lending platform: + +### Step-by-Step Leverage Mechanics + +**1. Collateral Deposit** +``` +User deposits: 1000 FLOW @ $1.00 = $1,000 +Collateral Factor: 0.8 (80%) +Effective Collateral (EC): $1,000 Γ— 0.8 = $800 +``` + +**2. Calculate Borrowing Capacity** +``` +Target Health Factor: 1.3 +Maximum Safe Borrow = EC / Target HF + = $800 / 1.3 + = $615.38 MOET +``` + +**3. Auto-Borrow** +``` +Position borrows: 615.38 MOET @ $1.00 = $615.38 +Debt created: $615.38 +Health Factor: $800 / $615.38 = 1.30 βœ“ +``` + +**4. Convert to Yield Tokens** +``` +Swap: 615.38 MOET β†’ ~610 YieldToken +Slippage: ~1% (typical) +Yield exposure: $610 +``` + +**5. Deposit to Yield Vault** +``` +AutoBalancer deposits: 610 YieldToken to ERC4626 +Total position value: $1,000 (collateral) + $610 (yield) = $1,610 +Effective leverage: $1,610 / $1,000 = 1.61x +``` + +## Leverage Ratio Calculation + +The leverage ratio indicates how much total exposure you have relative to your initial capital: + +``` +Leverage = Total Exposure / Initial Capital + = (Collateral + Borrowed Value) / Collateral + = (C + B) / C + = 1 + (B / C) +``` + +**For TracerStrategy with default settings:** +``` +Borrowed (B) = (C Γ— CF) / Target HF + = (C Γ— 0.8) / 1.3 + = 0.615 Γ— C + +Leverage = 1 + 0.615 = 1.615x +``` + +**Different collateral factors:** +``` +CF = 0.75, Target HF = 1.3: + Borrow = (C Γ— 0.75) / 1.3 = 0.577 Γ— C + Leverage = 1.577x + +CF = 0.85, Target HF = 1.3: + Borrow = (C Γ— 0.85) / 1.3 = 0.654 Γ— C + Leverage = 1.654x +``` + +## Risk-Adjusted Returns + +Leverage amplifies both gains and losses. Understanding the risk/reward tradeoff is critical: + +### Upside Scenario (Yield Positive) + +``` +Initial: 1000 FLOW, 1.61x leverage, 10% APY on yield tokens + +Without leverage (baseline): + - Capital: $1,000 + - Yield: 10% Γ— $1,000 = $100 + - Return: 10% + +With leverage (assuming 3% borrow cost): + - Collateral: $1,000 + - Borrowed: $615.38 + - Yield farming: $615.38 at 10% = $61.54 + - Borrow cost: $615.38 at 3% = $18.46 + - Net from leverage: $61.54 - $18.46 = $43.08 + - Total return: $43.08 (4.3% additional from leverage) + - Combined: 10% (baseline) + 4.3% (leverage) = 14.3% + - Amplification: 1.43x returns +``` + +### Downside Scenario (Yield Negative) + +``` +Initial: 1000 FLOW, 1.61x leverage, -5% yield (vault loss) + +Without leverage: + - Capital: $1,000 + - Loss: -5% Γ— $1,000 = -$50 + - Return: -5% + +With leverage (3% borrow cost still applies): + - Yield farming loss: $615.38 Γ— -5% = -$30.77 + - Borrow cost: $615.38 Γ— 3% = $18.46 + - Net from leverage: -$30.77 - $18.46 = -$49.23 + - Total return: -$49.23 (-4.9% additional loss from leverage) + - Combined: -5% (baseline) - 4.9% (leverage) = -9.9% + - Amplification: 1.98x losses +``` + +**Key insight:** Leverage amplifies returns but also amplifies losses. The amplification factor depends on the spread between yield and borrow cost. + +## Health Factor Dynamics + +The health factor is critical for managing liquidation risk in leveraged positions: + +### Health Factor Formula + +``` +HF = Effective Collateral / Effective Debt + = (Collateral Value Γ— CF) / Debt Value +``` + +### Price Impact on Health + +When collateral price changes, health factor changes proportionally: + +``` +Initial state: + - 1000 FLOW @ $1.00 + - EC: $800 (80% CF) + - Debt: $615.38 + - HF: 1.30 + +FLOW price drops to $0.90 (-10%): + - Collateral value: $900 + - EC: $900 Γ— 0.8 = $720 + - Debt: $615.38 (unchanged) + - HF: $720 / $615.38 = 1.17 + +FLOW price drops to $0.75 (-25%): + - Collateral value: $750 + - EC: $750 Γ— 0.8 = $600 + - Debt: $615.38 + - HF: $600 / $615.38 = 0.975 ⚠️ LIQUIDATABLE! +``` + +### Safe Price Drop Calculation + +How much can price drop before liquidation? + +``` +Liquidation occurs when HF < 1.0: + (C_new Γ— Price_new Γ— CF) / Debt = 1.0 + +Solving for Price_new: + Price_new = Debt / (C Γ— CF) + = $615.38 / (1000 Γ— 0.8) + = $0.769 + +Safe price drop from $1.00: + Drop = ($1.00 - $0.769) / $1.00 = 23.1% +``` + +**With target HF = 1.3, you have a 23.1% price drop buffer before liquidation.** + +## Rebalancing Impact on Leverage + +AutoBalancer's rebalancing affects your effective leverage over time: + +### Excess Profits Rebalancing + +When yield accrues and AutoBalancer withdraws excess: + +``` +Before rebalancing: + - Collateral: 1000 FLOW + - Debt: $615.38 + - Yield value: $671 (excess over historical $610) + - Leverage: ($1,000 + $671) / $1,000 = 1.671x + +After rebalancing (withdraw $61 excess): + - Swap $61 yield β†’ ~60 FLOW + - Deposit 60 FLOW to position + - Collateral: 1060 FLOW + - Debt: $615.38 (unchanged) + - Yield value: $610 (back to baseline) + - Leverage: ($1,060 + $610) / $1,060 = 1.575x + - New HF: (1060 Γ— 0.8) / 615.38 = 1.38 (improved!) +``` + +**Effect:** Leverage decreases slightly, safety buffer increases, profits locked in as collateral. + +### Deficit Recovery Rebalancing + +When vault loses value and AutoBalancer requests recovery: + +``` +Before rebalancing: + - Collateral: 1000 FLOW + - Debt: $615.38 + - Yield value: $580 (deficit below historical $610) + - Leverage: ($1,000 + $580) / $1,000 = 1.58x + +After rebalancing (borrow $30 more to cover deficit): + - Borrow additional $30 MOET + - Swap $30 MOET β†’ ~29.7 YieldToken + - Deposit to vault + - Collateral: 1000 FLOW (unchanged) + - Debt: $615.38 + $30 = $645.38 + - Yield value: $609.70 (recovered) + - Leverage: ($1,000 + $609.70) / $1,000 = 1.6097x + - New HF: (1000 Γ— 0.8) / 645.38 = 1.24 (lower but still safe) +``` + +**Effect:** Leverage stays similar, safety buffer decreases, deficit recovered. + +## Optimizing Leverage + +You can adjust leverage by changing configuration parameters: + +### Target Health Factor Adjustment + +``` +Higher Target HF (more conservative): + - Target HF = 1.5 + - Borrow = (C Γ— CF) / 1.5 = (C Γ— 0.8) / 1.5 = 0.533 Γ— C + - Leverage = 1.533x + - Larger safety buffer (50% above liquidation) + - Lower yield amplification + +Lower Target HF (more aggressive): + - Target HF = 1.1 + - Borrow = (C Γ— CF) / 1.1 = (C Γ— 0.8) / 1.1 = 0.727 Γ— C + - Leverage = 1.727x + - Smaller safety buffer (10% above liquidation) + - Higher yield amplification but higher risk +``` + +### Multi-Vault Strategy + +Advanced users can create multiple vaults with different leverage levels: + +``` +Conservative vault: + - 50% of capital + - Target HF = 1.5 + - Leverage: 1.53x + - Low risk + +Aggressive vault: + - 50% of capital + - Target HF = 1.2 + - Leverage: 1.67x + - Higher risk + +Combined effective leverage: (1.53 + 1.67) / 2 = 1.60x +Risk diversification: Two independent positions +``` + +## Best Practices + +**Understand Your Risk**: Higher leverage = higher returns potential but also higher liquidation risk. Know your risk tolerance. + +**Monitor Health Factor**: Check regularly, especially during volatile markets. Set alerts if possible for HF < 1.2. + +**Conservative Targeting**: Start with higher target HF (1.4-1.5) until you understand the system, then optimize based on experience. + +**Diversify Collateral**: If using multiple vaults, diversify across different collateral types to reduce price correlation risk. + +**Account for Costs**: Factor in swap slippage, gas costs, and borrow costs when calculating expected returns. + +**Emergency Plan**: Keep liquid funds available to add collateral if prices move against you. + +## Summary + +Leveraged farming in FYV achieves 1.6x+ exposure through ALP integration, borrowing at target health factor (typically 1.3), converting borrowed capital to yield tokens, and maintaining automated health management. The system amplifies returns when yields exceed borrow costs, increases liquidation risk through reduced price buffers, and continuously optimizes through AutoBalancer rebalancing. + +**Risk/Reward tradeoff:** +- **Higher leverage** β†’ Greater amplification but higher liquidation risk +- **Lower leverage** β†’ Lower amplification but greater safety buffer +- **Optimal leverage** β†’ Balanced based on your risk tolerance and market outlook + +--- + +:::tip Key Takeaway +Leveraged farming amplifies both gains and losses. With FYV's default 1.61x leverage and 23% price drop buffer, you get meaningful yield amplification while maintaining reasonable safety. Always monitor your health factor and understand the liquidation risks. +::: diff --git a/docs/defi/flow-yield-vaults/scheduling.md b/docs/defi/flow-yield-vaults/scheduling.md new file mode 100644 index 0000000000..a7f9807d7c --- /dev/null +++ b/docs/defi/flow-yield-vaults/scheduling.md @@ -0,0 +1,410 @@ +--- +title: Scheduling System +sidebar_position: 7 +--- + +# Scheduling System + +FYV implements a sophisticated self-scheduling mechanism that enables perpetual automated rebalancing without relying on external bots or keepers. This document explains how the scheduling system works and ensures continuous vault optimization. + +## Overview + +The scheduling system consists of three main components: + +1. **FlowTransactionScheduler** - Flow's native transaction scheduling infrastructure +2. **SchedulerRegistry** - Tracks all vaults and their scheduling state +3. **Supervisor** - Recovery mechanism for stuck vaults + +Together, these components create a self-sustaining automation system where vaults schedule their own rebalancing indefinitely. + +## Self-Scheduling Mechanism + +### How It Works + +Each AutoBalancer implements a self-perpetuating scheduling loop: + +**Initial Schedule** (vault creation): +```cadence +// During vault creation +autoBalancer.scheduleFirstRebalance() + ↓ +FlowTransactionScheduler.schedule( + functionCall: "rebalance()", + executeAt: currentTime + 60 seconds +) +``` + +**Execution** (scheduled time arrives): +```cadence +// Scheduler calls +autoBalancer.rebalance() + ↓ +// Perform rebalancing logic +checkRatio() +executeIfNeeded() + ↓ +// Reschedule next execution +scheduleNextRebalance() + ↓ +FlowTransactionScheduler.schedule( + functionCall: "rebalance()", + executeAt: currentTime + 60 seconds +) +``` + +**Perpetual Loop**: +``` +Execute β†’ Rebalance β†’ Schedule Next β†’ Wait 60s β†’ Execute β†’ ... +``` + +This creates an infinite loop where each rebalance execution schedules the next one, requiring no external coordination. + +### Atomic Registration + +Vault creation and scheduling registration happen atomically to prevent orphaned vaults: + +```cadence +transaction createVault() { + prepare(signer: AuthAccount) { + // Create all components + let vault <- createYieldVault(...) + let autoBalancer <- createAutoBalancer(...) + let position <- createPosition(...) + + // Register (all steps must succeed) + registerInRegistry(autoBalancer) // Step 1 + scheduleFirstRebalance(autoBalancer) // Step 2 + linkComponents(...) // Step 3 + + // If ANY step fails β†’ entire transaction reverts + // No partial vaults created + } +} +``` + +**Atomicity guarantee**: Either vault is fully created with working schedule, OR transaction fails and nothing is created. + +## SchedulerRegistry + +The SchedulerRegistry maintains a global record of all active vaults and their scheduling state. + +### Registry Structure + +```cadence +pub contract FlowYieldVaultsSchedulerRegistry { + // Maps vault ID β†’ scheduling info + access(contract) var registry: {UInt64: ScheduleInfo} + + pub struct ScheduleInfo { + pub let vaultID: UInt64 + pub let autoBalancerCap: Capability<&AutoBalancer> + pub let nextScheduledTime: UFix64 + pub let status: ScheduleStatus // Active, Pending, Stuck + } + + pub enum ScheduleStatus: UInt8 { + pub case Active // Scheduling working normally + pub case Pending // Awaiting schedule + pub case Stuck // Failed to reschedule + } +} +``` + +### Registration Lifecycle + +**On vault creation:** +```cadence +registry.register( + vaultID: 42, + autoBalancerCap: capability, + status: ScheduleStatus.Pending +) +``` + +**After first successful schedule:** +```cadence +registry.updateStatus( + vaultID: 42, + status: ScheduleStatus.Active, + nextScheduledTime: currentTime + 60 +) +``` + +**If schedule fails:** +```cadence +registry.updateStatus( + vaultID: 42, + status: ScheduleStatus.Stuck +) +// Supervisor will attempt recovery +``` + +**On vault liquidation:** +```cadence +registry.unregister(vaultID: 42) +// Vault removed from tracking +``` + +## Supervisor Recovery System + +The Supervisor handles vaults that become stuck or fail to self-schedule. + +### What Can Go Wrong? + +Despite atomicity guarantees, vaults can become stuck for several reasons: + +1. **Transaction failure** during reschedule due to gas issues or network congestion +2. **Capability revocation** if user accidentally breaks autoBalancer capability +3. **Scheduler overload** if too many transactions scheduled simultaneously +4. **Network issues** during schedule transaction propagation + +### Supervisor Implementation + +```cadence +pub resource Supervisor { + // Scan registry and recover stuck vaults + pub fun recover() { + let pending = registry.getPendingVaults(limit: 50) + + for vaultID in pending { + let scheduleInfo = registry.getScheduleInfo(vaultID) + + // Attempt to reschedule + if let autoBalancer = scheduleInfo.autoBalancerCap.borrow() { + autoBalancer.scheduleNextRebalance() + + registry.updateStatus( + vaultID: vaultID, + status: ScheduleStatus.Active + ) + } + } + + // If more work remains, schedule next supervisor run + if registry.hasPendingVaults() { + self.scheduleSelf() + } + } + + access(self) fun scheduleSelf() { + FlowTransactionScheduler.schedule( + functionCall: "recover()", + executeAt: currentTime + 120 seconds + ) + } +} +``` + +### Bounded Processing + +The Supervisor processes a maximum of 50 vaults per execution to prevent timeout: + +``` +Iteration 1: Process vaults 1-50 β†’ Reschedule supervisor +Iteration 2: Process vaults 51-100 β†’ Reschedule supervisor +Iteration 3: Process vaults 101-120 β†’ No more pending, stop +``` + +This ensures the recovery process can handle any number of stuck vaults without failing due to gas limits. + +### Recovery Triggers + +The Supervisor runs in two scenarios: + +**1. Scheduled Recovery** (proactive): +``` +Every 10 minutes: + β†’ Check for pending vaults + β†’ Attempt recovery + β†’ Reschedule if more work exists +``` + +**2. Manual Recovery** (reactive): +```cadence +transaction triggerSupervisor() { + prepare(admin: AuthAccount) { + let supervisor = admin.borrow<&Supervisor>(...) + supervisor.recover() + } +} +``` + +## Scheduling Parameters + +Key configuration parameters control scheduling behavior: + +```cadence +pub struct SchedulingConfig { + // Rebalancing frequency + pub let rebalanceIntervalSeconds: UInt64 // Default: 60 + + // Supervisor recovery frequency + pub let supervisorIntervalSeconds: UInt64 // Default: 600 (10 min) + + // Max vaults per supervisor run + pub let maxSupervisorBatchSize: UInt64 // Default: 50 + + // Stale threshold (mark as stuck) + pub let staleThresholdSeconds: UInt64 // Default: 300 (5 min) +} +``` + +### Tuning Considerations + +**Rebalance Interval:** +- **Shorter** (30s): More responsive, higher gas costs, better optimization +- **Longer** (120s): Less responsive, lower gas costs, acceptable for stable vaults + +**Supervisor Interval:** +- **Shorter** (300s): Faster recovery, more frequent checks, higher overhead +- **Longer** (1200s): Slower recovery, less overhead, acceptable for stable network + +**Batch Size:** +- **Smaller** (25): Lower gas per execution, more supervisor runs needed +- **Larger** (100): Higher gas per execution, fewer runs needed, risk of timeout + +## Monitoring Scheduling Health + +Users and administrators can monitor the scheduling system's health: + +### Check Vault Schedule Status + +```cadence +import FlowYieldVaultsSchedulerRegistry from 0xFYV + +pub fun main(vaultID: UInt64): ScheduleStatus { + let registry = FlowYieldVaultsSchedulerRegistry.getRegistry() + let info = registry.getScheduleInfo(vaultID) + + return info.status +} +// Returns: Active, Pending, or Stuck +``` + +### Get Next Scheduled Time + +```cadence +pub fun main(vaultID: UInt64): UFix64 { + let registry = FlowYieldVaultsSchedulerRegistry.getRegistry() + let info = registry.getScheduleInfo(vaultID) + + return info.nextScheduledTime +} +// Returns: Unix timestamp of next rebalance +``` + +### Count Pending Vaults + +```cadence +pub fun main(): UInt64 { + let registry = FlowYieldVaultsSchedulerRegistry.getRegistry() + return registry.countPendingVaults() +} +// Returns: Number of vaults awaiting schedule +``` + +## Failure Modes and Recovery + +### Scenario 1: Single Vault Fails to Reschedule + +**What happens:** +1. Vault executes rebalance successfully +2. Reschedule transaction fails (network issue) +3. Vault marked as "Stuck" in registry +4. Supervisor detects stuck vault on next run +5. Supervisor reschedules the vault +6. Vault returns to "Active" status + +**User impact:** Minor delay (up to 10 minutes) before next rebalance + +### Scenario 2: Scheduler Overload + +**What happens:** +1. Many vaults scheduled at same time +2. Scheduler queue fills up +3. Some reschedule transactions timeout +4. Multiple vaults marked "Stuck" +5. Supervisor processes in batches of 50 +6. All vaults eventually recovered + +**User impact:** Temporary scheduling delays, no loss of funds + +### Scenario 3: Capability Revocation + +**What happens:** +1. User accidentally unlinks AutoBalancer capability +2. Vault can no longer be scheduled +3. Vault marked "Stuck" permanently +4. User must manually fix capability +5. Call forceRebalance() to restart scheduling + +**User impact:** Vault stops rebalancing until fixed + +### Scenario 4: Supervisor Failure + +**What happens:** +1. Supervisor itself fails to reschedule +2. Stuck vaults accumulate +3. Admin manually triggers supervisor +4. Supervisor recovers all pending vaults +5. Supervisor returns to normal operation + +**User impact:** Longer delays (requires admin intervention) + +## Best Practices + +**Monitor Your Vault**: Check scheduling status periodically to ensure "Active" state. + +**Don't Revoke Capabilities**: Avoid unlinking or destroying AutoBalancer capabilities as this breaks scheduling. + +**Use forceRebalance() Sparingly**: Manual rebalancing bypasses scheduling logic; only use if truly stuck. + +**Track Rebalance History**: Monitor rebalance frequency to detect scheduling issues early. + +**Report Stuck Vaults**: If your vault becomes stuck, report it so admins can investigate root cause. + +## Advanced: Custom Scheduling + +Developers can implement custom scheduling logic for specialized use cases: + +```cadence +pub resource CustomAutoBalancer: AutoBalancerInterface { + // Custom interval based on conditions + pub fun getNextInterval(): UInt64 { + let ratio = self.getCurrentRatio() + + if ratio > 1.10 || ratio < 0.90 { + return 30 // More frequent when far from target + } else { + return 120 // Less frequent when stable + } + } + + pub fun scheduleNextRebalance() { + let interval = self.getNextInterval() + + FlowTransactionScheduler.schedule( + functionCall: "rebalance()", + executeAt: currentTime + interval + ) + } +} +``` + +This enables dynamic scheduling based on vault state, optimizing gas costs vs. responsiveness. + +## Summary + +FYV's scheduling system achieves truly automated yield farming through self-scheduling where vaults schedule their own rebalancing, atomic registration preventing orphaned vaults, Supervisor recovery for stuck vaults, and bounded processing handling any scale. + +**Key guarantees:** +- Every vault has either working schedule OR doesn't exist (atomicity) +- Stuck vaults automatically recovered (within 10 minutes) +- No external dependencies (no bot infrastructure needed) +- Scales to thousands of vaults (batched processing) + +--- + +:::tip Key Takeaway +The self-scheduling mechanism is what makes FYV truly "set and forget." Vaults perpetually schedule themselves, the Supervisor recovers failures, and users never need to manually trigger rebalancing. It's automation all the way down. +::: diff --git a/docs/defi/flow-yield-vaults/strategies.md b/docs/defi/flow-yield-vaults/strategies.md new file mode 100644 index 0000000000..9dea02c676 --- /dev/null +++ b/docs/defi/flow-yield-vaults/strategies.md @@ -0,0 +1,369 @@ +--- +title: Yield Strategies +sidebar_position: 3 +--- + +# Yield Strategies + +Strategies in FYV define how yield is generated from deposited collateral. Each strategy implements a specific approach to converting collateral into yield-bearing positions, managing those positions, and handling withdrawals. This document explains the available strategies and how they work. + +## Strategy Interface + +All strategies implement the `Strategy` interface, which provides a consistent API regardless of the underlying yield mechanism. + +```cadence +pub resource interface Strategy { + // Initialize position with collateral deposit + pub fun deposit(collateralVault: @FungibleToken.Vault) + + // Withdraw specified amount of value + pub fun withdraw(amount: UFix64): @FungibleToken.Vault + + // Close position and return all accumulated value + pub fun liquidate(): @FungibleToken.Vault + + // Get current position value + pub fun getBalance(): UFix64 +} +``` + +This interface enables YieldVaults to remain strategy-agnostic, allowing users to switch strategies or compose multiple strategies without changing vault logic. + +## TracerStrategy + +TracerStrategy is the flagship strategy that implements automated leveraged yield farming by bridging ALP lending positions with external DeFi yield opportunities. + +### How It Works + +TracerStrategy combines three components to create leveraged yield: + +**ALP Position** (Collateral & Borrowing): Deposits collateral (FLOW, stFLOW, etc.) to ALP, borrows MOET against collateral up to 80% of value, and maintains health factor at target of 1.3. + +**Swap Connectors** (Token Conversion): Converts MOET to yield-bearing tokens (LP tokens, farm tokens), converts yield tokens back to FLOW for rebalancing, and provides slippage protection on all swaps. + +**AutoBalancer** (Yield Management): Deposits yield tokens to ERC4626 vaults, monitors value and triggers rebalancing at 95%-105% thresholds, and automatically manages position health. + +### Capital Flow Diagram + +```mermaid +sequenceDiagram + participant User + participant Strategy as TracerStrategy + participant Position as ALP Position + participant Swap as SwapConnectors + participant AB as AutoBalancer + participant Vault as ERC4626 Vault + + User->>Strategy: deposit(1000 FLOW) + Strategy->>Position: deposit(1000 FLOW) + Position->>Position: Calculate borrowing capacity + Note over Position: EC = 1000 Γ— $1 Γ— 0.8 = $800
Max borrow = 800 / 1.3 = $615.38 + Position->>Position: borrow(615.38 MOET) + Position-->>Strategy: 615.38 MOET + + Strategy->>Swap: swap(615.38 MOET β†’ YieldToken) + Swap-->>Strategy: ~610 YieldToken (slippage) + + Strategy->>AB: deposit(610 YieldToken) + AB->>Vault: deposit(610 YieldToken) + Vault-->>AB: 610 shares + + Note over AB,Vault: Yield accrues over time + + AB->>AB: Monitor ratio
(Current / Historical) + + alt Ratio > 105% + AB->>Vault: withdraw(excess) + Vault-->>AB: YieldToken + AB->>Swap: swap(YieldToken β†’ FLOW) + Swap-->>AB: FLOW + AB->>Position: deposit(FLOW) + end +``` + +### Example: Leveraged Farming with 1000 FLOW + +Let's walk through a complete TracerStrategy lifecycle: + +**Initial Deposit:** +``` +User deposits: 1000 FLOW @ $1.00 = $1,000 + +Step 1: Deposit to ALP Position + - Collateral: 1000 FLOW + - Collateral Factor: 0.8 (80%) + - Effective Collateral: $1,000 Γ— 0.8 = $800 + +Step 2: Calculate borrowing at target HF = 1.3 + - Target Debt = EC / Target HF = $800 / 1.3 = $615.38 + - Position borrows: 615.38 MOET + +Step 3: Swap MOET β†’ YieldToken + - Swap 615.38 MOET via Uniswap V3 + - Receive ~610 YieldToken (assuming 1% slippage) + - Slippage protection: min 608.92 YieldToken (1% tolerance) + +Step 4: Deposit to ERC4626 Vault + - AutoBalancer deposits 610 YieldToken + - Receives 610 vault shares + - Historical deposit value: $610 (tracked for rebalancing) + +Position Summary: + - Collateral: 1000 FLOW ($1,000) + - Debt: 615.38 MOET ($615.38) + - Yield Tokens: 610 ($610 equivalent) + - Health Factor: 800 / 615.38 = 1.30 βœ“ + - Effective Exposure: $1,000 collateral + $610 yield = $1,610 + - Leverage: 1.61x +``` + +**After Yield Accrues (10% APY over time):** +``` +ERC4626 vault generates yield: + - Initial: 610 YieldToken + - After yield: 671 YieldToken (+10%) + - Current value: $671 + +Rebalancing check: + - Current: $671 + - Historical: $610 + - Ratio: 671 / 610 = 1.10 = 110% + - Threshold exceeded! (> 105%) + +Rebalancing action: + - Excess: $671 - $610 = $61 + - Withdraw 61 YieldToken from vault + - Swap 61 YieldToken β†’ ~60.4 FLOW + - Deposit 60.4 FLOW to position as additional collateral + +After rebalancing: + - Collateral: 1060.4 FLOW ($1,060.40) + - Debt: 615.38 MOET (unchanged) + - Yield Tokens: 610 (back to historical baseline) + - Health Factor: (1060.4 Γ— 0.8) / 615.38 = 1.38 + - Result: Profits locked in as additional collateral +``` + +### Configuration Parameters + +TracerStrategy accepts the following configuration: + +```cadence +pub struct TracerStrategyConfig { + // ALP position parameters + pub let targetHealthFactor: UFix64 // Default: 1.3 + pub let collateralFactor: UFix64 // Token-specific (0.8 for FLOW) + + // AutoBalancer thresholds + pub let upperRebalanceThreshold: UFix64 // Default: 1.05 (105%) + pub let lowerRebalanceThreshold: UFix64 // Default: 0.95 (95%) + + // Swap connector configuration + pub let swapSlippageTolerance: UFix64 // Default: 0.01 (1%) + + // ERC4626 vault address + pub let vaultAddress: Address // Target yield vault + + // Rebalancing frequency + pub let rebalanceIntervalSeconds: UInt64 // Default: 60 +} +``` + +### Risk Considerations + +**Liquidation Risk**: If FLOW price drops significantly, health factor could fall below 1.0, triggering liquidation. The target HF of 1.3 provides a 30% buffer. + +**Smart Contract Risk**: Relies on ERC4626 vault security and ALP lending pool security. + +**Slippage Risk**: Large swaps may experience higher slippage than configured tolerance, causing transaction revert. + +**Yield Volatility**: ERC4626 vault yields fluctuate based on market conditions. Negative yield would trigger deficit rebalancing. + +**Impermanent Loss** (if using LP tokens): LP token strategies may experience impermanent loss relative to holding underlying assets. + +## mUSDCStrategy + +mUSDCStrategy enables cross-chain yield farming by bridging USDC from Flow to EVM-compatible chains and depositing into ERC4626 vaults. + +### How It Works + +mUSDCStrategy uses Flow's EVM bridge to access Ethereum-based yield opportunities: + +**Bridge Locking**: Locks USDC in Flow bridge escrow, mints bridged USDC on EVM side, and maintains 1:1 backing. + +**EVM Deployment**: CadenceOwnedAccount controls EVM address, deposits bridged USDC to ERC4626 vault, and accrues yield in EVM vault. + +**Yield Management**: AutoBalancer monitors EVM vault balance, triggers rebalancing at thresholds, and bridges tokens back to Flow when needed. + +### Capital Flow + +```mermaid +sequenceDiagram + participant User + participant Strategy as mUSDCStrategy + participant Bridge as FlowEVMBridge + participant EVM as EVM Side + participant Vault as ERC4626 (EVM) + + User->>Strategy: deposit(1000 USDC) + Strategy->>Bridge: bridge(1000 USDC) + Bridge->>Bridge: Lock USDC in escrow + Bridge->>EVM: Mint 1000 bridged USDC + + Strategy->>EVM: deposit(1000 USDC) + EVM->>Vault: deposit(1000 USDC) + Vault-->>EVM: 1000 shares + + Note over Vault: Yield accrues + + alt Rebalancing needed + Strategy->>Vault: withdraw(amount) + Vault-->>EVM: USDC + EVM->>Bridge: Burn bridged USDC + Bridge->>Bridge: Unlock USDC + Bridge-->>Strategy: USDC on Flow + end +``` + +### Example: Cross-Chain Yield + +``` +User deposits: 1000 USDC (Flow native) + +Step 1: Bridge to EVM + - Lock 1000 USDC in Flow bridge contract + - Mint 1000 bridged USDC on EVM side + - Transaction hash: 0x123... (tracked for verification) + +Step 2: Deposit to EVM Vault + - CadenceOwnedAccount deposits to ERC4626 vault + - Vault address: 0x789... (configured) + - Receive 1000 vault shares + +Step 3: Yield Accrual (8% APY on EVM side) + - After time: 1080 shares value + - Ratio: 1080 / 1000 = 1.08 = 108% + - Exceeds 105% threshold + +Step 4: Rebalancing + - Withdraw 80 USDC from EVM vault + - Burn 80 bridged USDC on EVM + - Unlock 80 USDC on Flow + - User can claim or compound +``` + +### Cross-Chain Considerations + +**Bridge Security**: Relies on Flow-EVM bridge security and escrow mechanisms. + +**Gas Costs**: EVM transactions require gas fees paid in bridged FLOW. + +**Bridge Latency**: Cross-chain operations take longer than native Flow transactions (typically 1-2 minutes). + +**EVM Vault Risk**: Subject to risks of the specific EVM vault implementation. + +**Exchange Rate Peg**: Bridged USDC maintains 1:1 peg with Flow USDC through bridge mechanics. + +## Strategy Comparison + +| Feature | TracerStrategy | mUSDCStrategy | +|---------|----------------|---------------| +| **Leverage** | Yes (via ALP borrowing) | No (direct deposit) | +| **Chain** | Flow native | Flow β†’ EVM bridge | +| **Complexity** | High (multi-step) | Medium (bridge + deposit) | +| **Gas Costs** | Low (Flow only) | Higher (Flow + EVM) | +| **Yield Source** | ERC4626 on Flow EVM | ERC4626 on external EVM | +| **Collateral** | FLOW, stFLOW, etc. | USDC | +| **Liquidation Risk** | Yes (borrowed position) | No (no borrowing) | +| **Target Users** | Higher risk/reward | Conservative yield farmers | + +## Creating a Strategy Instance + +To use a strategy, create it via the StrategyFactory: + +```cadence +import FlowYieldVaults from 0xFlowYieldVaults +import FungibleToken from 0xFungibleToken + +transaction { + prepare(signer: AuthAccount) { + // Get strategy factory + let factory = FlowYieldVaults.getStrategyFactory() + + // Check available strategies + let strategies = factory.getStrategyNames() + // Returns: ["TracerStrategy", "mUSDCStrategy"] + + // Create TracerStrategy instance + let strategy <- factory.createStrategy( + strategyName: "TracerStrategy", + collateralType: Type<@FlowToken.Vault>() + ) + + // Create vault with strategy + let manager = signer.borrow<&FlowYieldVaults.YieldVaultManager>( + from: FlowYieldVaults.YieldVaultManagerStoragePath + ) ?? panic("Manager not found") + + manager.createVault(strategy: <-strategy) + } +} +``` + +## Strategy Lifecycle + +All strategies follow a consistent lifecycle: + +**1. Initialization**: Strategy created via StrategyFactory with configured connectors, AutoBalancer created and linked, ALP Position created (for leveraged strategies), and strategy registered in SchedulerRegistry. + +**2. Deposit Phase**: User deposits collateral, strategy converts to yield-bearing position, AutoBalancer tracks initial value, and first rebalance scheduled. + +**3. Active Phase**: Yield accrues in target vaults, AutoBalancer monitors continuously (every 60 seconds), rebalancing triggers at thresholds, and profits are locked or deficits recovered. + +**4. Withdrawal**: User requests withdrawal, strategy converts yield tokens back to collateral (via swaps), AutoBalancer withdraws from vaults as needed, and user receives collateral tokens. + +**5. Liquidation**: User closes vault, strategy liquidates all positions (closes ALP position for leveraged strategies), converts all value to collateral, and returns final value to user. + +## Best Practices + +**Start Conservative**: Begin with smaller amounts to understand strategy behavior before committing large capital. + +**Monitor Health Factor** (TracerStrategy): Keep health factor well above 1.1 to avoid liquidation risk. The default 1.3 target provides good buffer. + +**Understand Rebalancing**: Rebalancing frequency and thresholds impact gas costs vs. optimization. Default 60-second interval with 95%-105% thresholds balance efficiency. + +**Consider Gas Costs** (mUSDCStrategy): EVM transactions cost more than Flow native operations. Factor gas into yield calculations. + +**Diversify Strategies**: Use multiple vaults with different strategies to spread risk across yield sources. + +**Track Performance**: Monitor actual yields vs. expectations. ERC4626 vault yields vary with market conditions. + +## Advanced: Custom Strategies + +Developers can create custom strategies by implementing the Strategy interface and registering a StrategyComposer with the factory. Custom strategies can leverage unique yield sources, implement different risk profiles, use alternative rebalancing logic, or combine multiple yield mechanisms. + +See [DeFi Actions](./defi-actions.md) for details on composing custom strategies. + +## Summary + +FYV strategies transform collateral into yield through different approaches: **TracerStrategy** uses leveraged borrowing and yield farming for amplified returns, while **mUSDCStrategy** provides cross-chain access to EVM yield opportunities. Both strategies leverage AutoBalancer for continuous optimization and maintain consistent interfaces through the Strategy pattern. + +**Key concepts:** +- All strategies implement the same interface for consistency +- TracerStrategy achieves 1.6x+ leverage through ALP integration +- mUSDCStrategy bridges to EVM for broader yield access +- AutoBalancer handles continuous optimization for all strategies +- Configuration parameters control risk/reward tradeoffs + +## Next Steps + +- **Understand rebalancing**: Read [AutoBalancer](./autobalancer.md) +- **Learn leverage mechanics**: Explore [Leveraged Farming](./leveraged-farming.md) +- **Create your first vault**: Follow [Vault Lifecycle](./vault-lifecycle.md) +- **Cross-chain details**: See [Cross-Chain Integration](./cross-chain.md) + +--- + +:::tip Key Takeaway +TracerStrategy amplifies returns through leverage (1.6x+ exposure) but carries liquidation risk. mUSDCStrategy provides conservative cross-chain yield without leverage. Choose based on your risk tolerance and yield goals. +::: diff --git a/docs/defi/flow-yield-vaults/vault-lifecycle.md b/docs/defi/flow-yield-vaults/vault-lifecycle.md new file mode 100644 index 0000000000..61d5b45f4d --- /dev/null +++ b/docs/defi/flow-yield-vaults/vault-lifecycle.md @@ -0,0 +1,437 @@ +--- +title: Vault Lifecycle +sidebar_position: 5 +--- + +# Vault Lifecycle + +This guide walks you through the complete lifecycle of a Flow Yield Vault, from initial setup to closing your position and claiming your accumulated value. + +## Overview + +A YieldVault goes through five main phases: + +1. **Setup** - Configure your account for FYV +2. **Creation** - Create a vault with chosen strategy +3. **Deposit** - Add collateral to start yield farming +4. **Management** - Monitor and manage your position +5. **Closure** - Withdraw or liquidate your vault + +## Phase 1: Account Setup + +Before creating your first vault, you need to set up your account with the required resources. + +### Setup Transaction + +```cadence +import FlowYieldVaults from 0xFlowYieldVaults +import FungibleToken from 0xFungibleToken + +transaction { + prepare(signer: AuthAccount) { + // Check if already set up + if signer.borrow<&FlowYieldVaults.YieldVaultManager>( + from: FlowYieldVaults.YieldVaultManagerStoragePath + ) != nil { + return // Already set up + } + + // Create YieldVaultManager + let manager <- FlowYieldVaults.createYieldVaultManager() + + // Store in account + signer.save(<-manager, to: FlowYieldVaults.YieldVaultManagerStoragePath) + + // Create public capability + signer.link<&FlowYieldVaults.YieldVaultManager{FlowYieldVaults.YieldVaultManagerPublic}>( + FlowYieldVaults.YieldVaultManagerPublicPath, + target: FlowYieldVaults.YieldVaultManagerStoragePath + ) + } +} +``` + +**What this does**: Creates a YieldVaultManager resource in your account, stores it at the designated storage path, and creates a public capability for querying your vaults. + +**You only need to do this once** - the manager persists in your account and can hold multiple vaults. + +## Phase 2: Vault Creation + +Create a new vault with your chosen strategy (TracerStrategy or mUSDCStrategy). + +### Create Vault Transaction + +```cadence +import FlowYieldVaults from 0xFlowYieldVaults +import FlowToken from 0xFlowToken + +transaction(strategyName: String) { + prepare(signer: AuthAccount) { + // Get your vault manager + let manager = signer.borrow<&FlowYieldVaults.YieldVaultManager>( + from: FlowYieldVaults.YieldVaultManagerStoragePath + ) ?? panic("YieldVaultManager not found") + + // Get strategy factory + let factory = FlowYieldVaults.getStrategyFactory() + + // Create strategy instance + let strategy <- factory.createStrategy( + strategyName: strategyName, + collateralType: Type<@FlowToken.Vault>() + ) + + // Create vault with strategy + let vaultID = manager.createVault(strategy: <-strategy) + + log("Created vault #".concat(vaultID.toString())) + } +} +``` + +**Parameters:** +- `strategyName`: "TracerStrategy" or "mUSDCStrategy" + +**What happens:** +1. Strategy instance created with configured connectors +2. AutoBalancer created and linked to strategy +3. ALP Position created (for leveraged strategies) +4. Vault registered in SchedulerRegistry +5. First rebalance scheduled for T+60 seconds +6. Vault ID returned (use this to interact with vault later) + +**Example:** +```bash +flow transactions send create-vault.cdc "TracerStrategy" +# Output: Created vault #42 +``` + +## Phase 3: Initial Deposit + +Deposit collateral to activate your vault and start yield farming. + +### Deposit Transaction + +```cadence +import FlowYieldVaults from 0xFlowYieldVaults +import FlowToken from 0xFlowToken +import FungibleToken from 0xFungibleToken + +transaction(vaultID: UInt64, amount: UFix64) { + prepare(signer: AuthAccount) { + // Get vault manager + let manager = signer.borrow<&FlowYieldVaults.YieldVaultManager>( + from: FlowYieldVaults.YieldVaultManagerStoragePath + ) ?? panic("Manager not found") + + // Get vault + let vault = manager.borrowVault(id: vaultID) + ?? panic("Vault not found") + + // Withdraw FLOW from account + let flowVault = signer.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) + ?? panic("Could not borrow FlowToken.Vault") + + let depositVault <- flowVault.withdraw(amount: amount) + + // Deposit to vault + vault.deposit(collateralVault: <-depositVault) + + log("Deposited ".concat(amount.toString()).concat(" FLOW to vault #").concat(vaultID.toString())) + } +} +``` + +**What happens (TracerStrategy example):** +``` +Your deposit: 1000 FLOW @ $1.00 + +Step 1: Collateral deposit + - Strategy deposits 1000 FLOW to ALP Position + - Position calculates: EC = 1000 Γ— $1 Γ— 0.8 = $800 + +Step 2: Auto-borrowing + - Target HF = 1.3 + - Max borrow = EC / Target HF = 800 / 1.3 = 615.38 MOET + - Position borrows 615.38 MOET + +Step 3: Swap to yield tokens + - SwapConnector converts 615.38 MOET β†’ ~610 YieldToken + - Slippage protection ensures minimum output + +Step 4: Deposit to yield vault + - AutoBalancer deposits 610 YieldToken to ERC4626 + - Historical value tracked: $610 + - First rebalance scheduled + +Result: + - You have leveraged position: $1,000 collateral + $610 yield exposure + - Effective leverage: 1.61x + - Health factor: 1.30 (safe) + - Yield farming begins automatically +``` + +## Phase 4: Position Management + +Once your vault is active, you can monitor its performance and make adjustments. + +### Monitoring Your Vault + +**Check vault balance:** +```cadence +import FlowYieldVaults from 0xFlowYieldVaults + +pub fun main(address: Address, vaultID: UInt64): UFix64 { + let managerRef = getAccount(address) + .getCapability<&FlowYieldVaults.YieldVaultManager{FlowYieldVaults.YieldVaultManagerPublic}>( + FlowYieldVaults.YieldVaultManagerPublicPath + ) + .borrow() ?? panic("Manager not found") + + return managerRef.getVaultBalance(id: vaultID) +} +``` + +**Check AutoBalancer ratio:** +```cadence +pub fun main(address: Address, vaultID: UInt64): UFix64 { + let managerRef = getAccount(address) + .getCapability<&FlowYieldVaults.YieldVaultManager{FlowYieldVaults.YieldVaultManagerPublic}>( + FlowYieldVaults.YieldVaultManagerPublicPath + ) + .borrow() ?? panic("Manager not found") + + let vault = managerRef.borrowVaultPublic(id: vaultID) + let autoBalancer = vault.getAutoBalancer() + + let current = autoBalancer.getCurrentValue() + let historical = autoBalancer.getHistoricalValue() + + return current / historical +} +``` + +**Check position health (TracerStrategy):** +```cadence +pub fun main(address: Address, vaultID: UInt64): UFix64 { + // Get vault's ALP position health factor + // Returns: 1.30 (safe), < 1.0 (danger) +} +``` + +### Additional Deposits + +You can add more collateral at any time: + +```cadence +// Same as initial deposit transaction +transaction(vaultID: UInt64, amount: UFix64) { + // ... deposit logic +} +``` + +**Impact of additional deposits:** +- Increases collateral in ALP Position +- Position borrows more MOET to maintain target HF +- Additional MOET swapped to yield tokens +- AutoBalancer tracks new historical baseline +- Leverage ratio maintained + +### Withdrawals + +Withdraw a portion of your vault's value: + +```cadence +import FlowYieldVaults from 0xFlowYieldVaults +import FungibleToken from 0xFungibleToken + +transaction(vaultID: UInt64, amount: UFix64) { + prepare(signer: AuthAccount) { + let manager = signer.borrow<&FlowYieldVaults.YieldVaultManager>( + from: FlowYieldVaults.YieldVaultManagerStoragePath + ) ?? panic("Manager not found") + + let vault = manager.borrowVault(id: vaultID) + ?? panic("Vault not found") + + // Withdraw from vault + let withdrawn <- vault.withdraw(amount: amount) + + // Deposit to your account + let receiver = signer.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) + ?? panic("Could not borrow receiver") + + receiver.deposit(from: <-withdrawn) + + log("Withdrew ".concat(amount.toString()).concat(" FLOW")) + } +} +``` + +**What happens:** +1. AutoBalancer withdraws yield tokens from ERC4626 +2. SwapConnector converts yield tokens β†’ FLOW +3. For leveraged positions: may need to repay some debt to maintain health +4. FLOW returned to your account +5. Historical tracking updated + +### Force Rebalancing + +Manually trigger rebalancing (useful if automated schedule is stuck): + +```cadence +transaction(vaultID: UInt64) { + prepare(signer: AuthAccount) { + let manager = signer.borrow<&FlowYieldVaults.YieldVaultManager>( + from: FlowYieldVaults.YieldVaultManagerStoragePath + ) ?? panic("Manager not found") + + let vault = manager.borrowVault(id: vaultID) + ?? panic("Vault not found") + + vault.forceRebalance() + + log("Manual rebalance triggered for vault #".concat(vaultID.toString())) + } +} +``` + +## Phase 5: Vault Closure + +When you're ready to exit your position, you can liquidate the vault and claim all accumulated value. + +### Liquidate Vault Transaction + +```cadence +import FlowYieldVaults from 0xFlowYieldVaults +import FungibleToken from 0xFungibleToken +import FlowToken from 0xFlowToken + +transaction(vaultID: UInt64) { + prepare(signer: AuthAccount) { + let manager = signer.borrow<&FlowYieldVaults.YieldVaultManager>( + from: FlowYieldVaults.YieldVaultManagerStoragePath + ) ?? panic("Manager not found") + + // Liquidate vault (destroys it and returns all value) + let finalValue <- manager.liquidateVault(id: vaultID) + + // Deposit to your account + let receiver = signer.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) + ?? panic("Could not borrow receiver") + + receiver.deposit(from: <-finalValue) + + log("Liquidated vault #".concat(vaultID.toString())) + } +} +``` + +**What happens:** +1. AutoBalancer withdraws all yield tokens from ERC4626 +2. All yield tokens swapped to collateral (FLOW) +3. For leveraged positions: + - All debt repaid to ALP + - Remaining collateral withdrawn +4. Vault removed from SchedulerRegistry +5. All resources destroyed +6. Final value returned to you in FLOW + +**Example liquidation:** +``` +Initial deposit: 1000 FLOW +After 1 year of farming at 10% APY: + +Liquidation process: + - Withdraw all yield tokens from ERC4626 + - Yield tokens value: ~$671 (10% growth on $610) + - Swap yield tokens β†’ 671 FLOW + - Repay debt: 615.38 MOET + - After debt: ~55.62 FLOW profit from yield + - Withdraw collateral: 1000 FLOW + - Total returned: 1000 + 55.62 = 1055.62 FLOW + +Your profit: 55.62 FLOW (5.562% return on initial deposit) +``` + +Note: Actual returns depend on ERC4626 vault performance, swap slippage, and gas costs. + +## Complete Lifecycle Example + +Let's walk through a full vault lifecycle from start to finish: + +**Day 1 - Setup and Creation:** +```bash +# Setup account (one-time) +flow transactions send setup-account.cdc + +# Create vault with TracerStrategy +flow transactions send create-vault.cdc "TracerStrategy" +# Output: Vault #42 created + +# Initial deposit +flow transactions send deposit.cdc 42 1000.0 +# Deposited 1000 FLOW, now farming with 1.61x leverage +``` + +**Day 1-365 - Automated Farming:** +``` +AutoBalancer runs every 60 seconds: + - Day 30: Ratio = 102%, no action + - Day 60: Ratio = 106%, rebalanced (withdrew 6% excess) + - Day 90: Ratio = 104%, no action + - Day 120: Ratio = 107%, rebalanced (withdrew 7% excess) + ... continues for full year +``` + +**Day 365 - Closure:** +```bash +# Check final balance +flow scripts execute get-vault-balance.cdc 0x123... 42 +# Output: 1055.62 FLOW + +# Liquidate and withdraw +flow transactions send liquidate-vault.cdc 42 +# Vault #42 liquidated, 1055.62 FLOW returned +``` + +**Result:** 5.562% annual return through automated leveraged yield farming. + +## Best Practices + +**Start Small**: Test with a small amount first to understand vault behavior before committing significant capital. + +**Monitor Regularly**: Check your vault's health factor (leveraged positions) and AutoBalancer ratio weekly to ensure healthy performance. + +**Understand Thresholds**: Know when rebalancing triggers (95%-105%). Frequent hits indicate systematic performance. + +**Plan for Gas**: Each rebalance costs gas. Factor this into yield calculations for smaller vaults. + +**Track Performance**: Record deposit amounts and dates to calculate actual returns vs. expectations. + +**Diversify**: Use multiple vaults with different strategies to spread risk across yield sources. + +**Emergency Withdrawals**: Keep some liquid FLOW in your account for emergency deposits if health factor drops unexpectedly. + +## Troubleshooting + +**Vault creation fails**: Ensure you have set up your account first with the setup transaction, have sufficient FLOW for gas, and hold a beta capability (during closed beta period). + +**Rebalancing not triggering**: Check that vault is registered in SchedulerRegistry, manually trigger with forceRebalance() if needed, and contact support if issue persists. + +**Health factor dropping** (TracerStrategy): Add more collateral via deposit transaction, withdraw some yield to reduce leverage, or monitor collateral price movements. + +**Cannot withdraw**: Ensure vault has sufficient balance, for leveraged positions: check health factor allows withdrawal, and verify no pending rebalances blocking operations. + +## Next Steps + +- **Understand leverage**: Read [Leveraged Farming](./leveraged-farming.md) +- **Learn strategies**: Explore [Strategies](./strategies.md) +- **Master rebalancing**: See [AutoBalancer](./autobalancer.md) +- **Cross-chain options**: Check [Cross-Chain Integration](./cross-chain.md) + +--- + +:::tip Key Takeaway +The vault lifecycle is designed for simplicity: set up once, deposit to start, let AutoBalancer optimize continuously, and liquidate when ready. The system handles all complexity of leveraged borrowing, yield farming, and rebalancing automatically. +::: From 21af78c5d48ad5e8cbb34f1bcfd84dd032a86663 Mon Sep 17 00:00:00 2001 From: Felipe Cevallos Date: Tue, 23 Dec 2025 09:41:24 -0600 Subject: [PATCH 8/8] Fix broken markdown links in FYV documentation --- docs/defi/flow-yield-vaults/index.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/defi/flow-yield-vaults/index.md b/docs/defi/flow-yield-vaults/index.md index 431c3c2cff..db5e348d62 100644 --- a/docs/defi/flow-yield-vaults/index.md +++ b/docs/defi/flow-yield-vaults/index.md @@ -56,9 +56,7 @@ Learn more in [Architecture Overview](./architecture.md). - [Scheduling System](./scheduling.md) - Automated execution and recovery ### Integration -- [FCM Integration](./fcm-integration.md) - Working with ALP and MOET - [DeFi Actions](./defi-actions.md) - Composable DeFi primitives -- [Swap Connectors](./swap-connectors.md) - Token conversion infrastructure ## Getting Started @@ -72,7 +70,7 @@ If you want to integrate FYV or create custom strategies, start with the [Archit ### For DeFi Builders -If you want to understand how FYV achieves automated leverage and liquidation protection, start with [Leveraged Farming](./leveraged-farming.md) and [FCM Integration](./fcm-integration.md). +If you want to understand how FYV achieves automated leverage and liquidation protection, start with [Leveraged Farming](./leveraged-farming.md) and explore how FYV integrates with [ALP](../alp/index.md) for borrowing. ## Key Features @@ -113,7 +111,7 @@ See [DeFi Contracts](../defi-contracts-mainnet.md) for complete contract address - **Understand the basics**: Read [Architecture Overview](./architecture.md) - **Learn strategies**: Explore [TracerStrategy](./strategies.md#tracerstrategy) - **Create your first vault**: Follow [Vault Lifecycle](./vault-lifecycle.md) -- **Integrate with FCM**: See [FCM Integration](./fcm-integration.md) +- **Integrate with FCM**: See [FCM Overview](../fcm/index.md) and [ALP Documentation](../alp/index.md) ---