> ## 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.

# Program Architecture

> Comprehensive technical overview of the Multiliquid Program's modular design and account infrastructure on Solana

## System Overview

The Multiliquid Program is built on a modular, account-based architecture that enables atomic swaps between multiple permissioned Real World Asset (RWA) tokens and multiple stablecoins on Solana. The system is designed for institutional-grade operations with comprehensive access controls, transparent fee structures, and flexible pricing mechanisms.

### Design Principles

1. **Account-Based State**: All state stored in Program-Derived Address (PDA) accounts
2. **Anchor Framework**: Type-safe program development with automatic serialization
3. **Atomicity**: All operations either fully succeed or fully revert within a transaction
4. **Transparency**: All state changes emit comprehensive events via Anchor's event system
5. **Extensibility**: New assets can be integrated without program upgrades

## Core Account System

The swap program's primary account types work together to enable secure, atomic swaps between configured assets.

### How the Accounts Work Together

At the heart of the system, **GlobalConfig** acts as the central configuration holding program-wide settings including the admin, fee wallet, and protocol fees. When an admin registers a new token, an **AssetConfig** account is created to store the token's NAV pricing sources and configuration. When a trading pair is created, a **Pair** account links two configured assets with settings specific to each capital provider, while **LpStableConfig** tracks the capital provider's stablecoin-specific pause state. Token custody is managed through capital provider vault token accounts owned by a capital provider's **VaultAuthority** PDA, with protocol fees collected in fee vault token accounts owned by the global **ProgramAuthority** PDA. This separation of concerns ensures each account focuses on its specialized responsibility while maintaining atomic execution.

### 1. GlobalConfig Account

**PDA Seeds**: `["global_config"]`

The central configuration account managing program-wide settings.

```rust theme={null}
pub struct GlobalConfig {
    pub admin: Pubkey,                      // Program administrator
    pub fee_wallet: Pubkey,                 // Protocol fee collection wallet
    pub protocol_fees_bps: u16,             // Protocol fees (0-9900 basis points)
    pub paused: bool,                       // Program-wide pause flag
    pub pending_new_admin: Option<Pubkey>,  // Two-step admin transfer
    pub bump: u8,                           // PDA bump seed
    pub fee_token_mint: Pubkey,
    pub spread_protocol_fees_bps: u16,
    pub padding: [u8; 94],
}
```

#### Core Responsibilities

* **Admin Management**: Track current admin and pending admin transfer
* **Fee Configuration**: Store protocol fee percentage
* **Global Pause**: Control program-wide pause state
* **Fee Wallet**: Destination for claimed protocol fees

> [card] [View GlobalConfig Reference](https://docs.multiliquid.xyz/svm/instructions/global-config.md)
>
> Program-wide settings and their effects on integrations

### 2. AssetConfig Account

**PDA Seeds**: `["asset", mint_address]`

Per-token configuration storing NAV pricing sources and asset-level controls.

```rust theme={null}
pub struct AssetConfig {
    pub mint_address: Pubkey,               // Token mint address
    pub nav_data: Vec<NavData>,             // Up to 5 NAV pricing sources
    pub price_difference_bps: u16,          // Maximum price divergence tolerance
    pub paused: bool,                       // Asset-level pause flag
    pub version: u8,                        // Configuration version
    pub asset_type: AssetType,              // Rwa or Stable
    pub used_in_pairs_count: u16,           // Number of pairs using this asset
    pub bump: u8,                           // PDA bump seed
    pub padding: Vec<[u8; 128]>,
}
```

#### Asset Types

```rust theme={null}
pub enum AssetType {
    Rwa,     // Real World Asset token
    Stable,  // Stablecoin token
}
```

#### Core Responsibilities

* **NAV Pricing**: Store and manage up to 5 pricing sources per asset
* **Price Validation**: Enforce maximum price divergence between sources
* **Asset Pause**: Independent pause control per asset
* **Usage Tracking**: Track how many pairs reference this asset

> [card] [View AssetConfig Reference](https://docs.multiliquid.xyz/svm/instructions/asset-config.md)
>
> Per-token NAV sources, classification, and pause state

### 3. Pair Account

**PDA Seeds**: `["pair", liquidity_provider, quote_mint, base_mint]`

Trading pair state linking two configured assets with configuration specific to each capital provider.

```rust theme={null}
pub struct Pair {
    pub redemption_fee_bps: u16,            // Fee for Quote → Base swaps
    pub discount_rate_bps: u16,             // Fee for Base → Quote swaps
    pub quote_token_mint_address: Pubkey,   // Quote token mint
    pub base_token_mint_address: Pubkey,    // Base token mint
    pub liquidity_provider: Pubkey,         // Capital provider owner address
    pub paused: bool,                       // Pair-level pause flag
    pub bump: u8,                           // PDA bump seed
    pub padding: [u8; 128],
}
```

#### Core Responsibilities

* **Fee Configuration**: Store redemption and discount fees for each capital provider
* **Pair Identity**: Link specific quote and base tokens
* **Capital Provider Ownership**: Track the capital provider controlling this pair
* **Pair Pause**: Independent pause control per pair

> [card] [View Pair Instructions](https://docs.multiliquid.xyz/svm/instructions/pair.md)
>
> Complete instruction details for pair management

### 4. LpStableConfig Account

**PDA Seeds**: `["lp_stable_config", stable_mint, liquidity_provider]`

Configuration per capital provider and stablecoin for controlling multiple pairs at once.

```rust theme={null}
pub struct LpStableConfig {
    pub quote_token_mint_address: Pubkey,   // Stablecoin mint
    pub paused: bool,                       // Pause all pairs with this config
    pub liquidity_provider: Pubkey,         // Capital provider address
    pub bump: u8,                           // PDA bump seed
    pub padding: [u8; 128],
}
```

#### Core Responsibilities

* **Batch Pause Control**: Pause all pairs for a specific capital provider/stablecoin combination
* **Capital Provider Identification**: Link configuration to specific capital provider
* **Stablecoin Association**: Scope configuration to specific stablecoin

### 5. Vault Accounts

**VaultAuthority PDA Seeds**: `["vault_authority", liquidity_provider]`

**Capital Provider Vault Token Account**: Associated token account for `(mint_address, vault_authority)`

**ProgramAuthority PDA Seeds**: `["program_authority"]`

**Fee Vault Token Account**: Associated token account for `(mint_address, program_authority)`

Token accounts for custody and fee collection.

> [!NOTE]
>
> For permissioned mints, both the listed **Capital Provider** address and its listed **Vault Authority (PDA)** must be separately whitelisted (allowlisted) by the token issuer. Whitelisting the capital provider does not whitelist its PDA. The capital provider's token account and PDA-owned vault ATA must also be thawed before liquidity or swap transfers can succeed.

#### Vault (Liquidity Custody)

* Holds liquidity for a specific capital provider/token combination
* Owned by the capital provider's `vault_authority` PDA, not by the global program authority
* Derived as the associated token account for the token mint and `vault_authority`
* Shared across multiple pairs using the same capital provider and token
* Tracked by `UserVaultInfo` account for usage counting

#### Fee Vault (Protocol Fees)

* Created per asset when asset config is initialized
* Owned by the global `program_authority` PDA
* Protocol fees accumulate in the configured fee-token vault
* Claimed via `claim_fees` instruction to fee wallet

### 6. UserVaultInfo Account

**PDA Seeds**: `["user_vault_info", mint_address, liquidity_provider]`

Tracks vault usage across pairs.

```rust theme={null}
pub struct UserVaultInfo {
    pub user: Pubkey,                       // Capital provider wallet
    pub mint_address: Pubkey,               // Token mint
    pub used: u16,                          // Number of pairs using this vault
    pub bump: u8,                           // PDA bump seed
    pub padding: [u8; 128],
}
```

### 7. Vault and Program Authorities

#### VaultAuthority

**PDA Seeds**: `["vault_authority", liquidity_provider]`

The vault authority is a capital provider's signer PDA used to own and authorize outbound transfers from capital provider liquidity vaults. Every vault for the same capital provider is an associated token account owned by this PDA.

#### ProgramAuthority

**PDA Seeds**: `["program_authority"]`

The program authority is a global signer PDA used for protocol fee vaults. It authorizes outbound transfers from fee vaults during `claim_fees`. It does not own capital provider liquidity vaults.

The capital provider's protocol-fee token account is owned by a separate PDA derived from `["lp_fee_vault_authority", liquidity_provider]`. Swaps debit this account to fund the global fee vault.

### 8. LpProtocolFeeConfig Account

**PDA Seeds**: `["lp_protocol_fee_config", liquidity_provider]`

This optional account stores the capital provider's protocol-fee overrides and `treasury_enabled` flag. Without it, swaps use the global fee settings and Treasury routing is disabled. The admin sets fee overrides; the capital provider controls Treasury routing.

### Treasury Accounts

The Treasury program maintains separate accounts under its own program ID:

| Account | PDA Seeds | Responsibility |
| - | - | - |
| `GlobalConfig` | `["GLOBAL_CONFIG"]` | Manager, oracle authority, receipt mint, yield index, fees, and pause state |
| `AssetConfig` | `["ASSET_CONFIG", asset_mint]` | Supported deposit/redemption asset and NAV configuration |
| `UserPosition` | `["USER_POSITION", owner]` | Principal, accumulated yield, and pending deposits |
| `ApyEntry` | `["APY_ENTRY", day_start_ts.to_le_bytes()]` | Daily net APY and preceding yield index |
| Vault authority | `["VAULT_AUTHORITY"]` | Authority for Treasury asset vaults and the receipt mint |

For swap-integrated Treasury routing, the position owner is the capital provider's swap vault-authority PDA. The capital provider opts in through `set_lp_treasury_enabled`; eligible stablecoin inputs can be deposited into Treasury, and stablecoin output shortfalls can be redeemed from it. The [Pair Management](https://docs.multiliquid.xyz/svm/instructions/pair.md#treasury-routing) page describes the routing and withdrawal behavior.

## Operational Flow

### Swap Execution Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Program
    participant GlobalConfig
    participant AssetConfigs
    participant Pair
    participant LpStableConfig
    participant Vaults
    participant FeeVault

    User->>Program: swap instruction

    Note over Program: 1. Validate pause states
    Program->>GlobalConfig: Check not paused
    Program->>AssetConfigs: Check RWA not paused
    Program->>AssetConfigs: Check Stablecoin and fee asset not paused
    Program->>Pair: Check pair not paused
    Program->>LpStableConfig: Check capital provider config not paused

    Note over Program: 2. Get NAV prices
    Program->>AssetConfigs: Read RWA NAV price
    Program->>AssetConfigs: Read Stablecoin NAV price

    Note over Program: 3. Calculate amounts
    Program->>Program: Apply protocol fees
    Program->>Program: Apply capital provider fees (discount/redemption)
    Program->>Program: Calculate exchange rate

    Note over Program: 4. Execute transfers
    Program->>FeeVault: Move protocol fees from capital provider fee account
    Program->>User: Move output tokens from capital provider vault
    Program->>Vaults: Move input tokens into capital provider vault

    Note over Program: 5. Emit event
    Program->>Program: Emit SwapExecuted event
```

## NAV Pricing System

The program supports four types of NAV (Net Asset Value) pricing sources:

### NavData Types

```rust theme={null}
pub enum NavData {
    /// Read price from a fixed on-chain account address
    U64FixedAddress {
        nav_account_address: Pubkey,        // Account containing price
        nav_price_offset: u16,              // Byte offset in account data
        price_decimals: u8,                 // Price decimals (0-9)
    },

    /// Static hardcoded price value
    Hardcoded {
        hardcoded_price: u64,               // Fixed price value
        price_decimals: u8,                 // Price decimals (0-9)
    },

    /// Pyth oracle push-based pricing
    PythPush {
        pyth_push_account_address: Pubkey,  // Pyth receiver price update account
        feed_id: [u8; 32],                  // Expected Pyth feed id
        max_age_secs: u64,                  // Maximum accepted price age
        max_conf_bps: u16,                  // Maximum accepted confidence ratio
    },

    RedstonePush {
        price_feed_account: Pubkey,
        feed_id: [u8; 32],
        max_age_secs: u64,
    },
}
```

### Price Aggregation

When multiple NAV sources are configured:

1. All prices are normalized to 9 decimal places
2. Price divergence is validated against `price_difference_bps` as `(max_nav - min_nav) / max_nav`
3. If divergence exceeds threshold, the function returns 0 (blocking swaps)
4. Average price is returned if all sources agree within tolerance

> [card] [View Price Source Details](https://docs.multiliquid.xyz/svm/instructions/price-sources.md)
>
> Complete documentation on NAV pricing configuration

## Fee Structure

### Protocol Fees

Configured in `GlobalConfig.protocol_fees_bps`, unless a capital provider protocol-fee configuration overrides the global defaults:

* Range: 0-9900 basis points (0% - 99%)
* Applied to all swaps regardless of direction
* Paid from the capital provider fee-token ATA into the configured global fee vault
* Claimed to `fee_wallet` via `claim_fees` instruction

### Capital Provider Fees

Configured per pair by the capital provider:

| Fee Type | Direction | Description |
| - | - | - |
| `redemption_fee_bps` | Quote → Base | Directional pair fee |
| `discount_rate_bps` | Base → Quote | Directional pair fee |

### Fee Calculation Order

**Quote → Base (QuoteToBase)**:

1. Calculate the pair fee and protocol spread charge from the quote input
2. Deduct both from the input amount
3. Apply the NAV exchange rate to the post-fee amount

**Base → Quote (BaseToQuote)**:

1. Apply the NAV exchange rate
2. Apply the pair fee and protocol spread charge to the quote equivalent
3. Transfer the resulting quote output to the user

Both directions pay protocol fees separately from the capital provider fee-token ATA. RWA/RWA pairs use the sum of both pair fee fields in either direction. Quote/base follows the stored mint order, not an asset-type label.

## Permission Model

The program implements a comprehensive permission model:

### Admin Role

**Controlled by**: `GlobalConfig.admin`

**Permissions**:

* Initialize and update global configuration
* Set and confirm new admin (two-step transfer)
* Initialize asset configurations
* Update asset configurations
* Configure capital provider protocol-fee overrides
* Set pause state for assets and capital provider configs

### Capital Provider Role

**Identified by**: Pair and vault ownership

**Permissions**:

* Initialize pairs and update pair configuration (fees, pause state)
* Close pairs they own
* Add and remove liquidity from their vaults
* Set pause state for their capital provider stable configs

### User Role (Permissionless)

**Anyone can**:

* Execute swaps on active pairs
* Claim protocol fees (sent to fee\_wallet)

### Permission Hierarchy

```mermaid theme={null}
graph TD
    ADMIN[Admin<br/>Global Configuration]
    LP[Capital Providers<br/>Pair Management]
    USER[Users<br/>Swap Execution]

    ADMIN -->|Initializes| ASSETS[Asset Configs]
    LP -->|Creates| PAIRS[Trading Pairs]
    ADMIN -->|Controls| GLOBAL_PAUSE[Global Pause]
    ADMIN -->|Controls| ASSET_PAUSE[Asset Pause]

    LP -->|Configures| PAIRS
    LP -->|Manages| LIQUIDITY[Vaults]
    LP -->|Controls| PAIR_PAUSE[Pair Pause]
    LP -->|Controls| LP_PAUSE[Capital Provider Config Pause]

    USER -->|Executes| SWAPS[Swaps]
    USER -->|Triggers| CLAIM_FEES[Fee Claims]
```

## Event System

The program emits events for all significant state changes using Anchor's event system:

### Swap Events

```rust theme={null}
#[event]
pub struct SwapExecuted {
    pub requestor: Pubkey,          // User executing swap
    pub amount_in: u64,             // Input amount
    pub protocol_fee_amount: u64,   // Protocol fees collected
    pub discount_bps: u16,          // Capital provider fee applied
    pub amount_out: u64,            // Output amount
    pub pair: Pubkey,               // Pair account address
    pub swap_direction: SwapDirection,
    pub swap_type: SwapType,
    pub redemption_fee_bps: u16,
    pub discount_rate_bps: u16,
}
```

### Administrative Events

Events are emitted for configuration changes, pair updates, liquidity operations, and pause state changes.

## Extensibility

The program's modular architecture enables straightforward extension:

### Adding a New Pair

1. **Capital Provider Action**: Call `init_pair` specifying the two mints in canonical byte order
2. **Vaults Created**: Automatic vault creation if needed
3. **Capital Provider Configuration**: The capital provider calls `update_pair` to adjust fees or pause state as needed
4. **Add Liquidity**: The capital provider adds tokens to vaults
5. **Enable Trading**: Pair is ready for swaps

***

> [card] [Next: Security & Access Control](https://docs.multiliquid.xyz/svm/overview/security.md)
>
> Review the comprehensive security measures, access controls, and pause mechanisms


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.