> ## Documentation Index
> Fetch the complete documentation index at: https://docs.multiliquid.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Protocol Architecture

> Comprehensive technical overview of the Multiliquid Protocol's modular design and smart contract infrastructure

## System Overview

The Multiliquid Protocol is built on a modular, upgradeable architecture that enables atomic swaps between multiple permissioned Real World Asset (RWA) tokens and multiple stablecoins. The system is designed for institutional-grade operations with comprehensive risk management, transparent fee structures, and extensible integration patterns.

### Design Principles

1. **Modularity**: Asset-specific logic isolated in delegate contracts
2. **Upgradeability**: UUPS proxy pattern enables secure evolution
3. **Atomicity**: All operations either fully succeed or fully revert
4. **Transparency**: All state changes emit comprehensive events
5. **Extensibility**: New assets can be integrated without modifying core logic

## Core Contract System

The protocol consists of four primary contract categories that work together to enable secure, atomic swaps between RWAs and stablecoins.

### How the Contracts Work Together

At the heart of the system, **MultiliquidSwap** acts as the central orchestrator that coordinates all swap operations. When a user initiates a swap, MultiliquidSwap queries **Price Adapters** to obtain real-time USD valuations for the assets involved, then calculates the exact amounts using WAD mathematics and applies the appropriate protocol fees. For added security, it calls **RWA Delegates** (if configured) to enforce volume limits and compliance checks before any tokens move. Finally, it delegates the actual token transfers to **Stablecoin Delegates**, which handle the asset-specific logic—whether minting new stablecoins, transferring from custody, or burning tokens. This separation of concerns ensures that each contract focuses on its specialized responsibility while maintaining atomic execution, meaning every swap either completes entirely or reverts with no partial state changes.

### 1. MultiliquidSwap Contract

**Location**: `MultiliquidSwap.sol`

The central orchestrator managing all swap operations, fee calculations, and asset interactions.

#### Core Responsibilities

* **Swap Orchestration**: Coordinates stablecoin↔RWA, RWA↔RWA, and stablecoin↔stablecoin routes with ExactIn and ExactOut variants
* **Fee Management**: Resolves LP-paid protocol fees, spread fees, and LP-configured asset fees
* **Price Calculation**: Integrates with price adapters for USD-denominated valuation
* **Access Control**: Enforces role-based permissions for all operations
* **Quote Generation**: Provides a view function for off-chain quote calculation

<Card title="View MultiliquidSwap Contract Details" icon="code" href="/evm/contracts/multiliquid-swap">
  Complete function signatures and implementation details
</Card>

### 2. Stablecoin Delegate System

**Base Contract**: `StablecoinDelegateBase.sol`

Stablecoin delegates handle asset-specific integration logic for each supported stablecoin.

#### Core Responsibilities

* **Stablecoin Operations**: Mint, burn, or transfer stablecoins based on delegate type
* **RWA Whitelist Management**: Maintain per-Liquidity Provider RWA whitelists controlled by LP admins
* **Fee Configuration**: Set discount rates, redemption fees, and acceptance fees per RWA
* **Risk Controls**: Pause mechanisms and compliance hooks for metadata validation
* **Custody Management**: Manage RWA token custody addresses (for balance sheet delegates)

#### Delegate Types

* **Mint/Burn Delegates**: Direct integration with stablecoins supporting native minting
* **Balance Sheet Delegates**: Custody-based model for existing stablecoin liquidity balances without mint/burn integration
* **Yield-Bearing Delegates**: Credit and yield accounting layered onto stablecoin settlement

<Card title="View Stablecoin Delegate Details" icon="code" href="/evm/contracts/stablecoin-delegate">
  Complete interface and implementation details
</Card>

### 3. RWA Delegate System

**Base Contract**: `RWADelegate.sol`

RWA delegates provide **optional** risk management and compliance controls for specific RWA tokens. Only deployed when custom controls beyond token-native functionality are needed.

#### Core Responsibilities

* **Volume Limits**: Enforce daily swap limits per wallet with configurable reset windows
* **Risk Validation**: Validate RWA transfers with `checkRWAIn()` and `checkRWAOut()` hooks
* **Pause Controls**: RWA-admin-controlled pause mechanism independent from protocol-wide pause

#### When to Use

RWA delegates are only required when additional risk management is needed beyond the RWA token's native controls (e.g., built-in KYC, transfer restrictions).

<Card title="View RWA Delegate Details" icon="code" href="/evm/contracts/rwa-delegate">
  Complete interface and implementation details
</Card>

### 4. Price Adapter System

**Interface**: `IPriceAdapter.sol`

Price adapters provide USD-denominated pricing for all assets in the protocol.

#### Core Responsibilities

* **Price Provision**: Return USD price in 18-decimal WAD format (1e18 = \$1.00 USD)
* **Asset-Specific Integration**: Query published NAV of the RWA
* **Standardization**: Normalize pricing across different RWA token architectures

<Card title="View Price Adapter Details" icon="code" href="/evm/contracts/price-adapters">
  Complete adapter implementations and integration patterns
</Card>

### 5. Application Layer: Liquid Treasury

The protocol's modular architecture enables higher-level financial products built on the core swap infrastructure. Liquid Treasury is the first such application.

**Liquid Treasury Token** (`Treasury.sol`):

* Multi-chain institutional treasury token with whitelist and blacklist compliance controls
* Dual minting modes: whitelist-enforced primary issuance and bridge-agnostic cross-chain minting
* Emergency controls (force burn, force transfer) and EIP-2612 permit support

**Treasury Delegate** (`TreasuryDelegate.sol`):

* Yield-bearing stablecoin delegate integrating Liquid Treasury with MultiliquidSwap
* Daily interest rate accrual based on underlying tokenized money market fund performance
* Withheld credits system with 24-hour hold period for risk management
* Permissionless interest accrual with bounded processing for gas safety

<Card title="View Liquid Treasury Details" icon="building-columns" href="/applications/liquid-treasury">
  Complete token mechanics, yield system, compliance controls, and bridge integration
</Card>

## Operational Flow

### Swap Execution Flow

```mermaid theme={null}
sequenceDiagram
    actor User
    actor Operator
    participant MultiliquidSwap
    participant Pricing
    participant Policy
    participant StablecoinDelegate
    participant Assets

    User-->>Operator: Authorize transaction
    Operator->>MultiliquidSwap: Submit one or more swap legs
    MultiliquidSwap->>MultiliquidSwap: Validate inputs and authorization
    MultiliquidSwap->>Pricing: Resolve prices and fees
    MultiliquidSwap->>Policy: Check applicable controls
    MultiliquidSwap->>StablecoinDelegate: Send resolved settlement
    StablecoinDelegate->>Assets: Transfer, mint, or burn
    StablecoinDelegate-->>MultiliquidSwap: Swap complete
    MultiliquidSwap-->>Operator: Emit Swap event
```

## Data Structures

### RWA Information

```solidity theme={null}
struct RWAInfo {
    bool accepted;                    // Whether RWA is accepted for swaps
    bool additionalRiskControls;      // Whether delegate risk checks are enabled
    uint8 decimals;                   // Token decimals (e.g., 6, 18)
    address delegate;                 // Optional delegate address (address(0) if none)
    address assetAddress;             // Address of the RWA token contract
}
```

### Stablecoin Information

```solidity theme={null}
struct StablecoinInfo {
    bool accepted;                    // Whether stablecoin is accepted
    bool yieldBearing;                // Whether the stablecoin accrues yield
    uint8 decimals;                   // Token decimals
    address delegate;                 // LP delegate, or zero for swap-only counterparty assets
    address assetAddress;             // Address of the stablecoin token contract
}
```

### Fee Model

The protocol separates LP-paid protocol fees, the protocol's share of LP spreads, and LP-configured asset fees. Each Liquidity Provider configures spreads and fees independently for every accepted asset within its own delegate domain.

## Permission Model

The protocol implements a comprehensive role-based access control system:

### Global Roles

**DEFAULT\_ADMIN\_ROLE**

* Can upgrade contracts via UUPS
* Administers roles according to each contract's configured role hierarchy
* Configures the Multiliquid protocol fee vault
* Intended for multi-sig governance

**OPERATOR\_ROLE**

* Day-to-day operational control
* Can accept new RWAs and stablecoins
* Can update price adapters
* Can configure protocol fee policy and stablecoin guardrails
* Can pause and unpause the MultiliquidSwap contract (emergency and maintenance)
* Cannot upgrade contracts

**PAUSE\_ROLE** *(Delegate Contracts)*

* Exists on stablecoin and RWA delegate contracts, not on MultiliquidSwap
* Can pause individual delegate operations
* Provides granular, per-delegate emergency controls

### Asset-Specific Roles

**Liquidity Provider Admin**
Each stablecoin delegate has its own Liquidity Provider admin who can:

* Set RWA discount rates for their stablecoin
* Set RWA redemption fees for their stablecoin
* Manage the RWA whitelist for their stablecoin
* Pause their specific delegate
* Configure custody addresses

**RWA Admin**
Each RWA delegate has its own RWA admin who can:

* Configure volume limits
* Adjust risk parameters
* Pause their specific delegate

### Special Role

**MULTILIQUID\_SWAP\_CONTRACT**

* Granted to the MultiliquidSwap contract address
* Allows the swap contract to call delegate functions
* Ensures only the central orchestrator can trigger swaps

## Upgrade Mechanism

All core contracts use the UUPS (Universal Upgradeable Proxy Standard) pattern:

### Upgrade Process

1. **Preparation**: New implementation contract is deployed
2. **Testing**: Comprehensive testing on testnet with identical configuration
3. **Proposal**: DEFAULT\_ADMIN\_ROLE proposes upgrade
4. **Execution**: Authorized upgrade execution
5. **Verification**: Post-upgrade validation and monitoring

### Upgrade Safety

* **Storage Gaps**: All upgradeable contracts include storage gaps for future variables
* **Initialization Guards**: Prevents re-initialization of upgraded contracts
* **Access Control**: Only DEFAULT\_ADMIN\_ROLE can execute upgrades
* **Event Emission**: All upgrades emit events for transparency

### Storage Layout Preservation

When upgrading contracts, the storage layout must be preserved:

* New variables must preserve the slots of existing state
* Existing variables cannot be removed or reordered
* Storage gaps provide buffer for new variables

## Event System

The protocol emits events for settlement and major configuration changes:

### Swap Events

Every requested and internally derived leg emits the unified `Swap` event. It identifies the user, operator, receiver, assets, route, Liquidity Provider domain, resolved amounts, and fee amounts.

### Administrative Events

Dedicated administrative events cover asset registration, pricing, guardrails, fee policy, custody, Liquidity Provider settings, blacklists, and auto-liquidity.

## Extensibility

The protocol's modular architecture enables straightforward extension:

### Adding a New Stablecoin

1. **Deploy Delegate**: Create stablecoin delegate (mint/burn or balance sheet)
2. **Configure Delegate**: Set custody addresses, initial whitelists
3. **Configure USD Value**: Set the route value and optional oracle guardrail
4. **Register with MultiliquidSwap**: Add the stablecoin to protocol configuration
5. **Test Integration**: Validate swaps on testnet
6. **Production Deployment**: Enable on mainnet

### Adding a New RWA

1. **Technical Analysis**: Review RWA token contract for compatibility
2. **Deploy Delegate** (optional): Only if custom risk controls needed
3. **Deploy Price Adapter**: Create adapter for USD pricing
4. **Register with MultiliquidSwap**: Add the RWA and its optional policy adapters
5. **Whitelist Configuration**: Liquidity Providers accept the new RWA
6. **Test Integration**: Validate swaps on testnet
7. **Production Deployment**: Enable on mainnet

***

<Card title="Next: Security & Risk Management" icon="shield-halved" href="/evm/overview/security">
  Review the comprehensive security measures, access controls, and risk management framework
</Card>
