# Dynamic Fee

## Introduction

Ferra's DLMM implements a sophisticated dynamic fee system that automatically adjusts based on market volatility and trading patterns. This creates a fair and efficient pricing mechanism where fees increase during periods of high volatility or large trades, ensuring liquidity providers are properly compensated for the risks they take.

The system uses surge pricing that responds to real-time market conditions, protecting liquidity providers during volatile periods while maintaining competitive fees during stable market conditions.

## Benefits and Design Goals

#### For Liquidity Providers

* **Fair compensation**: Fees increase with risk during volatile periods
* **Predictable base income**: Base fees provide stable minimum returns
* **Anti-dilution**: Composition fees discourage harmful imbalanced deposits

#### For Traders

* **Competitive fees**: Low fees during stable market conditions
* **Transparent pricing**: Clear fee structure with predictable components
* **Fair pricing**: Surge pricing reflects true cost of liquidity provision

#### For Protocol

* **Sustainable revenue**: Protocol fees support development and operations
* **Market efficiency**: Dynamic fees encourage optimal trading behavior
* **Risk management**: Higher fees during volatile periods protect ecosystem

This dynamic fee system creates a balanced ecosystem where all participants are fairly compensated while maintaining efficient and competitive markets.

## Fee Architecture Overview

### Total Fee Structure

The total fee charged to traders consists of multiple components:

```javascript
Total_Fee = Base_Fee + Variable_Fee
```

All fees are calculated with **9 decimal precision** (1,000,000,000 = 100%) ensuring high accuracy in fee calculations.

**Fee Caps:**

* Maximum Total Fee: **10%**
* Maximum Protocol Share: **25%** of total fees

#### Fee Flow Process

* **Fee Calculation**: Fees computed per bin during swaps
* **Protocol Split**: Percentage allocated to protocol treasury
* **LP Distribution**: Remaining fees distributed to liquidity providers
* **Additional Fees**: Composition and flash loan fees handled separately

### Base Fee

The base fee provides a stable minimum fee floor for each trading pair, ensuring liquidity providers always receive basic compensation.

$$
\text{Base\_Fee} = \text{Base\_Factor} \times \text{Bin\_Step}
$$

Wher&#x65;**:**

* `Base_Factor`: Pool-specific amplification multiplier (set by pool creator)
* `Bin_Step`: Price increment between adjacent bins

#### Purpose

* Ensures minimum compensation for liquidity providers
* Covers basic operational costs
* Provides predictable fee component independent of volatility

### Variable Fee

The variable fee creates dynamic pricing that responds to market volatility, implementing surge pricing during periods of high trading activity or significant price movements:

$$
\text{Variable\_Fee} = \left( \text{Volatility\_Accumulator} \times \text{Bin\_Step} \right)^2 \times \text{Variable\_Fee\_Control} \div 100
$$

Wher&#x65;**:**

* `Volatility_Accumulator`: Current measure of market volatility
* `Bin_Step`: Price increment between bins
* `Variable_Fee_Control`: Sensitivity parameter for volatility response

#### Key Characteristics

* **Quadratic scaling**: Fees increase exponentially with volatility
* **Bin-aware**: Considers price step size of the specific market
* **Configurable sensitivity**: Markets can tune volatility response

### Volatility Management System

The volatility system captures market dynamics while preventing manipulation through sophisticated time-weighted mechanisms.

#### Volatility Accumulator

The core volatility measure that tracks price movement intensity:

$$
\text{Volatility\_Accumulator} = \text{Volatility\_Reference} + \left| \text{Current\_Bin\_ID} - \text{Reference\_Bin\_ID} \right| \times 10,000
$$

Wher&#x65;**:**

* `Volatility_Reference`: Decayed volatility from previous periods
* `Bin_ID_Delta`: Absolute difference in bin positions
* `10,000`: Scaling factor (basis points)

#### Time-Based Volatility Management

The system uses three time periods to manage volatility evolution:

**Filter Period (t**<sub>**f**</sub>**)**

Minimum time before volatility parameters update:

* **Purpose**: Prevents rapid manipulation
* **Effect**: High-frequency trades maintain current volatility reference

**Decay Period (t**<sub>**d**</sub>**)**

Maximum time before volatility resets:

* **Purpose**: Ensures old volatility doesn't persist indefinitely
* **Effect**: Long periods without trades reset volatility to zero

**Volatility Reference Updates**

Based on time elapsed (Δt) since last transaction:

**Case 1: High Frequency (Δt < t**<sub>**f**</sub>**)**

```clike
Volatility_Reference = Previous_Volatility_Reference (unchanged)
Reference_Bin_ID = Previous_Reference_Bin_ID (unchanged)
```

**Case 2: Normal Frequency (t**<sub>**f**</sub>**&#x20;≤ Δt < t**<sub>**d**</sub>**)**

```clike
New_Volatility_Reference = Current_Volatility_Accumulator × Reduction_Factor ÷ 10,000
Reference_Bin_ID = Current_Active_Bin_ID
```

**Case 3: Low Frequency (Δt ≥ t**<sub>**d**</sub>**)**

```clike
Volatility_Reference = 0
Reference_Bin_ID = Current_Active_Bin_ID
```

#### Anti-Manipulation Protection

The system includes multiple layers of protection:

* **Time filtering**: Prevents rapid volatility manipulation through frequent small trades
* **Reference stability**: Maintains stable reference points during high-frequency periods
* **Gradual decay**: Volatility naturally decreases over time
* **Maximum caps**: Limits extreme volatility accumulation

### Composition Fees

Composition fees encourage balanced liquidity provision by charging additional fees when liquidity providers deposit tokens in imbalanced ratios.

#### When Applied

Composition fees are **only charged in the active bin** and only when:

* Liquidity provider deposits create imbalance
* One token is over-represented relative to current bin ratio

#### Fee Calculation

The composition fee uses a quadratic formula to discourage large imbalances:

$$
\text{Composition\_Fee} = \text{Excess\_Amount} \times \text{Total\_Fee\_Rate} \times (\text{Total\_Fee\_Rate} + 1)
$$

Wher&#x65;**:**

* `Excess_Amount`: Amount of over-represented token
* `Total_Fee_Rate`: Current base + variable fee (as decimal)

#### Imbalance Detection

For Token X excess:

```pascal
if (Amount_X_In > Expected_X_Out) AND (Amount_Y_In < Expected_Y_Out) then 
    Composition_Fee = (Amount_X_In - Expected_X_Out) * Fee_Formula
```

For Token Y excess:

```pascal
if (Amount_Y_In > Expected_Y_Out) AND (Amount_X_In < Expected_X_Out) then 
    Composition_Fee = (Amount_Y_In - Expected_Y_Out) * Fee Formula 
```

### Protocol Fee System

Protocol fees support network development and maintenance by extracting a percentage of all collected fees.

#### Protocol Share Distribution

```javascript
Protocol_Fee = Total_Fee * Protocol_Share ÷ 10,000
LP_Fee = Total_Fee - Protocol_Fee
```

Wher&#x65;**:**

* `Protocol_Share`: Configurable percentage (max 25%)
* `Total_Fee`: Sum of all fee components

#### Fee Types Subject to Protocol Share

* Swap fees (base + variable)
* Composition fees
* Flash loan fees

### Flash Loan Fees

Flash loans have a separate fee mechanism independent of the volatility system.

#### Flash Loan Fee Calculation

```javascript
Flash_Loan_Fee = Loan_Amount * Flash_Loan_Rate ÷ 1,000,000,000
```

Wher&#x65;**:**

* `Loan_Amount`: Principal amount borrowed
* `Flash_Loan_Rate`: Configurable rate (max 10%)

#### Characteristics

* **Fixed rate**: Not affected by volatility
* **Immediate**: Charged upon loan initiation
* **Protocol allocation**: Subject to protocol share split

### Fee Distribution Mechanics

#### Per-Bin Fee Tracking

Each liquidity bin maintains detailed fee accounting using growth tracking:

```javascript
Fee_Growth_per_Unit = Accumulated_Fees ÷ Total_Liquidity_in_Bin
```

#### LP Fee Calculation

When liquidity providers claim fees:

```javascript
LP_Fees_Owed = LP_Liquidity * (Current_Fee_Growth - Last_Claimed_Fee_Growth)
```

This ensures proportional fee distribution based on:

* Liquidity amount provided
* Duration of liquidity provision
* Bins crossed during trading

### Parameter Configuration

#### Static Parameters (Set at Pool Creation)

* `Base_Factor`: Determines base fee level
* `Variable_Fee_Control`: Volatility sensitivity
* `Filter_Period`: High-frequency threshold
* `Decay_Period`: Volatility reset threshold
* `Reduction_Factor`: Volatility decay rate
* `Protocol_Share`: Protocol fee percentage
* `Max_Volatility_Accumulator`: Volatility ceiling

#### Dynamic Parameters (Updated During Trading)

* `Volatility_Accumulator`: Current volatility level
* `Volatility_Reference`: Decayed volatility baseline
* `Reference_Bin_ID`: Reference point for volatility calculation
* `Last_Update_Time`: Timestamp for time-based calculations

### Practical Examples

#### Example 1: Variable Fee Calculation

Market Setup:

* Base Factor: 100
* Bin Step: 5
* Volatility Accumulator: 50,000
* Variable Fee Control: 2,500

Fee Calculation:

```javascript
Base_Fee = 100 × 5 × 10 = 5,000 units (0.0005%)
Variable_Fee = (50,000 × 5)² × 2,500 ÷ 100
             = (250,000)² × 2,500 ÷ 100
             = 62,500,000,000 × 2,500 ÷ 100
             = 1,562,500,000,000 units (0.156%)
Total_Fee = 5,000 + 1,562,500,000,000 = 1,562,505,000,000 units (0.1565%)
```

#### Example 2: Volatility Evolution Over Time

Initial State:

* Volatility\_Accumulator: 0
* Reference\_Bin\_ID: 1000
* Filter\_Period: 30 seconds
* Decay\_Period: 300 seconds
* Reduction\_Factor: 5,000 (50%)

Transaction Sequence:

T=0: Large Swap (crosses 8 bins to ID 1008)

```javascript
Volatility_Accumulator = 0 + |1008 - 1000| × 10,000 = 80,000
```

T=45s: Medium Swap (crosses 3 bins to ID 1011) Since 45s > 30s (filter period) and < 300s (decay period):

```javascript
New_Volatility_Reference = 80,000 × 5,000 ÷ 10,000 = 40,000
New_Reference_Bin_ID = 1008
Volatility_Accumulator = 40,000 + |1011 - 1008| × 10,000 = 70,000
```

T=350s: Small Swap (crosses 1 bin to ID 1012) Since 350s > 300s (decay period):

```javascript
Volatility_Reference = 0 (reset)
Reference_Bin_ID = 1011
Volatility_Accumulator = 0 + |1012 - 1011| × 10,000 = 10,000
```

#### Example 3: Composition Fee Application

Bin State:

* Current reserves: 3,000 USDC, 1,000 SUI
* SUI price: 3.0 USDC

LP Deposit:

* Deposits: 1,800 USDC, 500 SUI
* Expected balanced ratio: 1,500 USDC, 500 SUI
* Excess USDC: 300 USDC

Fee Calculation:

```javascript
Total_Fee_Rate = 0.01 (1%)
Composition Fee = 300 × 0.01 × (0.01 + 1)              
                = 300 × 0.01 × 1.01   
                = 3.02 USDC             
```

#### Example 4: Protocol Fee Distribution

Swap generates:

* Total Fee: 100 USDC
* Protocol Share: 20% (2,000 basis points)

Distribution:

```javascript
Protocol_Fee = 100 × 2,000 ÷ 10,000 = 20 USDC
LP_Fee = 100 - 20 = 80 USDC
```
