# Core Contracts & Architecture

Ocean Finance implements a sophisticated modular architecture with clear separation of concerns, comprehensive access control, and cross-chain functionality. The protocol is built around OCUSD, a yield-bearing stablecoin backed by diversified strategies.

## Architecture Overview

![Architecture Overview](/files/MNvKwNSN5niK0o9tabUn)

## Core Contract Components

### OCUSD Token

**Contract**: `OCUSD.sol` **Purpose**: Main yield-bearing stablecoin with cross-chain capabilities

**Key Features**:

* ERC20 with permit functionality for gasless transactions
* LayerZero OFT (Omnichain Fungible Token) for seamless cross-chain transfers
* Minting restricted to MintingManager for regular operations
* Special mint function for YieldDistributor rewards
* Burning restricted to MintingManager

**Technical Details**:

```solidity
contract OCUSD is ERC20Permit, OFT {
    function mint(address to, uint256 amount) external onlyMintingManager
    function mintRewards(address to, uint256 amount) external onlyYieldDistributor
    function burn(address from, uint256 amount) external onlyMintingManager
}
```

### StakedOCUSD

**Contract**: `StakedOCUSD.sol` **Purpose**: ERC4626 vault for staking OCUSD and earning yield

**Key Features**:

* ERC4626 compliant with 18 decimal precision
* Configurable cooldown period (0-90 days) for withdrawals
* Linear yield vesting over 24 hours to prevent manipulation
* OCUSDSilo integration for cooldown asset storage
* 4 decimal offset for enhanced share precision

**Cooldown Mechanism**:

```solidity
function cooldownAssets(uint256 assets) external returns (uint256 shares)
function cooldownShares(uint256 shares) external returns (uint256 assets)
function unstake(address receiver) external returns (uint256 assets)
```

**Yield Distribution**:

```solidity
function receiveRewards(uint256 amount) external onlyYieldDistributor {
    // 24-hour linear vesting prevents yield manipulation
    _startVesting(amount);
}
```

### MintingManager

**Contract**: `MintingManager.sol` **Purpose**: Manages OCUSD minting and redemption against collateral

**Key Features**:

* Multi-asset collateral support with administrative controls
* Whitelisted minter system for access control
* Asynchronous redemption request system
* Permit-based transactions for improved UX
* Oracle integration for accurate pricing
* Emergency pause functionality

**Minting Flow**:

```solidity
function mint(
    address asset,
    uint256 amount,
    address receiver
) external whenNotPaused onlyValidMinter returns (uint256 ocusdAmount) {
    // Transfer collateral → Get oracle price → Mint OCUSD
}
```

**Redemption System**:

```solidity
struct RedeemRequest {
    address requester;
    address asset;
    uint256 ocusdAmount;
    uint256 requestTime;
    bool fulfilled;
}

function requestRedeem(address asset, uint256 ocusdAmount) external
function fulfillRedeemRequest(uint256 requestId) external onlyServiceRole
```

### StrategyAllocator

**Contract**: `StrategyAllocator.sol` **Purpose**: Central hub for managing protocol assets and strategy operations

**Key Features**:

* Receives collateral from MintingManager
* Manages approvals to strategy handlers
* Executes batched operations on handlers
* Administrative withdrawal capabilities
* Whitelisted assets and handlers for security

**Operation Execution**:

```solidity
function execute(
    address[] calldata targets,
    bytes[] calldata data
) external onlyServiceRole {
    // Batch execute operations on strategy handlers
}
```

### YieldDistributor

**Contract**: `YieldDistributor.sol` **Purpose**: Distributes protocol earnings to stakeholders

**Key Features**:

* Configurable fee splitting (protocol, reserve, stakers)
* Direct OCUSD minting for rewards (no collateral backing required)
* Basis point fee configuration
* Emergency rescue functions

**Distribution Logic**:

```solidity
function transferRewards(uint256 totalAmount) external onlyServiceRole {
    // Mint OCUSD for total rewards
    // Calculate and distribute fees
    // Send remaining to StakedOCUSD
}
```

### AddressProvider

**Contract**: `AddressProvider.sol` **Purpose**: UUPS upgradeable central registry for protocol addresses

**Key Features**:

* Single source of truth for all protocol addresses
* UUPS upgrade pattern for future improvements
* Comprehensive getters for all protocol components
* Batch address setting for efficiency

## Strategy Handler Architecture

The protocol uses a standardized modular handler system built on the BaseHandler abstract contract:

### BaseHandler (Abstract Contract)

**Contract**: `BaseHandler.sol` **Purpose**: Standardized interface and common functionality for all strategy handlers

**Core Features**:

* Unified access control via `onlyStrategyAllocator` modifier
* Standardized asset management through `receiveAsset` and `claimAsset`
* Centralized address resolution via `AddressProvider`
* Common input validation modifiers
* Consistent event patterns

```solidity
abstract contract BaseHandler is IBaseHandler {
    IAddressProvider public addressProvider;
    
    modifier onlyStrategyAllocator() { 
        require(msg.sender == addressProvider.strategyAllocator(), "Not strategy allocator");
        _;
    }
    
    function receiveAsset(address asset_, uint256 amount_) external virtual;
    function claimAsset(address to_, address asset_, uint256 amount_) external virtual;
}
```

### EthenaHandler

**Contract**: `EthenaHandler.sol` (inherits BaseHandler) **Integration**: Ethena Protocol (USDe/sUSDe) **Operations**: Staking, cooldown management, unstaking **Key Functions**: `stakeUSDe()`, `cooldownAssets()`, `unstakeUSDe()`

### SkyHandler

**Contract**: `SkyHandler.sol` (inherits BaseHandler) **Integration**: Sky Protocol (USDS/sUSDS) **Operations**: Staking, PSM swapping, unstaking **Key Functions**: `stakeUsds()`, `swapUsdcToUsds()`, `withdrawUsds()`

### NestHandler

**Contract**: `NestHandler.sol` (inherits BaseHandler) **Integration**: Nest Vaults **Operations**: Vault deposits, atomic withdrawals **Key Functions**: `deposit()`, `withdraw()` via Teller/AtomicQueue

## Oracle System

### OceanOracle

**Contract**: `OceanOracle.sol` **Purpose**: Reliable price feeds with comprehensive validation

**Features**:

* Multi-oracle support (Chainlink, Pyth)
* Stablecoin deviation monitoring (configurable threshold)
* Price staleness checking with per-token timeouts
* WAD-normalized pricing (18 decimals)

**Safety Mechanisms**:

```solidity
function getTokenPrice(address token) external view returns (uint256) {
    // Validate oracle response
    // Check price staleness
    // Monitor stablecoin deviation
    // Return WAD-normalized price
}
```

## Access Control System

### DefaultAdminAccessControl

**Contract**: `DefaultAdminAccessControl.sol` **Purpose**: Centralized role-based access control

**Role Hierarchy**:

* `DEFAULT_ADMIN_ROLE`: Ultimate administrative control
* `SERVICE_ROLE`: Operational functions (strategy execution, redemption fulfillment)

**Security Features**:

* Cooldown periods for admin role changes
* Centralized role checking through AddressProvider
* Emergency functions with appropriate restrictions

## Technical Specifications

### Precision and Decimals

* **OCUSD**: 18 decimals (standard ERC20)
* **StakedOCUSD**: 18 decimals with 4 decimal offset for shares
* **Oracle Prices**: WAD normalized (18 decimals)
* **Fee Calculations**: Basis points (10000 = 100%)

### Cross-Chain Functionality

* **LayerZero Integration**: Seamless cross-chain OCUSD transfers
* **Unified Liquidity**: Maintains consistent token supply across chains
* **Message Passing**: Secure cross-chain communication

### Upgradeability

* **AddressProvider**: UUPS upgradeable for protocol evolution
* **Core Contracts**: Immutable for security and trust
* **Handler System**: Pluggable for new strategy integrations

### Security Features

* **Reentrancy Protection**: ReentrancyGuard on all external functions
* **Oracle Validation**: Multiple layers of price feed verification
* **Access Control**: Comprehensive role-based permissions
* **Emergency Controls**: Pause mechanisms and rescue functions
* **Cooldown Systems**: Time-based security for critical operations

This modular architecture ensures scalability, security, and flexibility while maintaining clear separation of concerns and comprehensive access controls throughout the protocol.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.ocean.fi/protocol-architecture/04-protocol-architecture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
