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
| Contract | Purpose | Risk Level |
|---|---|---|
| DiffusalOracle | Multi-source price aggregation, volatility/premium storage | Medium |
| DiffusalOptionsQuoter | Black-Scholes pricing with Greeks (view-only) | Medium |
Trading Contracts
| Contract | Purpose | Risk Level |
|---|---|---|
| DiffusalOptionsOrderBook | Event-based limit order book with off-chain matching | Medium |
| DiffusalOptionsRFQ | Request-for-Quote execution with Main Market Makers | Medium |
Position Management
| Contract | Purpose | Risk Level |
|---|---|---|
| DiffusalOptionsSeriesRegistry | Option series lifecycle and TWAP settlement | Medium |
| DiffusalOptionsPositionManager | Position tracking and entry premium | Medium |
| DiffusalPortfolioManager | Portfolio management for gas-bounded liquidation | Medium |
Risk & Collateral
| Contract | Purpose | Risk Level |
|---|---|---|
| DiffusalCollateralVault | USDC deposits, margin enforcement | High |
| DiffusalSettlementEngine | Expired option settlement | High |
| DiffusalLiquidationEngine | Undercollateralized user liquidation | High |
| DiffusalSettlementReadinessLiquidator | Settlement readiness liquidation | High |
| DiffusalInsuranceFund | Fee collection and shortfall coverage | High |
| DiffusalPriceHistory | Price snapshots for TWAP settlement | Medium |
Helper Contracts (Extracted for Contract Size)
| Contract | Purpose | Risk Level |
|---|---|---|
| DiffusalMarginCalculator | Margin calculations (extracted from CollateralVault) | High |
| DiffusalLiquidationCalculator | Liquidation view functions (extracted from LiquidationEngine) | Medium |
| DiffusalLiquidationSettlement | Settlement & bounty logic (extracted from LiquidationEngine) | High |
| DiffusalSettlementReadinessCalculator | Settlement readiness view functions (extracted from SettlementReadinessLiquidator) | Medium |
Libraries
| Library | Purpose | Risk Level |
|---|---|---|
| BlackScholesLib | Core option pricing (includes normalCdf) | Critical |
| MarginEngine | SPAN-like portfolio margin calculations | Critical |
| LiquidationLib | Liquidation price, proceeds, bounty, sorting | Critical |
| SplitLib | Precise division and splitting utilities | Critical |
| ABDKMath64x64 | 64.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:
| Layer | Format | Description | Example |
|---|---|---|---|
| Oracle | 8 decimals | Pyth/Chainlink price format | 50% vol = 50_000_000 |
| External Interface | WAD (1e18) | Standard DeFi precision | $3000 = 3000e18 |
| Internal Math | 64.64 fixed-point | ABDK library format | int128 values |
| Collateral | 6 decimals | USDC precision | $100 = 100_000_000 |
Conversion Flow
Oracle (int64, 8 dec) → int64ToWad() → WAD (1e18) → toInt128() → 64.64 math → back to WADCommon 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 fillsDiffusalOptionsRFQ— updates positions on RFQ fillsDiffusalSettlementEngine— zeros positions on settlementDiffusalLiquidationEngine— closes positions on liquidationDiffusalSettlementReadinessLiquidator— 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
►CollateralVaultSecurity Model
Access Control Levels
| Level | Who | Can Do |
|---|---|---|
| Owner | Protocol admin | Set parameters, authorize operators, approve liquidators, emergency functions |
| Admin | Authorized addresses | Set volatility, premium, oracle feeds |
| Operator | Trading/settlement contracts | Update positions, transfer collateral |
| Approved Liquidator | Owner-approved addresses | Execute liquidations (margin and settlement readiness) |
| Public | Anyone | Price snapshots, series settlement, view functions |
Key Invariants
- Position Conservation: For every series, sum of all positions = 0
- Collateral Sufficiency: Healthy users have Equity ≥ Maintenance Margin
- Settlement Balance: At expiry, payouts to longs = payments from shorts
- No Protocol Debt: Protocol never owes users from its own funds
Trust Assumptions
| Component | Trust Level |
|---|---|
| Position conservation | Trustless (enforced by code) |
| User margin requirements | Trustless (enforced by code) |
| Liquidation triggers | Trustless (enforced by code) |
| Oracle price feeds | Trusted (Pyth/Chainlink) |
| MMM solvency | Trusted (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
Related Documentation
- Protocol Design — High-level protocol architecture
- Margin System — Portfolio margin mechanics
- Liquidation — Liquidation process details
- Black-Scholes — Option pricing formulas