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

# Security & Risk Management

> Comprehensive security measures, risk controls, and operational safeguards in the Multiliquid Protocol

## Security Overview

The Multiliquid Protocol is built with institutional-grade security as a core requirement. Every contract, function, and integration point has been designed with security-first principles, incorporating multiple layers of protection, comprehensive access controls, and battle-tested frameworks. See our audits [here](https://cantina.xyz/u/multiliquid).

<CardGroup cols={2}>
  <Card title="Smart Contract Security" icon="code" href="#smart-contract-security">
    OpenZeppelin frameworks and secure coding practices
  </Card>

  <Card title="Access Control" icon="lock" href="#access-control-system">
    Multi-tiered role-based permission model
  </Card>

  <Card title="Risk Management" icon="shield-halved" href="#risk-management-controls">
    Asset-specific controls and volume limits
  </Card>

  <Card title="Emergency Response" icon="triangle-exclamation" href="#emergency-mechanisms">
    Pause capabilities and incident response
  </Card>
</CardGroup>

## Smart Contract Security

### Industry-Standard Frameworks

The protocol is built exclusively using audited, production-tested libraries:

**OpenZeppelin Upgradeable Contracts**

* **Usage**: Access control, proxy patterns, reentrancy protection, safe external operations
* **Security**: Industry-standard, extensively audited by multiple firms
* **Key Modules**:
  * `AccessControlUpgradeable`: Role-based permissions
  * `UUPSUpgradeable`: Secure upgrade mechanism
  * `ReentrancyGuardUpgradeable`: Reentrancy attack prevention
  * `PausableUpgradeable`: Emergency pause functionality

**Solady**

* **Usage**: Gas-optimized mathematical operations
* **Security**: Extensively tested, overflow-safe operations
* **Key Module**: `FixedPointMathLib` for WAD/RAY mathematics

### Core Security Mechanisms

#### 1. Reentrancy Protection

All external-facing functions that involve token transfers are protected against reentrancy attacks:

```solidity theme={null}
function swapIntoStablecoin(...) external nonReentrant whenNotPaused {
    // Checks
    require(validInputs, "Invalid parameters");

    // Effects
    updateInternalState();

    // Interactions
    executeExternalCalls();
}
```

The protocol follows the **Checks-Effects-Interactions** pattern rigorously:

1. **Checks**: Validate all inputs and preconditions
2. **Effects**: Update all internal state
3. **Interactions**: Execute external calls (transfers, delegate calls)

#### 2. SafeERC20 Operations

All ERC20 token interactions use OpenZeppelin's `SafeERC20` library:

* Handles non-standard ERC20 implementations
* Reverts on failed transfers (even if token returns `false`)
* Protects against tokens with unusual return values

```solidity theme={null}
using SafeERC20 for IERC20;

// Safe transfer with automatic revert on failure
IERC20(rwaToken).safeTransferFrom(user, custody, amount);
```

#### 3. Integer Overflow Protection

* **Solidity 0.8.30**: Built-in overflow/underflow protection
* **Checked Arithmetic**: All operations automatically revert on overflow
* **WAD Mathematics**: Consistent 18-decimal precision prevents rounding errors

#### 4. Input Validation

Every function validates inputs before execution:

* Asset IDs must correspond to accepted assets
* Amounts must be non-zero
* Addresses must be non-zero

### Upgrade Safety

#### UUPS Proxy Pattern

The protocol uses the **Universal Upgradeable Proxy Standard (UUPS)**:

**Security Advantages**:

* Upgrade logic lives in implementation (not proxy)
* Smaller proxy contract reduces attack surface
* Explicit authorization required for upgrades
* Event emission for all upgrades

**Upgrade Authorization**:

```solidity theme={null}
function _authorizeUpgrade(address newImplementation)
    internal
    override
    onlyRole(DEFAULT_ADMIN_ROLE)
{
    // Only DEFAULT_ADMIN_ROLE (typically multi-sig) can upgrade
}
```

#### Storage Layout Protection

* **Storage Gaps**: All upgradeable contracts include `__gap` arrays
* **Layout Verification**: Automated tools verify storage compatibility
* **Initialization Guards**: `initializer` modifier prevents re-initialization

```solidity theme={null}
contract MultiliquidSwap is Initializable, UUPSUpgradeable {
    // State variables...

    // Storage gap for future versions
    uint256[43] private __gap;
}
```

## Access Control System

The protocol implements a sophisticated multi-tier permission model using OpenZeppelin's `AccessControl`:

### Global Roles

#### DEFAULT\_ADMIN\_ROLE

**Permissions**:

* Upgrade all UUPS contracts
* Grant and revoke all other internal roles (does not include external role IssuerAdmin)
* Modify core protocol parameters
* Execute emergency recovery operations

**Security Considerations**:

* Should never be held by EOA (Externally Owned Account)
* Requires multi-party consensus for all operations

#### OPERATOR\_ROLE

**Permissions**:

* Accept new RWAs and stablecoins
* Update price adapters
* Configure fee tiers
* Manage operational parameters

**Security Considerations**:

* Should never be held by EOA (Externally Owned Account)
* Requires multi-party consensus for all operations

**Restrictions**:

* Cannot upgrade contracts
* Cannot modify access control
* Cannot directly transfer user funds

#### PAUSE\_ROLE

**Permissions**:

* Pause stablecoin delegate contracts via `pauseMultiliquid()`
* Unpause stablecoin delegate contracts via `unpauseMultiliquid()`

**Intended Holder**: Security operations team

**Use Cases**:

* Smart contract vulnerability discovered
* Suspicious trading activity detected
* Oracle manipulation detected
* Regulatory requirement

<Note>
  On MultiliquidSwap itself, `pause()` and `unpause()` are controlled by `OPERATOR_ROLE`, not a separate `PAUSE_ROLE`.
</Note>

### Asset-Specific Roles

#### Stablecoin Issuer Admin

Each stablecoin delegate has an independent issuer admin role:

**Permissions**:

* Set RWA discount rates for their stablecoin
* Set RWA redemption fees for their stablecoin
* Add/remove RWAs from their whitelist
* Pause their specific delegate
* Configure custody addresses
* Update stablecoin minting/burning parameters

**Security Boundary**:

* Cannot affect other stablecoins
* Cannot modify core protocol logic
* Cannot access other issuers' funds

**Example**:

```solidity theme={null}
stablecoinDelegate.setRWADiscountRate(rwaID, 1e16); // 1% discount
```

#### RWA Issuer Admin

Each RWA delegate (when deployed) has an independent issuer admin role:

**Permissions**:

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

**Security Boundary**:

* Cannot affect other RWAs
* Cannot modify core protocol logic
* Cannot override stablecoin issuer controls

### Permission Hierarchy

```mermaid theme={null}
graph TD
    DEPLOYMENT
    ADMIN[DEFAULT_ADMIN_ROLE<br/>Multi-Sig]
    OP[OPERATOR_ROLE<br/>Ops Multi-Sig]
    PAUSE[PAUSE_ROLE<br/>Security Team]
    SC_ADMIN[Stablecoin Issuer Admin]
    RWA_ADMIN[RWA Issuer Admin]

    
    ADMIN -->|Grants/Revokes| OP
    ADMIN -->|Grants/Revokes| PAUSE
    DEPLOYMENT -->|Assigns| ADMIN
    DEPLOYMENT -->|Assigns| SC_ADMIN
    DEPLOYMENT -->|Assigns| RWA_ADMIN

    ADMIN -->|Can Upgrade| CONTRACTS[Smart Contracts]
    OP -->|Can Configure| PARAMS[Protocol Parameters]
    PAUSE -->|Can Pause| SC_DELEGATE
    OP -->|Can Pause| CONTRACTS
    SC_ADMIN -->|Can Configure| SC_DELEGATE[Stablecoin Delegate]
    RWA_ADMIN -->|Can Configure| RWA_DELEGATE[RWA Delegate]
```

## Risk Management Controls

### Volume Limits

RWA delegates can implement daily volume limits to prevent:

* Market manipulation through large swaps
* Sudden liquidity drains
* Compliance violations

**Implementation Example (ULTRA)**:

* **Daily Limit**: Configurable per wallet
* **Reset Time**: 2pm Singapore Time (UTC+8)
* **Tracking**: Cumulative swap volume over rolling 24-hour window
* **Enforcement**: Automatic rejection when limit exceeded

```solidity theme={null}
// Example: User attempts swap
function checkRWAOut(address user, uint256 amount, bytes calldata metadata)
    external
    returns (bool)
{
    uint256 currentVolume = dailyVolume[user];
    uint256 limit = dailyVolumeLimit[user];

    require(currentVolume + amount <= limit, "Daily limit exceeded");

    dailyVolume[user] += amount;
    return true;
}
```

### Whitelist Management

**Per-Stablecoin RWA Whitelisting**:

* Each stablecoin issuer controls which RWAs they accept
* Granular risk management per issuer
* Prevents unwanted asset exposure

**Whitelist Modification**:

* Only issuer admin can modify their whitelist
* Events emitted for transparency
* Takes effect immediately

**Benefits**:

* Issuers maintain control over their risk profile
* Flexible onboarding without protocol-wide impact
* Compliance alignment with issuer policies

### Slippage Protection

All swap functions require users to specify minimum output amounts:

**ExactIn Swaps** (user specifies input amount):

```solidity theme={null}
// User sends exactly 1000 USDC, expects at least 995 RWA tokens
swapIntoRWA(SwapIntoRWAInputs({
    stablecoinID: usdcID,
    stablecoinAmount: 1000e6,     // Exact input
    rwaID: ultraID,
    rwaAmount: 995e6,             // Minimum output (slippage tolerance)
    ...
}));
```

**ExactOut Swaps** (user specifies output amount):

```solidity theme={null}
// User wants exactly 1000 RWA tokens, willing to pay up to 1005 USDC
swapIntoRWAExactOut(SwapIntoRWAInputs({
    rwaID: ultraID,
    rwaAmount: 1000e6,            // Exact output
    stablecoinID: usdcID,
    stablecoinAmount: 1005e6,     // Maximum input (slippage tolerance)
    ...
}));
```

If the calculated amount violates the slippage bounds, the transaction reverts atomically.

### Discount Rate and Fee Caps

**Discount Rates**:

* Stored as WAD (1e18 = 100%)
* Maximum discount: Configurable, typically 20% (2e17)
* Prevents excessive value extraction

**Redemption Fees**:

* Stored as WAD
* Maximum fee: Configurable, typically 5% (5e16)
* Prevents prohibitive redemption costs

**Acceptance Fees** (Stablecoin-to-Stablecoin):

* Charged when accepting a new stablecoin in a swap
* Configurable per stablecoin pair
* Transparent on-chain calculation

## Emergency Mechanisms

### Pause Functionality

The protocol implements multi-level pause capabilities:

#### Global Pause (MultiliquidSwap)

**Trigger**: `OPERATOR_ROLE` calls `pause()`

**Effects**:

* All swap functions revert
* Price queries still available
* Administrative functions still accessible

**Use Cases**:

* Critical vulnerability discovered
* Oracle manipulation detected
* Regulatory requirement
* Smart contract upgrade preparation

#### Delegate-Level Pause

**Stablecoin Delegate Pause**:

* Triggered by issuer admin or `PAUSE_ROLE`
* Affects only swaps involving that stablecoin delegate
* Other stablecoin delegates remain operational

**RWA Delegate Pause**:

* Triggered by issuer admin or `PAUSE_ROLE`
* Affects only swaps involving that RWA
* Other RWAs remain operational

```javascript theme={null}
// ULTRA continues to work with other stablecoins
multiliquidSwap.swapIntoStablecoin(ultraID, uniformLabsStablecoinID, ...);
```

### Unpause Requirements

Unpausing requires:

1. Root cause analysis completed
2. Fix implemented and tested (if applicable)
3. Security review of changes
4. Explicit unpause transaction by authorized role

## Audit and Review Process

### Pre-Deployment Security

Before mainnet deployment, all contracts undergo:

1. **Extensive Internal Code Review and Testing**
   * 835 Unit Tests (including fuzzing)
   * Security-focused checklist validation
   * Gas optimization review
   * Slither static analysis

2. **Testnet Deployment**
   * Full system deployment on testnet
   * Integration testing with real user flows
   * Stress testing with edge cases
   * Multi-day operational validation

3. **Third-Party Security Audit**
   * Engagement with reputable security firm
   * Comprehensive audit report
   * Remediation of all findings

4. **Final Verification and Deployment**
   * Mainnet deployment scripts used
   * Multi-sig setup verified
   * Role assignments documented

### Post-Deployment Monitoring

Continuous monitoring includes:

* **Event Indexing**: All contract events logged and analyzed
* **Transaction Monitoring**: Unusual patterns detected
* **Price Oracle Monitoring**: Deviation alerts for price feeds

### Incident Response

In the event of a security incident:

1. **Detection**: Monitoring systems alert security team
2. **Assessment**: Rapid evaluation of severity and impact
3. **Pause** (if necessary): Immediate pause of affected components
4. **Communication**: Transparent disclosure to stakeholders
5. **Remediation**: Fix development and testing
6. **Deployment**: Upgrade execution via multi-sig
7. **Post-Mortem**: Detailed report and process improvement

## Operational Security Best Practices

For institutions integrating with the protocol:

### Key Management

* **Use Hardware Wallets**: For all signing operations
* **Multi-Sig Wallets**: Minimum 2-of-3 for operational roles
* **Geographic Distribution**: Key holders in different locations
* **Regular Rotation**: Periodic key refresh schedule

### Transaction Security

* **Simulation**: Use transaction simulation before signing
* **Verification**: Double-check recipient addresses and amounts
* **Gas Limits**: Set reasonable limits to prevent griefing
* **Nonce Management**: Track nonces to prevent replay attacks

## Known Limitations and Assumptions

### Token Compatibility

The protocol assumes:

* Tokens do not implement transfer fees or rebasing
* Tokens do not have transfer requirements that break atomicity
* Tokens follow standard ERC20 behavior
* Price oracles remain available and accurate

If integrating a token with non-standard behavior, additional analysis and potentially custom delegate development is required.

***

## Security Contacts

For security vulnerabilities or concerns:

<Warning>
  **DO NOT** disclose security vulnerabilities publicly. Contact the Multiliquid team directly through secure channels.
</Warning>

* **Website**: [https://www.multiliquid.xyz/](https://www.multiliquid.xyz/)
* **Public Repository**: [https://github.com/uniformlabs/Multiliquid](https://github.com/uniformlabs/Multiliquid)

***

<Info>
  This security documentation is a living document and will be updated as the protocol evolves, new security measures are implemented, and audit results become available.
</Info>

***

<Card title="Next: MultiliquidSwap Contract" icon="file-code" href="/evm/contracts/multiliquid-swap">
  Explore the central orchestrator contract managing all swap operations
</Card>
