Diffusal

Smart Contracts

Technical reference for all Diffusal protocol smart contracts

This section provides detailed documentation for every smart contract in the Diffusal protocol. Each contract page includes an overview, function reference, storage layout, events, and security considerations.


Contract Architecture

The Diffusal protocol consists of 18 core contracts plus 4 extracted helper contracts, organized into functional layers:

┌─────────────────────────────────────────────────────────────────────┐
│                          PRICING LAYER                              │
│  ┌─────────────────────┐      ┌─────────────────────────────────┐   │
│  │  DiffusalOracle     │◀─────│  DiffusalOptionsQuoter          │   │
│  │  • Price feeds      │      │  • Black-Scholes pricing        │   │
│  │  • Volatility       │      │  • Greeks calculation           │   │
│  │  • Premium rates    │      │  • View-only (no state change)  │   │
│  └─────────────────────┘      └─────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                          TRADING LAYER                              │
│  ┌────────────────────────────┐  ┌────────────────────────────────┐ │
│  │  DiffusalOptionsOrderBook  │  │  DiffusalOptionsRFQ            │ │
│  │  • Event-based orders      │  │  • MMM quote execution         │ │
│  │  • Maker/taker fees        │  │  • Direct MMM trades           │ │
│  │  • Partial fills           │  │  • RFQ-specific fees           │ │
│  │  • Off-chain matching      │  │                                │ │
│  └────────────────────────────┘  └────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                     POSITION MANAGEMENT LAYER                       │
│  ┌──────────────────────────────┐  ┌──────────────────────────────┐ │
│  │ DiffusalOptionsSeriesRegistry│  │DiffusalOptionsPositionManager│ │
│  │  • Series lifecycle          │  │  • Position tracking         │ │
│  │  • Lazy creation             │  │  • Entry premium             │ │
│  │  • TWAP settlement           │  │  • MMM designation           │ │
│  └──────────────────────────────┘  └──────────────────────────────┘ │
│  ┌─────────────────────────────────────────────────────────────────┐│
│  │          DiffusalPortfolioManager                               ││
│  │  • Multiple portfolios per user (gas-bounded liquidations)      ││
│  │  • Max 16 positions per portfolio, cross-margin within portfolio││
│  │  • Position transfer between portfolios                         ││
│  └─────────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                      RISK & COLLATERAL LAYER                        │
│  ┌─────────────────────────┐  ┌─────────────────────────────────┐   │
│  │  DiffusalCollateralVault│  │  DiffusalSettlementEngine       │   │
│  │  • USDC deposits        │  │  • Expired option settlement    │   │
│  │  • Portfolio margin     │  │  • Intrinsic value calculation  │   │
│  │  • Equity calculation   │  │  • Long/short payouts           │   │
│  └─────────────────────────┘  └─────────────────────────────────┘   │
│  ┌─────────────────────────┐  ┌─────────────────────────────────┐   │
│  │DiffusalLiquidationEngine│  │  DiffusalInsuranceFund          │   │
│  │  • Liquidation trigger  │  │  • Fee collection               │   │
│  │  • Penalty pricing      │  │  • Shortfall coverage           │   │
│  │  • Liquidator bounty    │  │  • Bad debt backstop            │   │
│  └─────────────────────────┘  └─────────────────────────────────┘   │
│  ┌─────────────────────────────────────┐  ┌─────────────────────┐   │
│  │DiffusalSettlementReadinessLiquidator│  │ DiffusalPriceHistory│   │
│  │  • Settlement readiness trigger     │  │  • Price snapshots  │   │
│  │  • Cash shortfall liquidation       │  │  • TWAP calculation │   │
│  │  • Non-expiring long liquidation    │  └─────────────────────┘   │
│  └─────────────────────────────────────┘                            │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │                    Extracted Helper Contracts                 │  │
│  │  DiffusalMarginCalculator - Margin calculations (from Vault)  │  │
│  │  DiffusalLiquidationCalculator - View functions for liq info  │  │
│  │  DiffusalLiquidationSettlement - Settlement & bounty logic    │  │
│  │  DiffusalSettlementReadinessCalculator - SR view functions    │  │
│  └───────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────┘

Contract Reference

Core Contracts

ContractPurposeRisk Level
DiffusalOracleMulti-source price aggregation, volatility/premium storageMedium
DiffusalOptionsQuoterBlack-Scholes pricing with Greeks (view-only)Medium

Trading Contracts

ContractPurposeRisk Level
DiffusalOptionsOrderBookEvent-based limit order book with off-chain matchingMedium
DiffusalOptionsRFQRequest-for-Quote execution with Main Market MakersMedium

Position Management

ContractPurposeRisk Level
DiffusalOptionsSeriesRegistryOption series lifecycle and TWAP settlementMedium
DiffusalOptionsPositionManagerPosition tracking and entry premiumMedium
DiffusalPortfolioManagerPortfolio management for gas-bounded liquidationMedium

Risk & Collateral

ContractPurposeRisk Level
DiffusalCollateralVaultUSDC deposits, margin enforcementHigh
DiffusalSettlementEngineExpired option settlementHigh
DiffusalLiquidationEngineUndercollateralized user liquidationHigh
DiffusalSettlementReadinessLiquidatorSettlement readiness liquidationHigh
DiffusalInsuranceFundFee collection and shortfall coverageHigh
DiffusalPriceHistoryPrice snapshots for TWAP settlementMedium

Helper Contracts (Extracted for Contract Size)

ContractPurposeRisk Level
DiffusalMarginCalculatorMargin calculations (extracted from CollateralVault)High
DiffusalLiquidationCalculatorLiquidation view functions (extracted from LiquidationEngine)Medium
DiffusalLiquidationSettlementSettlement & bounty logic (extracted from LiquidationEngine)High
DiffusalSettlementReadinessCalculatorSettlement readiness view functions (extracted from SettlementReadinessLiquidator)Medium

Libraries

LibraryPurposeRisk Level
BlackScholesLibCore option pricing (includes normalCdf)Critical
MarginEngineSPAN-like portfolio margin calculationsCritical
LiquidationLibLiquidation price, proceeds, bounty, sortingCritical
SplitLibPrecise division and splitting utilitiesCritical
ABDKMath64x6464.64 fixed-point arithmetic (external dep)Critical

Precision Model

Understanding the precision model is critical for working with Diffusal contracts. Values flow through multiple precision layers:

LayerFormatDescriptionExample
Oracle8 decimalsPyth/Chainlink price format50% vol = 50_000_000
External InterfaceWAD (1e18)Standard DeFi precision$3000 = 3000e18
Internal Math64.64 fixed-pointABDK library formatint128 values
Collateral6 decimalsUSDC precision$100 = 100_000_000

Conversion Flow

Oracle (int64, 8 dec) → int64ToWad() → WAD (1e18) → toInt128() → 64.64 math → back to WAD

Common Precision Errors

  • Forgetting expo adjustment when reading Pyth prices
  • WAD overflow on large multiplications
  • 64.64 underflow on very small values
  • Volatility must be annualized (σ per year, not per day)

Architectural Patterns

ERC-7201 Namespaced Storage

Most contracts use ERC-7201 namespaced storage to prevent storage collisions during upgrades:

/// @custom:storage-location erc7201:diffusal.storage.Oracle
struct OracleStorage {
    mapping(bytes32 => PairConfig) pairs;
    uint256 riskFreeRate;
    // ...
}

Operator Pattern

Multiple contracts can update positions through an authorized operator pattern:

modifier onlyOperator() {
    require(operators[msg.sender], "NotOperator");
    _;
}

Authorized operators:

  • DiffusalOptionsOrderBook — updates positions on order fills
  • DiffusalOptionsRFQ — updates positions on RFQ fills
  • DiffusalSettlementEngine — zeros positions on settlement
  • DiffusalLiquidationEngine — closes positions on liquidation
  • DiffusalSettlementReadinessLiquidator — transfers positions for settlement readiness

Fee Recipient Model

Trading contracts direct fees to a configurable feeRecipient (typically the InsuranceFund):

IERC20(collateralToken).safeTransfer(feeRecipient, feeAmount);

Contract Dependencies

DiffusalOracle ◀───────────────────────────────────────────┐
       │                                                   │
       ▼                                                   │
DiffusalOptionsQuoter ◀────────────────────────────────────┤
       │                                                   │
       ▼                                                   │
DiffusalOptionsSeriesRegistry ◀────────────────────────────┤
       │                                                   │
       ▼                                                   │
DiffusalOptionsPositionManager ◀───────────────────────────┤
       │                                                   │
       ├──────────────────────────────────────────────────►│
       │                                                   │
       ▼                                                   │
DiffusalPortfolioManager ◀─────────────────────────────────┤
       │  (manages portfolios per user, max 16 pos each)   │
       ▼                                                   │
DiffusalCollateralVault ◀──────────────────────────────────┤
       │                                                   │
       ├───────────────►DiffusalSettlementEngine           │
       │                                                   │
       ├───────────────►DiffusalLiquidationEngine──────────┤
       │                       │                           │
       │                       ▼                           │
       │                DiffusalInsuranceFund              │
       │                       ▲                           │
       ├───────────────►DiffusalSettlementReadinessLiquidator
       │                                                   │
       └───────────────►DiffusalPriceHistory───────────────┘

DiffusalOptionsOrderBook ──────────────────────────────────►PositionManager
                                                           ►SeriesRegistry
                                                           ►CollateralVault
                                                           ►Oracle (tick decimals)

DiffusalOptionsRFQ ────────────────────────────────────────►PositionManager
                                                           ►SeriesRegistry
                                                           ►CollateralVault

Security Model

Access Control Levels

LevelWhoCan Do
OwnerProtocol adminSet parameters, authorize operators, approve liquidators, emergency functions
AdminAuthorized addressesSet volatility, premium, oracle feeds
OperatorTrading/settlement contractsUpdate positions, transfer collateral
Approved LiquidatorOwner-approved addressesExecute liquidations (margin and settlement readiness)
PublicAnyonePrice snapshots, series settlement, view functions

Key Invariants

  1. Position Conservation: For every series, sum of all positions = 0
  2. Collateral Sufficiency: Healthy users have Equity ≥ Maintenance Margin
  3. Settlement Balance: At expiry, payouts to longs = payments from shorts
  4. No Protocol Debt: Protocol never owes users from its own funds

Trust Assumptions

ComponentTrust Level
Position conservationTrustless (enforced by code)
User margin requirementsTrustless (enforced by code)
Liquidation triggersTrustless (enforced by code)
Oracle price feedsTrusted (Pyth/Chainlink)
MMM solvencyTrusted (operational)

Source Code

All contracts are open source and available on GitHub:

  • Main contracts: packages/contracts/src/Diffusal*.sol
  • Interfaces: packages/contracts/src/interfaces/I*.sol
  • Libraries: packages/contracts/src/utils/*.sol

On this page