# Core Architecture

## Design of Automated Restaking Mechanisms

Automated restaking mechanisms in DeFi aim to streamline the process of compounding rewards for users by automating the reallocation of Liquid Staking Tokens (LSTs) across platforms with optimal APY. This design covers the core architecture, APY optimization algorithm, and gas fee minimization techniques.

***

### Core Architecture of Automated Restaking Protocols

The protocol consists of three layers:

#### 1. Smart Contract Layer

This is the backbone of the system, handling deposits, withdrawals, and staking operations. It also manages user balances and executes batch transactions for efficiency.

* **Components**:

  * **Deposit/Withdrawal Manager**: Tracks user actions:&#x20;

  $$\[ B\_i = D\_i - W\_i + R\_i ]$$

where ( B\_i ) is the balance, ( D\_i ) is the deposit, ( W\_i ) is the withdrawal, and ( R\_i ) is the reward.

* **Restaking Manager**: Automates reallocation based on APY optimization.
* **Batch Processor**: Reduces gas costs by combining multiple user transactions into one.

***

#### 2. Off-Chain Oracles

Fetch data such as APYs, fees, and liquidity from staking platforms. This ensures the system always has the latest information for decision-making.

* Data fetched:

$$
\[ {\text{APY}\_i, \text{Fee}\_i, \text{Liquidity}\_i} \quad \forall i \in P ]
$$

***

#### 3. User Interface (UI) Layer

A dashboard displays current and historical APY performance, user balance, and restaking metrics.

***

### Algorithm for APY Optimization Across Multiple Staking Platforms

#### Steps:

* **Data Collection**: Retrieve platform data ((\text{APY}\_i), (\text{Fee}\_i), (\text{Liquidity}\_i)).
* **Net APY Calculation**:\
  $$\[ \text{Net APY}\_i = \text{APY}\_i - \text{Fee}\_i ]$$
* **Platform Selection**: Choose the platform ( j ) with the highest net&#x20;
* **Restaking Decision**: If ( j \neq \text{current platform} ), reallocate assets to ( j ).
* **Rebalancing**: Periodically re-evaluate and repeat the process.

***

#### Pseudocode :

```rust
struct PlatformData {
    apy: f64,
    fee: f64,
    liquidity: f64,
}

fn calculate_net_apy(platform: &PlatformData) -> f64 {
    platform.apy - platform.fee
}

fn select_optimal_platform(platforms: Vec<PlatformData>) -> usize {
    let mut max_apy = f64::MIN;
    let mut optimal_index = 0;

    for (index, platform) in platforms.iter().enumerate() {
        let net_apy = calculate_net_apy(platform);
        if net_apy > max_apy {
            max_apy = net_apy;
            optimal_index = index;
        }
    }
    optimal_index
}

fn restake_if_necessary(current_index: usize, platforms: Vec<PlatformData>) {
    let optimal_index = select_optimal_platform(platforms);
    if current_index != optimal_index {
        println!("Reallocating to platform {}", optimal_index);
        // Reallocate assets logic here
    } else {
        println!("No reallocation needed.");
    }
}
```
