# Spec: Panoptic Protocol
An exchange protocol for trading non-linear perpetuals on the Ethereum Virtual Machine (EVM).
## Introduction
### Cryptocurrency Perpetuals
The cryptocurrency perpetuals market is massive. In fact, over a \$1B in notional value is traded on Deribit, a centralized options exchange on any given day. This is becuase options which are financial instrument that gives a buyer the right but not obligation to buy an asset have been incredibly useful for hedging the volatility that is seen in cryptocurrency markets. Yet it's growth has been limited by the liquidity fragmentation inherent to option contracts. Options volume bale in comparison to perpetual futures which trade upwards of \$60B a day on centralized venues. In an attempt replicate the success of "perpetual futures," Dave White et al. (2021) introduced in \emph{power perpetuals} a mechanism for making an option's convexity exposure perpetual. The derivative achieves this by squaring the price of an underlier to mathematically ensure constant gamma. While the continuous leverage is attractive, the constant gamma exposure could also open the door to hedging volatility in cryptocurrency markets. Yet, volume remains low, constrained by the available liquidity on-chain. For the few power perpetual derivatives that do exist on-chain such as Squeeth, they rely on sophisticated market makers, centralized infrastructure, and oracles. This has caused them to suffer many shortcomings including scaling liquidity with demand and supporting long tail assets.
### CFMMs
CFMMs, short for constant function market makers describe an automated system for pooling liquidity to a single trading function where the payoff of the pooled liquidity produces a non-linear payoff. These payoffs have been shown to be that of a replicated portfolio of options.
In the case of Panoptic, it leverages the liquidity in the Uniswap V3 protocol to create a greater array of payoffs, including leveraged ones.
#### Duality
The duality between a CFMM trading function and its payoff can be expressed as.
## Architecture
[Panoptic](https://arxiv.org/pdf/2204.14232.pdf) is built as a collection of smart contracts that enable the lending and liquidity management of existing Uniswap V3 positions for the purpose of turning them into tokenized options.
The core logic is written in four contracts `PanopticPool.sol` contract where the actual option is minited, burned, and can be managed. Each instance is deployed sperately. Panoptic uses its own for expressing option position called **SFPM** short for **SemiFungiblePositionManager** which inherits ERC-1155. Then there is the `collateralTracker` which is a system for which margining is set for each individual pool.
**Diagram from panoptic repo:**
```ml
contracts/
├── CollateralTracker — "ERC4626 vault where token liquidity from Panoptic Liquidity Providers (PLPs) and collateral for option positions are deposited and collateral requirements are computed"
├── PanopticFactory — "Handles deployment new Panoptic instances on top of Uniswap pools, initial liquidity deployments, and NFT rewards for deployers"
├── PanopticPool — "Coordinates all options trading activity - minting, burning, rolling, force exercises, liquidations"
├── SemiFungiblePositionManager — "The 'engine' of Panoptic - manages all Uniswap V3 positions in the protocol as well as being a more advanced, gas-efficient alternative to NFPM for Uniswap LPs"
├── tokens
│ ├── ERC1155Minimal — "A minimalist implementation of the ERC1155 token standard without metadata"
│ ├── ERC20Minimal — "A minimialist implementation of the ERC20 token standard without metadata"
│ └── interfaces
│ └── IERC20Partial — "An incomplete ERC20 interface containing functions used in Panoptic with some return values omitted to support noncompliant tokens such as USDT"
├── types
│ ├── TickStateCallContext — "Implementation for a custom data type that can hold a current and a median Uniswap pool tick, as well as a caller"
│ ├── LeftRight — "Implementation for a set of custom data types that can hold two 128-bit numbers"
│ ├── LiquidityChunk — "Implementation for a custom data type that can represent a liquidity chunk of a given size in Uniswap - containing a tickLower, tickUpper, and liquidity"
│ └── TokenId — "Implemenation for the custom data type used in the SFPM and Panoptic to encode position data in 256-bit ERC1155 tokenIds - holds a pool identifier and up to four full position legs"
├── libraries
│ ├── CallbackLib — "Library for verifying and decoding Uniswap callbacks"
│ ├── Constants — "Library of Constants used in Panoptic"
│ ├── Errors — "Contains all custom errors used in Panoptic's core contracts"
│ ├── FeesCalc — "Utility to calculate up-to-date swap fees for liquidity chunks"
│ ├── InteractionHelper — "Helpers to perform bytecode-size-heavy interactions with external contracts like batch approvals and metadata queries"
│ ├── Math — "Library of generic math functions like abs(), mulDiv, etc"
│ └── PanopticMath — "Library containing advanced Panoptic/Uniswap-specific functionality such as our TWAP, price conversions, and position sizing math"
│ └── SafeTransferLib — "Safe ERC20 transfer library that gracefully handles missing return values"
├── univ3-libraries
│ ├── TickMath — "Math library for computing sqrt prices from ticks and vice versa"
│ └── LiquidityAmounts — "Provides functions for computing liquidity amounts from token amounts and prices"
├── multicall
│ └── Multicall — "Adds a function to inheriting contracts that allows for multiple calls to be executed in a single transaction"
└── periphery
└── PanopticHelper — "Contains useful position construction and query functions, including collateral checks and account liquidation price finders"
```
### Option properties
Every option is perpetual with
#### Stremia
The "streaming premia" or the continous fee earned by an option seller for the duration that liquidity is deposited in Panoptic.
Each pool in Uniswap V3 has to keep track of fees so that when a LP withdraws and burns their position, they earn back the value of their portfolio and the fees accumlated. To do this, the protocol uses two variables called `feeGrowthGlobal0X128` and `feeGrowthGlobal1X128` as global accumaltors. Where fees owed for each position are in terms of `token0` and `token1`
```
/// @notice Emitted when a position is created/minted
/// @dev Recipient is used to track whether it was minted directly by the user or through an option contract
/// @param caller the caller who created the position. In 99% of cases `caller` == `recipient`.
/// @param tokenId The tokenId of the minted position
/// @param positionSize The number of contracts minted, expressed in terms of the asset
event TokenizedPositionMinted(
address indexed caller,
uint256 indexed tokenId,
uint128 positionSize
);
```
`positionSize` is the number of
Fees accumlate to on deposited V3 positions using the SFPM. The fees earned is accounted as the `s_grossPremia` and `s_owedPremia` is the premia owed after the user withdraws from Panoptic.
ll
`PanopticPool.sol`
`mintOptions`
`burnOptions`
`rollOptions`
UniswapV3
`TickStateCallContent.sol` contains that tick state. `LeftRight.sol`
SemiFungiblePositionManager.sol
SFPM
legs of different sizes
optionRatio: 1
isLong:
tokenType: 0 or 1 (put or call option)
riskPartner:
strike:
width:
pp.mintOptions()
`effectiveLiquidityLimitX32` is the an **optional** parameter that allows us to specify an upper bound of liquidity for a certain chunk.
Option buyers (borrowing a LP position) will set this so that the stremia multiplier is below a certain threshold.
Max slippage value => tickLimit??
### CollateralTracker
An ERC-4626 Vault
* commission fees and options premia
* payments for options
* calculating liquidation bonuses
* collateral requirment of every account and position
A Uniswap LP position is deposited into a CollateralTracker Vault.
### Minting an Option
`legIndex` is 0 to 3 (four legs) and is the position of the leg in the tokenId.
`optionRatio` is the size of the leg compared to other legs.
We need to pass in a positionIDList and specify a size.
Answers from Henry
#### How do fees factor in to how much debt you owe?
By "debt" I assume you mean debt from option sellers to PLPs. We have fixed commission fees, so after you open your position you owe a constant amount of debt (denominated in tokenType) until it is closed.
#### Are you only allowed to borrow the same positions (tick upper and tick lower) that have already been deposited by shorts?
Yep! You cannot open a long position if the underlying (tickLower, tickUpper, tokenType) chunk has not already been sold by a seller - it is not there to remove in the first place!
## Liquidity tracking in Panoptic
Liquidity in "chunks" and moved from `uniswap pool` into panoptic to mint a option position.
* `tokenType`: long or short
* `TickLowLimit`: lower tick limit for price slippage
* `TickHighLimit`: upper tick
All define a specific location for the UniswapV3 Pool.
* `liquidity`:
The total amount of liquidity sitting in Uniswap is the `netLiquidity` and `removeLiquidity` signifying the total liquidity that has been removed to mint option.
`owed`
#### Liquidity Calculation
### Payoff compiler
Each tick is a dirac delta function with the
#### Power Perpetual
A power perpetual is a fixed gamma derivative that aims consolidate liquidity across an options chain in one fungible contract.
On panoptic, one could mint "Squeeth," a power perpetual with a fixed gamma of two, by specifying the `width` paramater when minting an multi-legged option from the `PanopticPool.sol` contract.
Applications include hedging off-chain options, arbitraging volatility, or going long on an underlier with added convexity.