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..cdcfb97388 --- /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)](#). 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..6e9ea308c3 --- /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)](#) handles yield aggregation strategies, and [MOET](#) 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](#) +- [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..c82a7fcd89 --- /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 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](#) +- **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..0cdc6adb08 --- /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](#) +- **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 +::: diff --git a/docs/defi/fcm/basics.md b/docs/defi/fcm/basics.md new file mode 100644 index 0000000000..37f3d1478f --- /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](#) + +### 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](#) + +## 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](#), [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. +::: diff --git a/docs/defi/fcm/index.md b/docs/defi/fcm/index.md new file mode 100644 index 0000000000..8e85651a59 --- /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)](#)**: 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](#)**: 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](#)** - Yield strategies and vaults +- **[MOET Documentation](#)** - The synthetic stablecoin + +### Advanced Topics +- **[Capital Flows](#)** - How value moves through the system +- **[Risk Management](#)** - Understanding and managing risks +- **[Integration Guide](#)** - 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](#) +- **Building an integration?** Check the [Integration Guide](#) + +--- + +:::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..dbe22a6af3 --- /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: + +```math +EC = βˆ‘(A_t Γ— P_t Γ— CF_t) for all t in Collateral +``` + +**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: + +```math +ED = \sum_t \in Debt A_t Γ— P_t Γ— 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: + +```math +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 + +HF = 1250 / 800 = 1.5625 +``` + +### 4. Maximum Borrowing Capacity + +The maximum amount that can be borrowed to reach target health: + +```math +MaxBorrow = (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: + +```math +BorrowAmount = (EC / HF_target) +``` + +**Step-by-step calculation**: + +1. **Calculate effective collateral**: +``` + EC = A_collateral Γ— P_collateral Γ— CF_collateral +``` + +2. **Calculate target debt**: +``` + ED_target = (EC / HF_target) +``` + +3. **Borrow to reach target**: +``` + Borrow = ED_target = (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: + +``` +AdditionalBorrow = (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: + +``` +RequiredRepayment = ED_current - (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) Γ— (1 + r Γ— \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 Γ— e^{r Γ— 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 Γ— 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: + +``` +CollateralSeized = \frac{ED_repaid Γ— (1 + bonus)}{P_collateral Γ— CF_collateral} +``` + +Where: +- $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 + +**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 - (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 Γ— \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? + +``` +MaxDropPercent = 1 - (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 Γ— P_i Γ— 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)**: +``` +Risk = \sum_i Risk_i +``` + +**With correlation** (advanced): +``` +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: + +``` +APY_simple = (FinalValue - InitialValue / InitialValue) Γ— (365 / Days) +``` + +### Compound APY + +With continuous compounding: + +``` +APY_compound = e^r - 1 +``` + +Where $r$ is the continuous annual rate. + +### Leveraged Yield + +When borrowing to increase yield exposure: + +``` +Yield_leveraged = Yield_strategy - 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} = (1 / HF - 1.0) Γ— Volatility_collateral +``` + +Higher score = higher risk. + +### Value at Risk (VaR) + +Maximum expected loss over time period at confidence level: + +``` +VaR_95% = EC Γ— \sigma Γ— 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 ≀ 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 ≀ 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: + +``` +MaxLeverage = (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: + +``` +SafeLeverage = (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 Γ— 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. +:::