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
| 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 | EIP-712 limit order book for options trading | 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 |
Risk & Collateral
| Contract | Purpose | Risk Level |
|---|---|---|
| DiffusalCollateralVault | USDC deposits, margin enforcement | High |
| DiffusalSettlementEngine | Expired option settlement | High |
| DiffusalLiquidationEngine | Undercollateralized user liquidation | High |
| DiffusalInsuranceFund | Fee collection and shortfall coverage | High |
| DiffusalPriceHistory | Price snapshots for TWAP settlement | Medium |
Libraries
| Library | Purpose | Risk Level |
|---|---|---|
| BlackScholesLib | Core option pricing mathematics | Critical |
| Math64x64Extended | 64.64 fixed-point math, normalCdf | Critical |
| MarginEngine | SPAN-like portfolio margin calculations | 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 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
►CollateralVaultSecurity Model
Access Control Levels
| Level | Who | Can Do |
|---|---|---|
| Owner | Protocol admin | Set parameters, authorize operators, emergency functions |
| Admin | Authorized addresses | Set volatility, premium, oracle feeds |
| Operator | Trading/settlement contracts | Update positions, transfer collateral |
| Public | Anyone | Price snapshots, liquidations, 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