Diffusal
Contracts

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 11 core 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            │ │
│  │  • EIP-712 limit orders    │  │  • MMM quote execution         │ │
│  │  • Maker/taker fees        │  │  • Direct MMM trades           │ │
│  │  • Partial fills           │  │  • RFQ-specific fees           │ │
│  └────────────────────────────┘  └────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                     POSITION MANAGEMENT LAYER                       │
│  ┌──────────────────────────────┐  ┌──────────────────────────────┐ │
│  │ DiffusalOptionsSeriesRegistry│  │DiffusalOptionsPositionManager│ │
│  │  • Series lifecycle          │  │  • Position tracking         │ │
│  │  • Lazy creation             │  │  • Entry premium             │ │
│  │  • TWAP settlement           │  │  • MMM designation           │ │
│  └──────────────────────────────┘  └──────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                      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            │   │
│  └─────────────────────────┘  └─────────────────────────────────┘   │
│  ┌─────────────────────────┐                                        │
│  │  DiffusalPriceHistory   │                                        │
│  │  • Price snapshots      │                                        │
│  │  • TWAP calculation     │                                        │
│  └─────────────────────────┘                                        │
└─────────────────────────────────────────────────────────────────────┘

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
DiffusalOptionsOrderBookEIP-712 limit order book for options tradingMedium
DiffusalOptionsRFQRequest-for-Quote execution with Main Market MakersMedium

Position Management

ContractPurposeRisk Level
DiffusalOptionsSeriesRegistryOption series lifecycle and TWAP settlementMedium
DiffusalOptionsPositionManagerPosition tracking and entry premiumMedium

Risk & Collateral

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

Libraries

LibraryPurposeRisk Level
BlackScholesLibCore option pricing mathematicsCritical
Math64x64Extended64.64 fixed-point math, normalCdfCritical
MarginEngineSPAN-like portfolio margin calculationsCritical

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

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 ◀───────────────────────────┤
       │                                                   │
       ├──────────────────────────────────────────────────►│
       │                                                   │
       ▼                                                   │
DiffusalCollateralVault ◀──────────────────────────────────┤
       │                                                   │
       ├───────────────►DiffusalSettlementEngine           │
       │                                                   │
       ├───────────────►DiffusalLiquidationEngine──────────┤
       │                       │                           │
       │                       ▼                           │
       │                DiffusalInsuranceFund              │
       │                                                   │
       └───────────────►DiffusalPriceHistory───────────────┘

DiffusalOptionsOrderBook ──────────────────────────────────►PositionManager
                                                           ►SeriesRegistry
                                                           ►CollateralVault

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

Security Model

Access Control Levels

LevelWhoCan Do
OwnerProtocol adminSet parameters, authorize operators, emergency functions
AdminAuthorized addressesSet volatility, premium, oracle feeds
OperatorTrading/settlement contractsUpdate positions, transfer collateral
PublicAnyonePrice snapshots, liquidations, 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