Premia - Next-Generation Options AMM

https://premia.finance

Deployments

DeploymentArbitrumArbitrum GoerliArbitrum Nova
Core Contracts📜📜📜
Option Physically Settled📜📜
Option Rewards📜📜
Vaults📜📜

Development

Install dependencies via Yarn:

yarn install

Setup Husky to format code on commit:

yarn postinstall

Create a .env file with the following values defined:

KeyDescriptionRequired for
API_KEY_ALCHEMYAlchemy API key for node connectivityTests + deployments
API_KEY_ARBISCANArbiscan API key for source code verificationContracts verification
PKEY_DEPLOYER_MAINcontract deployer private key for production use on mainnetsMainnet deployment
PKEY_DEPLOYER_TESTcontract deployer private key for test/development use on testnetsTestnet deployment
PKEY_PROPOSER_MAINSafe multi-sig transaction proposer private key for production use on mainnetsMainnet deployment
PKEY_PROPOSER_TESTSafe multi-sig transaction proposer private key for test/development use on testnetsTestnet deployment

Testing

Test contracts via Forge:

forge test -vv

Generate a code coverage report using Forge:

forge coverage

Generate a HTML code coverage report using Forge :

forge coverage --report lcov && genhtml lcov.info --branch-coverage --output-dir coverage

Deployment

Contracts deployment is done through Hardhat. Available networks : arbitrum, arbitrumNova, goerli, arbitrumGoerli

hardhat run ./scripts/deploy/0000-baseLayer.ts --network goerli

Contracts upgrade

Example to upgrade pools implementation on goerli network :

hardhat run ./scripts/upgrade/0000-pools.ts --network goerli

Other upgrades scripts are available in ./scripts/upgrade to upgrade different components of the protocol.

Docker

To run the code in developer mode using docker, start by building the docker image:

docker build -t premia-v3 .

Then run the docker container by using the command:

MacOS/Linux

docker run -it -u=$(id -u $USER):$(id -g $USER) \
           -v $PWD:/src \
           premia-v3

Windows

docker run -it -v %CD%:/src premia-v3

Upon executing, you will have access to the command line inside the container and will be able to run the commands for forge and hardhat.

Licensing

TBD

Contents

Contents

ChainlinkAdapter

Git Source

Inherits: IChainlinkAdapter, FeedRegistry, OracleAdapter, PriceRepository

This oracle adapter will attempt to use all available feeds to determine prices between pairs

State Variables

STALE_PRICE_THRESHOLD

If the difference between target and last update is greater than the STALE_PRICE_THRESHOLD, the price is considered stale

uint256 internal constant STALE_PRICE_THRESHOLD = 25 hours;

Functions

constructor

constructor(address _wrappedNativeToken, address _wrappedBTCToken)
    FeedRegistry(_wrappedNativeToken, _wrappedBTCToken);

isPairSupported

Returns whether the pair has already been added to the adapter and if it supports the path required for the pair (true, true): Pair is fully supported (false, true): Pair is not supported, but can be added (false, false): Pair cannot be supported

tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order

function isPairSupported(address tokenA, address tokenB) external view returns (bool isCached, bool hasPath);

Parameters

NameTypeDescription
tokenAaddressOne of the pair's tokens
tokenBaddressThe other of the pair's tokens

Returns

NameTypeDescription
isCachedboolTrue if the pair has been cached, false otherwise
hasPathboolTrue if the pair has a valid path, false otherwise

upsertPair

Stores or updates the given token pair data provider configuration. This function will let the adapter take some actions to configure the pair, in preparation for future quotes. Can be called many times in order to let the adapter re-configure for a new context

function upsertPair(address tokenA, address tokenB) external nonReentrant;

Parameters

NameTypeDescription
tokenAaddressOne of the pair's tokens
tokenBaddressThe other of the pair's tokens

getPrice

Returns the most recent price for the given token pair

function getPrice(address tokenIn, address tokenOut) external view returns (UD60x18);

Parameters

NameTypeDescription
tokenInaddressThe exchange token (base token)
tokenOutaddressThe token to quote against (quote token)

Returns

NameTypeDescription
<none>UD60x18The most recent price for the token pair (18 decimals)

getPriceAt

Returns the price closest to target for the given token pair

function getPriceAt(address tokenIn, address tokenOut, uint256 target) external view returns (UD60x18);

Parameters

NameTypeDescription
tokenInaddressThe exchange token (base token)
tokenOutaddressThe token to quote against (quote token)
targetuint256Reference timestamp of the quote

Returns

NameTypeDescription
<none>UD60x18Historical price for the token pair (18 decimals)

_getPriceAt

Returns a price based on the pricing path between tokenIn and tokenOut

function _getPriceAt(address tokenIn, address tokenOut, uint256 target) internal view returns (UD60x18);

describePricingPath

Describes the pricing path used to convert the token to ETH

function describePricingPath(address token)
    external
    view
    returns (AdapterType adapterType, address[][] memory path, uint8[] memory decimals);

Parameters

NameTypeDescription
tokenaddressThe token from where the pricing path starts

Returns

NameTypeDescription
adapterTypeAdapterTypeThe type of adapter
pathaddress[][]The path required to convert the token to ETH
decimalsuint8[]The decimals of each token in the path

pricingPath

Returns the pricing path that will be used when quoting the given pair

tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order

function pricingPath(address tokenA, address tokenB) external view returns (PricingPath);

Parameters

NameTypeDescription
tokenAaddressOne of the pair's tokens
tokenBaddressThe other of the pair's tokens

Returns

NameTypeDescription
<none>PricingPathThe pricing path that will be used

batchRegisterFeedMappings

Registers mappings of ERC20 token, and denomination (ETH, BTC, or USD) to feed

function batchRegisterFeedMappings(FeedMappingArgs[] memory args)
    external
    override(FeedRegistry, IFeedRegistry)
    onlyOwner;

Parameters

NameTypeDescription
argsFeedMappingArgs[]The arguments for the new mappings

setTokenPriceAt

Set the price of token denominated in denomination at the given timestamp

function setTokenPriceAt(address token, address denomination, uint256 timestamp, UD60x18 price)
    external
    override(PriceRepository, IPriceRepository)
    nonReentrant;

Parameters

NameTypeDescription
tokenaddressThe exchange token (ERC20 token)
denominationaddressThe Chainlink token denomination to quote against (ETH, BTC, or USD)
timestampuint256Reference timestamp (in seconds)
priceUD60x18The amount of token denominated in denomination (18 decimals)

_pricingPath

Returns the pricing path between tokenA and tokenB and the mapped tokens (unsorted)

function _pricingPath(address tokenA, address tokenB)
    internal
    view
    returns (PricingPath path, address mappedTokenA, address mappedTokenB);

_getDirectPrice

Returns the price of tokenIn denominated in tokenOut when the pair is either ETH/USD, token/ETH or token/USD

function _getDirectPrice(PricingPath path, address tokenIn, address tokenOut, uint256 target)
    internal
    view
    returns (UD60x18);

_getPriceSameDenomination

Returns the price of tokenIn denominated in tokenOut when both tokens share the same token denomination (either ETH or USD)

function _getPriceSameDenomination(PricingPath path, address tokenIn, address tokenOut, uint256 target)
    internal
    view
    returns (UD60x18);

_getPriceDifferentDenomination

Returns the price of tokenIn denominated in tokenOut when one of the tokens uses ETH as the denomination, and the other USD

function _getPriceDifferentDenomination(PricingPath path, address tokenIn, address tokenOut, uint256 target)
    internal
    view
    returns (UD60x18);

_getPriceWBTCPrice

Returns the price of tokenIn denominated in tokenOut when the pair is token/WBTC

function _getPriceWBTCPrice(address tokenIn, address tokenOut, uint256 target) internal view returns (UD60x18);

_determinePricingPath

Returns the pricing path between tokenA and tokenB

function _determinePricingPath(address tokenA, address tokenB) internal view virtual returns (PricingPath);

_tryToFindPath

Attempts to find the best pricing path for token based on the conversionType, if a feed exists

function _tryToFindPath(
    address token,
    ConversionType conversionType,
    PricingPath preferredPath,
    PricingPath fallbackPath
) internal view returns (PricingPath);

_fetchPrice

Returns the latest price of token denominated in denomination, if target is 0, otherwise we algorithmically search for a price which meets our criteria

function _fetchPrice(address token, address denomination, uint256 target, int8 factor)
    internal
    view
    returns (uint256);

_fetchLatestPrice

Returns the latest price of token denominated in denomination

function _fetchLatestPrice(address token, address denomination) internal view returns (uint256);

_fetchPriceAt

Returns the price of token denominated in denomination at or left of target. If the price left of target is stale, we revert and wait until a price override is set.

function _fetchPriceAt(address token, address denomination, uint256 target, int8 factor)
    internal
    view
    returns (uint256);

_performBinarySearchForRoundData

Performs a binary search to find the round data closest to the target timestamp

function _performBinarySearchForRoundData(
    BinarySearchDataInternal memory binarySearchData,
    address feed,
    uint16 phaseId,
    uint64 nextAggregatorRoundId,
    uint256 target
) internal view returns (BinarySearchDataInternal memory);

_latestRoundData

Try/Catch wrapper for Chainlink aggregator's latestRoundData() function

function _latestRoundData(address feed) internal view returns (uint80, int256, uint256, uint256, uint80);

_getRoundData

Try/Catch wrapper for Chainlink aggregator's getRoundData() function

function _getRoundData(address feed, uint80 roundId) internal view returns (uint80, int256, uint256, uint256, uint80);

_aggregator

Returns the Chainlink aggregator for token / denomination

function _aggregator(address token, address denomination) internal view returns (address[] memory aggregator);

_aggregatorDecimals

Returns decimals for aggregator

function _aggregatorDecimals(address aggregator) internal view returns (uint8);

_getPriceAgainstUSD

Returns the scaled price of token denominated in USD at target

function _getPriceAgainstUSD(address token, uint256 target) internal view returns (UD60x18);

_getPriceAgainstETH

Returns the scaled price of token denominated in ETH at target

function _getPriceAgainstETH(address token, uint256 target) internal view returns (UD60x18);

_getETHUSD

Returns the scaled price of ETH denominated in USD at target

function _getETHUSD(uint256 target) internal view returns (UD60x18);

_getBTCUSD

Returns the scaled price of BTC denominated in USD at target

function _getBTCUSD(uint256 target) internal view returns (UD60x18);

_getWBTCBTC

Returns the scaled price of WBTC denominated in BTC at target

function _getWBTCBTC(uint256 target) internal view returns (UD60x18);

_revertIfPriceLeftOfTargetStale

Revert if the difference between target and updateAt is greater than STALE_PRICE_THRESHOLD

function _revertIfPriceLeftOfTargetStale(uint256 updatedAt, uint256 target) internal pure;

_revertIfInvalidDenomination

Revert if denomination is not a valid

function _revertIfInvalidDenomination(address denomination) internal pure;

ChainlinkAdapterStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.ChainlinkAdapter");

Functions

layout

function layout() internal pure returns (Layout storage l);

formatRoundId

function formatRoundId(uint16 phaseId, uint64 aggregatorRoundId) internal pure returns (uint80);

parseRoundId

function parseRoundId(uint256 roundId) internal pure returns (uint16 phaseId, uint64 aggregatorRoundId);

isUSD

function isUSD(address token) internal pure returns (bool);

isBTC

function isBTC(address token) internal pure returns (bool);

isETH

function isETH(address token) internal pure returns (bool);

Structs

Layout

struct Layout {
    mapping(bytes32 key => IChainlinkAdapter.PricingPath) pricingPath;
    mapping(address token => EnumerableSet.AddressSet tokens) pairedTokens;
}

IChainlinkAdapter

Git Source

Inherits: IOracleAdapter, IFeedRegistry, IPriceRepository

Functions

pricingPath

Returns the pricing path that will be used when quoting the given pair

tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order

function pricingPath(address tokenA, address tokenB) external view returns (PricingPath);

Parameters

NameTypeDescription
tokenAaddressOne of the pair's tokens
tokenBaddressThe other of the pair's tokens

Returns

NameTypeDescription
<none>PricingPathThe pricing path that will be used

Events

UpdatedPathForPair

Emitted when the adapter updates the pricing path for a pair

event UpdatedPathForPair(address tokenA, address tokenB, PricingPath path);

Parameters

NameTypeDescription
tokenAaddressOne of the pair's tokens
tokenBaddressThe other of the pair's tokens
pathPricingPathThe new path

Errors

ChainlinkAdapter__GetRoundDataCallReverted

Thrown when the getRoundData call reverts without a reason

error ChainlinkAdapter__GetRoundDataCallReverted(bytes data);

ChainlinkAdapter__InvalidDenomination

Thrown when the denomination is invalid

error ChainlinkAdapter__InvalidDenomination(address denomination);

ChainlinkAdapter__LatestRoundDataCallReverted

Thrown when the lastRoundData call reverts without a reason

error ChainlinkAdapter__LatestRoundDataCallReverted(bytes data);

ChainlinkAdapter__PriceAtOrLeftOfTargetNotFound

Thrown when a price at or to the left of target is not found

error ChainlinkAdapter__PriceAtOrLeftOfTargetNotFound(address token, address denomination, uint256 target);

ChainlinkAdapter__PriceLeftOfTargetStale

Thrown when price left of target is stale

error ChainlinkAdapter__PriceLeftOfTargetStale(uint256 updatedAt, uint256 target);

Structs

BinarySearchDataInternal

struct BinarySearchDataInternal {
    int256 leftPrice;
    uint256 leftUpdatedAt;
    int256 rightPrice;
    uint256 rightUpdatedAt;
}

Enums

PricingPath

The path that will be used to calculate quotes for a given pair

enum PricingPath {
    NONE,
    ETH_USD,
    TOKEN_USD,
    TOKEN_ETH,
    TOKEN_USD_TOKEN,
    TOKEN_ETH_TOKEN,
    A_USD_ETH_B,
    A_ETH_USD_B,
    TOKEN_USD_BTC_WBTC
}

ConversionType

The conversion type used when determining the token pair pricing path

enum ConversionType {
    TO_BTC,
    TO_USD,
    TO_ETH,
    TO_USD_TO_TOKEN,
    TO_ETH_TO_TOKEN
}

FeedRegistry

Git Source

Inherits: IFeedRegistry

State Variables

WRAPPED_NATIVE_TOKEN

address internal immutable WRAPPED_NATIVE_TOKEN;

WRAPPED_BTC_TOKEN

address internal immutable WRAPPED_BTC_TOKEN;

Functions

constructor

constructor(address _wrappedNativeToken, address _wrappedBTCToken);

batchRegisterFeedMappings

Registers mappings of ERC20 token, and denomination (ETH, BTC, or USD) to feed

function batchRegisterFeedMappings(FeedMappingArgs[] memory args) external virtual;

Parameters

NameTypeDescription
argsFeedMappingArgs[]The arguments for the new mappings

feed

Returns the feed for token and denomination

function feed(address token, address denomination) external view returns (address);

Parameters

NameTypeDescription
tokenaddressThe exchange token (ERC20 token)
denominationaddressThe Chainlink token denomination to quote against (ETH, BTC, or USD)

Returns

NameTypeDescription
<none>addressThe feed address

_feed

Returns the feed for token and denomination

function _feed(address token, address denomination) internal view returns (address);

_feedExists

Returns true if a feed exists for token and denomination

function _feedExists(address token, address denomination) internal view returns (bool);

_tokenToDenomination

Returns the denomination mapped to token, if it has one

Should only map wrapped tokens which are guaranteed to have a 1:1 ratio

function _tokenToDenomination(address token) internal view returns (address);

_mapToDenominationAndSort

Returns the sorted and mapped tokens for tokenA and tokenB

function _mapToDenominationAndSort(address tokenA, address tokenB) internal view returns (address, address);

_mapToDenomination

Returns the mapped tokens for tokenA and tokenB

function _mapToDenomination(address tokenA, address tokenB)
    internal
    view
    returns (address mappedTokenA, address mappedTokenB);

FeedRegistryStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.FeedRegistry");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    mapping(bytes32 key => address feed) feeds;
}

IFeedRegistry

Git Source

Functions

batchRegisterFeedMappings

Registers mappings of ERC20 token, and denomination (ETH, BTC, or USD) to feed

function batchRegisterFeedMappings(FeedMappingArgs[] memory args) external;

Parameters

NameTypeDescription
argsFeedMappingArgs[]The arguments for the new mappings

feed

Returns the feed for token and denomination

function feed(address token, address denomination) external view returns (address);

Parameters

NameTypeDescription
tokenaddressThe exchange token (ERC20 token)
denominationaddressThe Chainlink token denomination to quote against (ETH, BTC, or USD)

Returns

NameTypeDescription
<none>addressThe feed address

Events

FeedMappingsRegistered

Emitted when new price feed mappings are registered

event FeedMappingsRegistered(FeedMappingArgs[] args);

Parameters

NameTypeDescription
argsFeedMappingArgs[]The arguments for the new mappings

Structs

FeedMappingArgs

struct FeedMappingArgs {
    address token;
    address denomination;
    address feed;
}

IOracleAdapter

Git Source

Functions

isPairSupported

Returns whether the pair has already been added to the adapter and if it supports the path required for the pair (true, true): Pair is fully supported (false, true): Pair is not supported, but can be added (false, false): Pair cannot be supported

tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order

function isPairSupported(address tokenA, address tokenB) external view returns (bool isCached, bool hasPath);

Parameters

NameTypeDescription
tokenAaddressOne of the pair's tokens
tokenBaddressThe other of the pair's tokens

Returns

NameTypeDescription
isCachedboolTrue if the pair has been cached, false otherwise
hasPathboolTrue if the pair has a valid path, false otherwise

upsertPair

Stores or updates the given token pair data provider configuration. This function will let the adapter take some actions to configure the pair, in preparation for future quotes. Can be called many times in order to let the adapter re-configure for a new context

function upsertPair(address tokenA, address tokenB) external;

Parameters

NameTypeDescription
tokenAaddressOne of the pair's tokens
tokenBaddressThe other of the pair's tokens

getPrice

Returns the most recent price for the given token pair

function getPrice(address tokenIn, address tokenOut) external view returns (UD60x18);

Parameters

NameTypeDescription
tokenInaddressThe exchange token (base token)
tokenOutaddressThe token to quote against (quote token)

Returns

NameTypeDescription
<none>UD60x18The most recent price for the token pair (18 decimals)

getPriceAt

Returns the price closest to target for the given token pair

function getPriceAt(address tokenIn, address tokenOut, uint256 target) external view returns (UD60x18);

Parameters

NameTypeDescription
tokenInaddressThe exchange token (base token)
tokenOutaddressThe token to quote against (quote token)
targetuint256Reference timestamp of the quote

Returns

NameTypeDescription
<none>UD60x18Historical price for the token pair (18 decimals)

describePricingPath

Describes the pricing path used to convert the token to ETH

function describePricingPath(address token)
    external
    view
    returns (AdapterType adapterType, address[][] memory path, uint8[] memory decimals);

Parameters

NameTypeDescription
tokenaddressThe token from where the pricing path starts

Returns

NameTypeDescription
adapterTypeAdapterTypeThe type of adapter
pathaddress[][]The path required to convert the token to ETH
decimalsuint8[]The decimals of each token in the path

Errors

OracleAdapter__ArrayCannotExpand

Thrown when attempting to increase array size

error OracleAdapter__ArrayCannotExpand(uint256 arrayLength, uint256 size);

OracleAdapter__InvalidTarget

Thrown when the target is zero or before the current block timestamp

error OracleAdapter__InvalidTarget(uint256 target, uint256 blockTimestamp);

OracleAdapter__InvalidPrice

Thrown when the price is non-positive

error OracleAdapter__InvalidPrice(int256 price);

OracleAdapter__PairCannotBeSupported

Thrown when trying to add support for a pair that cannot be supported

error OracleAdapter__PairCannotBeSupported(address tokenA, address tokenB);

OracleAdapter__PairNotSupported

Thrown when trying to execute a quote with a pair that isn't supported

error OracleAdapter__PairNotSupported(address tokenA, address tokenB);

OracleAdapter__TokensAreSame

Thrown when trying to add pair where addresses are the same

error OracleAdapter__TokensAreSame(address tokenA, address tokenB);

OracleAdapter__ZeroAddress

Thrown when one of the parameters is a zero address

error OracleAdapter__ZeroAddress();

Enums

AdapterType

The type of adapter

enum AdapterType {
    None,
    Chainlink
}

IPriceRepository

Git Source

Functions

setTokenPriceAt

Set the price of token denominated in denomination at the given timestamp

function setTokenPriceAt(address token, address denomination, uint256 timestamp, UD60x18 price) external;

Parameters

NameTypeDescription
tokenaddressThe exchange token (ERC20 token)
denominationaddressThe Chainlink token denomination to quote against (ETH, BTC, or USD)
timestampuint256Reference timestamp (in seconds)
priceUD60x18The amount of token denominated in denomination (18 decimals)

Events

PriceUpdate

event PriceUpdate(address indexed token, address indexed denomination, uint256 timestamp, UD60x18 price);

OracleAdapter

Git Source

Inherits: IOracleAdapter

Functions

_scale

Scales amount by factor

function _scale(uint256 amount, int8 factor) internal pure returns (uint256);

_revertIfTargetInvalid

Revert if target is zero or after block.timestamp

function _revertIfTargetInvalid(uint256 target) internal view;

_revertIfPriceInvalid

Revert if price is zero or negative

function _revertIfPriceInvalid(int256 price) internal pure;

_revertIfTokensAreSame

Revert if tokenA has same address as tokenB

function _revertIfTokensAreSame(address tokenA, address tokenB) internal pure;

_revertIfZeroAddress

Revert if tokenA or tokenB are null addresses

function _revertIfZeroAddress(address tokenA, address tokenB) internal pure;

PriceRepository

Git Source

Inherits: IPriceRepository, ReentrancyGuard, RelayerAccessManager

Functions

setTokenPriceAt

Set the price of token denominated in denomination at the given timestamp

function setTokenPriceAt(address token, address denomination, uint256 timestamp, UD60x18 price) external virtual;

Parameters

NameTypeDescription
tokenaddressThe exchange token (ERC20 token)
denominationaddressThe Chainlink token denomination to quote against (ETH, BTC, or USD)
timestampuint256Reference timestamp (in seconds)
priceUD60x18The amount of token denominated in denomination (18 decimals)

_getTokenPriceAt

Returns the price of token denominated in denomination at a given timestamp, if zero, a price has not been recorded

function _getTokenPriceAt(address token, address denomination, uint256 timestamp)
    internal
    view
    returns (UD60x18 price);

PriceRepositoryStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PriceRepository");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    mapping(address token => mapping(address denomination => mapping(uint256 timestamp => UD60x18 price))) prices;
}

Tokens

Git Source

Functions

keyForUnsortedPair

Returns the key for the unsorted tokenA and tokenB

function keyForUnsortedPair(address tokenA, address tokenB) internal pure returns (bytes32);

keyForSortedPair

Returns the key for the sorted tokenA and tokenB

function keyForSortedPair(address tokenA, address tokenB) internal pure returns (bytes32);

sortTokens

Returns the sorted tokenA and tokenB, where sortedA < sortedB

function sortTokens(address tokenA, address tokenB) internal pure returns (address sortedA, address sortedB);

Constants

Git Source

FOREX_DECIMALS

uint8 constant FOREX_DECIMALS = 8;

ETH_DECIMALS

uint8 constant ETH_DECIMALS = 18;

Contents

IPoolFactory

Git Source

Inherits: IPoolFactoryEvents

Functions

isPool

Returns whether the given address is a pool

function isPool(address contractAddress) external view returns (bool);

Parameters

NameTypeDescription
contractAddressaddressThe address to check

Returns

NameTypeDescription
<none>boolWhether the given address is a pool

getPoolAddress

Returns the address of a valid pool, and whether it has been deployed. If the pool configuration is invalid the transaction will revert.

function getPoolAddress(PoolKey calldata k) external view returns (address pool, bool isDeployed);

Parameters

NameTypeDescription
kPoolKeyThe pool key

Returns

NameTypeDescription
pooladdressThe pool address
isDeployedboolWhether the pool has been deployed

deployPool

Deploy a new option pool

function deployPool(PoolKey calldata k) external payable returns (address poolAddress);

Parameters

NameTypeDescription
kPoolKeyThe pool key

Returns

NameTypeDescription
poolAddressaddressThe address of the deployed pool

initializationFee

DEPRECATED: Calculates the initialization fee for a pool

function initializationFee(PoolKey calldata k) external view returns (UD60x18);

Parameters

NameTypeDescription
kPoolKeyThe pool key

Returns

NameTypeDescription
<none>UD60x18The initialization fee (18 decimals)

Errors

PoolFactory__IdenticalAddresses

error PoolFactory__IdenticalAddresses();

PoolFactory__OptionExpired

error PoolFactory__OptionExpired(uint256 maturity);

PoolFactory__OptionMaturityExceedsMax

error PoolFactory__OptionMaturityExceedsMax(uint256 maturity);

PoolFactory__OptionMaturityNot8UTC

error PoolFactory__OptionMaturityNot8UTC(uint256 maturity);

PoolFactory__OptionMaturityNotFriday

error PoolFactory__OptionMaturityNotFriday(uint256 maturity);

PoolFactory__OptionMaturityNotLastFriday

error PoolFactory__OptionMaturityNotLastFriday(uint256 maturity);

PoolFactory__OptionStrikeEqualsZero

error PoolFactory__OptionStrikeEqualsZero();

PoolFactory__OptionStrikeInvalid

error PoolFactory__OptionStrikeInvalid(UD60x18 strike, UD60x18 strikeInterval);

PoolFactory__PoolAlreadyDeployed

error PoolFactory__PoolAlreadyDeployed(address poolAddress);

PoolFactory__TransferNativeTokenFailed

error PoolFactory__TransferNativeTokenFailed();

PoolFactory__ZeroAddress

error PoolFactory__ZeroAddress();

Structs

PoolKey

struct PoolKey {
    address base;
    address quote;
    address oracleAdapter;
    UD60x18 strike;
    uint256 maturity;
    bool isCallPool;
}

IPoolFactoryDeployer

Git Source

Functions

deployPool

Deploy a new option pool

function deployPool(IPoolFactory.PoolKey calldata k) external returns (address poolAddress);

Parameters

NameTypeDescription
kIPoolFactory.PoolKeyThe pool key

Returns

NameTypeDescription
poolAddressaddressThe address of the deployed pool

calculatePoolAddress

Calculate the deterministic address deployment of a pool

function calculatePoolAddress(IPoolFactory.PoolKey calldata k) external view returns (address);

Errors

PoolFactoryDeployer__NotPoolFactory

error PoolFactoryDeployer__NotPoolFactory(address caller);

IPoolFactoryEvents

Git Source

Events

PoolDeployed

event PoolDeployed(
    address indexed base,
    address indexed quote,
    address oracleAdapter,
    UD60x18 strike,
    uint256 maturity,
    bool isCallPool,
    address poolAddress
);

PricingPath

event PricingPath(
    address pool,
    address[][] basePath,
    uint8[] basePathDecimals,
    IOracleAdapter.AdapterType baseAdapterType,
    address[][] quotePath,
    uint8[] quotePathDecimals,
    IOracleAdapter.AdapterType quoteAdapterType
);

PoolFactory

Git Source

Inherits: IPoolFactory, OwnableInternal, ReentrancyGuard

State Variables

DIAMOND

address internal immutable DIAMOND;

POOL_FACTORY_DEPLOYER

address internal immutable POOL_FACTORY_DEPLOYER;

Functions

constructor

constructor(address diamond, address poolFactoryDeployer);

isPool

Returns whether the given address is a pool

function isPool(address contractAddress) external view returns (bool);

Parameters

NameTypeDescription
contractAddressaddressThe address to check

Returns

NameTypeDescription
<none>boolWhether the given address is a pool

getPoolAddress

Returns the address of a valid pool, and whether it has been deployed. If the pool configuration is invalid the transaction will revert.

function getPoolAddress(PoolKey calldata k) external view returns (address pool, bool isDeployed);

Parameters

NameTypeDescription
kPoolKeyThe pool key

Returns

NameTypeDescription
pooladdressThe pool address
isDeployedboolWhether the pool has been deployed

_getPoolAddress

Returns the address of a pool using the encoded poolKey

function _getPoolAddress(bytes32 poolKey) internal view returns (address);

deployPool

Deploy a new option pool

function deployPool(PoolKey calldata k) external payable nonReentrant returns (address poolAddress);

Parameters

NameTypeDescription
kPoolKeyThe pool key

Returns

NameTypeDescription
poolAddressaddressThe address of the deployed pool

initializationFee

DEPRECATED: Calculates the initialization fee for a pool

function initializationFee(IPoolFactory.PoolKey calldata k) public pure returns (UD60x18);

Parameters

NameTypeDescription
kIPoolFactory.PoolKeyThe pool key

Returns

NameTypeDescription
<none>UD60x18The initialization fee (18 decimals)

_safeTransferNativeToken

Safely transfer native token to the given address

function _safeTransferNativeToken(address to, uint256 amount) internal;

_revertIfAddressInvalid

Revert if the base and quote are identical or if the base, quote, or oracle adapter are zero

function _revertIfAddressInvalid(PoolKey calldata k) internal pure;

_revertIfOptionStrikeInvalid

Revert if the strike price is not a multiple of the strike interval

function _revertIfOptionStrikeInvalid(UD60x18 strike) internal pure;

_revertIfOptionMaturityInvalid

Revert if the maturity is invalid

function _revertIfOptionMaturityInvalid(uint256 maturity) internal view;

PoolFactoryDeployer

Git Source

Inherits: IPoolFactoryDeployer, ReentrancyGuard

State Variables

DIAMOND

address public immutable DIAMOND;

POOL_FACTORY

address public immutable POOL_FACTORY;

Functions

constructor

constructor(address diamond, address poolFactory);

deployPool

Deploy a new option pool

function deployPool(IPoolFactory.PoolKey calldata k) external nonReentrant returns (address poolAddress);

Parameters

NameTypeDescription
kIPoolFactory.PoolKeyThe pool key

Returns

NameTypeDescription
poolAddressaddressThe address of the deployed pool

calculatePoolAddress

Calculate the deterministic address deployment of a pool

function calculatePoolAddress(IPoolFactory.PoolKey calldata k) external view returns (address);

_encodePoolProxyArgs

Returns the encoded arguments for the pool proxy using pool key k

function _encodePoolProxyArgs(IPoolFactory.PoolKey calldata k) internal view returns (bytes memory);

_revertIfNotPoolFactory

function _revertIfNotPoolFactory(address caller) internal view;

PoolFactoryProxy

Git Source

Inherits: ProxyUpgradeableOwnable

Functions

constructor

constructor(address implementation) ProxyUpgradeableOwnable(implementation);

PoolFactoryStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PoolFactory");

Functions

layout

function layout() internal pure returns (Layout storage l);

poolKey

Returns the encoded pool key using the pool key k

function poolKey(IPoolFactory.PoolKey memory k) internal pure returns (bytes32);

strikeKey

Returns the encoded strike key using the pool key k

function strikeKey(IPoolFactory.PoolKey memory k) internal pure returns (bytes32);

maturityKey

Returns the encoded maturity key using the pool key k

function maturityKey(IPoolFactory.PoolKey memory k) internal pure returns (bytes32);

Structs

Layout

struct Layout {
    mapping(bytes32 key => address pool) pools;
    mapping(address pool => bool) isPool;
    mapping(bytes32 key => uint256 count) __deprecated_strikeCount;
    mapping(bytes32 key => uint256 count) __deprecated_maturityCount;
    UD60x18 __deprecated_discountPerPool;
    address __deprecated_feeReceiver;
}

Contents

Contents

ILayerZeroEndpoint

Git Source

Inherits: ILayerZeroUserApplicationConfig

Functions

send

Send a LayerZero message to the specified address at a LayerZero endpoint.

function send(
    uint16 dstChainId,
    bytes calldata destination,
    bytes calldata payload,
    address payable refundAddress,
    address zroPaymentAddress,
    bytes calldata adapterParams
) external payable;

Parameters

NameTypeDescription
dstChainIduint16The destination chain identifier
destinationbytesThe address on destination chain (in bytes). address length/format may vary by chains
payloadbytesA custom bytes payload to send to the destination contract
refundAddressaddress payableIf the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
zroPaymentAddressaddressThe address of the ZRO token holder who would pay for the transaction
adapterParamsbytesParameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination

receivePayload

Used by the messaging library to publish verified payload

function receivePayload(
    uint16 srcChainId,
    bytes calldata srcAddress,
    address dstAddress,
    uint64 nonce,
    uint256 gasLimit,
    bytes calldata payload
) external;

Parameters

NameTypeDescription
srcChainIduint16The source chain identifier
srcAddressbytesThe source contract (as bytes) at the source chain
dstAddressaddressThe address on destination chain
nonceuint64The unbound message ordering nonce
gasLimituint256The gas limit for external contract execution
payloadbytesVerified payload to send to the destination contract

getInboundNonce

Get the inboundNonce of a lzApp from a source chain which could be EVM or non-EVM chain

function getInboundNonce(uint16 srcChainId, bytes calldata srcAddress) external view returns (uint64);

Parameters

NameTypeDescription
srcChainIduint16The source chain identifier
srcAddressbytesThe source chain contract address

getOutboundNonce

Get the outboundNonce from this source chain which, consequently, is always an EVM

function getOutboundNonce(uint16 dstChainId, address srcAddress) external view returns (uint64);

Parameters

NameTypeDescription
dstChainIduint16
srcAddressaddressThe source chain contract address

estimateFees

Gets a quote in source native gas, for the amount that send() requires to pay for message delivery

function estimateFees(
    uint16 dstChainId,
    address userApplication,
    bytes calldata payload,
    bool payInZRO,
    bytes calldata adapterParam
) external view returns (uint256 nativeFee, uint256 zroFee);

Parameters

NameTypeDescription
dstChainIduint16The destination chain identifier
userApplicationaddressThe user app address on this EVM chain
payloadbytesThe custom message to send over LayerZero
payInZROboolIf false, user app pays the protocol fee in native token
adapterParambytesParameters for the adapter service, e.g. send some dust native token to dstChain

getChainId

get this Endpoint's immutable source identifier

function getChainId() external view returns (uint16);

retryPayload

The interface to retry failed message on this Endpoint destination

function retryPayload(uint16 srcChainId, bytes calldata srcAddress, bytes calldata payload) external;

Parameters

NameTypeDescription
srcChainIduint16The source chain identifier
srcAddressbytesThe source chain contract address
payloadbytesThe payload to be retried

hasStoredPayload

Query if any STORED payload (message blocking) at the endpoint.

function hasStoredPayload(uint16 srcChainId, bytes calldata srcAddress) external view returns (bool);

Parameters

NameTypeDescription
srcChainIduint16The source chain identifier
srcAddressbytesThe source chain contract address

getSendLibraryAddress

Query if the libraryAddress is valid for sending msgs.

function getSendLibraryAddress(address userApplication) external view returns (address);

Parameters

NameTypeDescription
userApplicationaddressThe user app address on this EVM chain

getReceiveLibraryAddress

Query if the libraryAddress is valid for receiving msgs.

function getReceiveLibraryAddress(address userApplication) external view returns (address);

Parameters

NameTypeDescription
userApplicationaddressThe user app address on this EVM chain

isSendingPayload

Query if the non-reentrancy guard for send() is on

function isSendingPayload() external view returns (bool);

Returns

NameTypeDescription
<none>boolTrue if the guard is on. False otherwise

isReceivingPayload

Query if the non-reentrancy guard for receive() is on

function isReceivingPayload() external view returns (bool);

Returns

NameTypeDescription
<none>boolTrue if the guard is on. False otherwise

getConfig

Get the configuration of the LayerZero messaging library of the specified version

function getConfig(uint16 version, uint16 chainId, address userApplication, uint256 configType)
    external
    view
    returns (bytes memory);

Parameters

NameTypeDescription
versionuint16Messaging library version
chainIduint16The chainId for the pending config change
userApplicationaddressThe contract address of the user application
configTypeuint256Type of configuration. every messaging library has its own convention.

getSendVersion

Get the send() LayerZero messaging library version

function getSendVersion(address userApplication) external view returns (uint16);

Parameters

NameTypeDescription
userApplicationaddressThe contract address of the user application

getReceiveVersion

Get the lzReceive() LayerZero messaging library version

function getReceiveVersion(address userApplication) external view returns (uint16);

Parameters

NameTypeDescription
userApplicationaddressThe contract address of the user application

ILayerZeroReceiver

Git Source

Functions

lzReceive

LayerZero endpoint will invoke this function to deliver the message on the destination

function lzReceive(uint16 srcChainId, bytes calldata srcAddress, uint64 nonce, bytes calldata payload) external;

Parameters

NameTypeDescription
srcChainIduint16The source endpoint identifier
srcAddressbytesThe source sending contract address from the source chain
nonceuint64The ordered message nonce
payloadbytesThe signed payload is the UA bytes has encoded to be sent

ILayerZeroUserApplicationConfig

Git Source

Functions

setConfig

Set the configuration of the LayerZero messaging library of the specified version

function setConfig(uint16 version, uint16 chainId, uint256 configType, bytes calldata config) external;

Parameters

NameTypeDescription
versionuint16Messaging library version
chainIduint16The chainId for the pending config change
configTypeuint256Type of configuration. every messaging library has its own convention.
configbytesConfiguration in the bytes. can encode arbitrary content.

setSendVersion

Set the send() LayerZero messaging library version to version

function setSendVersion(uint16 version) external;

Parameters

NameTypeDescription
versionuint16New messaging library version

setReceiveVersion

Set the lzReceive() LayerZero messaging library version to version

function setReceiveVersion(uint16 version) external;

Parameters

NameTypeDescription
versionuint16NMew messaging library version

forceResumeReceive

Only when the UA needs to resume the message flow in blocking mode and clear the stored payload

function forceResumeReceive(uint16 srcChainId, bytes calldata srcAddress) external;

Parameters

NameTypeDescription
srcChainIduint16The chainId of the source chain
srcAddressbytesThe contract address of the source contract at the source chain

Contents

LzApp

Git Source

Inherits: OwnableInternal, ILayerZeroReceiver, ILayerZeroUserApplicationConfig

State Variables

lzEndpoint

ILayerZeroEndpoint public immutable lzEndpoint;

Functions

constructor

constructor(address endpoint);

lzReceive

LayerZero endpoint will invoke this function to deliver the message on the destination

function lzReceive(uint16 srcChainId, bytes memory srcAddress, uint64 nonce, bytes memory payload) public virtual;

Parameters

NameTypeDescription
srcChainIduint16The source endpoint identifier
srcAddressbytesThe source sending contract address from the source chain
nonceuint64The ordered message nonce
payloadbytesThe signed payload is the UA bytes has encoded to be sent

_blockingLzReceive

function _blockingLzReceive(uint16 srcChainId, bytes memory srcAddress, uint64 nonce, bytes memory payload)
    internal
    virtual;

_lzSend

function _lzSend(
    uint16 dstChainId,
    bytes memory payload,
    address payable refundAddress,
    address zroPaymentAddress,
    bytes memory adapterParams,
    uint256 nativeFee
) internal virtual;

getConfig

function getConfig(uint16 version, uint16 chainId, address, uint256 configType) external view returns (bytes memory);

setConfig

Set the configuration of the LayerZero messaging library of the specified version

function setConfig(uint16 version, uint16 chainId, uint256 configType, bytes calldata config) external onlyOwner;

Parameters

NameTypeDescription
versionuint16Messaging library version
chainIduint16The chainId for the pending config change
configTypeuint256Type of configuration. every messaging library has its own convention.
configbytesConfiguration in the bytes. can encode arbitrary content.

setSendVersion

Set the send() LayerZero messaging library version to version

function setSendVersion(uint16 version) external onlyOwner;

Parameters

NameTypeDescription
versionuint16New messaging library version

setReceiveVersion

Set the lzReceive() LayerZero messaging library version to version

function setReceiveVersion(uint16 version) external onlyOwner;

Parameters

NameTypeDescription
versionuint16NMew messaging library version

forceResumeReceive

Only when the UA needs to resume the message flow in blocking mode and clear the stored payload

function forceResumeReceive(uint16 srcChainId, bytes calldata srcAddress) external onlyOwner;

Parameters

NameTypeDescription
srcChainIduint16The chainId of the source chain
srcAddressbytesThe contract address of the source contract at the source chain

setTrustedRemoteAddress

function setTrustedRemoteAddress(uint16 remoteChainId, bytes calldata remoteAddress) external onlyOwner;

getTrustedRemoteAddress

function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory);

isTrustedRemote

function isTrustedRemote(uint16 srcChainId, bytes memory srcAddress) external view returns (bool);

_isTrustedRemote

function _isTrustedRemote(uint16 srcChainId, bytes memory srcAddress) internal view returns (bool);

Events

SetTrustedRemoteAddress

event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);

Errors

LzApp__InvalidEndpointCaller

error LzApp__InvalidEndpointCaller();

LzApp__InvalidSource

error LzApp__InvalidSource();

LzApp__NotTrustedSource

error LzApp__NotTrustedSource();

LzApp__NoTrustedPathRecord

error LzApp__NoTrustedPathRecord();

LzAppStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.LzApp");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    mapping(uint16 => bytes) trustedRemote;
    address precrime;
}

NonblockingLzApp

Git Source

Inherits: LzApp

Functions

constructor

constructor(address endpoint) LzApp(endpoint);

_blockingLzReceive

function _blockingLzReceive(uint16 srcChainId, bytes memory srcAddress, uint64 nonce, bytes memory payload)
    internal
    virtual
    override;

nonblockingLzReceive

function nonblockingLzReceive(uint16 srcChainId, bytes memory srcAddress, uint64 nonce, bytes memory payload)
    public
    virtual;

_nonblockingLzReceive

function _nonblockingLzReceive(uint16 srcChainId, bytes memory srcAddress, uint64 nonce, bytes memory payload)
    internal
    virtual;

retryMessage

function retryMessage(uint16 srcChainId, bytes memory srcAddress, uint64 nonce, bytes memory payload)
    public
    payable
    virtual;

failedMessages

function failedMessages(uint16 srcChainId, bytes memory srcAddress, uint64 nonce) external view returns (bytes32);

Events

MessageFailed

event MessageFailed(uint16 srcChainId, bytes srcAddress, uint64 nonce, bytes payload, bytes reason);

RetryMessageSuccess

event RetryMessageSuccess(uint16 srcChainId, bytes srcAddress, uint64 nonce, bytes32 payloadHash);

Errors

NonblockingLzApp__CallerNotLzApp

error NonblockingLzApp__CallerNotLzApp();

NonblockingLzApp__InvalidPayload

error NonblockingLzApp__InvalidPayload();

NonblockingLzApp__NoStoredMessage

error NonblockingLzApp__NoStoredMessage();

NonblockingLzAppStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.NonblockingLzApp");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    mapping(uint16 => mapping(bytes => mapping(uint64 => bytes32))) failedMessages;
}

Contents

Contents

IOFT

Git Source

Inherits: IOFTCore, ISolidStateERC20

Interface of the OFT standard

Errors

OFT_InsufficientAllowance

error OFT_InsufficientAllowance();

IOFTCore

Git Source

Inherits: IERC165

Interface of the IOFT core standard

Functions

estimateSendFee

Estimate send token tokenId to (dstChainId, toAddress)

function estimateSendFee(
    uint16 dstChainId,
    bytes calldata toAddress,
    uint256 amount,
    bool useZro,
    bytes calldata adapterParams
) external view returns (uint256 nativeFee, uint256 zroFee);

Parameters

NameTypeDescription
dstChainIduint16L0 defined chain id to send tokens too
toAddressbytesDynamic bytes array which contains the address to whom you are sending tokens to on the dstChain
amountuint256Amount of the tokens to transfer
useZroboolIndicates to use zro to pay L0 fees
adapterParamsbytesFlexible bytes array to indicate messaging adapter services in L0

sendFrom

Send amount amount of token to (dstChainId, toAddress) from from

function sendFrom(
    address from,
    uint16 dstChainId,
    bytes calldata toAddress,
    uint256 amount,
    address payable refundAddress,
    address zroPaymentAddress,
    bytes calldata adapterParams
) external payable;

Parameters

NameTypeDescription
fromaddressThe owner of token
dstChainIduint16The destination chain identifier
toAddressbytesCan be any size depending on the dstChainId.
amountuint256The quantity of tokens in wei
refundAddressaddress payableThe address LayerZero refunds if too much message fee is sent
zroPaymentAddressaddressSet to address(0x0) if not paying in ZRO (LayerZero Token)
adapterParamsbytesFlexible bytes array to indicate messaging adapter services

circulatingSupply

Returns the circulating amount of tokens on current chain

function circulatingSupply() external view returns (uint256);

Events

SendToChain

Emitted when amount tokens are moved from the sender to (dstChainId, toAddress)

event SendToChain(address indexed sender, uint16 indexed dstChainId, bytes indexed toAddress, uint256 amount);

ReceiveFromChain

Emitted when amount tokens are received from srcChainId into the toAddress on the local chain.

event ReceiveFromChain(uint16 indexed srcChainId, bytes indexed srcAddress, address indexed toAddress, uint256 amount);

SetUseCustomAdapterParams

event SetUseCustomAdapterParams(bool _useCustomAdapterParams);

OFT

Git Source

Inherits: OFTCore, SolidStateERC20, IOFT

Functions

constructor

constructor(address lzEndpoint) OFTCore(lzEndpoint);

circulatingSupply

function circulatingSupply() public view virtual override returns (uint256);

_debitFrom

function _debitFrom(address from, uint16, bytes memory, uint256 amount) internal virtual override;

_creditTo

function _creditTo(uint16, address toAddress, uint256 amount) internal virtual override;

OFTCore

Git Source

Inherits: NonblockingLzApp, ERC165Base, IOFTCore

State Variables

PT_SEND

uint16 public constant PT_SEND = 0;

Functions

constructor

constructor(address lzEndpoint) NonblockingLzApp(lzEndpoint);

estimateSendFee

function estimateSendFee(
    uint16 dstChainId,
    bytes memory toAddress,
    uint256 amount,
    bool useZro,
    bytes memory adapterParams
) public view virtual override returns (uint256 nativeFee, uint256 zroFee);

sendFrom

function sendFrom(
    address from,
    uint16 dstChainId,
    bytes memory toAddress,
    uint256 amount,
    address payable refundAddress,
    address zroPaymentAddress,
    bytes memory adapterParams
) public payable virtual override;

_nonblockingLzReceive

function _nonblockingLzReceive(uint16 srcChainId, bytes memory srcAddress, uint64 nonce, bytes memory payload)
    internal
    virtual
    override;

_send

function _send(
    address from,
    uint16 dstChainId,
    bytes memory toAddress,
    uint256 amount,
    address payable refundAddress,
    address zroPaymentAddress,
    bytes memory adapterParams
) internal virtual;

_sendAck

function _sendAck(uint16 srcChainId, bytes memory, uint64, bytes memory payload) internal virtual;

_debitFrom

function _debitFrom(address from, uint16 dstChainId, bytes memory toAddress, uint256 amount) internal virtual;

_creditTo

function _creditTo(uint16 srcChainId, address toAddress, uint256 amount) internal virtual;

OFTCoreStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.OFTCore");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    bool useCustomAdapterParams;
}

OFTProxy

Git Source

Inherits: ProxyUpgradeableOwnable, ERC165BaseInternal

Functions

constructor

constructor(address implementation) ProxyUpgradeableOwnable(implementation);

Contents

BytesLib

Git Source

Author: Gonçalo Sá [email protected]

Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.

Functions

concat

function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory);

concatStorage

function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal;

slice

function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory);

toAddress

function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address);

toUint8

function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8);

toUint16

function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16);

toUint32

function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32);

toUint64

function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64);

toUint96

function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96);

toUint128

function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128);

toUint256

function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256);

toBytes32

function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32);

equal

function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool);

equalStorage

function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool);

Errors

BytesLib__Overflow

error BytesLib__Overflow();

BytesLib__OutOfBounds

error BytesLib__OutOfBounds();

ExcessivelySafeCall

Git Source

State Variables

LOW_28_MASK

uint256 constant LOW_28_MASK = 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;

Functions

excessivelySafeCall

Use when you really really really don't trust the called contract. This prevents the called contract from causing reversion of the caller in as many ways as we can.

The main difference between this and a solidity low-level call is that we limit the number of bytes that the callee can cause to be copied to caller memory. This prevents stupid things like malicious contracts returning 10,000,000 bytes causing a local OOG when copying to memory.

function excessivelySafeCall(address _target, uint256 _gas, uint16 _maxCopy, bytes memory _calldata)
    internal
    returns (bool, bytes memory);

Parameters

NameTypeDescription
_targetaddressThe address to call
_gasuint256The amount of gas to forward to the remote contract
_maxCopyuint16The maximum number of bytes of returndata to copy to memory.
_calldatabytesThe data to send to the remote contract

Returns

NameTypeDescription
<none>boolsuccess and returndata, as .call(). Returndata is capped to _maxCopy bytes.
<none>bytes

excessivelySafeStaticCall

Use when you really really really don't trust the called contract. This prevents the called contract from causing reversion of the caller in as many ways as we can.

The main difference between this and a solidity low-level call is that we limit the number of bytes that the callee can cause to be copied to caller memory. This prevents stupid things like malicious contracts returning 10,000,000 bytes causing a local OOG when copying to memory.

function excessivelySafeStaticCall(address _target, uint256 _gas, uint16 _maxCopy, bytes memory _calldata)
    internal
    view
    returns (bool, bytes memory);

Parameters

NameTypeDescription
_targetaddressThe address to call
_gasuint256The amount of gas to forward to the remote contract
_maxCopyuint16The maximum number of bytes of returndata to copy to memory.
_calldatabytesThe data to send to the remote contract

Returns

NameTypeDescription
<none>boolsuccess and returndata, as .call(). Returndata is capped to _maxCopy bytes.
<none>bytes

swapSelector

Swaps function selectors in encoded contract calls

Allows reuse of encoded calldata for functions with identical argument types but different names. It simply swaps out the first 4 bytes for the new selector. This function modifies memory in place, and should only be used with caution.

function swapSelector(bytes4 _newSelector, bytes memory _buf) internal pure;

Parameters

NameTypeDescription
_newSelectorbytes4The new 4-byte selector
_bufbytesThe encoded contract args

Contents

ArrayUtils

Git Source

Functions

resizeArray

Resizes the array to size, reverts if size > array.length

It is not safe to increase array size this way

function resizeArray(uint8[] memory array, uint256 size) internal pure;

resizeArray

Resizes the array to size, reverts if size > array.length

It is not safe to increase array size this way

function resizeArray(uint256[] memory array, uint256 size) internal pure;

resizeArray

Resizes the array to size, reverts if size > array.length

It is not safe to increase array size this way

function resizeArray(address[] memory array, uint256 size) internal pure;

revertIfTryingToExpand

Reverts if trying to expand array size, as increasing array size through inline assembly is not safe

function revertIfTryingToExpand(uint256 currentLength, uint256 targetSize) internal pure;

Errors

ArrayUtils__ArrayCannotExpand

Thrown when attempting to increase array size

error ArrayUtils__ArrayCannotExpand(uint256 arrayLength, uint256 size);

Constants

Git Source

ZERO

UD60x18 constant ZERO = UD60x18.wrap(0);

ONE_HALF

UD60x18 constant ONE_HALF = UD60x18.wrap(0.5e18);

ONE

UD60x18 constant ONE = UD60x18.wrap(1e18);

TWO

UD60x18 constant TWO = UD60x18.wrap(2e18);

THREE

UD60x18 constant THREE = UD60x18.wrap(3e18);

FIVE

UD60x18 constant FIVE = UD60x18.wrap(5e18);

iZERO

SD59x18 constant iZERO = SD59x18.wrap(0);

iONE

SD59x18 constant iONE = SD59x18.wrap(1e18);

iTWO

SD59x18 constant iTWO = SD59x18.wrap(2e18);

iNINE

SD59x18 constant iNINE = SD59x18.wrap(9e18);

UD50_ZERO

UD50x28 constant UD50_ZERO = UD50x28.wrap(0);

UD50_ONE

UD50x28 constant UD50_ONE = UD50x28.wrap(1e28);

UD50_TWO

UD50x28 constant UD50_TWO = UD50x28.wrap(2e28);

SD49_ZERO

SD49x28 constant SD49_ZERO = SD49x28.wrap(0);

SD49_ONE

SD49x28 constant SD49_ONE = SD49x28.wrap(1e28);

SD49_TWO

SD49x28 constant SD49_TWO = SD49x28.wrap(2e28);

WAD

uint256 constant WAD = 1e18;

ONE_YEAR

uint256 constant ONE_YEAR = 365 days;

ONE_HOUR

uint256 constant ONE_HOUR = 1 hours;

DoublyLinkedListUD60x18

Git Source

Functions

contains

Returns true if the doubly linked list self contains the value

function contains(DoublyLinkedList.Bytes32List storage self, UD60x18 value) internal view returns (bool);

prev

Returns the stored element before value in the doubly linked list self

function prev(DoublyLinkedList.Bytes32List storage self, UD60x18 value) internal view returns (UD60x18);

next

Returns the stored element after value in the doubly linked list self

function next(DoublyLinkedList.Bytes32List storage self, UD60x18 value) internal view returns (UD60x18);

insertBefore

Returns true if newValue was successfully inserted before nextValue in the doubly linked list self

function insertBefore(DoublyLinkedList.Bytes32List storage self, UD60x18 nextValue, UD60x18 newValue)
    internal
    returns (bool status);

insertAfter

Returns true if newValue was successfully inserted after prevValue in the doubly linked list self

function insertAfter(DoublyLinkedList.Bytes32List storage self, UD60x18 prevValue, UD60x18 newValue)
    internal
    returns (bool status);

push

Returns true if value was successfully inserted at the end of the doubly linked list self

function push(DoublyLinkedList.Bytes32List storage self, UD60x18 value) internal returns (bool status);

pop

Removes the first element in the doubly linked list self, returns the removed element value

function pop(DoublyLinkedList.Bytes32List storage self) internal returns (UD60x18 value);

shift

Removes the last element in the doubly linked list self, returns the removed element value

function shift(DoublyLinkedList.Bytes32List storage self) internal returns (UD60x18 value);

unshift

Returns true if value was successfully inserted at the front of the doubly linked list self

function unshift(DoublyLinkedList.Bytes32List storage self, UD60x18 value) internal returns (bool status);

remove

Returns true if value was successfully removed from the doubly linked list self

function remove(DoublyLinkedList.Bytes32List storage self, UD60x18 value) internal returns (bool status);

replace

Returns true if oldValue was successfully replaced with newValue in the doubly linked list self

function replace(DoublyLinkedList.Bytes32List storage self, UD60x18 oldValue, UD60x18 newValue)
    internal
    returns (bool status);

EnumerableSetUD60x18

Git Source

Functions

at

Returns the element at a given index i in the enumerable set self

function at(EnumerableSet.Bytes32Set storage self, uint256 i) internal view returns (UD60x18);

contains

Returns true if the enumerable set self contains value

function contains(EnumerableSet.Bytes32Set storage self, UD60x18 value) internal view returns (bool);

indexOf

Returns the index of value in the enumerable set self

function indexOf(EnumerableSet.Bytes32Set storage self, UD60x18 value) internal view returns (uint256);

length

Returns the number of elements in the enumerable set self

function length(EnumerableSet.Bytes32Set storage self) internal view returns (uint256);

add

Returns true if value is added to the enumerable set self

function add(EnumerableSet.Bytes32Set storage self, UD60x18 value) internal returns (bool);

remove

Returns true if value is removed from the enumerable set self

function remove(EnumerableSet.Bytes32Set storage self, UD60x18 value) internal returns (bool);

toArray

Returns an array of all elements in the enumerable set self

function toArray(EnumerableSet.Bytes32Set storage self) internal view returns (UD60x18[] memory);

IPosition

Git Source

Errors

Position__InvalidOrderType

error Position__InvalidOrderType();

Position__InvalidPositionUpdate

error Position__InvalidPositionUpdate(UD60x18 currentBalance, SD59x18 amount);

Position__LowerGreaterOrEqualUpper

error Position__LowerGreaterOrEqualUpper(UD60x18 lower, UD60x18 upper);

IPricing

Git Source

Errors

Pricing__PriceCannotBeComputedWithinTickRange

error Pricing__PriceCannotBeComputedWithinTickRange();

Pricing__PriceOutOfRange

error Pricing__PriceOutOfRange(UD60x18 lower, UD60x18 upper, UD60x18 marketPrice);

Pricing__UpperNotGreaterThanLower

error Pricing__UpperNotGreaterThanLower(UD60x18 lower, UD60x18 upper);

OptionMath

Git Source

State Variables

ALPHA

SD59x18 internal constant ALPHA = SD59x18.wrap(-6.37309208e18);

LAMBDA

SD59x18 internal constant LAMBDA = SD59x18.wrap(-0.61228883e18);

S1

SD59x18 internal constant S1 = SD59x18.wrap(-0.11105481e18);

S2

SD59x18 internal constant S2 = SD59x18.wrap(0.44334159e18);

SQRT_2PI

int256 internal constant SQRT_2PI = 2_506628274631000502;

MIN_INPUT_PRICE

UD60x18 internal constant MIN_INPUT_PRICE = UD60x18.wrap(1e1);

MAX_INPUT_PRICE

UD60x18 internal constant MAX_INPUT_PRICE = UD60x18.wrap(1e34);

Functions

helperNormal

Helper function to evaluate used to compute the normal CDF approximation

function helperNormal(SD59x18 x) internal pure returns (SD59x18 result);

Parameters

NameTypeDescription
xSD59x18The input to the normal CDF (18 decimals)

Returns

NameTypeDescription
resultSD59x18The value of the evaluated helper function (18 decimals)

normalCdf

Approximation of the normal CDF

The approximation implemented is based on the paper 'Accurate RMM-Based Approximations for the CDF of the Normal Distribution' by Haim Shore

function normalCdf(SD59x18 x) internal pure returns (SD59x18 result);

Parameters

NameTypeDescription
xSD59x18input value to evaluate the normal CDF on, F(Z<=x) (18 decimals)

Returns

NameTypeDescription
resultSD59x18The normal CDF evaluated at x (18 decimals)

normalPdf

Normal Distribution Probability Density Function.

Equal to Z(x) = (1 / σ√2π)e^( (-(x - µ)^2) / 2σ^2 ). Only computes pdf of a distribution with µ = 0 and σ = 1.

function normalPdf(SD59x18 x) internal pure returns (SD59x18 z);

Parameters

NameTypeDescription
xSD59x18Number to get PDF for (18 decimals)

Returns

NameTypeDescription
zSD59x18z-number (18 decimals)

relu

Implementation of the ReLu function f(x)=(x)^+ to compute call / put payoffs

function relu(SD59x18 x) internal pure returns (UD60x18);

Parameters

NameTypeDescription
xSD59x18Input value (18 decimals)

Returns

NameTypeDescription
<none>UD60x18result Output of the relu function (18 decimals)

d1d2

Returns the terms d1 and d2 from the Black-Scholes formula that are used to compute the price of a call / put option.

function d1d2(UD60x18 spot, UD60x18 strike, UD60x18 timeToMaturity, UD60x18 volAnnualized, UD60x18 riskFreeRate)
    internal
    pure
    returns (SD59x18 d1, SD59x18 d2);

Parameters

NameTypeDescription
spotUD60x18The spot price. (18 decimals)
strikeUD60x18The strike price of the option. (18 decimals)
timeToMaturityUD60x18The time until the option expires. (18 decimals)
volAnnualizedUD60x18The percentage volatility of the geometric Brownian motion. (18 decimals)
riskFreeRateUD60x18The rate of the risk-less asset, i.e. the risk-free interest rate. (18 decimals)

Returns

NameTypeDescription
d1SD59x18The term d1 from the Black-Scholes formula. (18 decimals)
d2SD59x18The term d2 from the Black-Scholes formula. (18 decimals)

optionDelta

Calculate option delta

function optionDelta(
    UD60x18 spot,
    UD60x18 strike,
    UD60x18 timeToMaturity,
    UD60x18 volAnnualized,
    UD60x18 riskFreeRate,
    bool isCall
) internal pure returns (SD59x18);

Parameters

NameTypeDescription
spotUD60x18Spot price
strikeUD60x18Strike price
timeToMaturityUD60x18Duration of option contract (in years)
volAnnualizedUD60x18Annualized volatility
riskFreeRateUD60x18
isCallboolwhether to price "call" or "put" option

Returns

NameTypeDescription
<none>SD59x18price Option delta

blackScholesPrice

Calculate the price of an option using the Black-Scholes model

this implementation assumes zero interest

function blackScholesPrice(
    UD60x18 spot,
    UD60x18 strike,
    UD60x18 timeToMaturity,
    UD60x18 volAnnualized,
    UD60x18 riskFreeRate,
    bool isCall
) internal pure returns (UD60x18);

Parameters

NameTypeDescription
spotUD60x18Spot price (18 decimals)
strikeUD60x18Strike price (18 decimals)
timeToMaturityUD60x18Duration of option contract (in years) (18 decimals)
volAnnualizedUD60x18Annualized volatility (18 decimals)
riskFreeRateUD60x18The risk-free rate (18 decimals)
isCallboolwhether to price "call" or "put" option

Returns

NameTypeDescription
<none>UD60x18price The Black-Scholes option price (18 decimals)

is8AMUTC

Returns true if the maturity time is 8AM UTC

function is8AMUTC(uint256 maturity) internal pure returns (bool);

Parameters

NameTypeDescription
maturityuint256The maturity timestamp of the option

Returns

NameTypeDescription
<none>boolTrue if the maturity time is 8AM UTC, false otherwise

isFriday

Returns true if the maturity day is Friday

function isFriday(uint256 maturity) internal pure returns (bool);

Parameters

NameTypeDescription
maturityuint256The maturity timestamp of the option

Returns

NameTypeDescription
<none>boolTrue if the maturity day is Friday, false otherwise

isLastFriday

Returns true if the maturity day is the last Friday of the month

function isLastFriday(uint256 maturity) internal pure returns (bool);

Parameters

NameTypeDescription
maturityuint256The maturity timestamp of the option

Returns

NameTypeDescription
<none>boolTrue if the maturity day is the last Friday of the month, false otherwise

calculateTimeToMaturity

Calculates the time to maturity in seconds

function calculateTimeToMaturity(uint256 maturity) internal view returns (uint256);

Parameters

NameTypeDescription
maturityuint256The maturity timestamp of the option

Returns

NameTypeDescription
<none>uint256Time to maturity in seconds

calculateStrikeInterval

Calculates the strike interval for strike

function calculateStrikeInterval(UD60x18 strike) internal pure returns (UD60x18);

Parameters

NameTypeDescription
strikeUD60x18The price to calculate strike interval for (18 decimals)

Returns

NameTypeDescription
<none>UD60x18The strike interval (18 decimals)

roundToStrikeInterval

Rounds strike using the calculated strike interval

function roundToStrikeInterval(UD60x18 strike) internal pure returns (UD60x18);

Parameters

NameTypeDescription
strikeUD60x18The price to round (18 decimals)

Returns

NameTypeDescription
<none>UD60x18The rounded strike price (18 decimals)

scaleDecimals

Converts a number with inputDecimals, to a number with given amount of decimals

function scaleDecimals(uint256 value, uint8 inputDecimals, uint8 targetDecimals) internal pure returns (uint256);

Parameters

NameTypeDescription
valueuint256The value to convert
inputDecimalsuint8The amount of decimals the input value has
targetDecimalsuint8The amount of decimals to convert to

Returns

NameTypeDescription
<none>uint256The converted value

scaleDecimals

Converts a number with inputDecimals, to a number with given amount of decimals

function scaleDecimals(int256 value, uint8 inputDecimals, uint8 targetDecimals) internal pure returns (int256);

Parameters

NameTypeDescription
valueint256The value to convert
inputDecimalsuint8The amount of decimals the input value has
targetDecimalsuint8The amount of decimals to convert to

Returns

NameTypeDescription
<none>int256The converted value

fromTokenDecimals

Converts a number with decimals, to a UD60x18 type

function fromTokenDecimals(uint256 value, uint8 decimals) internal pure returns (UD60x18);

Parameters

NameTypeDescription
valueuint256The value to convert
decimalsuint8The amount of decimals the value has

Returns

NameTypeDescription
<none>UD60x18The number as a UD60x18

toTokenDecimals

Converts a UD60x18 number with decimals, to it's uint256 type scaled down.

function toTokenDecimals(UD60x18 value, uint8 decimals) internal pure returns (uint256);

Parameters

NameTypeDescription
valueUD60x18The value to convert
decimalsuint8The amount of decimals the value has

Returns

NameTypeDescription
<none>uint256The number as a scaled down uint256

truncate

Truncates a UD60x18 number down to the correct precision.

function truncate(UD60x18 value, uint8 decimals) internal pure returns (UD60x18);

Parameters

NameTypeDescription
valueUD60x18The value to convert
decimalsuint8The amount of decimals the value has

Returns

NameTypeDescription
<none>UD60x18The truncated UD60x18 number

log10Floor

Performs a naive log10 calculation on input returning the floor of the result

function log10Floor(uint256 input) internal pure returns (uint256 count);

computeCLevel

Calculates the C-level given a utilisation value and time since last trade value (duration). (https://www.desmos.com/calculator/0uzv50t7jy)

function computeCLevel(
    UD60x18 utilisation,
    UD60x18 duration,
    UD60x18 alpha,
    UD60x18 minCLevel,
    UD60x18 maxCLevel,
    UD60x18 decayRate
) internal pure returns (UD60x18);

Parameters

NameTypeDescription
utilisationUD60x18The utilisation after some collateral is utilised
durationUD60x18The time since last trade (hours)
alphaUD60x18(needs to be filled in)
minCLevelUD60x18The minimum C-level
maxCLevelUD60x18The maximum C-level
decayRateUD60x18The decay rate of the C-level back down to minimum level (decay/hour)

Returns

NameTypeDescription
<none>UD60x18The C-level corresponding to the post-utilisation value.

computeCLevelGeoMean

Calculates the geo-mean C-level given a utilisation before and after collateral is utilised.

function computeCLevelGeoMean(
    UD60x18 utilisationBefore,
    UD60x18 utilisationAfter,
    UD60x18 duration,
    UD60x18 alpha,
    UD60x18 minCLevel,
    UD60x18 maxCLevel,
    UD60x18 decayRate
) internal pure returns (UD60x18 cLevel);

Parameters

NameTypeDescription
utilisationBeforeUD60x18The utilisation before some collateral is utilised.
utilisationAfterUD60x18The utilisation after some collateral is utilised
durationUD60x18The time since last trade (hours)
alphaUD60x18(needs to be filled in)
minCLevelUD60x18The minimum C-level
maxCLevelUD60x18The maximum C-level
decayRateUD60x18The decay rate of the C-level back down to minimum level (decay/hour)

Returns

NameTypeDescription
cLevelUD60x18The C-level corresponding to the geo-mean of the utilisation value before and after collateral is utilised.

Errors

OptionMath__NonPositiveVol

error OptionMath__NonPositiveVol();

OptionMath__OutOfBoundsPrice

error OptionMath__OutOfBoundsPrice(UD60x18 min, UD60x18 max, UD60x18 price);

OptionMath__Underflow

error OptionMath__Underflow();

OptionMath__UtilisationOutOfBounds

error OptionMath__UtilisationOutOfBounds();

Structs

BlackScholesPriceVarsInternal

struct BlackScholesPriceVarsInternal {
    int256 discountFactor;
    int256 timeScaledVol;
    int256 timeScaledVar;
    int256 timeScaledRiskFreeRate;
}

OptionMathExternal

Git Source

Functions

optionDelta

Calculate option delta

function optionDelta(
    UD60x18 spot,
    UD60x18 strike,
    UD60x18 timeToMaturity,
    UD60x18 volAnnualized,
    UD60x18 riskFreeRate,
    bool isCall
) public pure returns (SD59x18);

Parameters

NameTypeDescription
spotUD60x18Spot price
strikeUD60x18Strike price
timeToMaturityUD60x18Duration of option contract (in years)
volAnnualizedUD60x18Annualized volatility
riskFreeRateUD60x18
isCallboolwhether to price "call" or "put" option

Returns

NameTypeDescription
<none>SD59x18price Option delta

blackScholesPrice

Calculate the price of an option using the Black-Scholes model

this implementation assumes zero interest

function blackScholesPrice(
    UD60x18 spot,
    UD60x18 strike,
    UD60x18 timeToMaturity,
    UD60x18 volAnnualized,
    UD60x18 riskFreeRate,
    bool isCall
) public pure returns (UD60x18);

Parameters

NameTypeDescription
spotUD60x18Spot price (18 decimals)
strikeUD60x18Strike price (18 decimals)
timeToMaturityUD60x18Duration of option contract (in years) (18 decimals)
volAnnualizedUD60x18Annualized volatility (18 decimals)
riskFreeRateUD60x18The risk-free rate (18 decimals)
isCallboolwhether to price "call" or "put" option

Returns

NameTypeDescription
<none>UD60x18price The Black-Scholes option price (18 decimals)

computeCLevel

Calculates the C-level given a utilisation value and time since last trade value (duration). (https://www.desmos.com/calculator/0uzv50t7jy)

function computeCLevel(
    UD60x18 utilisation,
    UD60x18 duration,
    UD60x18 alpha,
    UD60x18 minCLevel,
    UD60x18 maxCLevel,
    UD60x18 decayRate
) public pure returns (UD60x18);

Parameters

NameTypeDescription
utilisationUD60x18The utilisation after some collateral is utilised
durationUD60x18The time since last trade (hours)
alphaUD60x18(needs to be filled in)
minCLevelUD60x18The minimum C-level
maxCLevelUD60x18The maximum C-level
decayRateUD60x18The decay rate of the C-level back down to minimum level (decay/hour)

Returns

NameTypeDescription
<none>UD60x18The C-level corresponding to the post-utilisation value.

computeCLevelGeoMean

Calculates the geo-mean C-level given a utilisation before and after collateral is utilised.

function computeCLevelGeoMean(
    UD60x18 utilisationBefore,
    UD60x18 utilisationAfter,
    UD60x18 duration,
    UD60x18 alpha,
    UD60x18 minCLevel,
    UD60x18 maxCLevel,
    UD60x18 decayRate
) public pure returns (UD60x18 cLevel);

Parameters

NameTypeDescription
utilisationBeforeUD60x18The utilisation before some collateral is utilised.
utilisationAfterUD60x18The utilisation after some collateral is utilised
durationUD60x18The time since last trade (hours)
alphaUD60x18(needs to be filled in)
minCLevelUD60x18The minimum C-level
maxCLevelUD60x18The maximum C-level
decayRateUD60x18The decay rate of the C-level back down to minimum level (decay/hour)

Returns

NameTypeDescription
cLevelUD60x18The C-level corresponding to the geo-mean of the utilisation value before and after collateral is utilised.

PRBMathExtra

Git Source

Functions

intoSD49x28

function intoSD49x28(SD59x18 x) internal pure returns (SD49x28 result);

intoUD50x28

function intoUD50x28(UD60x18 x) internal pure returns (UD50x28 result);

max

Returns the greater of two numbers a and b

function max(UD60x18 a, UD60x18 b) internal pure returns (UD60x18);

min

Returns the lesser of two numbers a and b

function min(UD60x18 a, UD60x18 b) internal pure returns (UD60x18);

max

Returns the greater of two numbers a and b

function max(SD59x18 a, SD59x18 b) internal pure returns (SD59x18);

min

Returns the lesser of two numbers a and b

function min(SD59x18 a, SD59x18 b) internal pure returns (SD59x18);

add

Returns the sum of a and b

function add(UD60x18 a, SD59x18 b) internal pure returns (UD60x18);

sub

Returns the difference of a and b

function sub(UD60x18 a, SD59x18 b) internal pure returns (UD60x18);

max

Returns the greater of two numbers a and b

function max(UD50x28 a, UD50x28 b) internal pure returns (UD50x28);

min

Returns the lesser of two numbers a and b

function min(UD50x28 a, UD50x28 b) internal pure returns (UD50x28);

max

Returns the greater of two numbers a and b

function max(SD49x28 a, SD49x28 b) internal pure returns (SD49x28);

min

Returns the lesser of two numbers a and b

function min(SD49x28 a, SD49x28 b) internal pure returns (SD49x28);

add

Returns the sum of a and b

function add(UD50x28 a, SD49x28 b) internal pure returns (UD50x28);

sub

Returns the difference of a and b

function sub(UD50x28 a, SD49x28 b) internal pure returns (UD50x28);

roundToNearestUD60x18

Rounds an UD50x28 to the nearest UD60x18

function roundToNearestUD60x18(UD50x28 value) internal pure returns (UD60x18 result);

Errors

SD59x18_IntoSD49x28_Overflow

error SD59x18_IntoSD49x28_Overflow(SD59x18 x);

UD60x18_IntoUD50x28_Overflow

error UD60x18_IntoUD50x28_Overflow(UD60x18 x);

PoolName

Git Source

Functions

name

Returns pool parameters as human-readable text

function name(address base, address quote, uint256 maturity, uint256 strike, bool isCallPool)
    internal
    view
    returns (string memory);

strikeToString

Converts the strike into a string

function strikeToString(uint256 strike) internal pure returns (string memory);

maturityToString

Converts the maturity into a string

function maturityToString(uint256 maturity) internal pure returns (string memory);

monthToString

Converts the month into a string

function monthToString(uint256 month) internal pure returns (string memory);

Position

Git Source

Keeps track of LP positions. Stores the lower and upper Ticks of a user's range order, and tracks the pro-rata exposure of the order.

Functions

keyHash

Returns the position key hash for self

function keyHash(Key memory self) internal pure returns (bytes32);

keyHash

Returns the position key hash for self

function keyHash(KeyInternal memory self) internal pure returns (bytes32);

toKeyInternal

Returns the internal position key for self

function toKeyInternal(Key memory self, UD60x18 strike, bool isCall) internal pure returns (KeyInternal memory);

Parameters

NameTypeDescription
selfKey
strikeUD60x18The strike of the option (18 decimals)
isCallbool

isShort

Returns true if the position orderType is short

function isShort(OrderType orderType) internal pure returns (bool);

isLong

Returns true if the position orderType is long

function isLong(OrderType orderType) internal pure returns (bool);

pieceWiseLinear

Returns the percentage by which the market price has passed through the lower and upper prices from left to right.

Usage:
CS order: f(x) defines the amount of shorts of a CS order holding one unit of liquidity.
LC order: (1 - f(x)) defines the amount of longs of a LC order holding one unit of liquidity.
Function definition:
case 1. f(x) = 0                                for x < lower
case 2. f(x) = (x - lower) / (upper - lower)    for lower <= x <= upper
case 3. f(x) = 1                                for x > upper
function pieceWiseLinear(KeyInternal memory self, UD50x28 price) internal pure returns (UD50x28);

pieceWiseQuadratic

Returns the amount of 'bid-side' collateral associated to a range order with one unit of liquidity.

Usage:
CS order: bid-side collateral defines the premiums generated from selling options.
LC order: bid-side collateral defines the collateral used to pay for buying long options.
Function definition:
case 1. f(x) = 0                                            for x < lower
case 2. f(x) = (price**2 - lower) / [2 * (upper - lower)]   for lower <= x <= upper
case 3. f(x) = (upper + lower) / 2                          for x > upper
function pieceWiseQuadratic(KeyInternal memory self, UD50x28 price) internal pure returns (UD50x28);

collateralToContracts

Converts _collateral to the amount of contracts normalized to 18 decimals

function collateralToContracts(UD60x18 _collateral, UD60x18 strike, bool isCall) internal pure returns (UD60x18);

Parameters

NameTypeDescription
_collateralUD60x18
strikeUD60x18The strike price (18 decimals)
isCallbool

contractsToCollateral

Converts _contracts to the amount of collateral normalized to 18 decimals

WARNING: Decimals needs to be scaled before using this amount for collateral transfers

function contractsToCollateral(UD60x18 _contracts, UD60x18 strike, bool isCall) internal pure returns (UD60x18);

Parameters

NameTypeDescription
_contractsUD60x18
strikeUD60x18The strike price (18 decimals)
isCallbool

collateralToContracts

Converts _collateral to the amount of contracts normalized to 28 decimals

function collateralToContracts(UD50x28 _collateral, UD60x18 strike, bool isCall) internal pure returns (UD50x28);

Parameters

NameTypeDescription
_collateralUD50x28
strikeUD60x18The strike price (18 decimals)
isCallbool

contractsToCollateral

Converts _contracts to the amount of collateral normalized to 28 decimals

WARNING: Decimals needs to be scaled before using this amount for collateral transfers

function contractsToCollateral(UD50x28 _contracts, UD60x18 strike, bool isCall) internal pure returns (UD50x28);

Parameters

NameTypeDescription
_contractsUD50x28
strikeUD60x18The strike price (18 decimals)
isCallbool

liquidityPerTick

Returns the per-tick liquidity phi (delta) for a specific position key self

function liquidityPerTick(KeyInternal memory self, UD60x18 size) internal pure returns (UD50x28);

Parameters

NameTypeDescription
selfKeyInternal
sizeUD60x18The contract amount (18 decimals)

bid

Returns the bid collateral (18 decimals) either used to buy back options or revenue/ income generated from underwriting / selling options.

For a <= p <= b we have:
bid(p; a, b) = [ (p - a) / (b - a) ] * [ (a + p)  / 2 ]
= (p^2 - a^2) / [2 * (b - a)]
function bid(KeyInternal memory self, UD60x18 size, UD50x28 price) internal pure returns (UD60x18);

Parameters

NameTypeDescription
selfKeyInternalThe internal position key
sizeUD60x18The contract amount (18 decimals)
priceUD50x28The current market price (28 decimals)

collateral

Returns the total collateral (18 decimals) held by the position key self. Note that here we do not distinguish between ask- and bid-side collateral. This increases the capital efficiency of the range order

function collateral(KeyInternal memory self, UD60x18 size, UD50x28 price) internal pure returns (UD60x18 _collateral);

Parameters

NameTypeDescription
selfKeyInternal
sizeUD60x18The contract amount (18 decimals)
priceUD50x28The current market price (28 decimals)

contracts

Returns the total contracts (18 decimals) held by the position key self

function contracts(KeyInternal memory self, UD60x18 size, UD50x28 price) internal pure returns (UD60x18);

Parameters

NameTypeDescription
selfKeyInternal
sizeUD60x18The contract amount (18 decimals)
priceUD50x28The current market price (28 decimals)

long

Returns the number of long contracts (18 decimals) held in position self at current price

function long(KeyInternal memory self, UD60x18 size, UD50x28 price) internal pure returns (UD60x18);

Parameters

NameTypeDescription
selfKeyInternal
sizeUD60x18The contract amount (18 decimals)
priceUD50x28The current market price (28 decimals)

short

Returns the number of short contracts (18 decimals) held in position self at current price

function short(KeyInternal memory self, UD60x18 size, UD50x28 price) internal pure returns (UD60x18);

Parameters

NameTypeDescription
selfKeyInternal
sizeUD60x18The contract amount (18 decimals)
priceUD50x28The current market price (28 decimals)

calculatePositionUpdate

Calculate the update for the Position. Either increments them in case withdraw is False (i.e. in case there is a deposit) and otherwise decreases them. Returns the change in collateral, longs, shorts. These are transferred to (withdrawal)or transferred from (deposit) Position.operator.

function calculatePositionUpdate(KeyInternal memory self, UD60x18 currentBalance, SD59x18 amount, UD50x28 price)
    internal
    pure
    returns (Delta memory delta);

Parameters

NameTypeDescription
selfKeyInternal
currentBalanceUD60x18The current balance of tokens (18 decimals)
amountSD59x18The number of tokens deposited or withdrawn (18 decimals)
priceUD50x28The current market price, used to compute the change in collateral, long and shorts due to the change in tokens (28 decimals)

Returns

NameTypeDescription
deltaDeltaAbsolute change in collateral / longs / shorts due to change in tokens

revertIfLowerGreaterOrEqualUpper

Revert if lower is greater or equal to upper

function revertIfLowerGreaterOrEqualUpper(UD60x18 lower, UD60x18 upper) internal pure;

Structs

Key

struct Key {
    address owner;
    address operator;
    UD60x18 lower;
    UD60x18 upper;
    OrderType orderType;
}

KeyInternal

All the data used to calculate the key of the position

struct KeyInternal {
    address owner;
    address operator;
    UD60x18 lower;
    UD60x18 upper;
    OrderType orderType;
    bool isCall;
    UD60x18 strike;
}

Data

All the data required to be saved in storage

struct Data {
    SD49x28 lastFeeRate;
    UD60x18 claimableFees;
    uint256 lastDeposit;
}

Delta

struct Delta {
    SD59x18 collateral;
    SD59x18 longs;
    SD59x18 shorts;
}

Enums

OrderType

The order type of a position

enum OrderType {
    CSUP,
    CS,
    LC
}

Pricing

Git Source

This library implements the functions necessary for computing price movements within a tick range.

WARNING: This library should not be used for computations that span multiple ticks. Instead, the user should use the functions of this library to simplify computations for more complex price calculations.

Functions

proportion

Returns the percentage by which the market price has passed through the lower and upper prices from left to right. Reverts if the market price is not within the range of the lower and upper prices.

function proportion(UD60x18 lower, UD60x18 upper, UD50x28 marketPrice) internal pure returns (UD50x28);

proportion

Returns the percentage by which the market price has passed through the lower and upper prices from left to right. Reverts if the market price is not within the range of the lower and upper prices.

function proportion(Args memory args) internal pure returns (UD50x28);

amountOfTicksBetween

Find the number of ticks of an active tick range. Used to compute the aggregate, bid or ask liquidity either of the pool or the range order.

min_tick_distance = 0.01
lower = 0.01
upper = 0.03
num_ticks = 2
0.01               0.02               0.03
|xxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxxx|
Then there are two active ticks, 0.01 and 0.02, within the active tick range.
function amountOfTicksBetween(UD60x18 lower, UD60x18 upper) internal pure returns (UD60x18);

amountOfTicksBetween

Returns the number of ticks between args.lower and args.upper

function amountOfTicksBetween(Args memory args) internal pure returns (UD60x18);

liquidity

Returns the liquidity between args.lower and args.upper

function liquidity(Args memory args) internal pure returns (UD60x18);

bidLiquidity

Returns the bid-side liquidity between args.lower and args.upper

function bidLiquidity(Args memory args) internal pure returns (UD60x18);

askLiquidity

Returns the ask-side liquidity between args.lower and args.upper

function askLiquidity(Args memory args) internal pure returns (UD60x18);

maxTradeSize

Returns the maximum trade size (askLiquidity or bidLiquidity depending on the TradeSide).

function maxTradeSize(Args memory args) internal pure returns (UD60x18);

price

Computes price reached from the current lower/upper tick after buying/selling trade_size amount of contracts

function price(Args memory args, UD60x18 tradeSize) internal pure returns (UD50x28);

nextPrice

Gets the next market price within a tick range after buying/selling tradeSize amount of contracts

function nextPrice(Args memory args, UD60x18 tradeSize) internal pure returns (UD50x28);

Structs

Args

struct Args {
    UD50x28 liquidityRate;
    UD50x28 marketPrice;
    UD60x18 lower;
    UD60x18 upper;
    bool isBuy;
}

SD49x28

Git Source

type SD49x28 is int256;

SD49x28_Mul_InputTooSmall

Git Source

error SD49x28_Mul_InputTooSmall();

SD49x28_Mul_Overflow

Git Source

error SD49x28_Mul_Overflow(SD49x28 x, SD49x28 y);

SD49x28_Div_InputTooSmall

Git Source

error SD49x28_Div_InputTooSmall();

SD49x28_Div_Overflow

Git Source

error SD49x28_Div_Overflow(SD49x28 x, SD49x28 y);

SD49x28_IntoUD50x28_Underflow

Git Source

error SD49x28_IntoUD50x28_Underflow(SD49x28 x);

SD49x28_Abs_MinSD49x28

Git Source

error SD49x28_Abs_MinSD49x28();

avg

Git Source

Calculates the arithmetic average of x and y.

*Notes:

  • The result is rounded toward zero.*
function avg(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

Parameters

NameTypeDescription
xSD49x28The first operand as an SD49x28 number.
ySD49x28The second operand as an SD49x28 number.

Returns

NameTypeDescription
resultSD49x28The arithmetic average as an SD49x28 number.

wrap

Git Source

Wraps a int256 number into the SD49x28 value type.

function wrap(int256 x) pure returns (SD49x28 result);

gt

Git Source

Implements the greater than operation (>) in the SD49x28 type.

function gt(SD49x28 x, SD49x28 y) pure returns (bool result);

lshift

Git Source

Implements the left shift operation (<<) in the SD49x28 type.

function lshift(SD49x28 x, uint256 bits) pure returns (SD49x28 result);

sub

Git Source

Implements the checked subtraction operation (-) in the SD49x28 type.

function sub(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

isZero

Git Source

Implements a zero comparison check function in the SD49x28 type.

function isZero(SD49x28 x) pure returns (bool result);

mod

Git Source

Implements the unchecked modulo operation (%) in the SD49x28 type.

function mod(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

and

Git Source

Implements the AND (&) bitwise operation in the SD49x28 type.

function and(SD49x28 x, int256 bits) pure returns (SD49x28 result);

abs

Git Source

Calculates the absolute value of x.

*Requirements:

  • x must be greater than MIN_SD49x28.*
function abs(SD49x28 x) pure returns (SD49x28 result);

Parameters

NameTypeDescription
xSD49x28The SD49x28 number for which to calculate the absolute value.

add

Git Source

Implements the checked addition operation (+) in the SD49x28 type.

function add(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

intoSD59x18

Git Source

function intoSD59x18(SD49x28 x) pure returns (SD59x18 result);

and2

Git Source

Implements the AND (&) bitwise operation in the SD49x28 type.

function and2(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

sd49x28

Git Source

function sd49x28(int256 x) pure returns (SD49x28 result);

rshift

Git Source

Implements the right shift operation (>>) in the SD49x28 type.

function rshift(SD49x28 x, uint256 bits) pure returns (SD49x28 result);

gte

Git Source

Implements the greater than or equal to operation (>=) in the SD49x28 type.

function gte(SD49x28 x, SD49x28 y) pure returns (bool result);

lt

Git Source

Implements the lower than operation (<) in the SD49x28 type.

function lt(SD49x28 x, SD49x28 y) pure returns (bool result);

not

Git Source

Implements the NOT (~) bitwise operation in the SD49x28 type.

function not(SD49x28 x) pure returns (SD49x28 result);

div

Git Source

Divides two SD49x28 numbers, returning a new SD49x28 number.

*This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute values separately. Notes:

  • Refer to the notes in {Common.mulDiv}.
  • The result is rounded toward zero. Requirements:
  • Refer to the requirements in {Common.mulDiv}.
  • None of the inputs can be MIN_SD49x28.
  • The denominator must not be zero.
  • The result must fit in SD49x28.*
function div(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

Parameters

NameTypeDescription
xSD49x28The numerator as an SD49x28 number.
ySD49x28The denominator as an SD49x28 number.

uncheckedUnary

Git Source

Implements the unchecked unary minus operation (-) in the SD49x28 type.

function uncheckedUnary(SD49x28 x) pure returns (SD49x28 result);

or

Git Source

Implements the OR (|) bitwise operation in the SD49x28 type.

function or(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

intoUD50x28

Git Source

Casts an SD49x28 number into UD50x28.

*Requirements:

  • x must be positive.*
function intoUD50x28(SD49x28 x) pure returns (UD50x28 result);

unwrap

Git Source

Unwraps a SD49x28 number into int256.

function unwrap(SD49x28 x) pure returns (int256 result);

xor

Git Source

Implements the XOR (^) bitwise operation in the SD49x28 type.

function xor(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

neq

Git Source

Implements the not equal operation (!=) in the SD49x28 type.

function neq(SD49x28 x, SD49x28 y) pure returns (bool result);

mul

Git Source

Multiplies two SD49x28 numbers together, returning a new SD49x28 number.

*Notes:

  • Refer to the notes in {Common.mulDiv18}. Requirements:
  • Refer to the requirements in {Common.mulDiv18}.
  • None of the inputs can be MIN_SD49x28.
  • The result must fit in SD49x28.*
function mul(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

Parameters

NameTypeDescription
xSD49x28The multiplicand as an SD49x28 number.
ySD49x28The multiplier as an SD49x28 number.

Returns

NameTypeDescription
resultSD49x28The product as an SD49x28 number.

uncheckedSub

Git Source

Implements the unchecked subtraction operation (-) in the SD49x28 type.

function uncheckedSub(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

eq

Git Source

Implements the equal (=) operation in the SD49x28 type.

function eq(SD49x28 x, SD49x28 y) pure returns (bool result);

intoUD60x18

Git Source

function intoUD60x18(SD49x28 x) pure returns (UD60x18 result);

lte

Git Source

Implements the lower than or equal to operation (<=) in the SD49x28 type.

function lte(SD49x28 x, SD49x28 y) pure returns (bool result);

uncheckedAdd

Git Source

Implements the unchecked addition operation (+) in the SD49x28 type.

function uncheckedAdd(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);

unary

Git Source

Implements the checked unary minus operation (-) in the SD49x28 type.

function unary(SD49x28 x) pure returns (SD49x28 result);

Constants

Git Source

uMAX_SD49x28

Max SD49x28 value

int256 constant uMAX_SD49x28 = type(int256).max;

uMIN_SD49x28

Min SD49x28 value

int256 constant uMIN_SD49x28 = type(int256).min;

uUNIT

The unit number, which gives the decimal precision of SD49x28.

int256 constant uUNIT = 1e28;

UNIT

SD49x28 constant UNIT = SD49x28.wrap(uUNIT);

SCALING_FACTOR

int256 constant SCALING_FACTOR = 1e10;

UD50x28

Git Source

type UD50x28 is uint256;

UD50x28_IntoSD49x28_Overflow

Git Source

error UD50x28_IntoSD49x28_Overflow(UD50x28 x);

uncheckedAdd

Git Source

Implements the unchecked addition operation (+) in the UD50x28 type.

function uncheckedAdd(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

gte

Git Source

Implements the greater than or equal to operation (>=) in the UD50x28 type.

function gte(UD50x28 x, UD50x28 y) pure returns (bool result);

wrap

Git Source

Wraps a uint256 number into the UD50x28 value type.

function wrap(uint256 x) pure returns (UD50x28 result);

neq

Git Source

Implements the not equal operation (!=) in the UD50x28 type.

function neq(UD50x28 x, UD50x28 y) pure returns (bool result);

lte

Git Source

Implements the lower than or equal to operation (<=) in the UD50x28 type.

function lte(UD50x28 x, UD50x28 y) pure returns (bool result);

sub

Git Source

Implements the checked subtraction operation (-) in the UD50x28 type.

function sub(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

not

Git Source

Implements the NOT (~) bitwise operation in the UD50x28 type.

function not(UD50x28 x) pure returns (UD50x28 result);

xor

Git Source

Implements the XOR (^) bitwise operation in the UD50x28 type.

function xor(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

uncheckedSub

Git Source

Implements the unchecked subtraction operation (-) in the UD50x28 type.

function uncheckedSub(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

unwrap

Git Source

Unwraps a UD50x28 number into uint256.

function unwrap(UD50x28 x) pure returns (uint256 result);

intoUD60x18

Git Source

function intoUD60x18(UD50x28 x) pure returns (UD60x18 result);

lshift

Git Source

Implements the left shift operation (<<) in the UD50x28 type.

function lshift(UD50x28 x, uint256 bits) pure returns (UD50x28 result);

avg

Git Source

Calculates the arithmetic average of x and y using the following formula: $$ avg(x, y) = (x & y) + ((xUint ^ yUint) / 2) $$ In English, this is what this formula does:

  1. AND x and y.
  2. Calculate half of XOR x and y.
  3. Add the two results together. This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here: https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223

*Notes:

  • The result is rounded down.*
function avg(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

Parameters

NameTypeDescription
xUD50x28The first operand as a UD50x28 number.
yUD50x28The second operand as a UD50x28 number.

Returns

NameTypeDescription
resultUD50x28The arithmetic average as a UD50x28 number.

add

Git Source

Implements the checked addition operation (+) in the UD50x28 type.

function add(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

gt

Git Source

Implements the greater than operation (>) in the UD50x28 type.

function gt(UD50x28 x, UD50x28 y) pure returns (bool result);

and

Git Source

Implements the AND (&) bitwise operation in the UD50x28 type.

function and(UD50x28 x, uint256 bits) pure returns (UD50x28 result);

eq

Git Source

Implements the equal operation (==) in the UD50x28 type.

function eq(UD50x28 x, UD50x28 y) pure returns (bool result);

mod

Git Source

Implements the checked modulo operation (%) in the UD50x28 type.

function mod(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

ud50x28

Git Source

function ud50x28(uint256 x) pure returns (UD50x28 result);

mul

Git Source

Multiplies two UD50x28 numbers together, returning a new UD50x28 number.

*Uses {Common.mulDiv} to enable overflow-safe multiplication and division. Notes:

  • Refer to the notes in {Common.mulDiv}. Requirements:
  • Refer to the requirements in {Common.mulDiv}.*

See the documentation in {Common.mulDiv18}.

function mul(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

Parameters

NameTypeDescription
xUD50x28The multiplicand as a UD50x28 number.
yUD50x28The multiplier as a UD50x28 number.

Returns

NameTypeDescription
resultUD50x28The product as a UD50x28 number.

or

Git Source

Implements the OR (|) bitwise operation in the UD50x28 type.

function or(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

intoSD49x28

Git Source

Casts a UD50x28 number into SD49x28.

*Requirements:

  • x must be less than or equal to uMAX_SD49x28.*
function intoSD49x28(UD50x28 x) pure returns (SD49x28 result);

rshift

Git Source

Implements the right shift operation (>>) in the UD50x28 type.

function rshift(UD50x28 x, uint256 bits) pure returns (UD50x28 result);

lt

Git Source

Implements the lower than operation (<) in the UD50x28 type.

function lt(UD50x28 x, UD50x28 y) pure returns (bool result);

isZero

Git Source

Implements a zero comparison check function in the UD50x28 type.

function isZero(UD50x28 x) pure returns (bool result);

div

Git Source

Divides two UD50x28 numbers, returning a new UD50x28 number.

*Uses {Common.mulDiv} to enable overflow-safe multiplication and division. Notes:

  • Refer to the notes in {Common.mulDiv}. Requirements:
  • Refer to the requirements in {Common.mulDiv}.*
function div(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

Parameters

NameTypeDescription
xUD50x28The numerator as a UD50x28 number.
yUD50x28The denominator as a UD50x28 number.

and2

Git Source

Implements the AND (&) bitwise operation in the UD50x28 type.

function and2(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);

Constants

Git Source

uMAX_UD50x28

Max UD50x28 value

uint256 constant uMAX_UD50x28 = type(uint256).max;

uUNIT

The unit number, which gives the decimal precision of UD50x28.

uint256 constant uUNIT = 1e28;

UNIT

UD50x28 constant UNIT = UD50x28.wrap(uUNIT);

SCALING_FACTOR

uint256 constant SCALING_FACTOR = 1e10;

Contents

Contents

DualMining

Git Source

Inherits: IDualMining, ReentrancyGuard

State Variables

VAULT_MINING

address internal immutable VAULT_MINING;

Functions

constructor

constructor(address vaultMining);

init

Initialize dual mining. Can only be called by VAULT_MINING contract

function init(UD60x18 initialParentAccRewardsPerShare) external nonReentrant;

addRewards

Add rewards to the contract

function addRewards(UD60x18 amount) external nonReentrant;

getRewardsAvailable

Return amount of rewards not yet allocated

function getRewardsAvailable() external view returns (UD60x18);

updatePool

Trigger an update for this mining pool. Can only be called by VAULT_MINING contract

function updatePool(UD60x18 poolRewards, UD60x18 accRewardsPerShare) external nonReentrant;

_updatePool

function _updatePool(DualMiningStorage.Layout storage l, UD60x18 parentPoolRewards, UD60x18 accRewardsPerShare)
    internal;

updateUser

Trigger an update for a specific user. Can only be called by VAULT_MINING contract

function updateUser(
    address user,
    UD60x18 oldShares,
    UD60x18 oldRewardDebt,
    UD60x18 parentPoolRewards,
    UD60x18 parentUserRewards,
    UD60x18 accRewardsPerShare
) external nonReentrant;

_calculateUserRewardToSubtract

Calculate user reward accumulated in parent contract before the start of the emission in this contract.

function _calculateUserRewardToSubtract(
    DualMiningStorage.Layout storage l,
    IDualMining.UserInfo storage uInfo,
    UD60x18 oldShares,
    UD60x18 oldRewardDebt,
    UD60x18 accRewardsPerShare
) internal view returns (UD60x18);

claim

Claim rewards. Can only be called by VAULT_MINING contract

The claim is done through VAULT_MINING, as we need to trigger updates through VAULT_MINING before being able to claim the rewards anyway.

function claim(address user) external nonReentrant;

Parameters

NameTypeDescription
useraddressThe user for which to claim

getPendingUserRewards

Return amount of pending rewards (not yet claimed) for the given user

function getPendingUserRewards(address user) external view returns (UD60x18);

getUserInfo

Return internal variables for the given user

function getUserInfo(address user) external view returns (UserInfo memory);

_calculateRewardsUpdate

function _calculateRewardsUpdate(DualMiningStorage.Layout storage l) internal view returns (UD60x18 rewardAmount);

_revertIfNotVaultMining

function _revertIfNotVaultMining(address caller) internal view;

_revertIfNotInitialized

function _revertIfNotInitialized(DualMiningStorage.Layout storage l) internal view;

_revertIfInitialized

function _revertIfInitialized(DualMiningStorage.Layout storage l) internal view;

_revertIfMiningEnded

function _revertIfMiningEnded(DualMiningStorage.Layout storage l) internal view;

_revertIfNoMiningRewards

function _revertIfNoMiningRewards(DualMiningStorage.Layout storage l) internal view;

DualMiningManager

Git Source

Inherits: ProxyManager, SafeOwnable

Manages the proxy implementation of DualMining contracts

Functions

constructor

constructor(address implementation);

_transferOwnership

function _transferOwnership(address account) internal virtual override(OwnableInternal, SafeOwnable);

DualMiningProxy

Git Source

Inherits: Proxy

State Variables

MANAGER

IProxyManager private immutable MANAGER;

Functions

constructor

constructor(IProxyManager manager, address vault, address rewardToken, UD60x18 rewardsPerYear);

_getImplementation

get logic implementation address

function _getImplementation() internal view override returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

getImplementation

get address of implementation contract

function getImplementation() external view returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

DualMiningStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.DualMining");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    address vault;
    uint256 startTimestamp;
    uint256 endTimestamp;
    UD60x18 rewardsPerYear;
    UD60x18 rewardsAvailable;
    address rewardToken;
    uint8 rewardTokenDecimals;
    UD60x18 parentAccTotalRewards;
    UD60x18 accTotalRewards;
    UD60x18 initialParentAccRewardsPerShare;
    UD60x18 finalParentAccRewardsPerShare;
    uint256 lastRewardTimestamp;
    mapping(address user => IDualMining.UserInfo info) userInfo;
}

IDualMining

Git Source

Functions

init

Initialize dual mining. Can only be called by VAULT_MINING contract

function init(UD60x18 initialParentAccRewardsPerShare) external;

addRewards

Add rewards to the contract

function addRewards(UD60x18 amount) external;

getRewardsAvailable

Return amount of rewards not yet allocated

function getRewardsAvailable() external view returns (UD60x18);

updatePool

Trigger an update for this mining pool. Can only be called by VAULT_MINING contract

function updatePool(UD60x18 poolRewards, UD60x18 accRewardsPerShare) external;

updateUser

Trigger an update for a specific user. Can only be called by VAULT_MINING contract

function updateUser(
    address user,
    UD60x18 oldShares,
    UD60x18 oldRewardDebt,
    UD60x18 poolRewards,
    UD60x18 userRewards,
    UD60x18 accRewardsPerShare
) external;

claim

Claim rewards. Can only be called by VAULT_MINING contract

The claim is done through VAULT_MINING, as we need to trigger updates through VAULT_MINING before being able to claim the rewards anyway.

function claim(address user) external;

Parameters

NameTypeDescription
useraddressThe user for which to claim

getPendingUserRewards

Return amount of pending rewards (not yet claimed) for the given user

function getPendingUserRewards(address user) external view returns (UD60x18);

getUserInfo

Return internal variables for the given user

function getUserInfo(address user) external view returns (UserInfo memory);

Events

Initialized

event Initialized(address indexed caller, UD60x18 initialParentAccRewardsPerShare, uint256 timestamp);

Claim

event Claim(address indexed user, UD60x18 rewardAmount);

MiningEnded

event MiningEnded(UD60x18 finalParentAccRewardsPerShare);

Errors

DualMining__AlreadyInitialized

error DualMining__AlreadyInitialized();

DualMining__NoMiningRewards

error DualMining__NoMiningRewards();

DualMining__NoShareSupply

error DualMining__NoShareSupply();

DualMining__NotAuthorized

error DualMining__NotAuthorized(address caller);

DualMining__NotInitialized

error DualMining__NotInitialized();

DualMining__MiningEnded

error DualMining__MiningEnded();

Structs

UserInfo

struct UserInfo {
    uint256 lastUpdateTimestamp;
    UD60x18 lastParentAccTotalRewards;
    UD60x18 lastAccTotalRewards;
    UD60x18 reward;
}

Contents

IOptionPS

Git Source

Inherits: IERC1155Base, IERC1155Enumerable

Functions

name

Returns the name of the physically settled option token

function name() external view returns (string memory);

symbol

Returns the symbol of the physically settled option token

function symbol() external view returns (string memory);

getSettings

Returns the pair infos for this option

function getSettings() external view returns (address base, address quote, bool isCall);

underwrite

Underwrite an option by depositing collateral

function underwrite(UD60x18 strike, uint64 maturity, address longReceiver, UD60x18 contractSize) external;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
longReceiveraddressthe address that will receive the long tokens
contractSizeUD60x18number of long tokens to mint (18 decimals)

annihilate

Burn longs and shorts, to recover collateral of the option

function annihilate(UD60x18 strike, uint64 maturity, UD60x18 contractSize) external;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18number of contracts to annihilate (18 decimals)

getExerciseCost

Returns the amount of exerciseToken to pay to exercise the given amount of contracts

function getExerciseCost(UD60x18 strike, UD60x18 contractSize)
    external
    view
    returns (uint256 totalExerciseCost, uint256 fee);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
contractSizeUD60x18number of long tokens to exercise (18 decimals)

Returns

NameTypeDescription
totalExerciseCostuint256the total amount of exerciseToken to pay, including fee (exerciseToken decimals)
feeuint256the amount of exerciseToken to pay as fee (exerciseToken decimals)

getExerciseValue

Returns the amount of collateral that would be received for a given amount of long tokens

function getExerciseValue(UD60x18 strike, UD60x18 contractSize) external view returns (uint256);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
contractSizeUD60x18number of long tokens to exercise (18 decimals)

Returns

NameTypeDescription
<none>uint256the amount of collateral (collateral decimals)

exercise

Pay the exercise cost for a given amount contracts. The exercise value will be claimable after maturity.

function exercise(UD60x18 strike, uint64 maturity, UD60x18 contractSize) external;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18amount of long tokens to exercise (18 decimals)

cancelExercise

Cancel an exercise before maturity, and recover the exerciseToken paid. (The fee paid during exercise is not recovered.

function cancelExercise(UD60x18 strike, uint64 maturity, UD60x18 contractSize) external;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18amount of long tokens for which cancel exercise (18 decimals)

settleLong

Settle the exercised long options held by the caller.

function settleLong(UD60x18 strike, uint64 maturity, UD60x18 contractSize) external returns (uint256 exerciseValue);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18number of long tokens to settle (18 decimals)

Returns

NameTypeDescription
exerciseValueuint256the amount of tokens transferred to the caller

settleShort

Settles the short options held by the caller.

function settleShort(UD60x18 strike, uint64 maturity, UD60x18 contractSize)
    external
    returns (uint256 collateralAmount, uint256 exerciseTokenAmount);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18number of short tokens to settle (18 decimals)

Returns

NameTypeDescription
collateralAmountuint256the amount of collateral transferred to the caller (base for calls, quote for puts)
exerciseTokenAmountuint256the amount of exerciseToken transferred to the caller (quote for calls, base for puts)

getTokenIds

Returns the list of existing tokenIds with non zero balance

function getTokenIds() external view returns (uint256[] memory);

Returns

NameTypeDescription
<none>uint256[]tokenIds The list of existing tokenIds

Events

Exercise

event Exercise(
    address indexed user, UD60x18 strike, uint256 maturity, UD60x18 contractSize, UD60x18 exerciseCost, UD60x18 fee
);

CancelExercise

event CancelExercise(
    address indexed user, UD60x18 strike, uint256 maturity, UD60x18 contractSize, UD60x18 exerciseCostRefunded
);

SettleLong

event SettleLong(address indexed user, UD60x18 strike, uint256 maturity, UD60x18 contractSize, UD60x18 exerciseValue);

SettleShort

event SettleShort(
    address indexed user,
    UD60x18 strike,
    uint256 maturity,
    UD60x18 contractSize,
    UD60x18 collateralAmount,
    UD60x18 exerciseTokenAmount
);

Underwrite

event Underwrite(
    address indexed underwriter, address indexed longReceiver, UD60x18 strike, uint256 maturity, UD60x18 contractSize
);

Annihilate

event Annihilate(address indexed annihilator, UD60x18 strike, uint256 maturity, UD60x18 contractSize);

Errors

OptionPS__OptionMaturityNot8UTC

error OptionPS__OptionMaturityNot8UTC(uint256 maturity);

OptionPS__OptionExpired

error OptionPS__OptionExpired(uint256 maturity);

OptionPS__OptionNotExpired

error OptionPS__OptionNotExpired(uint256 maturity);

OptionPS__StrikeNotMultipleOfStrikeInterval

error OptionPS__StrikeNotMultipleOfStrikeInterval(UD60x18 strike, UD60x18 strikeInterval);

Enums

TokenType

enum TokenType {
    Long,
    Short,
    LongExercised
}

IOptionPSFactory

Git Source

Inherits: IProxyManager

Functions

isProxyDeployed

Return whether proxy is a deployed proxy

function isProxyDeployed(address proxy) external view returns (bool);

getProxyAddress

Return the proxy address and whether it is deployed

function getProxyAddress(OptionPSArgs calldata args) external view returns (address proxy, bool isDeployed);

Parameters

NameTypeDescription
argsOptionPSArgsThe arguments used to deploy the proxy

Returns

NameTypeDescription
proxyaddressThe proxy address
isDeployedboolWhether the proxy is deployed

deployProxy

Deploy a new proxy

function deployProxy(OptionPSArgs calldata args) external returns (address);

Events

ProxyDeployed

event ProxyDeployed(address indexed base, address indexed quote, bool isCall, address proxy);

Errors

OptionPSFactory__ProxyAlreadyDeployed

error OptionPSFactory__ProxyAlreadyDeployed(address proxy);

Structs

OptionPSArgs

struct OptionPSArgs {
    address base;
    address quote;
    bool isCall;
}

OptionPS

Git Source

Inherits: ERC1155Base, ERC1155Enumerable, ERC165Base, IOptionPS, ReentrancyGuard

State Variables

FEE_RECEIVER

address internal immutable FEE_RECEIVER;

FEE

UD60x18 internal constant FEE = UD60x18.wrap(0.003e18);

Functions

constructor

constructor(address feeReceiver);

name

Returns the name of the physically settled option token

function name() external view returns (string memory);

symbol

Returns the symbol of the physically settled option token

function symbol() external view returns (string memory);

_symbol

function _symbol(OptionPSStorage.Layout storage l) internal view returns (string memory);

getSettings

Returns the pair infos for this option

function getSettings() external view returns (address base, address quote, bool isCall);

underwrite

Underwrite an option by depositing collateral

function underwrite(UD60x18 strike, uint64 maturity, address longReceiver, UD60x18 contractSize)
    external
    nonReentrant;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
longReceiveraddressthe address that will receive the long tokens
contractSizeUD60x18number of long tokens to mint (18 decimals)

annihilate

Burn longs and shorts, to recover collateral of the option

function annihilate(UD60x18 strike, uint64 maturity, UD60x18 contractSize) external nonReentrant;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18number of contracts to annihilate (18 decimals)

getExerciseCost

Returns the amount of exerciseToken to pay to exercise the given amount of contracts

function getExerciseCost(UD60x18 strike, UD60x18 contractSize)
    public
    view
    returns (uint256 totalExerciseCost, uint256 fee);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
contractSizeUD60x18number of long tokens to exercise (18 decimals)

Returns

NameTypeDescription
totalExerciseCostuint256the total amount of exerciseToken to pay, including fee (exerciseToken decimals)
feeuint256the amount of exerciseToken to pay as fee (exerciseToken decimals)

getExerciseValue

Returns the amount of collateral that would be received for a given amount of long tokens

function getExerciseValue(UD60x18 strike, UD60x18 contractSize) public view returns (uint256);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
contractSizeUD60x18number of long tokens to exercise (18 decimals)

Returns

NameTypeDescription
<none>uint256the amount of collateral (collateral decimals)

exercise

Pay the exercise cost for a given amount contracts. The exercise value will be claimable after maturity.

function exercise(UD60x18 strike, uint64 maturity, UD60x18 contractSize) external nonReentrant;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18amount of long tokens to exercise (18 decimals)

cancelExercise

Cancel an exercise before maturity, and recover the exerciseToken paid. (The fee paid during exercise is not recovered.

function cancelExercise(UD60x18 strike, uint64 maturity, UD60x18 contractSize) external nonReentrant;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18amount of long tokens for which cancel exercise (18 decimals)

settleLong

Settle the exercised long options held by the caller.

function settleLong(UD60x18 strike, uint64 maturity, UD60x18 contractSize)
    external
    nonReentrant
    returns (uint256 exerciseValue);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18number of long tokens to settle (18 decimals)

Returns

NameTypeDescription
exerciseValueuint256the amount of tokens transferred to the caller

settleShort

Settles the short options held by the caller.

function settleShort(UD60x18 strike, uint64 maturity, UD60x18 contractSize)
    external
    nonReentrant
    returns (uint256 collateralAmount, uint256 exerciseTokenAmount);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp
contractSizeUD60x18number of short tokens to settle (18 decimals)

Returns

NameTypeDescription
collateralAmountuint256the amount of collateral transferred to the caller (base for calls, quote for puts)
exerciseTokenAmountuint256the amount of exerciseToken transferred to the caller (quote for calls, base for puts)

getTokenIds

Returns the list of existing tokenIds with non zero balance

function getTokenIds() external view returns (uint256[] memory);

Returns

NameTypeDescription
<none>uint256[]tokenIds The list of existing tokenIds

_mintUD60x18

_mint wrapper, converts UD60x18 to uint256

function _mintUD60x18(address account, uint256 tokenId, UD60x18 amount) internal;

_burnUD60x18

_burn wrapper, converts UD60x18 to uint256

function _burnUD60x18(address account, uint256 tokenId, UD60x18 amount) internal;

_revertIfOptionExpired

Revert if option has expired

function _revertIfOptionExpired(uint64 maturity) internal view;

_revertIfOptionNotExpired

Revert if option has not expired

function _revertIfOptionNotExpired(uint64 maturity) internal view;

_beforeTokenTransfer

_beforeTokenTransfer wrapper, updates tokenIds set

function _beforeTokenTransfer(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal);

OptionPSFactory

Git Source

Inherits: IOptionPSFactory, ProxyManager, ReentrancyGuard

Functions

isProxyDeployed

Return whether proxy is a deployed proxy

function isProxyDeployed(address proxy) external view returns (bool);

getProxyAddress

Return the proxy address and whether it is deployed

function getProxyAddress(OptionPSArgs calldata args) external view returns (address proxy, bool isDeployed);

Parameters

NameTypeDescription
argsOptionPSArgsThe arguments used to deploy the proxy

Returns

NameTypeDescription
proxyaddressThe proxy address
isDeployedboolWhether the proxy is deployed

deployProxy

Deploy a new proxy

function deployProxy(OptionPSArgs calldata args) external nonReentrant returns (address proxy);

OptionPSFactoryStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.OptionPSFactory");

Functions

layout

function layout() internal pure returns (Layout storage l);

keyHash

Returns the encoded option physically settled key using args

function keyHash(IOptionPSFactory.OptionPSArgs memory args) internal pure returns (bytes32);

Structs

Layout

struct Layout {
    mapping(address proxy => bool) isProxyDeployed;
    mapping(bytes32 key => address proxy) proxyByKey;
}

OptionPSProxy

Git Source

Inherits: Proxy, ERC165BaseInternal

State Variables

MANAGER

IProxyManager private immutable MANAGER;

Functions

constructor

constructor(IProxyManager manager, address base, address quote, bool isCall);

getImplementation

Return the implementation address of the proxy

function getImplementation() external view returns (address);

_getImplementation

get logic implementation address

function _getImplementation() internal view override returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

receive

receive() external payable;

OptionPSStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.OptionPS");

Functions

layout

function layout() internal pure returns (Layout storage l);

formatTokenId

Calculate ERC1155 token id for given option parameters

function formatTokenId(IOptionPS.TokenType tokenType, uint64 maturity, UD60x18 strike)
    internal
    pure
    returns (uint256 tokenId);

parseTokenId

Derive option maturity and strike price from ERC1155 token id

function parseTokenId(uint256 tokenId)
    internal
    pure
    returns (IOptionPS.TokenType tokenType, uint64 maturity, int128 strike);

getCollateral

function getCollateral(Layout storage l) internal view returns (address);

getExerciseToken

function getExerciseToken(Layout storage l) internal view returns (address);

toTokenDecimals

Adjust decimals of a value with 18 decimals to match the token decimals

function toTokenDecimals(Layout storage l, UD60x18 value, address token) internal view returns (uint256);

fromTokenDecimals

Adjust decimals of a value with token decimals to 18 decimals

function fromTokenDecimals(Layout storage l, uint256 value, address token) internal view returns (UD60x18);

fromUD60x18ToInt128

Converts UD60x18 to int128

function fromUD60x18ToInt128(UD60x18 u) internal pure returns (int128);

Structs

Layout

struct Layout {
    bool isCall;
    uint8 baseDecimals;
    uint8 quoteDecimals;
    address base;
    address quote;
    mapping(UD60x18 strike => mapping(uint64 maturity => UD60x18 amount)) totalUnderwritten;
    mapping(UD60x18 strike => mapping(uint64 maturity => UD60x18 amount)) totalExercised;
    EnumerableSet.UintSet tokenIds;
}

Contents

IOptionReward

Git Source

Functions

previewOptionParams

Returns the option strike price and maturity timestamp. Note that the on-chain price is constantly updating, therefore, the strike price returned may not be the same as the strike price at the time of underwriting.

function previewOptionParams() external view returns (UD60x18 strike, uint64 maturity);

Returns

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

underwrite

Underwrite an option

function underwrite(address longReceiver, UD60x18 contractSize) external;

Parameters

NameTypeDescription
longReceiveraddressthe address that will receive the long tokens
contractSizeUD60x18number of long tokens to mint (18 decimals)

claimRewards

Use expired longs to claim a percentage of expired option intrinsic value as reward, after lockupDuration has passed

function claimRewards(UD60x18 strike, uint64 maturity) external returns (uint256 baseAmount);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

Returns

NameTypeDescription
baseAmountuint256the amount of base tokens earned as reward

getRewardPerContract

Returns the amount of base tokens which can be claimed per long not exercised after the lockup period.

function getRewardPerContract(UD60x18 strike, uint64 maturity) external view returns (UD60x18);

settle

Settle options after the exercise period has ended, reserve base tokens necessary for claimRewards, and transfer excess base tokens + quote tokens to paymentSplitter

function settle(UD60x18 strike, uint64 maturity) external;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

releaseRewardsNotClaimed

Releases base tokens reserved for claimRewards, if rewards have not be claimed at maturity + lockupDuration + claimDuration

function releaseRewardsNotClaimed(UD60x18 strike, uint64 maturity) external;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

getTotalBaseReserved

Returns the amount of base tokens reserved for claimRewards

function getTotalBaseReserved() external view returns (uint256);

getRedeemableLongs

Returns the max amount of expired longs that a user can use to claim rewards for a given option

function getRedeemableLongs(address user, UD60x18 strike, uint64 maturity) external view returns (UD60x18);

getSettings

Returns the option physically settled storage settings

function getSettings()
    external
    view
    returns (
        IOptionPS option,
        IOracleAdapter oracleAdapter,
        IPaymentSplitter paymentSplitter,
        UD60x18 percentOfSpot,
        UD60x18 penalty,
        uint256 optionDuration,
        uint256 lockupDuration,
        uint256 claimDuration,
        UD60x18 fee,
        address feeReceiver
    );

Events

Underwrite

event Underwrite(address indexed longReceiver, UD60x18 strike, uint64 maturity, UD60x18 contractSize);

RewardsClaimed

event RewardsClaimed(address indexed user, UD60x18 strike, uint64 maturity, UD60x18 contractSize, UD60x18 baseAmount);

RewardsNotClaimedReleased

event RewardsNotClaimedReleased(UD60x18 strike, uint64 maturity, UD60x18 baseAmount);

Settled

event Settled(
    UD60x18 strike,
    uint64 maturity,
    UD60x18 contractSize,
    UD60x18 intrinsicValuePerContract,
    UD60x18 maxRedeemableLongs,
    UD60x18 baseAmountPaid,
    UD60x18 baseAmountFee,
    UD60x18 quoteAmountPaid,
    UD60x18 quoteAmountFee,
    UD60x18 baseAmountReserved
);

Errors

OptionReward__ClaimPeriodEnded

error OptionReward__ClaimPeriodEnded(uint256 claimEnd);

OptionReward__ClaimPeriodNotEnded

error OptionReward__ClaimPeriodNotEnded(uint256 claimEnd);

OptionReward__InvalidSettlement

error OptionReward__InvalidSettlement();

OptionReward__LockupNotExpired

error OptionReward__LockupNotExpired(uint256 lockupEnd);

OptionReward__NoBaseReserved

error OptionReward__NoBaseReserved(UD60x18 strike, uint256 maturity);

OptionReward__NoRedeemableLongs

error OptionReward__NoRedeemableLongs();

OptionReward__NotCallOption

error OptionReward__NotCallOption(address option);

OptionReward__UnderwriterNotAuthorized

error OptionReward__UnderwriterNotAuthorized(address sender);

OptionReward__OptionNotExpired

error OptionReward__OptionNotExpired(uint256 maturity);

OptionReward__PriceIsZero

error OptionReward__PriceIsZero();

OptionReward__ZeroRewardPerContract

error OptionReward__ZeroRewardPerContract(UD60x18 strike, uint256 maturity);

Structs

SettleVarsInternal

struct SettleVarsInternal {
    UD60x18 intrinsicValuePerContract;
    UD60x18 rewardPerContract;
    UD60x18 totalUnderwritten;
    UD60x18 maxRedeemableLongs;
    UD60x18 baseAmountReserved;
    uint256 fee;
}

IOptionRewardFactory

Git Source

Inherits: IProxyManager

Functions

getDefaultFee

Returns the default fee

function getDefaultFee() external view returns (UD60x18);

getDefaultFeeReceiver

Returns the default fee receiver

function getDefaultFeeReceiver() external view returns (address);

isProxyDeployed

Returns true if proxy is a deployed proxy

function isProxyDeployed(address proxy) external view returns (bool);

getProxyAddress

Returns the proxy address and whether it is deployed

function getProxyAddress(OptionRewardKey calldata args) external view returns (address, bool);

deployProxy

Deploys a new proxy

function deployProxy(OptionRewardArgs calldata args) external returns (address);

Events

ProxyDeployed

event ProxyDeployed(
    IOptionPS indexed option,
    IOracleAdapter oracleAdapter,
    IPaymentSplitter paymentSplitter,
    UD60x18 percentOfSpot,
    UD60x18 penalty,
    uint256 optionDuration,
    uint256 lockupDuration,
    uint256 claimDuration,
    UD60x18 fee,
    address feeReceiver,
    address proxy
);

PricingPath

event PricingPath(
    address option,
    address[][] basePath,
    uint8[] basePathDecimals,
    IOracleAdapter.AdapterType baseAdapterType,
    address[][] quotePath,
    uint8[] quotePathDecimals,
    IOracleAdapter.AdapterType quoteAdapterType
);

Errors

OptionRewardFactory__ProxyAlreadyDeployed

error OptionRewardFactory__ProxyAlreadyDeployed(address proxy);

Structs

OptionRewardArgs

struct OptionRewardArgs {
    IOptionPS option;
    IOracleAdapter oracleAdapter;
    IPaymentSplitter paymentSplitter;
    UD60x18 percentOfSpot;
    UD60x18 penalty;
    uint256 optionDuration;
    uint256 lockupDuration;
    uint256 claimDuration;
}

OptionRewardKey

struct OptionRewardKey {
    IOptionPS option;
    IOracleAdapter oracleAdapter;
    IPaymentSplitter paymentSplitter;
    UD60x18 percentOfSpot;
    UD60x18 penalty;
    uint256 optionDuration;
    uint256 lockupDuration;
    uint256 claimDuration;
    UD60x18 fee;
    address feeReceiver;
}

OptionReward

Git Source

Inherits: IOptionReward, ReentrancyGuard

State Variables

BURN_ADDRESS

address internal constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;

Functions

previewOptionParams

Returns the option strike price and maturity timestamp. Note that the on-chain price is constantly updating, therefore, the strike price returned may not be the same as the strike price at the time of underwriting.

function previewOptionParams() public view returns (UD60x18 strike, uint64 maturity);

Returns

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

underwrite

Underwrite an option

function underwrite(address longReceiver, UD60x18 contractSize) external nonReentrant;

Parameters

NameTypeDescription
longReceiveraddressthe address that will receive the long tokens
contractSizeUD60x18number of long tokens to mint (18 decimals)

claimRewards

Use expired longs to claim a percentage of expired option intrinsic value as reward, after lockupDuration has passed

function claimRewards(UD60x18 strike, uint64 maturity) external nonReentrant returns (uint256 baseAmount);

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

Returns

NameTypeDescription
baseAmountuint256the amount of base tokens earned as reward

releaseRewardsNotClaimed

Releases base tokens reserved for claimRewards, if rewards have not be claimed at maturity + lockupDuration + claimDuration

function releaseRewardsNotClaimed(UD60x18 strike, uint64 maturity) external nonReentrant;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

getRewardPerContract

Returns the amount of base tokens which can be claimed per long not exercised after the lockup period.

function getRewardPerContract(UD60x18 strike, uint64 maturity) external view returns (UD60x18);

settle

Settle options after the exercise period has ended, reserve base tokens necessary for claimRewards, and transfer excess base tokens + quote tokens to paymentSplitter

function settle(UD60x18 strike, uint64 maturity) external nonReentrant;

Parameters

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

getTotalBaseReserved

Returns the amount of base tokens reserved for claimRewards

function getTotalBaseReserved() external view returns (uint256);

getRedeemableLongs

Returns the max amount of expired longs that a user can use to claim rewards for a given option

function getRedeemableLongs(address user, UD60x18 strike, uint64 maturity) external view returns (UD60x18);

getSettings

Returns the option physically settled storage settings

function getSettings()
    external
    view
    returns (
        IOptionPS option,
        IOracleAdapter oracleAdapter,
        IPaymentSplitter paymentSplitter,
        UD60x18 percentOfSpot,
        UD60x18 penalty,
        uint256 optionDuration,
        uint256 lockupDuration,
        uint256 claimDuration,
        UD60x18 fee,
        address feeReceiver
    );

_revertIfPriceIsZero

Revert if price is zero

function _revertIfPriceIsZero(UD60x18 price) internal pure;

_revertIfLockPeriodNotEnded

Revert if lock period has not ended

function _revertIfLockPeriodNotEnded(uint64 maturity) internal view;

_revertIfClaimPeriodEnded

Revert if claim period has not ended

function _revertIfClaimPeriodEnded(uint64 maturity) internal view;

_revertIfClaimPeriodNotEnded

Revert if claim period has not ended

function _revertIfClaimPeriodNotEnded(uint64 maturity) internal view;

_revertIfNotExpired

Revert if the option is not expired

function _revertIfNotExpired(uint64 maturity) internal view;

OptionRewardFactory

Git Source

Inherits: IOptionRewardFactory, ProxyManager, ReentrancyGuard

State Variables

DEFAULT_FEE

UD60x18 internal immutable DEFAULT_FEE;

DEFAULT_FEE_RECEIVER

address internal immutable DEFAULT_FEE_RECEIVER;

Functions

constructor

constructor(UD60x18 defaultFee, address defaultFeeReceiver);

getDefaultFee

Returns the default fee

function getDefaultFee() external view returns (UD60x18);

getDefaultFeeReceiver

Returns the default fee receiver

function getDefaultFeeReceiver() external view returns (address);

isProxyDeployed

Returns true if proxy is a deployed proxy

function isProxyDeployed(address proxy) external view returns (bool);

getProxyAddress

Returns the proxy address and whether it is deployed

function getProxyAddress(OptionRewardKey calldata key) external view returns (address proxy, bool);

deployProxy

Deploys a new proxy, with ability to override fee and feeReceiver (Only callable by owner)

function deployProxy(OptionRewardKey calldata key) external onlyOwner returns (address proxy);

deployProxy

Deploys a new proxy

function deployProxy(OptionRewardArgs calldata args) external nonReentrant returns (address proxy);

_deployProxy

function _deployProxy(OptionRewardKey memory key) internal returns (address proxy);

OptionRewardFactoryStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.OptionRewardFactory");

Functions

layout

function layout() internal pure returns (Layout storage l);

keyHash

Returns the encoded option reward key using args

function keyHash(IOptionRewardFactory.OptionRewardKey memory args) internal pure returns (bytes32);

Structs

Layout

struct Layout {
    mapping(address proxy => bool) isProxyDeployed;
    mapping(bytes32 key => address proxy) proxyByKey;
}

OptionRewardProxy

Git Source

Inherits: Proxy

State Variables

MANAGER

IProxyManager private immutable MANAGER;

Functions

constructor

constructor(
    IProxyManager manager,
    IOptionPS option,
    IOracleAdapter oracleAdapter,
    IPaymentSplitter paymentSplitter,
    UD60x18 percentOfSpot,
    UD60x18 penalty,
    uint256 optionDuration,
    uint256 lockupDuration,
    uint256 claimDuration,
    UD60x18 fee,
    address feeReceiver
);

getImplementation

Return the implementation address of the proxy

function getImplementation() external view returns (address);

_getImplementation

get logic implementation address

function _getImplementation() internal view override returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

receive

receive() external payable;

OptionRewardStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.OptionReward");

Functions

layout

function layout() internal pure returns (Layout storage l);

toTokenDecimals

Adjust decimals of a value with 18 decimals to match the token decimals

function toTokenDecimals(Layout storage l, UD60x18 value, bool isBase) internal view returns (uint256);

fromTokenDecimals

Adjust decimals of a value with token decimals to 18 decimals

function fromTokenDecimals(Layout storage l, uint256 value, bool isBase) internal view returns (UD60x18);

Structs

Layout

struct Layout {
    IOptionPS option;
    uint8 baseDecimals;
    uint8 quoteDecimals;
    address base;
    address quote;
    IOracleAdapter oracleAdapter;
    IPaymentSplitter paymentSplitter;
    UD60x18 percentOfSpot;
    UD60x18 penalty;
    uint256 optionDuration;
    uint256 lockupDuration;
    uint256 claimDuration;
    mapping(address user => mapping(UD60x18 strike => mapping(uint64 maturity => UD60x18 amount))) redeemableLongs;
    mapping(UD60x18 strike => mapping(uint64 maturity => UD60x18 amount)) totalUnderwritten;
    mapping(UD60x18 strike => mapping(uint64 maturity => UD60x18 amount)) rewardPerContract;
    uint256 totalBaseReserved;
    mapping(UD60x18 strike => mapping(uint64 maturity => uint256 amount)) baseReserved;
    UD60x18 fee;
    address feeReceiver;
}

Contents

IVaultMining

Git Source

Functions

addRewards

Add rewards to the contract

function addRewards(UD60x18 amount) external;

getRewardsAvailable

Return amount of rewards not yet allocated

function getRewardsAvailable() external view returns (UD60x18);

getPendingVaultRewards

Return amount of pending rewards (not yet allocated) for a specific vault

function getPendingVaultRewards(address vault) external view returns (UD60x18);

getUserRewards

Return the amount of user rewards already allocated and available to claim. This only account for l.userRewards[user] and does NOT include pending reward updates.

function getUserRewards(address user) external view returns (UD60x18);

getPendingUserRewardsFromVault

Return amount of pending rewards (not yet claimed) for a user for a vault This DOES NOT account for l.userRewards[user] and only account for pending rewards of given vault

function getPendingUserRewardsFromVault(address user, address vault) external view returns (UD60x18);

getTotalUserRewards

Return amount of total rewards (not yet claimed) for a user. This accounts for l.userRewards[user] and pending rewards of all vaults

function getTotalUserRewards(address user) external view returns (UD60x18);

getTotalVotes

Return the total amount of votes across all vaults (Used to calculate share of rewards allocation for each vault)

function getTotalVotes() external view returns (UD60x18);

getVaultInfo

Return internal variables for a vault

function getVaultInfo(address vault) external view returns (VaultInfo memory);

getUserInfo

Return internal variables for a user, on a specific vault

function getUserInfo(address user, address vault) external view returns (UserInfo memory);

getRewardsPerYear

Get the amount of rewards emitted per year

function getRewardsPerYear() external view returns (UD60x18);

getVoteMultiplier

Get the vote multiplier for a given vault

function getVoteMultiplier(address vault) external view returns (UD60x18);

getDualMiningPools

Return list of dual mining pools for a given vault

function getDualMiningPools(address vault) external view returns (address[] memory);

previewOptionParams

OptionReward.previewOptionParams wrapper, returns the params for the option reward token. Note that the on-chain price is constantly updating, therefore, the strike price returned may not be the same as the strike price at the time of underwriting.

function previewOptionParams() external view returns (UD60x18 strike, uint64 maturity);

Returns

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

claim

Allocate pending rewards for a list of vaults, and claim given amount of rewards.

function claim(address[] calldata vaults, UD60x18 amount) external;

Parameters

NameTypeDescription
vaultsaddress[]The vaults for which to trigger allocation of pending rewards
amountUD60x18The amount of rewards to claim.

claimAll

Allocate pending rewards for a list of vaults, and claim max amount of rewards possible.

function claimAll(address[] calldata vaults) external;

updateUser

Trigger an update for a user on a specific vault This needs to be called by the vault, anytime the user's shares change Can only be called by a vault registered on the VaultRegistry

function updateUser(address user, UD60x18 newUserShares, UD60x18 newTotalShares, UD60x18 utilisationRate) external;

Parameters

NameTypeDescription
useraddressThe user to update
newUserSharesUD60x18The new amount of shares for the user
newTotalSharesUD60x18The new amount of total shares for the vault
utilisationRateUD60x18DEPRECATED: This function no longer uses the utilisationRate which has been left blank in case it is used again.

updateVault

Trigger an update for a vault

function updateVault(address vault) external;

updateVaults

Trigger an update for all vaults

function updateVaults() external;

updateUser

Trigger an update for a user on a specific vault

function updateUser(address user, address vault) external;

Events

AllocateRewards

event AllocateRewards(address indexed user, address indexed vault, UD60x18 rewardAmount);

Claim

event Claim(address indexed user, UD60x18 rewardAmount);

UpdateVaultVotes

event UpdateVaultVotes(address indexed vault, UD60x18 votes, UD60x18 voteMultiplier);

SetRewardsPerYear

event SetRewardsPerYear(UD60x18 rewardsPerYear);

SetVoteMultiplier

event SetVoteMultiplier(address indexed vault, UD60x18 voteMultiplier);

AddDualMiningPool

event AddDualMiningPool(address indexed vault, address dualMiningPool);

RemoveDualMiningPool

event RemoveDualMiningPool(address indexed vault, address dualMiningPool);

Errors

VaultMining__NotVault

error VaultMining__NotVault(address caller);

VaultMining__InsufficientRewards

error VaultMining__InsufficientRewards(address user, UD60x18 rewardsAvailable, UD60x18 rewardsRequested);

Structs

VaultInfo

struct VaultInfo {
    UD60x18 totalShares;
    UD60x18 votes;
    uint256 __deprecated_lastRewardTimestamp;
    UD60x18 accRewardsPerShare;
    UD60x18 rewardDebt;
}

UserInfo

struct UserInfo {
    UD60x18 shares;
    UD60x18 __deprecated_reward;
    UD60x18 rewardDebt;
}

VaultVotes

struct VaultVotes {
    address vault;
    UD60x18 votes;
}

VaultMining

Git Source

Inherits: IVaultMining, OwnableInternal, ReentrancyGuard

State Variables

VAULT_REGISTRY

Address of the vault registry

address internal immutable VAULT_REGISTRY;

PREMIA

Address of the PREMIA token

address internal immutable PREMIA;

VX_PREMIA

Address of the vxPremia token

address internal immutable VX_PREMIA;

OPTION_REWARD

Address of the PREMIA physically settled options

address internal immutable OPTION_REWARD;

DEFAULT_VOTE_MULTIPLIER

If vote multiplier is zero or not set, we use this value instead

UD60x18 private constant DEFAULT_VOTE_MULTIPLIER = ONE;

Functions

constructor

constructor(address vaultRegistry, address premia, address vxPremia, address optionReward);

addRewards

Add rewards to the contract

function addRewards(UD60x18 amount) external nonReentrant;

getRewardsAvailable

Return amount of rewards not yet allocated

function getRewardsAvailable() external view returns (UD60x18);

getPendingVaultRewards

Return amount of pending rewards (not yet allocated) for a specific vault

function getPendingVaultRewards(address vault) external view returns (UD60x18);

_calculatePendingVaultRewardAmount

Calculate amount of rewards to allocate to the vault since last update

function _calculatePendingVaultRewardAmount(
    VaultMiningStorage.Layout storage l,
    VaultInfo storage vInfo,
    UD60x18 rewardAmount
) internal view returns (UD60x18);

getUserRewards

Return the amount of user rewards already allocated and available to claim. This only account for l.userRewards[user] and does NOT include pending reward updates.

function getUserRewards(address user) external view returns (UD60x18);

_calculateRewardsUpdate

Calculate the amount of rewards to allocate across all vaults since last update

function _calculateRewardsUpdate(VaultMiningStorage.Layout storage l) internal view returns (UD60x18 rewardAmount);

_calculateAccRewardsPerShare

Calculate the new accRewardsPerShare for a vault, based on total rewards to allocate, and share of rewards that vault should get

function _calculateAccRewardsPerShare(
    VaultMiningStorage.Layout storage l,
    VaultInfo storage vInfo,
    UD60x18 rewardAmount
) internal view returns (UD60x18 accRewardsPerShare);

getPendingUserRewardsFromVault

Return amount of pending rewards (not yet claimed) for a user for a vault This DOES NOT account for l.userRewards[user] and only account for pending rewards of given vault

function getPendingUserRewardsFromVault(address user, address vault) external view returns (UD60x18);

getTotalUserRewards

Return amount of total rewards (not yet claimed) for a user. This accounts for l.userRewards[user] and pending rewards of all vaults

function getTotalUserRewards(address user) external view returns (UD60x18);

getTotalVotes

Return the total amount of votes across all vaults (Used to calculate share of rewards allocation for each vault)

function getTotalVotes() external view returns (UD60x18);

getVaultInfo

Return internal variables for a vault

function getVaultInfo(address vault) external view returns (VaultInfo memory);

getUserInfo

Return internal variables for a user, on a specific vault

function getUserInfo(address user, address vault) external view returns (UserInfo memory);

getRewardsPerYear

Get the amount of rewards emitted per year

function getRewardsPerYear() external view returns (UD60x18);

setRewardsPerYear

Update the yearly emission rate of rewards

function setRewardsPerYear(UD60x18 rewardsPerYear) external onlyOwner;

getVoteMultiplier

Get the vote multiplier for a given vault

function getVoteMultiplier(address vault) external view returns (UD60x18);

setVoteMultiplier

Sets the vote multiplier for a specific vault

function setVoteMultiplier(address vault, UD60x18 voteMultiplier) external onlyOwner;

_setVoteMultiplier

function _setVoteMultiplier(address vault, UD60x18 voteMultiplier) internal;

addDualMiningPool

Add a dual mining pool for a specific vault

function addDualMiningPool(address vault, address dualMining) external onlyOwner;

removeDualMiningPool

Removes a dual mining pool from a specific vault

function removeDualMiningPool(address vault, address dualMining) external onlyOwner;

getDualMiningPools

Return list of dual mining pools for a given vault

function getDualMiningPools(address vault) public view returns (address[] memory);

previewOptionParams

OptionReward.previewOptionParams wrapper, returns the params for the option reward token. Note that the on-chain price is constantly updating, therefore, the strike price returned may not be the same as the strike price at the time of underwriting.

function previewOptionParams() external view returns (UD60x18 strike, uint64 maturity);

Returns

NameTypeDescription
strikeUD60x18the option strike price (18 decimals)
maturityuint64the option maturity timestamp

claimAll

Allocate pending rewards for a list of vaults, and claim max amount of rewards possible.

function claimAll(address[] calldata vaults) external nonReentrant;

claim

Allocate pending rewards for a list of vaults, and claim given amount of rewards.

function claim(address[] calldata vaults, UD60x18 amount) external nonReentrant;

Parameters

NameTypeDescription
vaultsaddress[]The vaults for which to trigger allocation of pending rewards
amountUD60x18The amount of rewards to claim.

_claimDualMiningRewards

Claim rewards from all dualMining contracts of given vaults

function _claimDualMiningRewards(address user, address[] calldata vaults) internal;

_claimRewards

Claim option rewards

function _claimRewards(VaultMiningStorage.Layout storage l, address user, UD60x18 amount) internal;

updateVaults

Trigger an update for all vaults

function updateVaults() public nonReentrant;

updateUser

Trigger an update for a user on a specific vault This needs to be called by the vault, anytime the user's shares change Can only be called by a vault registered on the VaultRegistry

function updateUser(address user, UD60x18 newUserShares, UD60x18 newTotalShares, UD60x18) external nonReentrant;

Parameters

NameTypeDescription
useraddressThe user to update
newUserSharesUD60x18The new amount of shares for the user
newTotalSharesUD60x18The new amount of total shares for the vault
<none>UD60x18

updateVault

Trigger an update for a vault

function updateVault(address vault) public nonReentrant;

_allocatePendingRewards

Allocate pending rewards from global reward emission

function _allocatePendingRewards(VaultMiningStorage.Layout storage l) internal;

_updateVault

function _updateVault(address vault, UD60x18 newTotalShares) internal returns (UD60x18 vaultRewards);

updateUser

Trigger an update for a user on a specific vault This needs to be called by the vault, anytime the user's shares change Can only be called by a vault registered on the VaultRegistry

function updateUser(address user, address vault) external nonReentrant;

Parameters

NameTypeDescription
useraddressThe user to update
vaultaddress

_updateUser

Update user rewards for a specific vault

function _updateUser(address user, address vault) internal;

_updateUser

Update user rewards for a list of vaults

function _updateUser(address user, address[] calldata vaults) internal;

_updateUser

Update user rewards for a specific vault

function _updateUser(address user, address vault, UD60x18 newUserShares, UD60x18 newTotalShares) internal;

_updateVaultAllocation

Update vault allocation based on votes and vote multiplier

function _updateVaultAllocation(VaultMiningStorage.Layout storage l, address vault) internal virtual;

_setVaultVotes

Set new vault votes, scaled by vote multiplier

function _setVaultVotes(VaultMiningStorage.Layout storage l, VaultVotes memory data) internal;

_revertIfNotVault

Revert if addr is not a vault

function _revertIfNotVault(address addr) internal view;

VaultMiningProxy

Git Source

Inherits: ProxyUpgradeableOwnable

Functions

constructor

constructor(address implementation, UD60x18 rewardsPerYear) ProxyUpgradeableOwnable(implementation);

VaultMiningStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VaultMining");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    UD60x18 rewardsPerYear;
    UD60x18 rewardsAvailable;
    mapping(address pool => IVaultMining.VaultInfo infos) vaultInfo;
    mapping(address pool => mapping(address user => IVaultMining.UserInfo info)) userInfo;
    UD60x18 totalVotes;
    mapping(address user => UD60x18) userRewards;
    uint256 lastUpdate;
    UD60x18 globalAccRewardsPerVote;
    mapping(address vault => EnumerableSet.AddressSet pools) dualMining;
    mapping(address vault => UD60x18 multiplier) voteMultiplier;
}

IMiningAddRewards

Git Source

Functions

addRewards

Add rewards to the mining contract

function addRewards(uint256 amount) external;

IPaymentSplitter

Git Source

Functions

pay

function pay(uint256 baseAmount, uint256 quoteAmount) external;

PaymentSplitter

Git Source

Inherits: IPaymentSplitter, ReentrancyGuard

State Variables

PREMIA

IERC20 public immutable PREMIA;

USDC

IERC20 public immutable USDC;

VX_PREMIA

IVxPremia public immutable VX_PREMIA;

MINING

IMiningAddRewards public immutable MINING;

Functions

constructor

constructor(IERC20 premia, IERC20 usdc, IVxPremia vxPremia, IMiningAddRewards mining);

pay

Distributes rewards to vxPREMIA staking contract, and send back PREMIA leftover to mining contract

function pay(uint256 premiaAmount, uint256 usdcAmount) external nonReentrant;

Parameters

NameTypeDescription
premiaAmountuint256Amount of PREMIA to send back to mining contract
usdcAmountuint256Amount of USDC to send to vxPREMIA staking contract

Contents

IVolatilityOracle

Git Source

Functions

formatParams

Pack IV model parameters into a single bytes32

This function is used to pack the parameters into a single variable, which is then used as input in update

function formatParams(int256[5] calldata params) external pure returns (bytes32 result);

Parameters

NameTypeDescription
paramsint256[5]Parameters of IV model to pack

Returns

NameTypeDescription
resultbytes32The packed parameters of IV model

parseParams

Unpack IV model parameters from a bytes32

function parseParams(bytes32 input) external pure returns (int256[5] memory params);

Parameters

NameTypeDescription
inputbytes32Packed IV model parameters to unpack

Returns

NameTypeDescription
paramsint256[5]The unpacked parameters of the IV model

updateParams

Update a list of Anchored eSSVI model parameters

function updateParams(
    address[] calldata tokens,
    bytes32[] calldata tau,
    bytes32[] calldata theta,
    bytes32[] calldata psi,
    bytes32[] calldata rho,
    UD60x18 riskFreeRate
) external;

Parameters

NameTypeDescription
tokensaddress[]List of the base tokens
taubytes32[]List of maturities
thetabytes32[]List of ATM total implied variance curves
psibytes32[]List of ATM skew curves
rhobytes32[]List of rho curves
riskFreeRateUD60x18The risk-free rate

getParams

Get the IV model parameters of a token pair

function getParams(address token) external view returns (VolatilityOracleStorage.Update memory);

Parameters

NameTypeDescription
tokenaddressThe token address

Returns

NameTypeDescription
<none>VolatilityOracleStorage.UpdateThe IV model parameters

getParamsUnpacked

Get unpacked IV model parameters

function getParamsUnpacked(address token) external view returns (VolatilityOracleStorage.Params memory);

Parameters

NameTypeDescription
tokenaddressThe token address

Returns

NameTypeDescription
<none>VolatilityOracleStorage.ParamsThe unpacked IV model parameters

getVolatility

Calculate the annualized volatility for given set of parameters

function getVolatility(address token, UD60x18 spot, UD60x18 strike, UD60x18 timeToMaturity)
    external
    view
    returns (UD60x18);

Parameters

NameTypeDescription
tokenaddressThe token address
spotUD60x18The spot price of the token
strikeUD60x18The strike price of the option
timeToMaturityUD60x18The time until maturity (denominated in years)

Returns

NameTypeDescription
<none>UD60x18The annualized implied volatility, where 1 is defined as 100%

getVolatility

Calculate the annualized volatility for given set of parameters

function getVolatility(address token, UD60x18 spot, UD60x18[] memory strike, UD60x18[] memory timeToMaturity)
    external
    view
    returns (UD60x18[] memory);

Parameters

NameTypeDescription
tokenaddressThe token address
spotUD60x18The spot price of the token
strikeUD60x18[]The strike price of the option
timeToMaturityUD60x18[]The time until maturity (denominated in years)

Returns

NameTypeDescription
<none>UD60x18[]The annualized implied volatility, where 1 is defined as 100%

getRiskFreeRate

Returns the current risk-free rate

function getRiskFreeRate() external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The current risk-free rate

Events

UpdateParameters

event UpdateParameters(address indexed token, bytes32 tau, bytes32 theta, bytes32 psi, bytes32 rho);

Errors

VolatilityOracle__ArrayLengthMismatch

error VolatilityOracle__ArrayLengthMismatch();

VolatilityOracle__OutOfBounds

error VolatilityOracle__OutOfBounds(int256 value);

VolatilityOracle__SpotIsZero

error VolatilityOracle__SpotIsZero();

VolatilityOracle__StrikeIsZero

error VolatilityOracle__StrikeIsZero();

VolatilityOracle__TimeToMaturityIsZero

error VolatilityOracle__TimeToMaturityIsZero();

VolatilityOracle

Git Source

Inherits: IVolatilityOracle, ReentrancyGuard, RelayerAccessManager

State Variables

DECIMALS

uint256 private constant DECIMALS = 12;

Functions

formatParams

Pack IV model parameters into a single bytes32

This function is used to pack the parameters into a single variable, which is then used as input in update

function formatParams(int256[5] calldata params) external pure returns (bytes32 result);

Parameters

NameTypeDescription
paramsint256[5]Parameters of IV model to pack

Returns

NameTypeDescription
resultbytes32The packed parameters of IV model

parseParams

Unpack IV model parameters from a bytes32

function parseParams(bytes32 input) external pure returns (int256[5] memory params);

Parameters

NameTypeDescription
inputbytes32Packed IV model parameters to unpack

Returns

NameTypeDescription
paramsint256[5]The unpacked parameters of the IV model

updateParams

Update a list of Anchored eSSVI model parameters

function updateParams(
    address[] calldata tokens,
    bytes32[] calldata tau,
    bytes32[] calldata theta,
    bytes32[] calldata psi,
    bytes32[] calldata rho,
    UD60x18 riskFreeRate
) external nonReentrant;

Parameters

NameTypeDescription
tokensaddress[]List of the base tokens
taubytes32[]List of maturities
thetabytes32[]List of ATM total implied variance curves
psibytes32[]List of ATM skew curves
rhobytes32[]List of rho curves
riskFreeRateUD60x18The risk-free rate

getParams

Get the IV model parameters of a token pair

function getParams(address token) external view returns (VolatilityOracleStorage.Update memory);

Parameters

NameTypeDescription
tokenaddressThe token address

Returns

NameTypeDescription
<none>VolatilityOracleStorage.UpdateThe IV model parameters

getParamsUnpacked

Get unpacked IV model parameters

function getParamsUnpacked(address token) external view returns (VolatilityOracleStorage.Params memory);

Parameters

NameTypeDescription
tokenaddressThe token address

Returns

NameTypeDescription
<none>VolatilityOracleStorage.ParamsThe unpacked IV model parameters

_findInterval

Finds the interval a particular value is located in.

function _findInterval(SD59x18[5] memory arr, SD59x18 value) internal pure returns (uint256);

Parameters

NameTypeDescription
arrSD59x18[5]The array of cutoff points that define the intervals
valueSD59x18The value to find the interval for

Returns

NameTypeDescription
<none>uint256The interval index that corresponds the value

_toArray59x18

Convert an int256[] array to a SD59x18[] array

function _toArray59x18(int256[5] memory src) internal pure returns (SD59x18[5] memory tgt);

Parameters

NameTypeDescription
srcint256[5]The array to be converted

Returns

NameTypeDescription
tgtSD59x18[5]The input array converted to a SD59x18[] array

_weightedAvg

function _weightedAvg(SD59x18 lam, SD59x18 value1, SD59x18 value2) internal pure returns (SD59x18);

getVolatility

Calculate the annualized volatility for given set of parameters

function getVolatility(address token, UD60x18 spot, UD60x18 strike, UD60x18 timeToMaturity)
    public
    view
    virtual
    returns (UD60x18);

Parameters

NameTypeDescription
tokenaddressThe token address
spotUD60x18The spot price of the token
strikeUD60x18The strike price of the option
timeToMaturityUD60x18The time until maturity (denominated in years)

Returns

NameTypeDescription
<none>UD60x18The annualized implied volatility, where 1 is defined as 100%

getVolatility

function getVolatility(address token, UD60x18 spot, UD60x18[] memory strike, UD60x18[] memory timeToMaturity)
    external
    view
    virtual
    returns (UD60x18[] memory);

getRiskFreeRate

function getRiskFreeRate() external view virtual returns (UD60x18);

Structs

Params

struct Params {
    SD59x18[5] tau;
    SD59x18[5] theta;
    SD59x18[5] psi;
    SD59x18[5] rho;
}

SliceInfo

struct SliceInfo {
    SD59x18 theta;
    SD59x18 psi;
    SD59x18 rho;
}

VolatilityOracleStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VolatilityOracle");

PARAM_BITS

uint256 internal constant PARAM_BITS = 51;

PARAM_BITS_MINUS_ONE

uint256 internal constant PARAM_BITS_MINUS_ONE = 50;

PARAM_AMOUNT

uint256 internal constant PARAM_AMOUNT = 5;

START_BIT

uint256 internal constant START_BIT = 204;

Functions

layout

function layout() internal pure returns (Layout storage l);

getParams

Returns the current parameters for token

function getParams(Layout storage l, address token) internal view returns (Update memory);

parseParams

Returns the parsed parameters for the encoded input

function parseParams(bytes32 input) internal pure returns (int256[5] memory params);

formatParams

Returns the encoded parameters for params

function formatParams(int256[5] memory params) internal pure returns (bytes32 result);

Structs

Update

struct Update {
    uint256 updatedAt;
    bytes32 tau;
    bytes32 theta;
    bytes32 psi;
    bytes32 rho;
}

Params

struct Params {
    int256[5] tau;
    int256[5] theta;
    int256[5] psi;
    int256[5] rho;
}

Layout

struct Layout {
    mapping(address token => Update) parameters;
    UD60x18 riskFreeRate;
}

Contents

OrderbookStream

Git Source

Functions

add

Emits PublishQuote event for quote

function add(Quote[] calldata quote) external;

Events

PublishQuote

event PublishQuote(
    IPoolFactory.PoolKey indexed poolKeyHash,
    address indexed provider,
    address taker,
    uint256 price,
    uint256 size,
    bool isBuy,
    uint256 deadline,
    uint256 salt,
    Signature signature,
    IPoolFactory.PoolKey poolKey
);

Structs

Signature

struct Signature {
    bytes32 r;
    bytes32 s;
    uint8 v;
}

Quote

struct Quote {
    IPoolFactory.PoolKey poolKey;
    address provider;
    address taker;
    uint256 price;
    uint256 size;
    bool isBuy;
    uint256 deadline;
    uint256 salt;
    Signature signature;
}

Contents

IPool

Git Source

Inherits: IPoolBase, IPoolCore, IPoolDepositWithdraw, IPoolEvents, IPoolTrade

IPoolBase

Git Source

Inherits: IERC1155Base, IERC1155Enumerable, IMulticall

Functions

name

get token collection name

function name() external view returns (string memory);

Returns

NameTypeDescription
<none>stringcollection name

Errors

Pool__UseTransferPositionToTransferLPTokens

error Pool__UseTransferPositionToTransferLPTokens();

IPoolCore

Git Source

Inherits: IPoolInternal

Functions

marketPrice

Get the current market price as normalized price

function marketPrice() external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The current market price as normalized price

takerFee

Calculates the fee for a trade based on the size and premium of the trade

function takerFee(address taker, UD60x18 size, uint256 premium, bool isPremiumNormalized, bool isOrderbook)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
premiumuint256The total cost of option(s) for a purchase (poolToken decimals)
isPremiumNormalizedboolWhether the premium given is already normalized by strike or not (Ex: For a strike of 1500, and a premium of 750, the normalized premium would be 0.5)
isOrderbookboolWhether the fee is for the fillQuoteOB function or not

Returns

NameTypeDescription
<none>uint256The taker fee for an option trade denormalized (poolToken decimals)

_takerFeeLowLevel

Calculates the fee for a trade based on the size and premiumNormalized of the trade.

WARNING: It is recommended to use takerFee instead of this function. This function is a lower level function here to be used when a pool has not yet be deployed, by calling it from the diamond contract directly rather than a pool proxy. If using it from the pool, you should pass the same value as the pool for strike and isCallPool in order to get the accurate takerFee

function _takerFeeLowLevel(
    address taker,
    UD60x18 size,
    UD60x18 premium,
    bool isPremiumNormalized,
    bool isOrderbook,
    UD60x18 strike,
    bool isCallPool
) external view returns (UD60x18);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
premiumUD60x18The total cost of option(s) for a purchase (18 decimals)
isPremiumNormalizedboolWhether the premium given is already normalized by strike or not (Ex: For a strike of 1500, and a premium of 750, the normalized premium would be 0.5)
isOrderbookboolWhether the fee is for the fillQuoteOB function or not
strikeUD60x18The strike of the option (18 decimals)
isCallPoolboolWhether the pool is a call pool or not

Returns

NameTypeDescription
<none>UD60x18The taker fee for an option trade denormalized. (18 decimals)

getPoolSettings

Returns all pool parameters used for deployment

function getPoolSettings()
    external
    view
    returns (address base, address quote, address oracleAdapter, UD60x18 strike, uint256 maturity, bool isCallPool);

Returns

NameTypeDescription
baseaddressAddress of base token
quoteaddressAddress of quote token
oracleAdapteraddressAddress of oracle adapter
strikeUD60x18The strike of the option (18 decimals)
maturityuint256The maturity timestamp of the option
isCallPoolboolWhether the pool is for call or put options

ticks

Returns all ticks in the pool, including net liquidity for each tick

function ticks() external view returns (IPoolInternal.TickWithRates[] memory);

Returns

NameTypeDescription
<none>IPoolInternal.TickWithRates[]ticks All pool ticks with the liquidityNet (18 decimals) of each tick

claim

Updates the claimable fees of a position and transfers the claimed fees to the operator of the position. Then resets the claimable fees to zero.

function claim(Position.Key calldata p) external returns (uint256);

Parameters

NameTypeDescription
pPosition.KeyThe position key

Returns

NameTypeDescription
<none>uint256The amount of claimed fees (poolToken decimals)

getClaimableFees

Returns total claimable fees for the position

function getClaimableFees(Position.Key calldata p) external view returns (uint256);

Parameters

NameTypeDescription
pPosition.KeyThe position key

Returns

NameTypeDescription
<none>uint256The total claimable fees for the position (poolToken decimals)

writeFrom

Underwrite an option by depositing collateral. By default the taker fee and referral are applied to the underwriter, if the caller is a registered vault the longReceiver is used instead.

function writeFrom(address underwriter, address longReceiver, UD60x18 size, address referrer) external;

Parameters

NameTypeDescription
underwriteraddressThe underwriter of the option (Collateral will be taken from this address, and it will receive the short token)
longReceiveraddressThe address which will receive the long token
sizeUD60x18The number of contracts being underwritten (18 decimals)
referreraddressThe referrer of the user doing the trade

annihilate

Annihilate a pair of long + short option contracts to unlock the stored collateral.

This function can be called post or prior to expiration.

function annihilate(UD60x18 size) external;

Parameters

NameTypeDescription
sizeUD60x18The size to annihilate (18 decimals)

annihilateFor

Annihilate a pair of long + short option contracts to unlock the stored collateral on behalf of another account. msg.sender must be approved through UserSettings.setAuthorizedAddress by the owner of the long/short contracts.

This function can be called post or prior to expiration.

function annihilateFor(address owner, UD60x18 size) external;

Parameters

NameTypeDescription
owneraddressThe owner of the shorts/longs to annihilate
sizeUD60x18The size to annihilate (18 decimals)

exercise

Exercises all long options held by caller

function exercise() external returns (uint256 exerciseValue, uint256 exerciseFee);

Returns

NameTypeDescription
exerciseValueuint256The exercise value as amount of collateral paid out to long holder (poolToken decimals)
exerciseFeeuint256The fee paid to protocol (poolToken decimals)

exerciseFor

Batch exercises all long options held by each holder, caller is reimbursed with the cost deducted from the proceeds of the exercised options. Only authorized agents may execute this function on behalf of the option holder.

function exerciseFor(address[] calldata holders, uint256 costPerHolder)
    external
    returns (uint256[] memory exerciseValues, uint256[] memory exerciseFees);

Parameters

NameTypeDescription
holdersaddress[]The holders of the contracts
costPerHolderuint256The cost charged by the authorized operator, per option holder (poolToken decimals)

Returns

NameTypeDescription
exerciseValuesuint256[]The exercise value as amount of collateral paid out per holder, ignoring costs applied during automatic exercise, but excluding protocol fees from amount (poolToken decimals)
exerciseFeesuint256[]The fees paid to protocol (poolToken decimals)

settle

Settles all short options held by caller

function settle() external returns (uint256 collateral);

Returns

NameTypeDescription
collateraluint256The amount of collateral left after settlement (poolToken decimals)

settleFor

Batch settles all short options held by each holder, caller is reimbursed with the cost deducted from the proceeds of the settled options. Only authorized operators may execute this function on behalf of the option holder.

function settleFor(address[] calldata holders, uint256 costPerHolder) external returns (uint256[] memory);

Parameters

NameTypeDescription
holdersaddress[]The holders of the contracts
costPerHolderuint256The cost charged by the authorized operator, per option holder (poolToken decimals)

Returns

NameTypeDescription
<none>uint256[]The amount of collateral left after settlement per holder, ignoring costs applied during automatic settlement (poolToken decimals)

settlePosition

Reconciles a user's position to account for settlement payouts post-expiration.

function settlePosition(Position.Key calldata p) external returns (uint256 collateral);

Parameters

NameTypeDescription
pPosition.KeyThe position key

Returns

NameTypeDescription
collateraluint256The amount of collateral left after settlement (poolToken decimals)

settlePositionFor

Batch reconciles each position to account for settlement payouts post-expiration. Caller is reimbursed with the cost deducted from the proceeds of the settled position. Only authorized operators may execute this function on behalf of the option holder.

function settlePositionFor(Position.Key[] calldata p, uint256 costPerHolder) external returns (uint256[] memory);

Parameters

NameTypeDescription
pPosition.Key[]The position keys
costPerHolderuint256The cost charged by the authorized operator, per position holder (poolToken decimals)

Returns

NameTypeDescription
<none>uint256[]The amount of collateral left after settlement per holder, ignoring costs applied during automatic settlement (poolToken decimals)

transferPosition

Transfer a LP position to a new owner/operator

function transferPosition(Position.Key calldata srcP, address newOwner, address newOperator, UD60x18 size) external;

Parameters

NameTypeDescription
srcPPosition.KeyThe position key
newOwneraddressThe new owner
newOperatoraddressThe new operator
sizeUD60x18The size to transfer (18 decimals)

tryCacheSettlementPrice

Attempts to cache the settlement price of the option after expiration. Reverts if a price has already been cached

function tryCacheSettlementPrice() external;

getSettlementPrice

Returns the settlement price of the option.

function getSettlementPrice() external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The settlement price of the option (18 decimals). Returns 0 if option is not settled yet.

getStrandedArea

Gets the lower and upper bound of the stranded market area when it exists. In case the stranded market area does not exist it will return the stranded market area the maximum tick price for both the lower and the upper, in which case the market price is not stranded given any range order info order.

function getStrandedArea() external view returns (UD60x18 lower, UD60x18 upper);

Returns

NameTypeDescription
lowerUD60x18Lower bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)
upperUD60x18Upper bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)

getTokenIds

Returns the list of existing tokenIds with non zero balance

function getTokenIds() external view returns (uint256[] memory);

Returns

NameTypeDescription
<none>uint256[]tokenIds The list of existing tokenIds

IPoolDepositWithdraw

Git Source

Inherits: IPoolInternal

Functions

deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool. Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function deposit(
    Position.Key calldata p,
    UD60x18 belowLower,
    UD60x18 belowUpper,
    UD60x18 size,
    UD60x18 minMarketPrice,
    UD60x18 maxMarketPrice
) external returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyThe position key
belowLowerUD60x18The normalized price of nearest existing tick below lower. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
belowUpperUD60x18The normalized price of nearest existing tick below upper. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
sizeUD60x18The position size to deposit (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool. Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function deposit(
    Position.Key calldata p,
    UD60x18 belowLower,
    UD60x18 belowUpper,
    UD60x18 size,
    UD60x18 minMarketPrice,
    UD60x18 maxMarketPrice,
    bool isBidIfStrandedMarketPrice
) external returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyThe position key
belowLowerUD60x18The normalized price of nearest existing tick below lower. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
belowUpperUD60x18The normalized price of nearest existing tick below upper. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
sizeUD60x18The position size to deposit (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)
isBidIfStrandedMarketPriceboolWhether this is a bid or ask order when the market price is stranded (This argument doesnt matter if market price is not stranded)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

withdraw

Withdraws a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) from the pool. Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function withdraw(Position.Key calldata p, UD60x18 size, UD60x18 minMarketPrice, UD60x18 maxMarketPrice)
    external
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyThe position key
sizeUD60x18The position size to withdraw (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts withdrawn

getNearestTicksBelow

Get nearest ticks below lower and upper.

If no tick between lower and upper, then the nearest tick below upper, will be lower

function getNearestTicksBelow(UD60x18 lower, UD60x18 upper)
    external
    view
    returns (UD60x18 nearestBelowLower, UD60x18 nearestBelowUpper);

Parameters

NameTypeDescription
lowerUD60x18The lower bound of the range (18 decimals)
upperUD60x18The upper bound of the range (18 decimals)

Returns

NameTypeDescription
nearestBelowLowerUD60x18The nearest tick below lower (18 decimals)
nearestBelowUpperUD60x18The nearest tick below upper (18 decimals)

IPoolEvents

Git Source

Events

UpdateTick

event UpdateTick(
    UD60x18 indexed tick,
    UD60x18 indexed prev,
    UD60x18 indexed next,
    SD59x18 delta,
    UD60x18 externalFeeRate,
    SD59x18 longDelta,
    SD59x18 shortDelta,
    uint256 counter
);

Deposit

event Deposit(
    address indexed owner,
    uint256 indexed tokenId,
    UD60x18 contractSize,
    UD60x18 collateral,
    UD60x18 longs,
    UD60x18 shorts,
    SD59x18 lastFeeRate,
    UD60x18 claimableFees,
    UD60x18 marketPrice,
    UD60x18 liquidityRate,
    UD60x18 currentTick
);

Withdrawal

event Withdrawal(
    address indexed owner,
    uint256 indexed tokenId,
    UD60x18 contractSize,
    UD60x18 collateral,
    UD60x18 longs,
    UD60x18 shorts,
    SD59x18 lastFeeRate,
    UD60x18 claimableFees,
    UD60x18 marketPrice,
    UD60x18 liquidityRate,
    UD60x18 currentTick
);

ClaimFees

event ClaimFees(address indexed owner, uint256 indexed tokenId, UD60x18 feesClaimed, SD59x18 lastFeeRate);

ClaimProtocolFees

event ClaimProtocolFees(address indexed feeReceiver, UD60x18 feesClaimed);

FillQuoteOB

event FillQuoteOB(
    bytes32 indexed quoteOBHash,
    address indexed user,
    address indexed provider,
    UD60x18 contractSize,
    Position.Delta deltaMaker,
    Position.Delta deltaTaker,
    UD60x18 premium,
    UD60x18 protocolFee,
    UD60x18 totalReferralRebate,
    bool isBuy
);

WriteFrom

event WriteFrom(
    address indexed underwriter,
    address indexed longReceiver,
    address indexed taker,
    UD60x18 contractSize,
    UD60x18 collateral,
    UD60x18 protocolFee
);

Trade

event Trade(
    address indexed user,
    UD60x18 contractSize,
    Position.Delta delta,
    UD60x18 premium,
    UD60x18 takerFee,
    UD60x18 protocolFee,
    UD60x18 marketPrice,
    UD60x18 liquidityRate,
    UD60x18 currentTick,
    UD60x18 totalReferralRebate,
    bool isBuy
);

Exercise

event Exercise(
    address indexed operator,
    address indexed holder,
    UD60x18 contractSize,
    UD60x18 exerciseValue,
    UD60x18 settlementPrice,
    UD60x18 fee,
    UD60x18 operatorCost
);

Settle

event Settle(
    address indexed operator,
    address indexed holder,
    UD60x18 contractSize,
    UD60x18 exerciseValue,
    UD60x18 settlementPrice,
    UD60x18 fee,
    UD60x18 operatorCost
);

Annihilate

event Annihilate(address indexed owner, UD60x18 contractSize, uint256 fee);

SettlePosition

event SettlePosition(
    address indexed operator,
    address indexed owner,
    uint256 indexed tokenId,
    UD60x18 contractSize,
    UD60x18 collateral,
    UD60x18 exerciseValue,
    UD60x18 feesClaimed,
    UD60x18 settlementPrice,
    UD60x18 fee,
    UD60x18 operatorCost
);

TransferPosition

event TransferPosition(
    address indexed owner, address indexed receiver, uint256 srcTokenId, uint256 destTokenId, UD60x18 contractSize
);

CancelQuoteOB

event CancelQuoteOB(address indexed provider, bytes32 quoteOBHash);

FlashLoan

event FlashLoan(address indexed initiator, address indexed receiver, UD60x18 amount, UD60x18 fee);

SettlementPriceCached

event SettlementPriceCached(UD60x18 settlementPrice);

IPoolInternal

Git Source

Inherits: IPosition, IPricing

Errors

Pool__AboveQuoteSize

error Pool__AboveQuoteSize(UD60x18 size, UD60x18 quoteSize);

Pool__AboveMaxSlippage

error Pool__AboveMaxSlippage(uint256 value, uint256 minimum, uint256 maximum);

Pool__ActionNotAuthorized

error Pool__ActionNotAuthorized(address user, address sender, IUserSettings.Action action);

Pool__CostExceedsPayout

error Pool__CostExceedsPayout(UD60x18 cost, UD60x18 payout);

Pool__CostNotAuthorized

error Pool__CostNotAuthorized(UD60x18 costInWrappedNative, UD60x18 authorizedCostInWrappedNative);

Pool__DifferenceOfSizeAndContractDeltaTooLarge

error Pool__DifferenceOfSizeAndContractDeltaTooLarge(UD60x18 diff, UD60x18 size);

Pool__FlashLoanCallbackFailed

error Pool__FlashLoanCallbackFailed();

Pool__FlashLoanNotRepayed

error Pool__FlashLoanNotRepayed();

Pool__InsufficientAskLiquidity

error Pool__InsufficientAskLiquidity();

Pool__InsufficientBidLiquidity

error Pool__InsufficientBidLiquidity();

Pool__InsufficientFunds

error Pool__InsufficientFunds();

Pool__InsufficientLiquidity

error Pool__InsufficientLiquidity();

Pool__InvalidAssetUpdate

error Pool__InvalidAssetUpdate(SD59x18 deltaLongs, SD59x18 deltaShorts);

Pool__InvalidBelowPrice

error Pool__InvalidBelowPrice(UD60x18 price, UD60x18 priceBelow);

Pool__InvalidMonth

error Pool__InvalidMonth(uint256 month);

Pool__InvalidPositionState

error Pool__InvalidPositionState(uint256 balance, uint256 lastDeposit);

Pool__InvalidQuoteOBSignature

error Pool__InvalidQuoteOBSignature();

Pool__InvalidQuoteOBTaker

error Pool__InvalidQuoteOBTaker();

Pool__InvalidRange

error Pool__InvalidRange(UD60x18 lower, UD60x18 upper);

Pool__InvalidReconciliation

error Pool__InvalidReconciliation(uint256 crossings);

Pool__InvalidSize

error Pool__InvalidSize(UD60x18 lower, UD60x18 upper, UD60x18 depositSize);

Pool__InvalidTickPrice

error Pool__InvalidTickPrice();

Pool__InvalidTickUpdate

error Pool__InvalidTickUpdate();

Pool__InvalidTransfer

error Pool__InvalidTransfer();

Pool__NotEnoughTokens

error Pool__NotEnoughTokens(UD60x18 balance, UD60x18 size);

Pool__NotPoolToken

error Pool__NotPoolToken(address token);

Pool__NotWrappedNativeTokenPool

error Pool__NotWrappedNativeTokenPool();

Pool__OperatorNotAuthorized

error Pool__OperatorNotAuthorized(address sender);

Pool__OptionExpired

error Pool__OptionExpired();

Pool__OptionNotExpired

error Pool__OptionNotExpired();

Pool__OutOfBoundsPrice

error Pool__OutOfBoundsPrice(UD60x18 price);

Pool__PositionDoesNotExist

error Pool__PositionDoesNotExist(address owner, uint256 tokenId);

Pool__PositionCantHoldLongAndShort

error Pool__PositionCantHoldLongAndShort(UD60x18 longs, UD60x18 shorts);

Pool__QuoteOBCancelled

error Pool__QuoteOBCancelled();

Pool__QuoteOBExpired

error Pool__QuoteOBExpired();

Pool__QuoteOBOverfilled

error Pool__QuoteOBOverfilled(UD60x18 filledAmount, UD60x18 size, UD60x18 quoteOBSize);

Pool__SettlementFailed

error Pool__SettlementFailed();

Pool__SettlementPriceAlreadyCached

error Pool__SettlementPriceAlreadyCached();

Pool__TickDeltaNotZero

error Pool__TickDeltaNotZero(SD59x18 tickDelta);

Pool__TickNotFound

error Pool__TickNotFound(UD60x18 price);

Pool__TickOutOfRange

error Pool__TickOutOfRange(UD60x18 price);

Pool__TickWidthInvalid

error Pool__TickWidthInvalid(UD60x18 price);

Pool__WithdrawalDelayNotElapsed

error Pool__WithdrawalDelayNotElapsed(uint256 unlockTime);

Pool__ZeroSize

error Pool__ZeroSize();

Structs

Tick

struct Tick {
    SD49x28 delta;
    UD50x28 externalFeeRate;
    SD49x28 longDelta;
    SD49x28 shortDelta;
    uint256 counter;
}

TickWithRates

struct TickWithRates {
    Tick tick;
    UD60x18 price;
    UD50x28 longRate;
    UD50x28 shortRate;
}

QuoteOB

struct QuoteOB {
    address provider;
    address taker;
    UD60x18 price;
    UD60x18 size;
    bool isBuy;
    uint256 deadline;
    uint256 salt;
}

TradeArgsInternal

struct TradeArgsInternal {
    address user;
    address referrer;
    UD60x18 size;
    bool isBuy;
    uint256 premiumLimit;
}

ReferralVarsInternal

struct ReferralVarsInternal {
    UD60x18 totalRebate;
    UD60x18 primaryRebate;
    UD60x18 secondaryRebate;
}

TradeVarsInternal

struct TradeVarsInternal {
    UD60x18 maxSize;
    UD60x18 tradeSize;
    UD50x28 oldMarketPrice;
    UD60x18 totalPremium;
    UD60x18 totalTakerFees;
    UD60x18 totalProtocolFees;
    UD50x28 longDelta;
    UD50x28 shortDelta;
    ReferralVarsInternal referral;
    UD60x18 totalMintBurn;
    UD60x18 offset;
    UD60x18 premiumWithFees;
}

DepositArgsInternal

struct DepositArgsInternal {
    UD60x18 belowLower;
    UD60x18 belowUpper;
    UD60x18 size;
    UD60x18 minMarketPrice;
    UD60x18 maxMarketPrice;
}

WithdrawVarsInternal

struct WithdrawVarsInternal {
    bytes32 pKeyHash;
    uint256 tokenId;
    UD60x18 initialSize;
    UD50x28 liquidityPerTick;
    bool isFullWithdrawal;
    SD49x28 tickDelta;
}

Signature

struct Signature {
    uint8 v;
    bytes32 r;
    bytes32 s;
}

FillQuoteOBArgsInternal

struct FillQuoteOBArgsInternal {
    address user;
    address referrer;
    UD60x18 size;
    Signature signature;
}

PremiumAndFeeInternal

struct PremiumAndFeeInternal {
    UD60x18 totalReferralRebate;
    UD60x18 premium;
    UD60x18 protocolFee;
    UD60x18 premiumTaker;
    ReferralVarsInternal referral;
}

QuoteAMMVarsInternal

struct QuoteAMMVarsInternal {
    UD60x18 liquidity;
    UD60x18 maxSize;
    UD60x18 totalPremium;
    UD60x18 totalTakerFee;
}

SettlePositionVarsInternal

struct SettlePositionVarsInternal {
    bytes32 pKeyHash;
    uint256 tokenId;
    UD60x18 size;
    UD60x18 claimableFees;
    UD60x18 payoff;
    UD60x18 collateral;
}

Enums

InvalidQuoteOBError

enum InvalidQuoteOBError {
    None,
    QuoteOBExpired,
    QuoteOBCancelled,
    QuoteOBOverfilled,
    OutOfBoundsPrice,
    InvalidQuoteOBTaker,
    InvalidQuoteOBSignature,
    InvalidAssetUpdate,
    InsufficientCollateralAllowance,
    InsufficientCollateralBalance,
    InsufficientLongBalance,
    InsufficientShortBalance
}

IPoolTrade

Git Source

Inherits: IPoolInternal, IERC3156FlashLender

Functions

getQuoteAMM

Gives a quote for an AMM trade

function getQuoteAMM(address taker, UD60x18 size, bool isBuy)
    external
    view
    returns (uint256 premiumNet, uint256 takerFee);

Parameters

NameTypeDescription
takeraddressThe taker of the trade
sizeUD60x18The number of contracts being traded (18 decimals)
isBuyboolWhether the taker is buying or selling

Returns

NameTypeDescription
premiumNetuint256The premium which has to be paid to complete the trade (Net of fees) (poolToken decimals)
takerFeeuint256The taker fees to pay (Included in premiumNet) (poolToken decimals)

fillQuoteOB

Functionality to support the OB / OTC system. An LP can create a OB quote for which he will do an OTC trade through the exchange. Takers can buy from / sell to the LP partially or fully while having the price guaranteed.

function fillQuoteOB(QuoteOB calldata quoteOB, UD60x18 size, Signature calldata signature, address referrer)
    external
    returns (uint256 premiumTaker, Position.Delta memory delta);

Parameters

NameTypeDescription
quoteOBQuoteOBThe OB quote given by the provider
sizeUD60x18The size to fill from the OB quote (18 decimals)
signatureSignaturesecp256k1 'r', 's', and 'v' value
referreraddressThe referrer of the user filling the OB quote

Returns

NameTypeDescription
premiumTakeruint256The premium paid or received by the taker for the trade (poolToken decimals)
deltaPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

trade

Completes a trade of size on side via the AMM using the liquidity in the Pool. Tx will revert if total premium is above totalPremium when buying, or below totalPremium when selling.

function trade(UD60x18 size, bool isBuy, uint256 premiumLimit, address referrer)
    external
    returns (uint256 totalPremium, Position.Delta memory delta);

Parameters

NameTypeDescription
sizeUD60x18The number of contracts being traded (18 decimals)
isBuyboolWhether the taker is buying or selling
premiumLimituint256Tx will revert if total premium is above this value when buying, or below this value when selling. (poolToken decimals)
referreraddressThe referrer of the user doing the trade

Returns

NameTypeDescription
totalPremiumuint256The premium paid or received by the taker for the trade (poolToken decimals)
deltaPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

cancelQuotesOB

Cancel given OB quotes

No check is done to ensure the given hash correspond to a OB quote provider by msg.sender, but as we register the cancellation in a mapping provider -> hash, it is not possible to cancel a OB quote created by another provider

function cancelQuotesOB(bytes32[] calldata hashes) external;

Parameters

NameTypeDescription
hashesbytes32[]The hashes of the OB quotes to cancel

isQuoteOBValid

Returns whether or not an OB quote is valid, given a fill size

function isQuoteOBValid(address user, QuoteOB calldata quoteOB, UD60x18 size, Signature calldata sig)
    external
    view
    returns (bool, InvalidQuoteOBError);

Parameters

NameTypeDescription
useraddressThe address of the user that will call the fillQuoteOB function to fill the OB quote
quoteOBQuoteOBThe OB quote to check
sizeUD60x18Size to fill from the OB quote (18 decimals)
sigSignaturesecp256k1 Signature

getQuoteOBFilledAmount

Returns the size already filled for a given OB quote

function getQuoteOBFilledAmount(address provider, bytes32 quoteOBHash) external view returns (UD60x18);

Parameters

NameTypeDescription
provideraddressProvider of the OB quote
quoteOBHashbytes32Hash of the OB quote

Returns

NameTypeDescription
<none>UD60x18The size already filled (18 decimals)

PoolBase

Git Source

Inherits: IPoolBase, ERC1155Base, ERC1155Enumerable, ERC165Base, Multicall

Functions

name

get token collection name

function name() external view returns (string memory);

Returns

NameTypeDescription
<none>stringcollection name

_beforeTokenTransfer

_beforeTokenTransfer wrapper, reverts if transferring LP tokens

function _beforeTokenTransfer(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal);

PoolCore

Git Source

Inherits: IPoolCore, PoolInternal, ReentrancyGuard

Functions

constructor

constructor(
    address factory,
    address router,
    address wrappedNativeToken,
    address feeReceiver,
    address referral,
    address settings,
    address vaultRegistry,
    address vxPremia
) PoolInternal(factory, router, wrappedNativeToken, feeReceiver, referral, settings, vaultRegistry, vxPremia);

marketPrice

Get the current market price as normalized price

function marketPrice() external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The current market price as normalized price

takerFee

Calculates the fee for a trade based on the size and premium of the trade

function takerFee(address taker, UD60x18 size, uint256 premium, bool isPremiumNormalized, bool isOrderbook)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
premiumuint256The total cost of option(s) for a purchase (poolToken decimals)
isPremiumNormalizedboolWhether the premium given is already normalized by strike or not (Ex: For a strike of 1500, and a premium of 750, the normalized premium would be 0.5)
isOrderbookboolWhether the fee is for the fillQuoteOB function or not

Returns

NameTypeDescription
<none>uint256The taker fee for an option trade denormalized (poolToken decimals)

_takerFeeLowLevel

Calculates the fee for a trade based on the size and premiumNormalized of the trade.

WARNING: It is recommended to use takerFee instead of this function. This function is a lower level function here to be used when a pool has not yet be deployed, by calling it from the diamond contract directly rather than a pool proxy. If using it from the pool, you should pass the same value as the pool for strike and isCallPool in order to get the accurate takerFee

function _takerFeeLowLevel(
    address taker,
    UD60x18 size,
    UD60x18 premium,
    bool isPremiumNormalized,
    bool isOrderbook,
    UD60x18 strike,
    bool isCallPool
) external view returns (UD60x18);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
premiumUD60x18The total cost of option(s) for a purchase (18 decimals)
isPremiumNormalizedboolWhether the premium given is already normalized by strike or not (Ex: For a strike of 1500, and a premium of 750, the normalized premium would be 0.5)
isOrderbookboolWhether the fee is for the fillQuoteOB function or not
strikeUD60x18The strike of the option (18 decimals)
isCallPoolboolWhether the pool is a call pool or not

Returns

NameTypeDescription
<none>UD60x18The taker fee for an option trade denormalized. (18 decimals)

getPoolSettings

Returns all pool parameters used for deployment

function getPoolSettings()
    external
    view
    returns (address base, address quote, address oracleAdapter, UD60x18 strike, uint256 maturity, bool isCallPool);

Returns

NameTypeDescription
baseaddressAddress of base token
quoteaddressAddress of quote token
oracleAdapteraddressAddress of oracle adapter
strikeUD60x18The strike of the option (18 decimals)
maturityuint256The maturity timestamp of the option
isCallPoolboolWhether the pool is for call or put options

ticks

Returns all ticks in the pool, including net liquidity for each tick

function ticks() external view returns (IPoolInternal.TickWithRates[] memory);

Returns

NameTypeDescription
<none>IPoolInternal.TickWithRates[]ticks All pool ticks with the liquidityNet (18 decimals) of each tick

claim

Updates the claimable fees of a position and transfers the claimed fees to the operator of the position. Then resets the claimable fees to zero.

function claim(Position.Key calldata p) external nonReentrant returns (uint256);

Parameters

NameTypeDescription
pPosition.KeyThe position key

Returns

NameTypeDescription
<none>uint256The amount of claimed fees (poolToken decimals)

getClaimableFees

Returns total claimable fees for the position

function getClaimableFees(Position.Key calldata p) external view returns (uint256);

Parameters

NameTypeDescription
pPosition.KeyThe position key

Returns

NameTypeDescription
<none>uint256The total claimable fees for the position (poolToken decimals)

writeFrom

Underwrite an option by depositing collateral. By default the taker fee and referral are applied to the underwriter, if the caller is a registered vault the longReceiver is used instead.

function writeFrom(address underwriter, address longReceiver, UD60x18 size, address referrer) external nonReentrant;

Parameters

NameTypeDescription
underwriteraddressThe underwriter of the option (Collateral will be taken from this address, and it will receive the short token)
longReceiveraddressThe address which will receive the long token
sizeUD60x18The number of contracts being underwritten (18 decimals)
referreraddressThe referrer of the user doing the trade

annihilate

Annihilate a pair of long + short option contracts to unlock the stored collateral.

This function can be called post or prior to expiration.

function annihilate(UD60x18 size) external nonReentrant;

Parameters

NameTypeDescription
sizeUD60x18The size to annihilate (18 decimals)

annihilateFor

Annihilate a pair of long + short option contracts to unlock the stored collateral on behalf of another account. msg.sender must be approved through UserSettings.setAuthorizedAddress by the owner of the long/short contracts.

This function can be called post or prior to expiration.

function annihilateFor(address account, UD60x18 size) external nonReentrant;

Parameters

NameTypeDescription
accountaddress
sizeUD60x18The size to annihilate (18 decimals)

exercise

Exercises all long options held by caller

function exercise() external nonReentrant returns (uint256 exerciseValue, uint256 exerciseFee);

Returns

NameTypeDescription
exerciseValueuint256The exercise value as amount of collateral paid out to long holder (poolToken decimals)
exerciseFeeuint256The fee paid to protocol (poolToken decimals)

exerciseFor

Batch exercises all long options held by each holder, caller is reimbursed with the cost deducted from the proceeds of the exercised options. Only authorized agents may execute this function on behalf of the option holder.

function exerciseFor(address[] calldata holders, uint256 costPerHolder)
    external
    nonReentrant
    returns (uint256[] memory exerciseValues, uint256[] memory exerciseFees);

Parameters

NameTypeDescription
holdersaddress[]The holders of the contracts
costPerHolderuint256The cost charged by the authorized operator, per option holder (poolToken decimals)

Returns

NameTypeDescription
exerciseValuesuint256[]The exercise value as amount of collateral paid out per holder, ignoring costs applied during automatic exercise, but excluding protocol fees from amount (poolToken decimals)
exerciseFeesuint256[]The fees paid to protocol (poolToken decimals)

settle

Settles all short options held by caller

function settle() external nonReentrant returns (uint256 collateral);

Returns

NameTypeDescription
collateraluint256The amount of collateral left after settlement (poolToken decimals)

settleFor

Batch settles all short options held by each holder, caller is reimbursed with the cost deducted from the proceeds of the settled options. Only authorized operators may execute this function on behalf of the option holder.

function settleFor(address[] calldata holders, uint256 costPerHolder)
    external
    nonReentrant
    returns (uint256[] memory collateral);

Parameters

NameTypeDescription
holdersaddress[]The holders of the contracts
costPerHolderuint256The cost charged by the authorized operator, per option holder (poolToken decimals)

Returns

NameTypeDescription
collateraluint256[]The amount of collateral left after settlement per holder, ignoring costs applied during automatic settlement (poolToken decimals)

settlePosition

Reconciles a user's position to account for settlement payouts post-expiration.

function settlePosition(Position.Key calldata p) external nonReentrant returns (uint256 collateral);

Parameters

NameTypeDescription
pPosition.KeyThe position key

Returns

NameTypeDescription
collateraluint256The amount of collateral left after settlement (poolToken decimals)

settlePositionFor

Batch reconciles each position to account for settlement payouts post-expiration. Caller is reimbursed with the cost deducted from the proceeds of the settled position. Only authorized operators may execute this function on behalf of the option holder.

function settlePositionFor(Position.Key[] calldata p, uint256 costPerHolder)
    external
    nonReentrant
    returns (uint256[] memory collateral);

Parameters

NameTypeDescription
pPosition.Key[]The position keys
costPerHolderuint256The cost charged by the authorized operator, per position holder (poolToken decimals)

Returns

NameTypeDescription
collateraluint256[]The amount of collateral left after settlement per holder, ignoring costs applied during automatic settlement (poolToken decimals)

transferPosition

Transfer a LP position to a new owner/operator

function transferPosition(Position.Key calldata srcP, address newOwner, address newOperator, UD60x18 size)
    external
    nonReentrant;

Parameters

NameTypeDescription
srcPPosition.KeyThe position key
newOwneraddressThe new owner
newOperatoraddressThe new operator
sizeUD60x18The size to transfer (18 decimals)

tryCacheSettlementPrice

Attempts to cache the settlement price of the option after expiration. Reverts if a price has already been cached

function tryCacheSettlementPrice() external;

getSettlementPrice

Returns the settlement price of the option.

function getSettlementPrice() external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The settlement price of the option (18 decimals). Returns 0 if option is not settled yet.

getStrandedArea

Gets the lower and upper bound of the stranded market area when it exists. In case the stranded market area does not exist it will return the stranded market area the maximum tick price for both the lower and the upper, in which case the market price is not stranded given any range order info order.

function getStrandedArea() external view returns (UD60x18 lower, UD60x18 upper);

Returns

NameTypeDescription
lowerUD60x18Lower bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)
upperUD60x18Upper bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)

getTokenIds

Returns the list of existing tokenIds with non zero balance

function getTokenIds() external view returns (uint256[] memory);

Returns

NameTypeDescription
<none>uint256[]tokenIds The list of existing tokenIds

PoolDepositWithdraw

Git Source

Inherits: IPoolDepositWithdraw, PoolInternal, ReentrancyGuard

Functions

constructor

constructor(
    address factory,
    address router,
    address wrappedNativeToken,
    address feeReceiver,
    address referral,
    address settings,
    address vaultRegistry,
    address vxPremia
) PoolInternal(factory, router, wrappedNativeToken, feeReceiver, referral, settings, vaultRegistry, vxPremia);

deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool. Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function deposit(
    Position.Key calldata p,
    UD60x18 belowLower,
    UD60x18 belowUpper,
    UD60x18 size,
    UD60x18 minMarketPrice,
    UD60x18 maxMarketPrice
) external nonReentrant returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyThe position key
belowLowerUD60x18The normalized price of nearest existing tick below lower. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
belowUpperUD60x18The normalized price of nearest existing tick below upper. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
sizeUD60x18The position size to deposit (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool. Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function deposit(
    Position.Key calldata p,
    UD60x18 belowLower,
    UD60x18 belowUpper,
    UD60x18 size,
    UD60x18 minMarketPrice,
    UD60x18 maxMarketPrice,
    bool isBidIfStrandedMarketPrice
) external nonReentrant returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyThe position key
belowLowerUD60x18The normalized price of nearest existing tick below lower. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
belowUpperUD60x18The normalized price of nearest existing tick below upper. The search is done off-chain, passed as arg and validated on-chain to save gas (18 decimals)
sizeUD60x18The position size to deposit (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)
isBidIfStrandedMarketPricebool

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

withdraw

Withdraws a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) from the pool. Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function withdraw(Position.Key calldata p, UD60x18 size, UD60x18 minMarketPrice, UD60x18 maxMarketPrice)
    external
    nonReentrant
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyThe position key
sizeUD60x18The position size to withdraw (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts withdrawn

getNearestTicksBelow

Get nearest ticks below lower and upper.

If no tick between lower and upper, then the nearest tick below upper, will be lower

function getNearestTicksBelow(UD60x18 lower, UD60x18 upper)
    external
    view
    returns (UD60x18 nearestBelowLower, UD60x18 nearestBelowUpper);

Parameters

NameTypeDescription
lowerUD60x18The lower bound of the range (18 decimals)
upperUD60x18The upper bound of the range (18 decimals)

Returns

NameTypeDescription
nearestBelowLowerUD60x18The nearest tick below lower (18 decimals)
nearestBelowUpperUD60x18The nearest tick below upper (18 decimals)

PoolInternal

Git Source

Inherits: IPoolInternal, IPoolEvents, ERC1155EnumerableInternal

State Variables

FACTORY

address internal immutable FACTORY;

ROUTER

address internal immutable ROUTER;

WRAPPED_NATIVE_TOKEN

address internal immutable WRAPPED_NATIVE_TOKEN;

FEE_RECEIVER

address internal immutable FEE_RECEIVER;

REFERRAL

address internal immutable REFERRAL;

SETTINGS

address internal immutable SETTINGS;

VAULT_REGISTRY

address internal immutable VAULT_REGISTRY;

VXPREMIA

address internal immutable VXPREMIA;

PROTOCOL_FEE_PERCENTAGE

UD60x18 internal constant PROTOCOL_FEE_PERCENTAGE = UD60x18.wrap(0.5e18);

AMM_PREMIUM_FEE_PERCENTAGE

UD60x18 internal constant AMM_PREMIUM_FEE_PERCENTAGE = UD60x18.wrap(0.03e18);

AMM_NOTIONAL_FEE_PERCENTAGE

UD60x18 internal constant AMM_NOTIONAL_FEE_PERCENTAGE = UD60x18.wrap(0.003e18);

ORDERBOOK_NOTIONAL_FEE_PERCENTAGE

UD60x18 internal constant ORDERBOOK_NOTIONAL_FEE_PERCENTAGE = UD60x18.wrap(0.0008e18);

MAX_PREMIUM_FEE_PERCENTAGE

UD60x18 internal constant MAX_PREMIUM_FEE_PERCENTAGE = UD60x18.wrap(0.125e18);

EXERCISE_FEE_PERCENTAGE

UD60x18 internal constant EXERCISE_FEE_PERCENTAGE = UD60x18.wrap(0.003e18);

MAX_EXERCISE_FEE_PERCENTAGE

UD60x18 internal constant MAX_EXERCISE_FEE_PERCENTAGE = UD60x18.wrap(0.125e18);

WITHDRAWAL_DELAY

uint256 internal constant WITHDRAWAL_DELAY = 60;

FILL_QUOTE_OB_TYPE_HASH

bytes32 internal constant FILL_QUOTE_OB_TYPE_HASH = keccak256(
    "FillQuoteOB(address provider,address taker,uint256 price,uint256 size,bool isBuy,uint256 deadline,uint256 salt)"
);

Functions

constructor

constructor(
    address factory,
    address router,
    address wrappedNativeToken,
    address feeReceiver,
    address referral,
    address settings,
    address vaultRegistry,
    address vxPremia
);

_takerFee

Calculates the fee for a trade based on the size and premium of the trade.

function _takerFee(
    address taker,
    UD60x18 size,
    UD60x18 premium,
    bool isPremiumNormalized,
    UD60x18 strike,
    bool isCallPool,
    bool isOrderbook
) internal view returns (UD60x18);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
premiumUD60x18The total cost of option(s) for a purchase (18 decimals)
isPremiumNormalizedboolWhether the premium given is already normalized by strike or not (Ex: For a strike of 1500, and a premium of 750, the normalized premium would be 0.5)
strikeUD60x18The strike of the option (18 decimals)
isCallPoolboolWhether the pool is a call pool or not
isOrderbookboolWhether the fee is for the fillQuoteOB function or not

Returns

NameTypeDescription
<none>UD60x18The taker fee for an option trade denormalized. (18 decimals)

_exerciseFee

Calculates the fee for an exercise. It is the minimum between a percentage of the intrinsic value of options exercised, or a percentage of the notional value.

function _exerciseFee(address taker, UD60x18 size, UD60x18 intrinsicValue, UD60x18 strike, bool isCallPool)
    internal
    view
    returns (UD60x18);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
intrinsicValueUD60x18Total intrinsic value of all the contracts exercised, denormalized (18 decimals)
strikeUD60x18The strike of the option (18 decimals)
isCallPoolboolWhether the pool is a call pool or not

Returns

NameTypeDescription
<none>UD60x18The fee to exercise an option, denormalized (18 decimals)

_getQuoteAMM

Gives a quote for a trade

function _getQuoteAMM(address taker, UD60x18 size, bool isBuy)
    internal
    view
    returns (uint256 totalNetPremium, uint256 totalTakerFee);

Parameters

NameTypeDescription
takeraddressThe taker of the trade
sizeUD60x18The number of contracts being traded (18 decimals)
isBuyboolWhether the taker is buying or selling

Returns

NameTypeDescription
totalNetPremiumuint256The premium which has to be paid to complete the trade (Net of fees) (poolToken decimals)
totalTakerFeeuint256The taker fees to pay (Included in premiumNet) (poolToken decimals)

_pendingClaimableFees

Returns amount of claimable fees from pending update of claimable fees for the position. This does not include pData.claimableFees

function _pendingClaimableFees(
    PoolStorage.Layout storage l,
    Position.KeyInternal memory p,
    Position.Data storage pData,
    UD60x18 balance
) internal view returns (UD60x18 claimableFees, SD49x28 feeRate);

_calculateClaimableFees

Returns the amount of fees an LP can claim for a position (without claiming)

function _calculateClaimableFees(SD49x28 feeRate, SD49x28 lastFeeRate, UD50x28 liquidityPerTick)
    internal
    pure
    returns (UD60x18);

_updateClaimableFees

Updates the amount of fees an LP can claim for a position (without claiming)

function _updateClaimableFees(Position.Data storage pData, SD49x28 feeRate, UD50x28 liquidityPerTick) internal;

_updateClaimableFees

Updates the amount of fees an LP can claim for a position

function _updateClaimableFees(
    PoolStorage.Layout storage l,
    Position.KeyInternal memory p,
    Position.Data storage pData,
    UD60x18 balance
) internal;

_claim

Updates the claimable fees of a position and transfers the claimed fees to the operator of the position. Then resets the claimable fees to zero.

function _claim(Position.KeyInternal memory p) internal returns (uint256);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position to claim fees for

Returns

NameTypeDescription
<none>uint256The amount of fees claimed (poolToken decimals)

_claimProtocolFees

Claims the protocol fees and transfers them to the fee receiver

function _claimProtocolFees() internal;

_deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool.

function _deposit(Position.KeyInternal memory p, DepositArgsInternal memory args)
    internal
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
argsDepositArgsInternalThe deposit parameters

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

_deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool.

function _deposit(Position.KeyInternal memory p, DepositArgsInternal memory args, bool isBidIfStrandedMarketPrice)
    internal
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
argsDepositArgsInternalThe deposit parameters
isBidIfStrandedMarketPriceboolWhether this is a bid or ask order when the market price is stranded (This argument doesnt matter if market price is not stranded)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

_depositFeeAndTicksUpdate

Handles fee/tick updates and mints LP token on deposit

function _depositFeeAndTicksUpdate(
    PoolStorage.Layout storage l,
    Position.Data storage pData,
    Position.KeyInternal memory p,
    UD60x18 belowLower,
    UD60x18 belowUpper,
    UD60x18 size,
    uint256 tokenId
) internal;

_withdraw

Withdraws a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) from the pool Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function _withdraw(Position.KeyInternal memory p, UD60x18 size, UD60x18 minMarketPrice, UD60x18 maxMarketPrice)
    internal
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
sizeUD60x18The position size to withdraw (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts withdrawn

_transferTokens

Handle transfer of collateral / longs / shorts on deposit or withdrawal

WARNING: collateral must be scaled to the collateral token decimals

function _transferTokens(
    PoolStorage.Layout storage l,
    address from,
    address to,
    uint256 collateral,
    UD60x18 longs,
    UD60x18 shorts
) internal;

_writeFrom

Transfers collateral + fees from underwriter and sends long/short tokens to both parties

function _writeFrom(address underwriter, address longReceiver, UD60x18 size, address referrer) internal;

_trade

Completes a trade of size on side via the AMM using the liquidity in the Pool.

function _trade(TradeArgsInternal memory args)
    internal
    returns (uint256 premiumWithFees, Position.Delta memory delta);

Parameters

NameTypeDescription
argsTradeArgsInternalTrade parameters

Returns

NameTypeDescription
premiumWithFeesuint256The premium paid or received by the taker for the trade (poolToken decimals)
deltaPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

_getPricing

Returns the pricing arguments at the current tick

function _getPricing(PoolStorage.Layout storage l, bool isBuy) internal view returns (Pricing.Args memory);

_getTradeDelta

Compute the change in short / long option contracts of a user in order to transfer the contracts and execute a trade

function _getTradeDelta(address user, UD60x18 size, bool isBuy) internal view returns (Position.Delta memory delta);

_calculateAndUpdateUserAssets

function _calculateAndUpdateUserAssets(
    PoolStorage.Layout storage l,
    address user,
    UD60x18 totalPremium,
    UD60x18 size,
    bool isBuy
) internal returns (Position.Delta memory delta);

_calculateAssetsUpdate

Calculate the asset update for user

function _calculateAssetsUpdate(
    PoolStorage.Layout storage l,
    address user,
    UD60x18 totalPremium,
    UD60x18 size,
    bool isBuy
) internal view returns (Position.Delta memory delta);

_updateUserAssets

Execute a trade by transferring the net change in short and long option contracts and collateral to / from a user.

function _updateUserAssets(PoolStorage.Layout storage l, address user, Position.Delta memory delta) internal;

_calculateQuoteOBPremiumAndFee

Calculates the OB quote premium and fee

function _calculateQuoteOBPremiumAndFee(
    PoolStorage.Layout storage l,
    address taker,
    address referrer,
    UD60x18 size,
    UD60x18 price,
    bool isBuy
) internal view returns (PremiumAndFeeInternal memory r);

_fillQuoteOB

Functionality to support the OB / OTC system. An LP can create a OB quote for which he will do an OTC trade through the exchange. Takers can buy from / sell to the LP partially or fully while having the price guaranteed.

function _fillQuoteOB(FillQuoteOBArgsInternal memory args, QuoteOB memory quoteOB)
    internal
    returns (uint256 premiumTaker, Position.Delta memory deltaTaker);

Parameters

NameTypeDescription
argsFillQuoteOBArgsInternalThe fillQuoteOB parameters
quoteOBQuoteOBThe OB quote given by the provider

Returns

NameTypeDescription
premiumTakeruint256The premium paid by the taker (poolToken decimals)
deltaTakerPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

_annihilate

Annihilate a pair of long + short option contracts to unlock the stored collateral.

This function can be called post or prior to expiration.

function _annihilate(address owner, UD60x18 size) internal;

_transferPosition

Transfer an LP position to another owner.

This function can be called post or prior to expiration.

function _transferPosition(Position.KeyInternal memory srcP, address newOwner, address newOperator, UD60x18 size)
    internal;

Parameters

NameTypeDescription
srcPPosition.KeyInternalThe position key
newOwneraddressThe new owner of the transferred liquidity
newOperatoraddressThe new operator of the transferred liquidity
sizeUD60x18

_calculateExerciseValue

Calculates the exercise value of a position

function _calculateExerciseValue(PoolStorage.Layout storage l, UD60x18 size) internal returns (UD60x18);

_calculateCollateralValue

Calculates the collateral value of a position

function _calculateCollateralValue(PoolStorage.Layout storage l, UD60x18 size, UD60x18 exerciseValue)
    internal
    view
    returns (UD60x18);

_beforeExerciseOrSettle

Handle operations that need to be done before exercising or settling

function _beforeExerciseOrSettle(PoolStorage.Layout storage l, bool isLong, address holder)
    internal
    returns (UD60x18 size, UD60x18 exerciseValue, UD60x18 collateral);

_exercise

Exercises all long options held by an owner

function _exercise(address holder, UD60x18 costPerHolder)
    internal
    returns (uint256 exerciseValue, uint256 exerciseFee, bool success);

Parameters

NameTypeDescription
holderaddressThe holder of the contracts
costPerHolderUD60x18The cost charged by the authorized operator, per option holder (18 decimals)

Returns

NameTypeDescription
exerciseValueuint256The amount of collateral resulting from the exercise, ignoring costs applied during automatic exercise (poolToken decimals)
exerciseFeeuint256The amount of fees paid to the protocol during exercise (18 decimals)
successboolWhether the exercise was successful or not. This will be false if size to exercise size was zero

_settle

Settles all short options held by an owner

function _settle(address holder, UD60x18 costPerHolder) internal returns (uint256 collateral, bool success);

Parameters

NameTypeDescription
holderaddressThe holder of the contracts
costPerHolderUD60x18The cost charged by the authorized operator, per option holder (18 decimals)

Returns

NameTypeDescription
collateraluint256The amount of collateral resulting from the settlement, ignoring costs applied during automatic settlement (poolToken decimals)
successboolWhether the settlement was successful or not. This will be false if size to settle was zero

_settlePosition

Reconciles a user's position to account for settlement payouts post-expiration.

function _settlePosition(Position.KeyInternal memory p, UD60x18 costPerHolder)
    internal
    returns (uint256 collateral, bool success);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
costPerHolderUD60x18The cost charged by the authorized operator, per position holder (18 decimals)

Returns

NameTypeDescription
collateraluint256The amount of collateral resulting from the settlement, ignoring costs applied during automatic settlement (poolToken decimals)
successboolWhether the settlement was successful or not. This will be false if size to settle was zero

_tryCacheSettlementPrice

Fetch and cache the settlement price, if it has not been cached yet. Returns the cached price

function _tryCacheSettlementPrice(PoolStorage.Layout storage l) internal returns (UD60x18);

_deletePosition

Deletes the pKeyHash from positions mapping

function _deletePosition(PoolStorage.Layout storage l, bytes32 pKeyHash) internal;

_getNearestTicksBelow

Returns the nearest tick below lower and the nearest tick below upper

function _getNearestTicksBelow(UD60x18 lower, UD60x18 upper)
    internal
    view
    returns (UD60x18 nearestBelowLower, UD60x18 nearestBelowUpper);

_getNearestTickBelow

Gets the nearest tick that is less than or equal to price

function _getNearestTickBelow(UD60x18 price) internal view returns (UD60x18);

_getTick

Get a tick, reverts if tick is not found

function _getTick(UD60x18 price) internal view returns (Tick memory);

_tryGetTick

Try to get tick, does not revert if tick is not found

function _tryGetTick(UD60x18 price) internal view returns (Tick memory tick, bool tickFound);

_getOrCreateTick

Creates a Tick for a given price, or returns the existing tick.

function _getOrCreateTick(UD60x18 price, UD60x18 priceBelow) internal returns (Tick memory);

Parameters

NameTypeDescription
priceUD60x18The price of the Tick (18 decimals)
priceBelowUD60x18The price of the nearest Tick below (18 decimals)

Returns

NameTypeDescription
<none>Ticktick The Tick for a given price

_removeTickIfNotActive

Removes a tick if it does not mark the beginning or the end of a range order.

function _removeTickIfNotActive(UD60x18 price) internal;

_updateTicks

Updates the tick deltas following a deposit or withdrawal

function _updateTicks(
    UD60x18 lower,
    UD60x18 upper,
    UD50x28 marketPrice,
    SD49x28 delta,
    bool isNewDeposit,
    bool isFullWithdrawal,
    Position.OrderType orderType
) internal;

_updateGlobalFeeRate

Updates the global fee rate

function _updateGlobalFeeRate(PoolStorage.Layout storage l, UD60x18 makerRebate) internal;

_cross

Crosses the active tick either to the left if the LT is selling to the pool. A cross is only executed if no bid or ask liquidity is remaining within the active tick range.

function _cross(bool isBuy) internal;

Parameters

NameTypeDescription
isBuyboolWhether the trade is a buy or a sell.

_rangeFeeRate

Calculates the growth and exposure change between the lower and upper Ticks of a Position.

l         ▼         u
----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|---------
=> (global - external(l) - external(u))
▼    l                   u
----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|---------
=> (global - (global - external(l)) - external(u))
l                   u    ▼
----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|---------
=> (global - external(l) - (global - external(u)))
function _rangeFeeRate(
    PoolStorage.Layout storage l,
    UD60x18 lower,
    UD60x18 upper,
    UD50x28 lowerTickExternalFeeRate,
    UD50x28 upperTickExternalFeeRate
) internal view returns (SD49x28);

_getStrandedArea

Gets the lower and upper bound of the stranded market area when it exists. In case the stranded market area does not exist it will return the stranded market area the maximum tick price for both the lower and the upper, in which case the market price is not stranded given any range order info order.

function _getStrandedArea(PoolStorage.Layout storage l) internal view returns (UD60x18 lower, UD60x18 upper);

Returns

NameTypeDescription
lowerUD60x18Lower bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)
upperUD60x18Upper bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)

_isMarketPriceStranded

Returns true if the market price is stranded

function _isMarketPriceStranded(PoolStorage.Layout storage l, Position.KeyInternal memory p, bool isBid)
    internal
    view
    returns (bool);

_getStrandedMarketPriceUpdate

In case the market price is stranded the market price needs to be set to the upper (lower) tick of the bid (ask) order.

function _getStrandedMarketPriceUpdate(Position.KeyInternal memory p, bool isBid) internal pure returns (UD50x28);

_revertIfTickWidthInvalid

Revert if the tick width is invalid

function _revertIfTickWidthInvalid(UD60x18 price) internal pure;

_quoteOBHash

Returns the encoded OB quote hash

function _quoteOBHash(IPoolInternal.QuoteOB memory quoteOB) internal view returns (bytes32);

_balanceOfUD60x18

Returns the balance of user for tokenId as UD60x18

function _balanceOfUD60x18(address user, uint256 tokenId) internal view returns (UD60x18);

_mint

Mints amount of id and assigns it to account

function _mint(address account, uint256 id, UD60x18 amount) internal;

_burn

Burns amount of id assigned to account

function _burn(address account, uint256 id, UD60x18 amount) internal;

_useReferral

Applies the primary and secondary referral rebates, if total rebates are greater than zero

function _useReferral(
    PoolStorage.Layout storage l,
    address user,
    address referrer,
    UD60x18 primaryReferralRebate,
    UD60x18 secondaryReferralRebate
) internal;

_isRateNonTerminating

Checks if the liquidity rate of the range results in a non-terminating decimal.

lower should NOT be equal to upper, to avoid running into an infinite loop

function _isRateNonTerminating(UD60x18 lower, UD60x18 upper) internal pure returns (bool);

_revertIfRangeInvalid

Revert if the lower and upper tick range is invalid

function _revertIfRangeInvalid(UD60x18 lower, UD60x18 upper) internal pure;

_revertIfZeroSize

Revert if size is zero

function _revertIfZeroSize(UD60x18 size) internal pure;

_revertIfOptionNotExpired

Revert if option is not expired

function _revertIfOptionNotExpired(PoolStorage.Layout storage l) internal view;

_revertIfOptionExpired

Revert if option is expired

function _revertIfOptionExpired(PoolStorage.Layout storage l) internal view;

_revertIfWithdrawalDelayNotElapsed

Revert if withdrawal delay has not elapsed

function _revertIfWithdrawalDelayNotElapsed(Position.Data storage position) internal view;

_revertIfTradeAboveMaxSlippage

Revert if totalPremium is exceeds max slippage

function _revertIfTradeAboveMaxSlippage(uint256 totalPremium, uint256 premiumLimit, bool isBuy) internal pure;

_revertIfInvalidSize

function _revertIfInvalidSize(UD60x18 lower, UD60x18 upper, UD60x18 size) internal pure;

_revertIfDepositWithdrawalAboveMaxSlippage

Revert if marketPrice is below minMarketPrice or above maxMarketPrice

function _revertIfDepositWithdrawalAboveMaxSlippage(UD60x18 marketPrice, UD60x18 minMarketPrice, UD60x18 maxMarketPrice)
    internal
    pure;

_areQuoteOBAndBalanceValid

Returns true if OB quote and OB quote balance are valid

function _areQuoteOBAndBalanceValid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB,
    bytes32 quoteOBHash
) internal view returns (bool isValid, InvalidQuoteOBError error);

_revertIfQuoteOBInvalid

Revert if OB quote is invalid

function _revertIfQuoteOBInvalid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB,
    bytes32 quoteOBHash
) internal view;

_revertIfPositionDoesNotExist

Revert if the position does not exist

function _revertIfPositionDoesNotExist(address owner, uint256 tokenId, UD60x18 balance) internal pure;

_revertIfInvalidPositionState

Revert if the position is in an invalid state

function _revertIfInvalidPositionState(uint256 balance, uint256 lastDeposit) internal pure;

_isQuoteOBValid

Returns true if OB quote is valid

function _isQuoteOBValid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB,
    bytes32 quoteOBHash,
    bool revertIfInvalid
) internal view returns (bool, InvalidQuoteOBError);

_isQuoteOBBalanceValid

Returns true if OB quote balance is valid

function _isQuoteOBBalanceValid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB
) internal view returns (bool, InvalidQuoteOBError);

_revertIfOperatorNotAuthorized

Revert if operator is not msg.sender

function _revertIfOperatorNotAuthorized(address operator) internal view;

_revertIfActionNotAuthorized

Revert if operator is not authorized by holder to call action

function _revertIfActionNotAuthorized(address holder, IUserSettings.Action action) internal view;

_revertIfCostNotAuthorized

Revert if cost in wrapped native token is not authorized by holder

function _revertIfCostNotAuthorized(address holder, UD60x18 costInPoolToken) internal view;

_revertIfCostExceedsPayout

Revert if cost exceeds payout

function _revertIfCostExceedsPayout(UD60x18 cost, UD60x18 payout) internal pure;

_revertIfDifferenceOfSizeAndContractDeltaTooLarge

function _revertIfDifferenceOfSizeAndContractDeltaTooLarge(UD60x18 offset, UD60x18 size) internal pure;

_beforeTokenTransfer

_beforeTokenTransfer wrapper, updates tokenIds set

function _beforeTokenTransfer(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual override;

PoolProxy

Git Source

Inherits: Proxy, ERC165BaseInternal

State Variables

DIAMOND

address private immutable DIAMOND;

Functions

constructor

constructor(
    address diamond,
    address base,
    address quote,
    address oracleAdapter,
    UD60x18 strike,
    uint256 maturity,
    bool isCallPool
);

_getImplementation

get logic implementation address

function _getImplementation() internal view override returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

PoolStorage

Git Source

State Variables

SHORT

uint256 internal constant SHORT = 0;

LONG

uint256 internal constant LONG = 1;

TOKEN_VERSION

uint8 internal constant TOKEN_VERSION = 1;

MIN_TICK_DISTANCE

UD60x18 internal constant MIN_TICK_DISTANCE = UD60x18.wrap(0.001e18);

MIN_TICK_PRICE

UD60x18 internal constant MIN_TICK_PRICE = UD60x18.wrap(0.001e18);

MAX_TICK_PRICE

UD60x18 internal constant MAX_TICK_PRICE = UD60x18.wrap(1e18);

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Pool");

Functions

layout

function layout() internal pure returns (Layout storage l);

getPoolTokenDecimals

Returns the token decimals for the pool token

function getPoolTokenDecimals(Layout storage l) internal view returns (uint8);

toPoolTokenDecimals

Adjust decimals of a value with 18 decimals to match the pool token decimals

function toPoolTokenDecimals(Layout storage l, uint256 value) internal view returns (uint256);

toPoolTokenDecimals

Adjust decimals of a value with 18 decimals to match the pool token decimals

function toPoolTokenDecimals(Layout storage l, int256 value) internal view returns (int256);

toPoolTokenDecimals

Adjust decimals of a value with 18 decimals to match the pool token decimals

function toPoolTokenDecimals(Layout storage l, UD60x18 value) internal view returns (uint256);

toPoolTokenDecimals

Adjust decimals of a value with 18 decimals to match the pool token decimals

function toPoolTokenDecimals(Layout storage l, SD59x18 value) internal view returns (int256);

fromPoolTokenDecimals

Adjust decimals of a value with pool token decimals to 18 decimals

function fromPoolTokenDecimals(Layout storage l, uint256 value) internal view returns (UD60x18);

fromPoolTokenDecimals

Adjust decimals of a value with pool token decimals to 18 decimals

function fromPoolTokenDecimals(Layout storage l, int256 value) internal view returns (SD59x18);

roundDown

Scales the decimals places from UD60x18 to the pool token decimals.

function roundDown(Layout storage l, UD60x18 value) internal view returns (uint256);

Parameters

NameTypeDescription
lLayout
valueUD60x18The value that should be rounded down

Returns

NameTypeDescription
<none>uint256Returns the scaled value in uint256

roundDownUD60x18

Scales the decimals places from UD60x18 to the pool token decimals and casts it back to UD60x18.

function roundDownUD60x18(Layout storage l, UD60x18 value) internal view returns (UD60x18);

Parameters

NameTypeDescription
lLayout
valueUD60x18The value that should be rounded down

Returns

NameTypeDescription
<none>UD60x18Returns the scaled value in UD60x18

roundDownSD59x18

Scales the decimals places from SD59x18 to the pool token decimals and casts it back to SD59x18.

function roundDownSD59x18(Layout storage l, SD59x18 value) internal view returns (SD59x18);

Parameters

NameTypeDescription
lLayout
valueSD59x18The value that should be rounded down

Returns

NameTypeDescription
<none>SD59x18Returns the scaled value in SD59x18

roundUp

Scales the decimals places from UD60x18 to the pool token decimals and rounds up any residuals.

function roundUp(Layout storage l, UD60x18 value) internal view returns (uint256);

Parameters

NameTypeDescription
lLayout
valueUD60x18The value that should be rounded up

Returns

NameTypeDescription
<none>uint256Returns the rounded up value in uint256

roundUpUD60x18

Scales the decimals places from UD60x18 to the pool token decimals and casts it back to UD60x18. Any residuals are rounded up.

function roundUpUD60x18(Layout storage l, UD60x18 value) internal view returns (UD60x18);

Parameters

NameTypeDescription
lLayout
valueUD60x18The value that should be rounded up

Returns

NameTypeDescription
<none>UD60x18Returns the rounded up value in UD60x18

getPoolToken

Get the token used as options collateral and for payment of premium. (quote for PUT pools, base for CALL pools)

function getPoolToken(Layout storage l) internal view returns (address);

formatTokenId

calculate ERC1155 token id for given option parameters

function formatTokenId(address operator, UD60x18 lower, UD60x18 upper, Position.OrderType orderType)
    internal
    pure
    returns (uint256 tokenId);

Parameters

NameTypeDescription
operatoraddressThe current operator of the position
lowerUD60x18The lower bound normalized option price (18 decimals)
upperUD60x18The upper bound normalized option price (18 decimals)
orderTypePosition.OrderType

Returns

NameTypeDescription
tokenIduint256token id

parseTokenId

derive option maturity and strike price from ERC1155 token id

function parseTokenId(uint256 tokenId)
    internal
    pure
    returns (uint8 version, address operator, UD60x18 lower, UD60x18 upper, Position.OrderType orderType);

Parameters

NameTypeDescription
tokenIduint256token id

Returns

NameTypeDescription
versionuint8The version of LP token, used to know how to decode it, if upgrades are made
operatoraddressThe current operator of the position
lowerUD60x18The lower bound normalized option price (18 decimals)
upperUD60x18The upper bound normalized option price (18 decimals)
orderTypePosition.OrderType

approve

Converts value to pool token decimals and approves spender

function approve(IERC20 token, address spender, UD60x18 value) internal;

safeTransferFrom

Converts value to pool token decimals and transfers token

function safeTransferFrom(IERC20Router router, address token, address from, address to, UD60x18 value) internal;

safeTransferIgnoreDust

Transfers token amount to recipient. Ignores if dust is missing on the exchange level, i.e. if the pool balance is 0.01% less than the amount that should be sent, then the pool balance is transferred instead of the amount. If the relative difference is larger than 0.01% then the transaction will revert.

function safeTransferIgnoreDust(IERC20 token, address to, uint256 value) internal;

Parameters

NameTypeDescription
tokenIERC20IERC20 token that is intended to be sent.
toaddressRecipient address of the tokens.
valueuint256The amount of tokens that are intended to be sent (poolToken decimals).

safeTransferIgnoreDust

Transfers token amount to recipient. Ignores if dust is missing on the exchange level, i.e. if the pool balance is 0.01% less than the amount that should be sent, then the pool balance is transferred instead of the amount. If the relative difference is larger than 0.01% then the transaction will revert.

function safeTransferIgnoreDust(IERC20 token, address to, UD60x18 value) internal;

Parameters

NameTypeDescription
tokenIERC20IERC20 token that is intended to be sent.
toaddressRecipient address of the tokens.
valueUD60x18The amount of tokens that are intended to be sent. (18 decimals)

Structs

Layout

struct Layout {
    address base;
    address quote;
    address oracleAdapter;
    uint8 baseDecimals;
    uint8 quoteDecimals;
    uint256 maturity;
    bool isCallPool;
    DoublyLinkedList.Bytes32List tickIndex;
    mapping(UD60x18 normalizedPrice => IPoolInternal.Tick) ticks;
    UD50x28 marketPrice;
    UD50x28 globalFeeRate;
    UD60x18 protocolFees;
    UD60x18 strike;
    UD50x28 liquidityRate;
    UD50x28 longRate;
    UD50x28 shortRate;
    UD60x18 currentTick;
    UD60x18 settlementPrice;
    mapping(bytes32 key => Position.Data) positions;
    mapping(address provider => mapping(bytes32 hash => UD60x18 amountFilled)) quoteOBAmountFilled;
    bool __deprecated_initFeeDiscountRemoved;
    EnumerableSet.UintSet tokenIds;
}

PoolTrade

Git Source

Inherits: IPoolTrade, PoolInternal, ReentrancyGuard

State Variables

FLASH_LOAN_FEE

UD60x18 internal constant FLASH_LOAN_FEE = UD60x18.wrap(0.0009e18);

FLASH_LOAN_CALLBACK_SUCCESS

bytes32 internal constant FLASH_LOAN_CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");

Functions

constructor

constructor(
    address factory,
    address router,
    address wrappedNativeToken,
    address feeReceiver,
    address referral,
    address settings,
    address vaultRegistry,
    address vxPremia
) PoolInternal(factory, router, wrappedNativeToken, feeReceiver, referral, settings, vaultRegistry, vxPremia);

getQuoteAMM

Gives a quote for an AMM trade

function getQuoteAMM(address taker, UD60x18 size, bool isBuy)
    external
    view
    returns (uint256 premiumNet, uint256 takerFee);

Parameters

NameTypeDescription
takeraddressThe taker of the trade
sizeUD60x18The number of contracts being traded (18 decimals)
isBuyboolWhether the taker is buying or selling

Returns

NameTypeDescription
premiumNetuint256The premium which has to be paid to complete the trade (Net of fees) (poolToken decimals)
takerFeeuint256The taker fees to pay (Included in premiumNet) (poolToken decimals)

fillQuoteOB

Functionality to support the OB / OTC system. An LP can create a OB quote for which he will do an OTC trade through the exchange. Takers can buy from / sell to the LP partially or fully while having the price guaranteed.

function fillQuoteOB(QuoteOB calldata quoteOB, UD60x18 size, Signature calldata signature, address referrer)
    external
    nonReentrant
    returns (uint256 premiumTaker, Position.Delta memory delta);

Parameters

NameTypeDescription
quoteOBQuoteOBThe OB quote given by the provider
sizeUD60x18The size to fill from the OB quote (18 decimals)
signatureSignaturesecp256k1 'r', 's', and 'v' value
referreraddressThe referrer of the user filling the OB quote

Returns

NameTypeDescription
premiumTakeruint256The premium paid or received by the taker for the trade (poolToken decimals)
deltaPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

trade

Completes a trade of size on side via the AMM using the liquidity in the Pool. Tx will revert if total premium is above totalPremium when buying, or below totalPremium when selling.

function trade(UD60x18 size, bool isBuy, uint256 premiumLimit, address referrer)
    external
    nonReentrant
    returns (uint256 totalPremium, Position.Delta memory delta);

Parameters

NameTypeDescription
sizeUD60x18The number of contracts being traded (18 decimals)
isBuyboolWhether the taker is buying or selling
premiumLimituint256Tx will revert if total premium is above this value when buying, or below this value when selling. (poolToken decimals)
referreraddressThe referrer of the user doing the trade

Returns

NameTypeDescription
totalPremiumuint256The premium paid or received by the taker for the trade (poolToken decimals)
deltaPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

cancelQuotesOB

Cancel given OB quotes

No check is done to ensure the given hash correspond to a OB quote provider by msg.sender, but as we register the cancellation in a mapping provider -> hash, it is not possible to cancel a OB quote created by another provider

function cancelQuotesOB(bytes32[] calldata hashes) external nonReentrant;

Parameters

NameTypeDescription
hashesbytes32[]The hashes of the OB quotes to cancel

isQuoteOBValid

Returns whether or not an OB quote is valid, given a fill size

function isQuoteOBValid(address user, QuoteOB calldata quoteOB, UD60x18 size, Signature calldata sig)
    external
    view
    returns (bool, InvalidQuoteOBError);

Parameters

NameTypeDescription
useraddressThe address of the user that will call the fillQuoteOB function to fill the OB quote
quoteOBQuoteOBThe OB quote to check
sizeUD60x18Size to fill from the OB quote (18 decimals)
sigSignaturesecp256k1 Signature

getQuoteOBFilledAmount

Returns the size already filled for a given OB quote

function getQuoteOBFilledAmount(address provider, bytes32 quoteOBHash) external view returns (UD60x18);

Parameters

NameTypeDescription
provideraddressProvider of the OB quote
quoteOBHashbytes32Hash of the OB quote

Returns

NameTypeDescription
<none>UD60x18The size already filled (18 decimals)

maxFlashLoan

The amount of currency available to be lent.

function maxFlashLoan(address token) external view returns (uint256);

Parameters

NameTypeDescription
tokenaddressThe loan currency.

Returns

NameTypeDescription
<none>uint256The amount of token that can be borrowed.

flashFee

The fee to be charged for a given loan.

function flashFee(address token, uint256 amount) external view returns (uint256);

Parameters

NameTypeDescription
tokenaddressThe loan currency.
amountuint256The amount of tokens lent.

Returns

NameTypeDescription
<none>uint256The amount of token to be charged for the loan, on top of the returned principal.

_flashFee

Returns the fee required for a flash loan of amount

function _flashFee(uint256 amount) internal view returns (UD60x18);

flashLoan

Initiate a flash loan.

function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data)
    external
    nonReentrant
    returns (bool);

Parameters

NameTypeDescription
receiverIERC3156FlashBorrowerThe receiver of the tokens in the loan, and the receiver of the callback.
tokenaddressThe loan currency.
amountuint256The amount of tokens lent.
databytesArbitrary data structure, intended to contain user-defined parameters.

_revertIfNotPoolToken

Revert if token is not the pool token

function _revertIfNotPoolToken(address token) internal view;

Contents

IProxyManager

Git Source

Functions

getManagedProxyImplementation

Return the implementation address of the managed proxy

function getManagedProxyImplementation() external view returns (address);

setManagedProxyImplementation

Set the implementation address of the managed proxy

function setManagedProxyImplementation(address implementation) external;

Events

ManagedImplementationSet

event ManagedImplementationSet(address implementation);

IProxyUpgradeableOwnable

Git Source

Functions

getImplementation

Return the implementation address of the proxy

function getImplementation() external view returns (address);

Premia

Git Source

Inherits: SolidStateDiamond

based on the EIP2535 Diamond standard

ProxyManager

Git Source

Inherits: IProxyManager, OwnableInternal

Functions

getManagedProxyImplementation

Return the implementation address of the managed proxy

function getManagedProxyImplementation() external view returns (address);

setManagedProxyImplementation

Set the implementation address of the managed proxy

function setManagedProxyImplementation(address implementation) external onlyOwner;

_setManagedProxyImplementation

function _setManagedProxyImplementation(address implementation) internal;

ProxyManagerStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.ProxyManager");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    address managedProxyImplementation;
}

ProxyUpgradeableOwnable

Git Source

Inherits: IProxyUpgradeableOwnable, Proxy, SafeOwnable

Functions

constructor

constructor(address implementation);

receive

receive() external payable;

_getImplementation

get logic implementation address

function _getImplementation() internal view override returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

getImplementation

Return the implementation address of the proxy

function getImplementation() external view returns (address);

setImplementation

set address of implementation contract

function setImplementation(address implementation) external onlyOwner;

Parameters

NameTypeDescription
implementationaddressaddress of the new implementation

_setImplementation

set address of implementation contract

function _setImplementation(address implementation) internal;

Events

ImplementationSet

event ImplementationSet(address implementation);

Errors

ProxyUpgradeableOwnable__InvalidImplementation

error ProxyUpgradeableOwnable__InvalidImplementation(address implementation);

ProxyUpgradeableOwnableStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.ProxyUpgradeableOwnable");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    address implementation;
}

Contents

IReferral

Git Source

Functions

getReferrer

Returns the address of the referrer for a given user

function getReferrer(address user) external view returns (address referrer);

Parameters

NameTypeDescription
useraddressThe address of the user

Returns

NameTypeDescription
referreraddressThe address of the referrer

getRebateTier

Returns the rebate tier for a given referrer

function getRebateTier(address referrer) external view returns (RebateTier tier);

Parameters

NameTypeDescription
referreraddressThe address of the referrer

Returns

NameTypeDescription
tierRebateTierThe rebate tier

getRebatePercents

Returns the primary and secondary rebate percents

function getRebatePercents()
    external
    view
    returns (UD60x18[] memory primaryRebatePercents, UD60x18 secondaryRebatePercent);

Returns

NameTypeDescription
primaryRebatePercentsUD60x18[]The primary rebate percents (18 decimals)
secondaryRebatePercentUD60x18The secondary rebate percent (18 decimals)

getRebatePercents

Returns the primary and secondary rebate percents for a given referrer

function getRebatePercents(address referrer)
    external
    view
    returns (UD60x18 primaryRebatePercent, UD60x18 secondaryRebatePercent);

Parameters

NameTypeDescription
referreraddressThe address of the referrer

Returns

NameTypeDescription
primaryRebatePercentUD60x18The primary rebate percent (18 decimals)
secondaryRebatePercentUD60x18The secondary rebate percent (18 decimals)

getRebates

Returns the rebates for a given referrer

function getRebates(address referrer) external view returns (address[] memory tokens, uint256[] memory rebates);

Parameters

NameTypeDescription
referreraddressThe address of the referrer

Returns

NameTypeDescription
tokensaddress[]The tokens for which the referrer has rebates
rebatesuint256[]The rebates for each token (token decimals)

getRebateAmounts

Returns the primary and secondary rebate amounts for a given user and referrer

function getRebateAmounts(address user, address referrer, UD60x18 tradingFee)
    external
    view
    returns (UD60x18 primaryRebate, UD60x18 secondaryRebate);

Parameters

NameTypeDescription
useraddressThe address of the user
referreraddressThe address of the referrer
tradingFeeUD60x18The trading fee (18 decimals)

Returns

NameTypeDescription
primaryRebateUD60x18The primary rebate amount (18 decimals)
secondaryRebateUD60x18The secondary rebate amount (18 decimals)

setRebateTier

Sets the rebate tier for a given referrer - caller must be owner

function setRebateTier(address referrer, RebateTier tier) external;

Parameters

NameTypeDescription
referreraddressThe address of the referrer
tierRebateTierThe rebate tier

setPrimaryRebatePercent

Sets the primary rebate percents - caller must be owner

function setPrimaryRebatePercent(UD60x18 percent, RebateTier tier) external;

Parameters

NameTypeDescription
percentUD60x18The primary rebate percent (18 decimals)
tierRebateTierThe rebate tier

setSecondaryRebatePercent

Sets the secondary rebate percent - caller must be owner

function setSecondaryRebatePercent(UD60x18 percent) external;

Parameters

NameTypeDescription
percentUD60x18The secondary rebate percent (18 decimals)

useReferral

Pulls the total rebate amount from msg.sender - caller must be an authorized pool

The tokens must be approved for transfer

function useReferral(address user, address referrer, address token, UD60x18 primaryRebate, UD60x18 secondaryRebate)
    external;

Parameters

NameTypeDescription
useraddressThe address of the user
referreraddressThe address of the primary referrer
tokenaddressThe address of the token
primaryRebateUD60x18The primary rebate amount (18 decimals)
secondaryRebateUD60x18The secondary rebate amount (18 decimals)

claimRebate

Claims the rebates for the msg.sender

function claimRebate(address[] memory tokens) external;

Parameters

NameTypeDescription
tokensaddress[]The tokens to claim

Events

ClaimRebate

event ClaimRebate(address indexed referrer, address indexed token, uint256 amount);

SetPrimaryRebatePercent

event SetPrimaryRebatePercent(RebateTier tier, UD60x18 oldPercent, UD60x18 newPercent);

SetRebateTier

event SetRebateTier(address indexed referrer, RebateTier oldTier, RebateTier newTier);

SetSecondaryRebatePercent

event SetSecondaryRebatePercent(UD60x18 oldPercent, UD60x18 newPercent);

Refer

event Refer(
    address indexed user,
    address indexed primaryReferrer,
    address indexed secondaryReferrer,
    address token,
    UD60x18 primaryRebatePercent,
    UD60x18 primaryRebate,
    UD60x18 secondaryRebate
);

Errors

Referral__PoolNotAuthorized

error Referral__PoolNotAuthorized();

Enums

RebateTier

enum RebateTier {
    PrimaryRebate1,
    PrimaryRebate2,
    PrimaryRebate3
}

Referral

Git Source

Inherits: IReferral, OwnableInternal, ReentrancyGuard

State Variables

FACTORY

address internal immutable FACTORY;

Functions

constructor

constructor(address factory);

getReferrer

Returns the address of the referrer for a given user

function getReferrer(address user) public view returns (address);

Parameters

NameTypeDescription
useraddressThe address of the user

Returns

NameTypeDescription
<none>addressreferrer The address of the referrer

getRebateTier

Returns the rebate tier for a given referrer

function getRebateTier(address referrer) public view returns (RebateTier);

Parameters

NameTypeDescription
referreraddressThe address of the referrer

Returns

NameTypeDescription
<none>RebateTiertier The rebate tier

getRebatePercents

Returns the primary and secondary rebate percents

function getRebatePercents()
    external
    view
    returns (UD60x18[] memory primaryRebatePercents, UD60x18 secondaryRebatePercent);

Returns

NameTypeDescription
primaryRebatePercentsUD60x18[]The primary rebate percents (18 decimals)
secondaryRebatePercentUD60x18The secondary rebate percent (18 decimals)

getRebatePercents

Returns the primary and secondary rebate percents

function getRebatePercents(address referrer)
    public
    view
    returns (UD60x18 primaryRebatePercents, UD60x18 secondaryRebatePercent);

Returns

NameTypeDescription
primaryRebatePercentsUD60x18The primary rebate percents (18 decimals)
secondaryRebatePercentUD60x18The secondary rebate percent (18 decimals)

getRebates

Returns the rebates for a given referrer

function getRebates(address referrer) public view returns (address[] memory, uint256[] memory);

Parameters

NameTypeDescription
referreraddressThe address of the referrer

Returns

NameTypeDescription
<none>address[]tokens The tokens for which the referrer has rebates
<none>uint256[]rebates The rebates for each token (token decimals)

getRebateAmounts

Returns the primary and secondary rebate amounts for a given user and referrer

function getRebateAmounts(address user, address referrer, UD60x18 tradingFee)
    external
    view
    returns (UD60x18 primaryRebate, UD60x18 secondaryRebate);

Parameters

NameTypeDescription
useraddressThe address of the user
referreraddressThe address of the referrer
tradingFeeUD60x18The trading fee (18 decimals)

Returns

NameTypeDescription
primaryRebateUD60x18The primary rebate amount (18 decimals)
secondaryRebateUD60x18The secondary rebate amount (18 decimals)

setRebateTier

Sets the rebate tier for a given referrer - caller must be owner

function setRebateTier(address referrer, RebateTier tier) external onlyOwner;

Parameters

NameTypeDescription
referreraddressThe address of the referrer
tierRebateTierThe rebate tier

setPrimaryRebatePercent

Sets the primary rebate percents - caller must be owner

function setPrimaryRebatePercent(UD60x18 percent, RebateTier tier) external onlyOwner;

Parameters

NameTypeDescription
percentUD60x18The primary rebate percent (18 decimals)
tierRebateTierThe rebate tier

setSecondaryRebatePercent

Sets the secondary rebate percent - caller must be owner

function setSecondaryRebatePercent(UD60x18 percent) external onlyOwner;

Parameters

NameTypeDescription
percentUD60x18The secondary rebate percent (18 decimals)

useReferral

Pulls the total rebate amount from msg.sender - caller must be an authorized pool

The tokens must be approved for transfer

function useReferral(address user, address referrer, address token, UD60x18 primaryRebate, UD60x18 secondaryRebate)
    external
    nonReentrant;

Parameters

NameTypeDescription
useraddressThe address of the user
referreraddressThe address of the primary referrer
tokenaddressThe address of the token
primaryRebateUD60x18The primary rebate amount (18 decimals)
secondaryRebateUD60x18The secondary rebate amount (18 decimals)

claimRebate

Claims the rebates for the msg.sender

function claimRebate(address[] memory tokens) external nonReentrant;

Parameters

NameTypeDescription
tokensaddress[]The tokens to claim

_tryUpdateRebate

Updates the referrer rebate balance and rebate tokens, if amount is greater than zero

function _tryUpdateRebate(ReferralStorage.Layout storage l, address referrer, address token, UD60x18 amount) internal;

_trySetReferrer

Sets the referrer for a user if they don't already have one. If a referrer has already been set, return the existing referrer.

function _trySetReferrer(address user, address referrer) internal returns (address);

_revertIfPoolNotAuthorized

Reverts if the caller is not an authorized pool

function _revertIfPoolNotAuthorized() internal view;

ReferralProxy

Git Source

Inherits: ProxyUpgradeableOwnable

Functions

constructor

constructor(address implementation) ProxyUpgradeableOwnable(implementation);

ReferralStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Referral");

Functions

layout

function layout() internal pure returns (Layout storage l);

toTokenDecimals

Adjust decimals of value with 18 decimals to match the token decimals

function toTokenDecimals(address token, UD60x18 value) internal view returns (uint256);

Structs

Layout

struct Layout {
    UD60x18[] primaryRebatePercents;
    UD60x18 secondaryRebatePercent;
    mapping(address user => IReferral.RebateTier tier) rebateTiers;
    mapping(address user => address referrer) referrals;
    mapping(address user => mapping(address token => uint256 amount)) rebates;
    mapping(address user => EnumerableSet.AddressSet tokens) rebateTokens;
}

Contents

IRelayerAccessManager

Git Source

Functions

addWhitelistedRelayers

Add relayers to the whitelist so that they can add price updates

function addWhitelistedRelayers(address[] calldata relayers) external;

Parameters

NameTypeDescription
relayersaddress[]The addresses to add to the whitelist

removeWhitelistedRelayers

Remove relayers from the whitelist so that they cannot add priced updates

function removeWhitelistedRelayers(address[] calldata relayers) external;

Parameters

NameTypeDescription
relayersaddress[]The addresses to remove from the whitelist

getWhitelistedRelayers

Get the list of whitelisted relayers

function getWhitelistedRelayers() external view returns (address[] memory relayers);

Returns

NameTypeDescription
relayersaddress[]The list of whitelisted relayers

Events

AddWhitelistedRelayer

event AddWhitelistedRelayer(address indexed relayer);

RemoveWhitelistedRelayer

event RemoveWhitelistedRelayer(address indexed relayer);

Errors

RelayerAccessManager__NotWhitelistedRelayer

error RelayerAccessManager__NotWhitelistedRelayer(address relayer);

RelayerAccessManager

Git Source

Inherits: IRelayerAccessManager, OwnableInternal

Functions

addWhitelistedRelayers

Add relayers to the whitelist so that they can add price updates

function addWhitelistedRelayers(address[] calldata relayers) external virtual onlyOwner;

Parameters

NameTypeDescription
relayersaddress[]The addresses to add to the whitelist

removeWhitelistedRelayers

Remove relayers from the whitelist so that they cannot add priced updates

function removeWhitelistedRelayers(address[] calldata relayers) external virtual onlyOwner;

Parameters

NameTypeDescription
relayersaddress[]The addresses to remove from the whitelist

getWhitelistedRelayers

Get the list of whitelisted relayers

function getWhitelistedRelayers() external view virtual returns (address[] memory relayers);

Returns

NameTypeDescription
relayersaddress[]The list of whitelisted relayers

_revertIfNotWhitelistedRelayer

Revert if relayer is not whitelisted

function _revertIfNotWhitelistedRelayer(address relayer) internal view;

RelayerAccessManagerStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.RelayerAccessManager");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    EnumerableSet.AddressSet whitelistedRelayers;
}

Contents

ERC20Router

Git Source

Inherits: IERC20Router, ReentrancyGuard

State Variables

POOL_FACTORY

address public immutable POOL_FACTORY;

Functions

constructor

constructor(address poolFactory);

safeTransferFrom

Transfers tokens - caller must be an authorized pool

function safeTransferFrom(address token, address from, address to, uint256 amount) external nonReentrant;

Parameters

NameTypeDescription
tokenaddressAddress of token to transfer
fromaddressAddress to transfer tokens from
toaddressAddress to transfer tokens to
amountuint256Amount of tokens to transfer

IERC20Router

Git Source

Functions

safeTransferFrom

Transfers tokens - caller must be an authorized pool

function safeTransferFrom(address token, address from, address to, uint256 amount) external;

Parameters

NameTypeDescription
tokenaddressAddress of token to transfer
fromaddressAddress to transfer tokens from
toaddressAddress to transfer tokens to
amountuint256Amount of tokens to transfer

Errors

ERC20Router__NotAuthorized

error ERC20Router__NotAuthorized();

Contents

IUserSettings

Git Source

Inherits: IMulticall

Functions

isActionAuthorized

Returns true if operator is authorized to perform action for user

function isActionAuthorized(address user, address operator, Action action) external view returns (bool);

Parameters

NameTypeDescription
useraddressThe user who grants authorization
operatoraddressThe operator who is granted authorization
actionActionThe action operator is authorized to perform

Returns

NameTypeDescription
<none>boolTrue if operator is authorized to perform action for user

getActionAuthorization

Returns the actions and their corresponding authorization states. If the state of an action is true, indexed enum in Action is omitted from actions.

function getActionAuthorization(address user, address operator)
    external
    view
    returns (Action[] memory actions, bool[] memory authorization);

Parameters

NameTypeDescription
useraddressThe user who grants authorization
operatoraddressThe operator who is granted authorization

Returns

NameTypeDescription
actionsAction[]All available actions a user may grant authorization to operator for
authorizationbool[]The authorization states of each action

setActionAuthorization

Sets the authorization state for each action an operator may perform on behalf of user. actions must be indexed in the same order as their corresponding authorization state.

function setActionAuthorization(address operator, Action[] memory actions, bool[] memory authorization) external;

Parameters

NameTypeDescription
operatoraddressThe operator who is granted authorization
actionsAction[]The actions to modify authorization state for
authorizationbool[]The authorization states to set for each action

getAuthorizedCost

Returns the users authorized cost in the ERC20 Native token (WETH, WFTM, etc) used in conjunction with exerciseFor, settleFor, and settlePositionFor`

function getAuthorizedCost(address user) external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The users authorized cost in the ERC20 Native token (WETH, WFTM, etc) (18 decimals)

setAuthorizedCost

Sets the users authorized cost in the ERC20 Native token (WETH, WFTM, etc) used in conjunction with exerciseFor, settleFor, and settlePositionFor

function setAuthorizedCost(UD60x18 amount) external;

Parameters

NameTypeDescription
amountUD60x18The users authorized cost in the ERC20 Native token (WETH, WFTM, etc) (18 decimals)

Events

ActionAuthorizationUpdated

event ActionAuthorizationUpdated(
    address indexed user, address indexed operator, Action[] actions, bool[] authorization
);

AuthorizedCostUpdated

event AuthorizedCostUpdated(address indexed user, UD60x18 amount);

Errors

UserSettings__InvalidAction

error UserSettings__InvalidAction();

UserSettings__InvalidArrayLength

error UserSettings__InvalidArrayLength();

Enums

Action

Enumeration representing different actions which user may authorize an operator to perform

enum Action {
    __,
    Annihilate,
    Exercise,
    Settle,
    SettlePosition,
    WriteFrom
}

UserSettings

Git Source

Inherits: IUserSettings, Multicall, ReentrancyGuard

Functions

isActionAuthorized

Returns true if operator is authorized to perform action for user

function isActionAuthorized(address user, address operator, Action action) external view returns (bool);

Parameters

NameTypeDescription
useraddressThe user who grants authorization
operatoraddressThe operator who is granted authorization
actionActionThe action operator is authorized to perform

Returns

NameTypeDescription
<none>boolTrue if operator is authorized to perform action for user

getActionAuthorization

Returns the actions and their corresponding authorization states. If the state of an action is true, indexed enum in Action is omitted from actions.

function getActionAuthorization(address user, address operator)
    external
    view
    returns (Action[] memory actions, bool[] memory authorization);

Parameters

NameTypeDescription
useraddressThe user who grants authorization
operatoraddressThe operator who is granted authorization

Returns

NameTypeDescription
actionsAction[]All available actions a user may grant authorization to operator for
authorizationbool[]The authorization states of each action

setActionAuthorization

Sets the authorization state for each action an operator may perform on behalf of user. actions must be indexed in the same order as their corresponding authorization state.

function setActionAuthorization(address operator, Action[] memory actions, bool[] memory authorization)
    external
    nonReentrant;

Parameters

NameTypeDescription
operatoraddressThe operator who is granted authorization
actionsAction[]The actions to modify authorization state for
authorizationbool[]The authorization states to set for each action

getAuthorizedCost

Returns the users authorized cost in the ERC20 Native token (WETH, WFTM, etc) used in conjunction with exerciseFor, settleFor, and settlePositionFor`

function getAuthorizedCost(address user) external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The users authorized cost in the ERC20 Native token (WETH, WFTM, etc) (18 decimals)

setAuthorizedCost

Sets the users authorized cost in the ERC20 Native token (WETH, WFTM, etc) used in conjunction with exerciseFor, settleFor, and settlePositionFor

function setAuthorizedCost(UD60x18 amount) external nonReentrant;

Parameters

NameTypeDescription
amountUD60x18The users authorized cost in the ERC20 Native token (WETH, WFTM, etc) (18 decimals)

UserSettingsStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.UserSettings");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    mapping(address user => mapping(address operator => EnumerableSet.UintSet actions)) authorizedActions;
    mapping(address user => UD60x18 cost) authorizedCost;
}

Contents

FeeConverter

Git Source

Inherits: IFeeConverter, OwnableInternal, ReentrancyGuard

Author: Premia

State Variables

EXCHANGE_HELPER

address private immutable EXCHANGE_HELPER;

USDC

address private immutable USDC;

VX_PREMIA

address private immutable VX_PREMIA;

Functions

onlyAuthorized

modifier onlyAuthorized();

isInitialized

modifier isInitialized();

constructor

constructor(address exchangeHelper, address usdc, address vxPremia);

receive

receive() external payable;

getExchangeHelper

get the exchange helper address

function getExchangeHelper() external view returns (address exchangeHelper);

Returns

NameTypeDescription
exchangeHelperaddressexchange helper address

getTreasury

get the treasury address and treasuryShare

function getTreasury() external view returns (address treasury, UD60x18 treasuryShare);

Returns

NameTypeDescription
treasuryaddresstreasury address
treasuryShareUD60x18treasury share (The % of funds allocated to the treasury address)

setAuthorized

Set authorization for address to use the convert function

function setAuthorized(address account, bool isAuthorized) external onlyOwner;

Parameters

NameTypeDescription
accountaddressThe account for which to set new authorization status
isAuthorizedboolWhether the account is authorized or not

setTreasury

Set a new treasury address, and its share (The % of funds allocated to the treasury address)

function setTreasury(address newTreasury, UD60x18 newTreasuryShare) external onlyOwner;

convert

convert held tokens to USDC and distribute as rewards

function convert(address sourceToken, address callee, address allowanceTarget, bytes calldata data)
    external
    isInitialized
    nonReentrant
    onlyAuthorized;

Parameters

NameTypeDescription
sourceTokenaddressaddress of token to convert
calleeaddressexchange address to call to execute the trade.
allowanceTargetaddressaddress for which to set allowance for the trade
databytescalldata to execute the trade

redeem

Redeem shares from an ERC4626 vault

function redeem(address vault, uint256 shareAmount)
    external
    isInitialized
    nonReentrant
    onlyAuthorized
    returns (uint256 assetAmount);

Parameters

NameTypeDescription
vaultaddressaddress of the ERC4626 vault to redeem from
shareAmountuint256quantity of shares to redeem

Returns

NameTypeDescription
assetAmountuint256quantity of assets received

FeeConverterStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.FeeConverter");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    mapping(address => bool) isAuthorized;
    address treasury;
    UD60x18 treasuryShare;
}

IFeeConverter

Git Source

Functions

getExchangeHelper

get the exchange helper address

function getExchangeHelper() external view returns (address exchangeHelper);

Returns

NameTypeDescription
exchangeHelperaddressexchange helper address

getTreasury

get the treasury address and treasuryShare

function getTreasury() external view returns (address treasury, UD60x18 treasuryShare);

Returns

NameTypeDescription
treasuryaddresstreasury address
treasuryShareUD60x18treasury share (The % of funds allocated to the treasury address)

convert

convert held tokens to USDC and distribute as rewards

function convert(address sourceToken, address callee, address allowanceTarget, bytes calldata data) external;

Parameters

NameTypeDescription
sourceTokenaddressaddress of token to convert
calleeaddressexchange address to call to execute the trade.
allowanceTargetaddressaddress for which to set allowance for the trade
databytescalldata to execute the trade

redeem

Redeem shares from an ERC4626 vault

function redeem(address vault, uint256 shareAmount) external returns (uint256 assetAmount);

Parameters

NameTypeDescription
vaultaddressaddress of the ERC4626 vault to redeem from
shareAmountuint256quantity of shares to redeem

Returns

NameTypeDescription
assetAmountuint256quantity of assets received

Events

Converted

event Converted(
    address indexed account, address indexed token, uint256 inAmount, uint256 outAmount, uint256 treasuryAmount
);

SetAuthorized

event SetAuthorized(address indexed account, bool isAuthorized);

SetTreasury

event SetTreasury(address indexed newTreasury, UD60x18 newTreasuryShare);

Errors

FeeConverter__NotAuthorized

error FeeConverter__NotAuthorized();

FeeConverter__NotInitialized

error FeeConverter__NotInitialized();

FeeConverter__TreasuryShareGreaterThanOne

error FeeConverter__TreasuryShareGreaterThanOne();

IPoolV2ProxyManager

Git Source

Functions

getPoolList

function getPoolList() external view returns (address[] memory);

IPremiaStaking

Git Source

Inherits: IERC2612, IOFT

Functions

getRewardToken

Returns the reward token address

function getRewardToken() external view returns (address);

Returns

NameTypeDescription
<none>addressThe reward token address

addRewards

add premia tokens as available tokens to be distributed as rewards

function addRewards(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256amount of premia tokens to add as rewards

getAvailableRewards

get amount of tokens that have not yet been distributed as rewards

function getAvailableRewards() external view returns (uint256 rewards, uint256 unstakeRewards);

Returns

NameTypeDescription
rewardsuint256amount of tokens not yet distributed as rewards
unstakeRewardsuint256amount of PREMIA not yet claimed from early unstake fees

getPendingRewards

get pending amount of tokens to be distributed as rewards to stakers

function getPendingRewards() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256amount of tokens pending to be distributed as rewards

getPendingWithdrawals

Return the total amount of premia pending withdrawal

function getPendingWithdrawals() external view returns (uint256);

getPendingWithdrawal

get pending withdrawal data of a user

function getPendingWithdrawal(address user)
    external
    view
    returns (uint256 amount, uint256 startDate, uint256 unlockDate);

Returns

NameTypeDescription
amountuint256pending withdrawal amount
startDateuint256start timestamp of withdrawal
unlockDateuint256timestamp at which withdrawal becomes available

getAvailablePremiaAmount

get the amount of PREMIA available for withdrawal

function getAvailablePremiaAmount() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256amount of PREMIA available for withdrawal

stakeWithPermit

Stake using IERC2612 permit

function stakeWithPermit(uint256 amount, uint64 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;

Parameters

NameTypeDescription
amountuint256The amount of xPremia to stake
perioduint64The lockup period (in seconds)
deadlineuint256Deadline after which permit will fail
vuint8V
rbytes32R
sbytes32S

stake

Lockup xPremia for protocol fee discounts Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation

function stake(uint256 amount, uint64 period) external;

Parameters

NameTypeDescription
amountuint256The amount of xPremia to stake
perioduint64The lockup period (in seconds)

updateLock

update vxPremia lock

function updateLock(uint64 period) external;

Parameters

NameTypeDescription
perioduint64The new lockup period (in seconds)

harvestAndStake

harvest rewards, convert to PREMIA using exchange helper, and stake

function harvestAndStake(IPremiaStaking.SwapArgs calldata s, uint64 stakePeriod) external;

Parameters

NameTypeDescription
sIPremiaStaking.SwapArgsswap arguments
stakePerioduint64The lockup period (in seconds)

harvest

Harvest rewards directly to user wallet

function harvest() external;

getPendingUserRewards

Get pending rewards amount, including pending pool update

function getPendingUserRewards(address user) external view returns (uint256 reward, uint256 unstakeReward);

Parameters

NameTypeDescription
useraddressUser for which to calculate pending rewards

Returns

NameTypeDescription
rewarduint256amount of pending rewards from protocol fees (in REWARD_TOKEN)
unstakeRewarduint256amount of pending rewards from early unstake fees (in PREMIA)

earlyUnstake

unstake tokens before end of the lock period, for a fee

function earlyUnstake(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256the amount of vxPremia to unstake

getEarlyUnstakeFee

get early unstake fee for given user

function getEarlyUnstakeFee(address user) external view returns (uint256 feePercentage);

Parameters

NameTypeDescription
useraddressaddress of the user

Returns

NameTypeDescription
feePercentageuint256% fee to pay for early unstake (1e18 = 100%)

startWithdraw

Initiate the withdrawal process by burning xPremia, starting the delay period

function startWithdraw(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256quantity of xPremia to unstake

withdraw

Withdraw underlying premia

function withdraw() external;

getUserPower

Calculate the stake amount of a user, after applying the bonus from the lockup period chosen

function getUserPower(address user) external view returns (uint256);

Parameters

NameTypeDescription
useraddressThe user from which to query the stake amount

Returns

NameTypeDescription
<none>uint256The user stake amount after applying the bonus

getTotalPower

Return the total power across all users (applying the bonus from lockup period chosen)

function getTotalPower() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total power across all users

getDiscount

Calculate the % of fee discount for user, based on his stake

function getDiscount(address user) external view returns (uint256);

Parameters

NameTypeDescription
useraddressThe _user for which the discount is for

Returns

NameTypeDescription
<none>uint256Percentage of protocol fee discount Ex : 1e17 = 10% fee discount

getStakeLevels

Get stake levels

function getStakeLevels() external pure returns (StakeLevel[] memory);

Returns

NameTypeDescription
<none>StakeLevel[]Stake levels Ex : 25e16 = -25%

getStakePeriodMultiplier

Get stake period multiplier

function getStakePeriodMultiplier(uint256 period) external pure returns (uint256);

Parameters

NameTypeDescription
perioduint256The duration (in seconds) for which tokens are locked

Returns

NameTypeDescription
<none>uint256The multiplier for this staking period Ex : 2e18 = x2

getUserInfo

Get staking infos of a user

function getUserInfo(address user) external view returns (PremiaStakingStorage.UserInfo memory);

Parameters

NameTypeDescription
useraddressThe user address for which to get staking infos

Returns

NameTypeDescription
<none>PremiaStakingStorage.UserInfoThe staking infos of the user

Events

Stake

event Stake(address indexed user, uint256 amount, uint64 stakePeriod, uint64 lockedUntil);

Unstake

event Unstake(address indexed user, uint256 amount, uint256 fee, uint256 startDate);

Harvest

event Harvest(address indexed user, uint256 amount);

EarlyUnstakeRewardCollected

event EarlyUnstakeRewardCollected(address indexed user, uint256 amount);

Withdraw

event Withdraw(address indexed user, uint256 amount);

RewardsAdded

event RewardsAdded(uint256 amount);

BridgeLock

event BridgeLock(address indexed user, uint64 stakePeriod, uint64 lockedUntil);

UpdateLock

event UpdateLock(address indexed user, uint64 oldStakePeriod, uint64 newStakePeriod);

Errors

PremiaStaking__CantTransfer

error PremiaStaking__CantTransfer();

PremiaStaking__ExcessiveStakePeriod

error PremiaStaking__ExcessiveStakePeriod();

PremiaStaking__InsufficientSwapOutput

error PremiaStaking__InsufficientSwapOutput();

PremiaStaking__NoPendingWithdrawal

error PremiaStaking__NoPendingWithdrawal();

PremiaStaking__NotEnoughLiquidity

error PremiaStaking__NotEnoughLiquidity();

PremiaStaking__PeriodTooShort

error PremiaStaking__PeriodTooShort();

PremiaStaking__StakeLocked

error PremiaStaking__StakeLocked();

PremiaStaking__StakeNotLocked

error PremiaStaking__StakeNotLocked();

PremiaStaking__WithdrawalStillPending

error PremiaStaking__WithdrawalStillPending();

Structs

StakeLevel

struct StakeLevel {
    uint256 amount;
    uint256 discount;
}

SwapArgs

struct SwapArgs {
    uint256 amountOutMin;
    address callee;
    address allowanceTarget;
    bytes data;
    address refundAddress;
}

IVxPremia

Git Source

Inherits: IPremiaStaking

Functions

getPoolVotes

get total votes for specific pools

function getPoolVotes(VoteVersion version, bytes calldata target) external view returns (uint256);

Parameters

NameTypeDescription
versionVoteVersionversion of target (used to know how to decode data)
targetbytesABI encoded target of the votes

Returns

NameTypeDescription
<none>uint256total votes for specific pool

getUserVotes

get votes of user

function getUserVotes(address user) external view returns (VxPremiaStorage.Vote[] memory);

Parameters

NameTypeDescription
useraddressuser from which to get votes

Returns

NameTypeDescription
<none>VxPremiaStorage.Vote[]votes of user

castVotes

add or remove votes, in the limit of the user voting power

function castVotes(VxPremiaStorage.Vote[] calldata votes) external;

Parameters

NameTypeDescription
votesVxPremiaStorage.Vote[]votes to cast

Events

AddVote

event AddVote(address indexed voter, VoteVersion indexed version, bytes target, uint256 amount);

RemoveVote

event RemoveVote(address indexed voter, VoteVersion indexed version, bytes target, uint256 amount);

Errors

VxPremia__InvalidPoolAddress

error VxPremia__InvalidPoolAddress();

VxPremia__InvalidVoteTarget

error VxPremia__InvalidVoteTarget();

VxPremia__NotEnoughVotingPower

error VxPremia__NotEnoughVotingPower();

Enums

VoteVersion

enum VoteVersion {
    V2,
    VaultV3
}

PremiaStaking

Git Source

Inherits: IPremiaStaking, OFT, ReentrancyGuard

State Variables

PREMIA

address internal immutable PREMIA;

REWARD_TOKEN

address internal immutable REWARD_TOKEN;

EXCHANGE_HELPER

address internal immutable EXCHANGE_HELPER;

DECAY_RATE

UD60x18 internal constant DECAY_RATE = UD60x18.wrap(270000000000);

MAX_PERIOD

uint64 internal constant MAX_PERIOD = 4 * 365 days;

ACC_REWARD_PRECISION

uint256 internal constant ACC_REWARD_PRECISION = 1e30;

MAX_CONTRACT_DISCOUNT

uint256 internal constant MAX_CONTRACT_DISCOUNT = 0.3e18;

WITHDRAWAL_DELAY

uint256 internal constant WITHDRAWAL_DELAY = 10 days;

BPS_CONVERSION

uint256 internal constant BPS_CONVERSION = 1e14;

Functions

constructor

constructor(address lzEndpoint, address premia, address rewardToken, address exchangeHelper) OFT(lzEndpoint);

_beforeTokenTransfer

function _beforeTokenTransfer(address from, address to, uint256) internal virtual override;

getRewardToken

Returns the reward token address

function getRewardToken() external view returns (address);

Returns

NameTypeDescription
<none>addressThe reward token address

estimateSendFee

function estimateSendFee(
    uint16 dstChainId,
    bytes memory toAddress,
    uint256 amount,
    bool useZro,
    bytes memory adapterParams
) public view virtual override(OFTCore, IOFTCore) returns (uint256 nativeFee, uint256 zroFee);

_send

function _send(
    address from,
    uint16 dstChainId,
    bytes memory,
    uint256 amount,
    address payable refundAddress,
    address zroPaymentAddress,
    bytes memory adapterParams
) internal virtual override;

_sendAck

function _sendAck(uint16 srcChainId, bytes memory srcAddress, uint64, bytes memory payload) internal virtual override;

_creditTo

function _creditTo(address toAddress, uint256 amount, uint64 stakePeriod, uint64 creditLockedUntil, bool bridge)
    internal;

addRewards

add premia tokens as available tokens to be distributed as rewards

function addRewards(uint256 amount) external nonReentrant;

Parameters

NameTypeDescription
amountuint256amount of premia tokens to add as rewards

getAvailableRewards

get amount of tokens that have not yet been distributed as rewards

function getAvailableRewards() external view returns (uint256 rewards, uint256 unstakeRewards);

Returns

NameTypeDescription
rewardsuint256amount of tokens not yet distributed as rewards
unstakeRewardsuint256amount of PREMIA not yet claimed from early unstake fees

getPendingRewards

get pending amount of tokens to be distributed as rewards to stakers

function getPendingRewards() public view returns (uint256);

Returns

NameTypeDescription
<none>uint256amount of tokens pending to be distributed as rewards

_updateRewards

function _updateRewards() internal;

stakeWithPermit

Stake using IERC2612 permit

function stakeWithPermit(uint256 amount, uint64 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
    external
    nonReentrant;

Parameters

NameTypeDescription
amountuint256The amount of xPremia to stake
perioduint64The lockup period (in seconds)
deadlineuint256Deadline after which permit will fail
vuint8V
rbytes32R
sbytes32S

stake

Lockup xPremia for protocol fee discounts Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation

function stake(uint256 amount, uint64 period) external nonReentrant;

Parameters

NameTypeDescription
amountuint256The amount of xPremia to stake
perioduint64The lockup period (in seconds)

updateLock

update vxPremia lock

function updateLock(uint64 period) external nonReentrant;

Parameters

NameTypeDescription
perioduint64The new lockup period (in seconds)

harvestAndStake

harvest rewards, convert to PREMIA using exchange helper, and stake

function harvestAndStake(IPremiaStaking.SwapArgs calldata s, uint64 stakePeriod) external nonReentrant;

Parameters

NameTypeDescription
sIPremiaStaking.SwapArgsswap arguments
stakePerioduint64The lockup period (in seconds)

_calculateWeightedAverage

function _calculateWeightedAverage(uint256 A, uint256 B, uint256 weightA, uint256 weightB)
    internal
    pure
    returns (uint256);

_stake

function _stake(address toAddress, uint256 amount, uint64 stakePeriod) internal;

getPendingUserRewards

Get pending rewards amount, including pending pool update

function getPendingUserRewards(address user) external view returns (uint256 reward, uint256 unstakeReward);

Parameters

NameTypeDescription
useraddressUser for which to calculate pending rewards

Returns

NameTypeDescription
rewarduint256amount of pending rewards from protocol fees (in REWARD_TOKEN)
unstakeRewarduint256amount of pending rewards from early unstake fees (in PREMIA)

harvest

Harvest rewards directly to user wallet

function harvest() external nonReentrant;

_harvest

function _harvest(address account) internal returns (uint256 amount);

_updateTotalPower

function _updateTotalPower(PremiaStakingStorage.Layout storage l, uint256 oldUserPower, uint256 newUserPower)
    internal;

_beforeUnstake

function _beforeUnstake(address user, uint256 amount) internal virtual;

earlyUnstake

unstake tokens before end of the lock period, for a fee

function earlyUnstake(uint256 amount) external nonReentrant;

Parameters

NameTypeDescription
amountuint256the amount of vxPremia to unstake

getEarlyUnstakeFee

get early unstake fee for given user

function getEarlyUnstakeFee(address user) public view returns (uint256 feePercentage);

Parameters

NameTypeDescription
useraddressaddress of the user

Returns

NameTypeDescription
feePercentageuint256% fee to pay for early unstake (1e18 = 100%)

getEarlyUnstakeFeeBPS

function getEarlyUnstakeFeeBPS(address user) external view returns (uint256 feePercentageBPS);

startWithdraw

Initiate the withdrawal process by burning xPremia, starting the delay period

function startWithdraw(uint256 amount) external nonReentrant;

Parameters

NameTypeDescription
amountuint256quantity of xPremia to unstake

_startWithdraw

function _startWithdraw(
    PremiaStakingStorage.Layout storage l,
    PremiaStakingStorage.UserInfo storage u,
    uint256 amount,
    uint256 fee
) internal;

withdraw

Withdraw underlying premia

function withdraw() external nonReentrant;

getTotalPower

Return the total power across all users (applying the bonus from lockup period chosen)

function getTotalPower() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total power across all users

getUserPower

Calculate the stake amount of a user, after applying the bonus from the lockup period chosen

function getUserPower(address user) external view returns (uint256);

Parameters

NameTypeDescription
useraddressThe user from which to query the stake amount

Returns

NameTypeDescription
<none>uint256The user stake amount after applying the bonus

getDiscount

Calculate the % of fee discount for user, based on his stake

function getDiscount(address user) public view returns (uint256);

Parameters

NameTypeDescription
useraddressThe _user for which the discount is for

Returns

NameTypeDescription
<none>uint256Percentage of protocol fee discount Ex : 1e17 = 10% fee discount

getDiscountBPS

function getDiscountBPS(address user) external view returns (uint256);

getUserInfo

Get staking infos of a user

function getUserInfo(address user) external view returns (PremiaStakingStorage.UserInfo memory);

Parameters

NameTypeDescription
useraddressThe user address for which to get staking infos

Returns

NameTypeDescription
<none>PremiaStakingStorage.UserInfoThe staking infos of the user

getPendingWithdrawals

Return the total amount of premia pending withdrawal

function getPendingWithdrawals() external view returns (uint256);

getPendingWithdrawal

get pending withdrawal data of a user

function getPendingWithdrawal(address user)
    external
    view
    returns (uint256 amount, uint256 startDate, uint256 unlockDate);

Returns

NameTypeDescription
amountuint256pending withdrawal amount
startDateuint256start timestamp of withdrawal
unlockDateuint256timestamp at which withdrawal becomes available

_decay

function _decay(uint256 pendingRewards, uint256 oldTimestamp, uint256 newTimestamp) internal pure returns (uint256);

getStakeLevels

Get stake levels

function getStakeLevels() public pure returns (IPremiaStaking.StakeLevel[] memory stakeLevels);

Returns

NameTypeDescription
stakeLevelsIPremiaStaking.StakeLevel[]Stake levels Ex : 25e16 = -25%

getStakePeriodMultiplier

Get stake period multiplier

function getStakePeriodMultiplier(uint256 period) public pure returns (uint256);

Parameters

NameTypeDescription
perioduint256The duration (in seconds) for which tokens are locked

Returns

NameTypeDescription
<none>uint256The multiplier for this staking period Ex : 2e18 = x2

getStakePeriodMultiplierBPS

getStakePeriodMultiplier is preferred as it is more precise. This function is kept for backwards compatibility.

function getStakePeriodMultiplierBPS(uint256 period) external pure returns (uint256);

_calculateUserPower

function _calculateUserPower(uint256 balance, uint64 stakePeriod) internal pure returns (uint256);

_calculateReward

function _calculateReward(uint256 accRewardPerShare, uint256 power, uint256 rewardDebt)
    internal
    pure
    returns (uint256);

_creditRewards

function _creditRewards(
    PremiaStakingStorage.Layout storage l,
    PremiaStakingStorage.UserInfo storage u,
    address user,
    uint256 reward,
    uint256 unstakeReward
) internal;

_getInitialUpdateArgsInternal

function _getInitialUpdateArgsInternal(
    PremiaStakingStorage.Layout storage l,
    PremiaStakingStorage.UserInfo storage u,
    address user
) internal view returns (UpdateArgsInternal memory);

_calculateRewardDebt

function _calculateRewardDebt(uint256 accRewardPerShare, uint256 power) internal pure returns (uint256);

_updateUser

function _updateUser(
    PremiaStakingStorage.Layout storage l,
    PremiaStakingStorage.UserInfo storage u,
    UpdateArgsInternal memory args
) internal;

getAvailablePremiaAmount

get the amount of PREMIA available for withdrawal

function getAvailablePremiaAmount() public view returns (uint256);

Returns

NameTypeDescription
<none>uint256amount of PREMIA available for withdrawal

Structs

UpdateArgsInternal

struct UpdateArgsInternal {
    address user;
    uint256 balance;
    uint256 oldPower;
    uint256 newPower;
    uint256 reward;
    uint256 unstakeReward;
}

PremiaStakingStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.PremiaStaking");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Withdrawal

struct Withdrawal {
    uint256 amount;
    uint256 startDate;
}

UserInfo

struct UserInfo {
    uint256 reward;
    uint256 rewardDebt;
    uint256 unstakeRewardDebt;
    uint64 stakePeriod;
    uint64 lockedUntil;
}

Layout

struct Layout {
    uint256 pendingWithdrawal;
    uint256 _deprecated_withdrawalDelay;
    mapping(address => Withdrawal) withdrawals;
    uint256 availableRewards;
    uint256 lastRewardUpdate;
    uint256 totalPower;
    mapping(address => UserInfo) userInfo;
    uint256 accRewardPerShare;
    uint256 accUnstakeRewardPerShare;
    uint256 availableUnstakeRewards;
}

VxPremia

Git Source

Inherits: IVxPremia, PremiaStaking

Author: Premia

State Variables

PROXY_MANAGER_V2

The proxy manager contract used to deploy PremiaV2 pools

address private immutable PROXY_MANAGER_V2;

VAULT_REGISTRY

The vault registry contract for PremiaV3 vaults

address private immutable VAULT_REGISTRY;

Functions

constructor

constructor(
    address proxyManager,
    address lzEndpoint,
    address premia,
    address rewardToken,
    address exchangeHelper,
    address vaultRegistry
) PremiaStaking(lzEndpoint, premia, rewardToken, exchangeHelper);

_beforeUnstake

function _beforeUnstake(address user, uint256 amount) internal override;

_subtractExtraUserVotes

subtract user votes, starting from the end of the list, if not enough voting power is left after amountUnstaked is unstaked

function _subtractExtraUserVotes(VxPremiaStorage.Layout storage l, address user, uint256 amountUnstaked) internal;

_subtractUserVotes

subtract user votes, starting from the end of the list

function _subtractUserVotes(VxPremiaStorage.Layout storage l, address user, uint256 amount) internal;

_calculateUserVotingPowerUsed

function _calculateUserVotingPowerUsed(address user) internal view returns (uint256 votingPowerUsed);

getPoolVotes

get total votes for specific pools

function getPoolVotes(VoteVersion version, bytes calldata target) external view returns (uint256);

Parameters

NameTypeDescription
versionVoteVersionversion of target (used to know how to decode data)
targetbytesABI encoded target of the votes

Returns

NameTypeDescription
<none>uint256total votes for specific pool

getUserVotes

get votes of user

function getUserVotes(address user) external view returns (VxPremiaStorage.Vote[] memory);

Parameters

NameTypeDescription
useraddressuser from which to get votes

Returns

NameTypeDescription
<none>VxPremiaStorage.Vote[]votes of user

castVotes

add or remove votes, in the limit of the user voting power

function castVotes(VxPremiaStorage.Vote[] calldata votes) external nonReentrant;

Parameters

NameTypeDescription
votesVxPremiaStorage.Vote[]votes to cast

_resetUserVotes

function _resetUserVotes(VxPremiaStorage.Layout storage l, VxPremiaStorage.Vote[] storage userVotes, address user)
    internal;

resetUserVotes

function resetUserVotes(address user) external onlyOwner;

VxPremiaProxy

Git Source

Inherits: ProxyUpgradeableOwnable, ERC20MetadataInternal

Functions

constructor

constructor(address implementation) ProxyUpgradeableOwnable(implementation);

VxPremiaStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.VxPremia");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Vote

struct Vote {
    uint256 amount;
    IVxPremia.VoteVersion version;
    bytes target;
}

Layout

struct Layout {
    mapping(address => Vote[]) userVotes;
    mapping(IVxPremia.VoteVersion => mapping(bytes => uint256)) votes;
}

Contents

ExchangeHelper

Git Source

Inherits: IExchangeHelper, ReentrancyGuard

deployed standalone and referenced by ExchangeProxy

do NOT set additional approval to this contract!

Functions

swapWithToken

perform arbitrary swap transaction

function swapWithToken(
    address sourceToken,
    address targetToken,
    uint256 sourceTokenAmount,
    address callee,
    address allowanceTarget,
    bytes calldata data,
    address refundAddress
) external nonReentrant returns (uint256 amountOut, uint256 sourceLeft);

Parameters

NameTypeDescription
sourceTokenaddresssource token to pull into this address
targetTokenaddresstarget token to buy
sourceTokenAmountuint256amount of source token to start the trade
calleeaddressexchange address to call to execute the trade.
allowanceTargetaddressaddress for which to set allowance for the trade
databytescalldata to execute the trade
refundAddressaddressaddress that un-used source token goes to

Returns

NameTypeDescription
amountOutuint256quantity of targetToken yielded by swap
sourceLeftuint256quantity of sourceToken left and refunded to refundAddress

IExchangeHelper

Git Source

deployed standalone and referenced by internal functions

do NOT set approval to this contract!

Functions

swapWithToken

perform arbitrary swap transaction

function swapWithToken(
    address sourceToken,
    address targetToken,
    uint256 sourceTokenAmount,
    address callee,
    address allowanceTarget,
    bytes calldata data,
    address refundAddress
) external returns (uint256 amountOut, uint256 sourceLeft);

Parameters

NameTypeDescription
sourceTokenaddresssource token to pull into this address
targetTokenaddresstarget token to buy
sourceTokenAmountuint256amount of source token to start the trade
calleeaddressexchange address to call to execute the trade.
allowanceTargetaddressaddress for which to set allowance for the trade
databytescalldata to execute the trade
refundAddressaddressaddress that un-used source token goes to

Returns

NameTypeDescription
amountOutuint256quantity of targetToken yielded by swap
sourceLeftuint256quantity of sourceToken left and refunded to refundAddress

IRewardDistributor

Git Source

Functions

addRewards

function addRewards(address[] calldata users, uint256[] calldata amounts) external;

claim

function claim() external;

Events

AddedRewards

event AddedRewards(address indexed rewardProvider, address indexed user, uint256 amount);

Claimed

event Claimed(address indexed user, uint256 amount);

Errors

RewardDistributor__InvalidArrayLength

error RewardDistributor__InvalidArrayLength();

RewardDistributor__NoRewards

error RewardDistributor__NoRewards();

Placeholder

Git Source

Placeholder contract that can be used to deploy a proxy without initial implementation

Functions

placeholder

function placeholder() external;

RewardDistributor

Git Source

Inherits: IRewardDistributor, ReentrancyGuard

State Variables

REWARD_TOKEN

address internal immutable REWARD_TOKEN;

rewards

mapping(address => uint256) public rewards;

Functions

constructor

constructor(address rewardToken);

addRewards

function addRewards(address[] calldata users, uint256[] calldata amounts) external nonReentrant;

claim

function claim() external nonReentrant;

Contents

Contents

Contents

IUnderwriterVault

Git Source

Inherits: IVault

Functions

settle

Settles all expired option positions.

function settle() external;

Errors

Vault__UtilisationOutOfBounds

error Vault__UtilisationOutOfBounds();

Structs

UnderwriterVaultSettings

struct UnderwriterVaultSettings {
    UD60x18 alpha;
    UD60x18 hourlyDecayDiscount;
    UD60x18 minCLevel;
    UD60x18 maxCLevel;
    UD60x18 maxDTE;
    UD60x18 minDTE;
    UD60x18 minDelta;
    UD60x18 maxDelta;
}

UnexpiredListingVars

struct UnexpiredListingVars {
    UD60x18 spot;
    UD60x18 riskFreeRate;
    UD60x18[] strikes;
    UD60x18[] timeToMaturities;
    uint256[] maturities;
    UD60x18[] sigmas;
}

LockedSpreadInternal

struct LockedSpreadInternal {
    UD60x18 totalLockedSpread;
    UD60x18 spreadUnlockingRate;
    uint256 lastSpreadUnlockUpdate;
}

QuoteVars

struct QuoteVars {
    UD60x18 spot;
    UD60x18 tau;
    UD60x18 sigma;
    UD60x18 riskFreeRate;
    SD59x18 delta;
    UD60x18 price;
    UD60x18 cLevel;
}

QuoteInternal

struct QuoteInternal {
    address pool;
    UD60x18 premium;
    UD60x18 spread;
    UD60x18 mintingFee;
}

QuoteArgsInternal

struct QuoteArgsInternal {
    UD60x18 strike;
    uint256 maturity;
    bool isCall;
    UD60x18 size;
    bool isBuy;
    address taker;
}

UnderwriterVault

Git Source

Inherits: IUnderwriterVault, Vault, ReentrancyGuard

State Variables

VAULT_REGISTRY

address internal immutable VAULT_REGISTRY;

FEE_RECEIVER

address internal immutable FEE_RECEIVER;

IV_ORACLE

address internal immutable IV_ORACLE;

FACTORY

address internal immutable FACTORY;

ROUTER

address internal immutable ROUTER;

VX_PREMIA

address internal immutable VX_PREMIA;

POOL_DIAMOND

address internal immutable POOL_DIAMOND;

Functions

constructor

constructor(
    address vaultRegistry,
    address feeReceiver,
    address oracle,
    address factory,
    address router,
    address vxPremia,
    address poolDiamond,
    address vaultMining
) Vault(vaultMining);

getUtilisation

Returns the utilisation rate of the vault

function getUtilisation() public view override(IVault, Vault) returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The utilisation rate of the vault

updateSettings

Updates the vault settings

function updateSettings(bytes memory settings) external;

Parameters

NameTypeDescription
settingsbytesEncoding of the new settings

getSettings

Return vault abi encoded vault settings

function getSettings() external view returns (bytes memory);

_getBlockTimestamp

Gets the timestamp of the current block.

We are using a virtual internal function to be able to override in Mock contract for testing purpose

function _getBlockTimestamp() internal view virtual returns (uint256);

_totalAssets

get the total quantity of the base asset currently managed by the vault

function _totalAssets() internal view override returns (uint256);

Returns

NameTypeDescription
<none>uint256total managed asset amount

_getSpotPrice

Gets the spot price at the current time

function _getSpotPrice() internal view virtual returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The spot price at the current time

_getTotalLiabilitiesUnexpired

Gets the total liabilities value of the basket of unexpired options underwritten by this vault at the current time

function _getTotalLiabilitiesUnexpired(UnderwriterVaultStorage.Layout storage l) internal view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The the total liabilities of the basket of unexpired options underwritten

_getLockedSpreadInternal

Gets the total locked spread for the vault

function _getLockedSpreadInternal(UnderwriterVaultStorage.Layout storage l)
    internal
    view
    returns (LockedSpreadInternal memory vars);

Returns

NameTypeDescription
varsLockedSpreadInternalThe total locked spread

_balanceOfUD60x18

_balanceOf returns the balance of the ERC20 share token which is always in 18 decimal places, therefore no further scaling has to be applied

function _balanceOfUD60x18(address owner) internal view returns (UD60x18);

_totalSupplyUD60x18

function _totalSupplyUD60x18() internal view returns (UD60x18);

_availableAssetsUD60x18

Gets the amount of available assets that are available after settlement

function _availableAssetsUD60x18(UnderwriterVaultStorage.Layout storage l) internal view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The amount of available assets after calling the settle function

_getPricePerShareUD60x18

Gets the current price per share for the vault

function _getPricePerShareUD60x18() internal view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The current price per share

_updateState

updates total spread in storage to be able to compute the price per share

function _updateState(UnderwriterVaultStorage.Layout storage l) internal;

_convertToSharesUD60x18

function _convertToSharesUD60x18(UD60x18 assetAmount, UD60x18 pps) internal view returns (UD60x18 shareAmount);

_convertToShares

calculate the quantity of shares received in exchange for a given quantity of assets, not accounting for slippage

function _convertToShares(uint256 assetAmount) internal view override returns (uint256 shareAmount);

Parameters

NameTypeDescription
assetAmountuint256quantity of assets to convert

Returns

NameTypeDescription
shareAmountuint256quantity of shares calculated

_convertToAssetsUD60x18

function _convertToAssetsUD60x18(UD60x18 shareAmount, UD60x18 pps) internal view returns (UD60x18 assetAmount);

_convertToAssets

calculate the quantity of assets received in exchange for a given quantity of shares, not accounting for slippage

function _convertToAssets(uint256 shareAmount) internal view virtual override returns (uint256 assetAmount);

Parameters

NameTypeDescription
shareAmountuint256quantity of shares to convert

Returns

NameTypeDescription
assetAmountuint256quantity of assets calculated

_deposit

execute a deposit of assets on behalf of given address

function _deposit(
    address caller,
    address receiver,
    uint256 assetAmount,
    uint256 shareAmount,
    uint256 assetAmountOffset,
    uint256 shareAmountOffset
) internal virtual override;

Parameters

NameTypeDescription
calleraddress
receiveraddressrecipient of shares resulting from deposit
assetAmountuint256quantity of assets to deposit
shareAmountuint256
assetAmountOffsetuint256
shareAmountOffsetuint256

_deposit

execute a deposit of assets on behalf of given address

function _deposit(uint256 assetAmount, address receiver)
    internal
    virtual
    override
    nonReentrant
    returns (uint256 shareAmount);

Parameters

NameTypeDescription
assetAmountuint256quantity of assets to deposit
receiveraddressrecipient of shares resulting from deposit

Returns

NameTypeDescription
shareAmountuint256quantity of shares to mint

_previewMintUD60x18

function _previewMintUD60x18(UD60x18 shareAmount) internal view returns (UD60x18 assetAmount);

_previewMint

simulate a minting of given quantity of shares

function _previewMint(uint256 shareAmount) internal view virtual override returns (uint256 assetAmount);

Parameters

NameTypeDescription
shareAmountuint256quantity of shares to mint

Returns

NameTypeDescription
assetAmountuint256quantity of assets to deposit

_mint

execute a minting of shares on behalf of given address

function _mint(uint256 shareAmount, address receiver)
    internal
    virtual
    override
    nonReentrant
    returns (uint256 assetAmount);

Parameters

NameTypeDescription
shareAmountuint256quantity of shares to mint
receiveraddressrecipient of shares resulting from deposit

Returns

NameTypeDescription
assetAmountuint256quantity of assets to deposit

_maxRedeemUD60x18

function _maxRedeemUD60x18(UnderwriterVaultStorage.Layout storage l, address owner, UD60x18 pps)
    internal
    view
    returns (UD60x18 shareAmount);

_maxRedeem

calculate the maximum quantity of shares which may be redeemed by given holder

function _maxRedeem(address owner) internal view virtual override returns (uint256);

Parameters

NameTypeDescription
owneraddressholder of shares to be redeemed

Returns

NameTypeDescription
<none>uint256maxShares maximum share redeem amount

_redeem

execute a redemption of shares on behalf of given address

function _redeem(uint256 shareAmount, address receiver, address owner)
    internal
    virtual
    override
    nonReentrant
    returns (uint256 assetAmount);

Parameters

NameTypeDescription
shareAmountuint256quantity of shares to redeem
receiveraddressrecipient of assets resulting from withdrawal
owneraddressholder of shares to be redeemed

Returns

NameTypeDescription
assetAmountuint256quantity of assets to withdraw

_maxWithdrawUD60x18

function _maxWithdrawUD60x18(UnderwriterVaultStorage.Layout storage l, address owner, UD60x18 pps)
    internal
    view
    returns (UD60x18 withdrawableAssets);

_maxWithdraw

calculate the maximum quantity of base assets which may be withdrawn by given holder

function _maxWithdraw(address owner) internal view virtual override returns (uint256 withdrawableAssets);

Parameters

NameTypeDescription
owneraddressholder of shares to be redeemed

Returns

NameTypeDescription
withdrawableAssetsuint256maxAssets maximum asset mint amount

_previewWithdrawUD60x18

function _previewWithdrawUD60x18(UnderwriterVaultStorage.Layout storage l, UD60x18 assetAmount, UD60x18 pps)
    internal
    view
    returns (UD60x18 shareAmount);

_previewWithdraw

simulate a withdrawal of given quantity of assets

function _previewWithdraw(uint256 assetAmount) internal view virtual override returns (uint256 shareAmount);

Parameters

NameTypeDescription
assetAmountuint256quantity of assets to withdraw

Returns

NameTypeDescription
shareAmountuint256quantity of shares to redeem

_withdraw

execute a withdrawal of assets on behalf of given address

function _withdraw(uint256 assetAmount, address receiver, address owner)
    internal
    virtual
    override
    nonReentrant
    returns (uint256 shareAmount);

Parameters

NameTypeDescription
assetAmountuint256quantity of assets to withdraw
receiveraddressrecipient of assets resulting from withdrawal
owneraddressholder of shares to be redeemed

Returns

NameTypeDescription
shareAmountuint256quantity of shares to redeem

_afterDeposit

ERC4626 hook, called deposit and mint actions

function should be overridden and new implementation must call super

function _afterDeposit(address receiver, uint256 assetAmount, uint256 shareAmount) internal virtual override;

Parameters

NameTypeDescription
receiveraddressrecipient of shares resulting from deposit
assetAmountuint256quantity of assets being deposited
shareAmountuint256quantity of shares being minted

_beforeWithdraw

ERC4626 hook, called before withdraw and redeem actions

function should be overridden and new implementation must call super

function _beforeWithdraw(address owner, uint256 assetAmount, uint256 shareAmount) internal virtual override;

Parameters

NameTypeDescription
owneraddressholder of shares to be redeemed
assetAmountuint256quantity of assets being withdrawn
shareAmountuint256quantity of shares being redeemed

_afterTrade

An internal hook inside the trade function that is called after logic inside the trade function is run to update state variables

function _afterTrade(
    UnderwriterVaultStorage.Layout storage l,
    bool isBuy,
    UD60x18 strike,
    uint256 maturity,
    UD60x18 size,
    UD60x18 spread,
    UD60x18 premium
) internal;

Parameters

NameTypeDescription
lUnderwriterVaultStorage.Layout
isBuyboolWhether this is a buy or a sell
strikeUD60x18The strike price of the option.
maturityuint256The maturity of the option.
sizeUD60x18The amount of contracts.
spreadUD60x18The spread added on to the premium due to C-level
premiumUD60x18The base premium that is charged

_getPoolAddress

Gets the pool address corresponding to the given strike and maturity. Returns zero address if pool is not deployed.

function _getPoolAddress(UnderwriterVaultStorage.Layout storage l, UD60x18 strike, uint256 maturity)
    internal
    view
    returns (address);

Parameters

NameTypeDescription
lUnderwriterVaultStorage.Layout
strikeUD60x18The strike price for the pool
maturityuint256The maturity for the pool

Returns

NameTypeDescription
<none>addressThe pool address (zero address if pool is not deployed)

_computeAssetsAfterSettlementOfExpiredOptions

Computes the totalAssets and totalLockedAssets after the settlement of expired options. The totalAssets after settlement are the totalAssets less the exercise value of the call or put options that were sold. The totalLockedAssets after settlement are the totalLockedAssets less the collateral unlocked by the call or put.

function _computeAssetsAfterSettlementOfExpiredOptions(UnderwriterVaultStorage.Layout storage l)
    internal
    view
    returns (UD60x18 totalAssets, UD60x18 totalLockedAssets);

Returns

NameTypeDescription
totalAssetsUD60x18the total assets post settlement
totalLockedAssetsUD60x18the total locked assets post settlement

_getQuoteInternal

Get the variables needed in order to compute the quote for a trade

function _getQuoteInternal(
    UnderwriterVaultStorage.Layout storage l,
    QuoteArgsInternal memory args,
    bool revertIfPoolNotDeployed
) internal view returns (QuoteInternal memory quote);

getQuote

Returns the trade quote premium

function getQuote(IPoolFactory.PoolKey calldata poolKey, UD60x18 size, bool isBuy, address taker)
    external
    view
    returns (uint256 premium);

Parameters

NameTypeDescription
poolKeyIPoolFactory.PoolKeyThe option pool key
sizeUD60x18The size of the trade
isBuyboolWhether the trade is a buy or sell
takeraddressThe address of the taker

Returns

NameTypeDescription
premiumuint256The trade quote premium

trade

Executes a trade with the vault

function trade(IPoolFactory.PoolKey calldata poolKey, UD60x18 size, bool isBuy, uint256 premiumLimit, address referrer)
    external
    override
    nonReentrant;

Parameters

NameTypeDescription
poolKeyIPoolFactory.PoolKeyThe option pool key
sizeUD60x18The size of the trade
isBuyboolWhether the trade is a buy or sell
premiumLimituint256The premium limit of the trade
referreraddressThe address of the referrer

_settleMaturity

Settles all options that are on a single maturity

function _settleMaturity(UnderwriterVaultStorage.Layout storage l, uint256 maturity) internal;

Parameters

NameTypeDescription
lUnderwriterVaultStorage.Layout
maturityuint256The maturity that options will be settled for

_settle

Settles all options that are expired

function _settle(UnderwriterVaultStorage.Layout storage l) internal;

settle

Settles all expired option positions.

function settle() external override nonReentrant;

onERC1155Received

function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4);

onERC1155BatchReceived

function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)
    external
    pure
    returns (bytes4);

_computeManagementFee

Computes and returns the management fee in shares that have to be paid by vault share holders for using the vault.

function _computeManagementFee(UnderwriterVaultStorage.Layout storage l, uint256 timestamp)
    internal
    view
    returns (UD60x18 managementFeeInShares);

Parameters

NameTypeDescription
lUnderwriterVaultStorage.LayoutContains stored parameters of the vault, including the managementFeeRate and the lastManagementFeeTimestamp
timestampuint256The block's current timestamp.

Returns

NameTypeDescription
managementFeeInSharesUD60x18Returns the amount due in management fees in terms of shares (18 decimals).

_chargeManagementFees

Charges the management fees from by liquidity providers.

function _chargeManagementFees() internal;

_claimFees

Transfers fees to the FEE_RECEIVER.

function _claimFees(UnderwriterVaultStorage.Layout storage l) internal;

_revertIfNotRegistryOwner

function _revertIfNotRegistryOwner(address addr) internal view;

_revertIfZeroSize

Ensures that an option is tradeable with the vault.

function _revertIfZeroSize(UD60x18 size) internal pure;

Parameters

NameTypeDescription
sizeUD60x18The amount of contracts

_revertIfZeroShares

Ensures that a share amount is non zero.

function _revertIfZeroShares(uint256 shares) internal pure;

Parameters

NameTypeDescription
sharesuint256The amount of shares

_revertIfZeroAsset

Ensures that an asset amount is non zero.

function _revertIfZeroAsset(uint256 amount) internal pure;

Parameters

NameTypeDescription
amountuint256The amount of assets

_revertIfAddressZero

Ensures that an address is non zero.

function _revertIfAddressZero(address addr) internal pure;

Parameters

NameTypeDescription
addraddressThe address to check

_revertIfMaximumAmountExceeded

Ensures that an amount is not above maximum

function _revertIfMaximumAmountExceeded(UD60x18 maximum, UD60x18 amount) internal pure;

Parameters

NameTypeDescription
maximumUD60x18The maximum amount
amountUD60x18The amount to check

_revertIfNotTradeableWithVault

Ensures that an option is tradeable with the vault.

function _revertIfNotTradeableWithVault(bool isCallVault, bool isCallOption) internal pure;

Parameters

NameTypeDescription
isCallVaultboolWhether the vault is a call or put vault.
isCallOptionboolWhether the option is a call or put.

_revertIfOptionInvalid

Ensures that an option is valid for trading.

function _revertIfOptionInvalid(UD60x18 strike, uint256 maturity) internal view;

Parameters

NameTypeDescription
strikeUD60x18The strike price of the option.
maturityuint256The maturity of the option.

_revertIfInsufficientFunds

Ensures there is sufficient funds for processing a trade.

function _revertIfInsufficientFunds(UD60x18 strike, UD60x18 size, UD60x18 availableAssets) internal view;

Parameters

NameTypeDescription
strikeUD60x18The strike price.
sizeUD60x18The amount of contracts.
availableAssetsUD60x18The amount of available assets currently in the vault.

_revertIfOutOfDTEBounds

Ensures that a value is within the DTE bounds.

function _revertIfOutOfDTEBounds(UD60x18 value, UD60x18 minimum, UD60x18 maximum) internal pure;

Parameters

NameTypeDescription
valueUD60x18The observed value of the variable.
minimumUD60x18The minimum value the variable can be.
maximumUD60x18The maximum value the variable can be.

_revertIfOutOfDeltaBounds

Ensures that a value is within the delta bounds.

function _revertIfOutOfDeltaBounds(UD60x18 value, UD60x18 minimum, UD60x18 maximum) internal pure;

Parameters

NameTypeDescription
valueUD60x18The observed value of the variable.
minimumUD60x18The minimum value the variable can be.
maximumUD60x18The maximum value the variable can be.

_revertIfAboveTradeMaxSlippage

Ensures that a value is within the delta bounds.

function _revertIfAboveTradeMaxSlippage(UD60x18 totalPremium, UD60x18 premiumLimit, bool isBuy) internal pure;

Parameters

NameTypeDescription
totalPremiumUD60x18The total premium of the trade
premiumLimitUD60x18The premium limit of the trade
isBuyboolWhether the trade is a buy or a sell.

_revertIfInsufficientShorts

Ensures there is sufficient shorts for processing a sell trade.

function _revertIfInsufficientShorts(
    UnderwriterVaultStorage.Layout storage l,
    uint256 maturity,
    UD60x18 strike,
    UD60x18 size
) internal view;

Parameters

NameTypeDescription
lUnderwriterVaultStorage.Layout
maturityuint256The maturity.
strikeUD60x18The strike price.
sizeUD60x18The amount of contracts.

_revertIfSellIsDisabled

Ensures that the vault can't buy-to-close unless it is enabled.

function _revertIfSellIsDisabled(bool enableSell) internal pure;

Parameters

NameTypeDescription
enableSellboolWhether sell is enabled or not.

UnderwriterVaultProxy

Git Source

Inherits: Proxy

State Variables

VAULT_TYPE

bytes32 public constant VAULT_TYPE = keccak256("UnderwriterVault");

VAULT_REGISTRY

address internal immutable VAULT_REGISTRY;

Functions

constructor

constructor(
    address vaultRegistry,
    address base,
    address quote,
    address oracleAdapter,
    string memory name,
    string memory symbol,
    bool isCall,
    bytes memory settings
);

receive

receive() external payable;

_getImplementation

get logic implementation address

function _getImplementation() internal view override returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

getImplementation

get address of implementation contract

function getImplementation() external view returns (address);

Returns

NameTypeDescription
<none>addressimplementation address

UnderwriterVaultStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.UnderwriterVaultStorage");

Functions

layout

function layout() internal pure returns (Layout storage l);

updateSettings

function updateSettings(Layout storage l, bytes memory settings) internal;

assetDecimals

function assetDecimals(Layout storage l) internal view returns (uint8);

collateral

function collateral(Layout storage l, UD60x18 size, UD60x18 strike) internal view returns (UD60x18);

truncate

function truncate(Layout storage l, UD60x18 value) internal view returns (UD60x18);

fromTokenDecimals

function fromTokenDecimals(Layout storage l, uint256 value) internal view returns (UD60x18);

toTokenDecimals

function toTokenDecimals(Layout storage l, UD60x18 value) internal view returns (uint256);

getMaturityAfterTimestamp

Gets the nearest maturity after the given timestamp, exclusive of the timestamp being on a maturity

function getMaturityAfterTimestamp(Layout storage l, uint256 timestamp) internal view returns (uint256);

Parameters

NameTypeDescription
lLayout
timestampuint256The given timestamp

Returns

NameTypeDescription
<none>uint256The nearest maturity after the given timestamp

getNumberOfUnexpiredListings

Gets the number of unexpired listings within the basket of options underwritten by this vault at the current time

function getNumberOfUnexpiredListings(Layout storage l, uint256 timestamp) internal view returns (uint256);

Parameters

NameTypeDescription
lLayout
timestampuint256The given timestamp

Returns

NameTypeDescription
<none>uint256The number of unexpired listings

contains

Checks if a listing exists within internal data structures

function contains(Layout storage l, UD60x18 strike, uint256 maturity) internal view returns (bool);

Parameters

NameTypeDescription
lLayout
strikeUD60x18The strike price of the listing
maturityuint256The maturity of the listing

Returns

NameTypeDescription
<none>boolIf listing exists, return true, false otherwise

addListing

Adds a listing to the internal data structures

function addListing(Layout storage l, UD60x18 strike, uint256 maturity) internal;

Parameters

NameTypeDescription
lLayout
strikeUD60x18The strike price of the listing
maturityuint256The maturity of the listing

removeListing

Removes a listing from internal data structures

function removeListing(Layout storage l, UD60x18 strike, uint256 maturity) internal;

Parameters

NameTypeDescription
lLayout
strikeUD60x18The strike price of the listing
maturityuint256The maturity of the listing

Structs

Layout

struct Layout {
    address base;
    address quote;
    uint8 baseDecimals;
    uint8 quoteDecimals;
    address oracleAdapter;
    bool isCall;
    UD60x18 totalAssets;
    UD60x18 totalLockedAssets;
    UD60x18 minDTE;
    UD60x18 maxDTE;
    UD60x18 minDelta;
    UD60x18 maxDelta;
    UD60x18 minCLevel;
    UD60x18 maxCLevel;
    UD60x18 alphaCLevel;
    UD60x18 hourlyDecayDiscount;
    uint256 lastTradeTimestamp;
    uint256 minMaturity;
    uint256 maxMaturity;
    DoublyLinkedList.Uint256List maturities;
    mapping(uint256 => EnumerableSet.Bytes32Set) maturityToStrikes;
    mapping(uint256 => mapping(UD60x18 => UD60x18)) positionSizes;
    UD60x18 totalLockedSpread;
    UD60x18 spreadUnlockingRate;
    uint256 lastSpreadUnlockUpdate;
    mapping(uint256 => UD60x18) spreadUnlockingTicks;
    UD60x18 managementFeeRate;
    UD60x18 performanceFeeRate;
    UD60x18 protocolFees;
    uint256 lastManagementFeeTimestamp;
    uint256 pendingAssetsDeposit;
    bool enableSell;
    mapping(uint256 maturity => mapping(UD60x18 strike => UD60x18)) avgPremium;
}

IVault

Git Source

Inherits: ISolidStateERC4626

Functions

updateSettings

Updates the vault settings

function updateSettings(bytes memory settings) external;

Parameters

NameTypeDescription
settingsbytesEncoding of the new settings

getSettings

Return vault abi encoded vault settings

function getSettings() external view returns (bytes memory);

getQuote

Returns the trade quote premium

function getQuote(IPoolFactory.PoolKey calldata poolKey, UD60x18 size, bool isBuy, address taker)
    external
    view
    returns (uint256 premium);

Parameters

NameTypeDescription
poolKeyIPoolFactory.PoolKeyThe option pool key
sizeUD60x18The size of the trade
isBuyboolWhether the trade is a buy or sell
takeraddressThe address of the taker

Returns

NameTypeDescription
premiumuint256The trade quote premium

trade

Executes a trade with the vault

function trade(IPoolFactory.PoolKey calldata poolKey, UD60x18 size, bool isBuy, uint256 premiumLimit, address referrer)
    external;

Parameters

NameTypeDescription
poolKeyIPoolFactory.PoolKeyThe option pool key
sizeUD60x18The size of the trade
isBuyboolWhether the trade is a buy or sell
premiumLimituint256The premium limit of the trade
referreraddressThe address of the referrer

getUtilisation

Returns the utilisation rate of the vault

function getUtilisation() external view returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The utilisation rate of the vault

Events

UpdateQuotes

event UpdateQuotes();

PricePerShare

event PricePerShare(UD60x18 pricePerShare);

Trade

event Trade(
    address indexed user,
    address indexed pool,
    UD60x18 contractSize,
    bool isBuy,
    UD60x18 premium,
    UD60x18 takerFee,
    UD60x18 makerRebate,
    UD60x18 vaultFee
);

Settle

event Settle(address indexed pool, UD60x18 contractSize, UD60x18 fee);

ManagementFeePaid

event ManagementFeePaid(address indexed recipient, uint256 managementFee);

PerformanceFeePaid

event PerformanceFeePaid(address indexed recipient, uint256 performanceFee);

ClaimProtocolFees

event ClaimProtocolFees(address indexed feeReceiver, uint256 feesClaimed);

UpdateSettings

event UpdateSettings(bytes settings);

Errors

Vault__AboveMaxSlippage

error Vault__AboveMaxSlippage(UD60x18 totalPremium, UD60x18 premiumLimit);

Vault__AddressZero

error Vault__AddressZero();

Vault__InsufficientFunds

error Vault__InsufficientFunds();

Vault__InsufficientShorts

error Vault__InsufficientShorts();

Vault__InvalidSettingsUpdate

error Vault__InvalidSettingsUpdate();

Vault__InvariantViolated

error Vault__InvariantViolated();

Vault__MaximumAmountExceeded

error Vault__MaximumAmountExceeded(UD60x18 maximum, UD60x18 amount);

Vault__NotAuthorized

error Vault__NotAuthorized();

Vault__OptionExpired

error Vault__OptionExpired(uint256 timestamp, uint256 maturity);

Vault__OptionPoolNotListed

error Vault__OptionPoolNotListed();

Vault__OptionTypeMismatchWithVault

error Vault__OptionTypeMismatchWithVault();

Vault__OutOfDeltaBounds

error Vault__OutOfDeltaBounds();

Vault__OutOfDTEBounds

error Vault__OutOfDTEBounds();

Vault__SellDisabled

error Vault__SellDisabled();

Vault__SettingsNotFromRegistry

error Vault__SettingsNotFromRegistry();

Vault__SettingsUpdateIsEmpty

error Vault__SettingsUpdateIsEmpty();

Vault__StrikeZero

error Vault__StrikeZero();

Vault__TradeMustBeBuy

error Vault__TradeMustBeBuy();

Vault__TransferExceedsBalance

error Vault__TransferExceedsBalance(UD60x18 balance, UD60x18 amount);

Vault__ZeroAsset

error Vault__ZeroAsset();

Vault__ZeroShares

error Vault__ZeroShares();

Vault__ZeroSize

error Vault__ZeroSize();

IVaultRegistry

Git Source

Functions

getNumberOfVaults

Gets the total number of vaults in the registry.

function getNumberOfVaults() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of vaults in the registry.

addVault

Adds a vault to the registry.

function addVault(address vault, address asset, bytes32 vaultType, TradeSide side, OptionType optionType) external;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
assetaddressThe address for the token deposited in the vault.
vaultTypebytes32The type of the vault.
sideTradeSideThe trade side of the vault.
optionTypeOptionTypeThe option type of the vault.

removeVault

Removes a vault from the registry.

function removeVault(address vault) external;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.

isVault

Returns whether the given address is a vault

function isVault(address vault) external view returns (bool);

Parameters

NameTypeDescription
vaultaddressThe address to check

Returns

NameTypeDescription
<none>boolWhether the given address is a vault

updateVault

Updates a vault in the registry.

function updateVault(address vault, address asset, bytes32 vaultType, TradeSide side, OptionType optionType) external;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
assetaddressThe address for the token deposited in the vault.
vaultTypebytes32The type of the vault.
sideTradeSideThe trade side of the vault.
optionTypeOptionTypeThe option type of the vault.

addSupportedTokenPairs

Adds a set of supported token pairs to the vault.

function addSupportedTokenPairs(address vault, TokenPair[] memory tokenPairs) external;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
tokenPairsTokenPair[]The token pairs to add.

removeSupportedTokenPairs

Removes a set of supported token pairs from the vault.

function removeSupportedTokenPairs(address vault, TokenPair[] memory tokenPairsToRemove) external;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
tokenPairsToRemoveTokenPair[]The token pairs to remove.

getVault

Gets the vault at the specified by the proxy address.

function getVault(address vault) external view returns (Vault memory);

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.

Returns

NameTypeDescription
<none>VaultThe vault associated with the proxy address.

getSupportedTokenPairs

Gets the token supports supported for trading within the vault.

function getSupportedTokenPairs(address vault) external view returns (TokenPair[] memory);

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.

Returns

NameTypeDescription
<none>TokenPair[]The token pairs supported for trading within the vault.

getVaults

Gets all vaults in the registry.

function getVaults() external view returns (Vault[] memory);

Returns

NameTypeDescription
<none>Vault[]All vaults in the registry.

getVaultsByFilter

Gets all vaults with trade side side and option type optionType.

function getVaultsByFilter(address[] memory assets, TradeSide side, OptionType optionType)
    external
    view
    returns (Vault[] memory);

Parameters

NameTypeDescription
assetsaddress[]The accepted assets (empty list for all assets).
sideTradeSideThe trade side.
optionTypeOptionTypeThe option type.

Returns

NameTypeDescription
<none>Vault[]All vaults meeting all of the passed filter criteria.

getVaultsByAsset

Gets all vaults with asset as their deposit token.

function getVaultsByAsset(address asset) external view returns (Vault[] memory);

Parameters

NameTypeDescription
assetaddressThe desired asset.

Returns

NameTypeDescription
<none>Vault[]All vaults with asset as their deposit token.

getVaultsByTokenPair

Gets all vaults with tokenPair in their trading set.

function getVaultsByTokenPair(TokenPair memory tokenPair) external view returns (Vault[] memory);

Parameters

NameTypeDescription
tokenPairTokenPairThe desired token pair.

Returns

NameTypeDescription
<none>Vault[]All vaults with tokenPair in their trading set.

getVaultsByTradeSide

Gets all vaults with trade side side.

function getVaultsByTradeSide(TradeSide side) external view returns (Vault[] memory);

Parameters

NameTypeDescription
sideTradeSideThe trade side.

Returns

NameTypeDescription
<none>Vault[]All vaults with trade side side.

getVaultsByOptionType

Gets all vaults with option type optionType.

function getVaultsByOptionType(OptionType optionType) external view returns (Vault[] memory);

Parameters

NameTypeDescription
optionTypeOptionTypeThe option type.

Returns

NameTypeDescription
<none>Vault[]All vaults with option type optionType.

getVaultsByType

Gets all the vaults of type vaultType.

function getVaultsByType(bytes32 vaultType) external view returns (Vault[] memory);

Parameters

NameTypeDescription
vaultTypebytes32The vault type.

Returns

NameTypeDescription
<none>Vault[]All the vaults of type vaultType.

getImplementation

Gets the implementation for the vaultType.

function getImplementation(bytes32 vaultType) external view returns (address);

Parameters

NameTypeDescription
vaultTypebytes32The vault type.

Returns

NameTypeDescription
<none>addressThe implementation address.

setImplementation

Sets the implementation for the vaultType.

function setImplementation(bytes32 vaultType, address implementation) external;

Parameters

NameTypeDescription
vaultTypebytes32The vault type.
implementationaddressThe implementation contract address

Events

VaultImplementationSet

event VaultImplementationSet(bytes32 indexed vaultType, address implementation);

VaultAdded

event VaultAdded(
    address indexed vault, address indexed asset, bytes32 vaultType, TradeSide side, OptionType optionType
);

VaultRemoved

event VaultRemoved(address indexed vault);

VaultUpdated

event VaultUpdated(
    address indexed vault, address indexed asset, bytes32 vaultType, TradeSide side, OptionType optionType
);

SupportedTokenPairAdded

event SupportedTokenPairAdded(
    address indexed vault, address indexed base, address indexed quote, address oracleAdapter
);

SupportedTokenPairRemoved

event SupportedTokenPairRemoved(
    address indexed vault, address indexed base, address indexed quote, address oracleAdapter
);

Structs

Vault

struct Vault {
    address vault;
    address asset;
    bytes32 vaultType;
    TradeSide side;
    OptionType optionType;
}

TokenPair

struct TokenPair {
    address base;
    address quote;
    address oracleAdapter;
}

Enums

TradeSide

enum TradeSide {
    Buy,
    Sell,
    Both
}

OptionType

enum OptionType {
    Call,
    Put,
    Both
}

Vault

Git Source

Inherits: IVault, SolidStateERC4626

State Variables

VAULT_MINING

address internal immutable VAULT_MINING;

Functions

constructor

constructor(address vaultMining);

_beforeTokenTransfer

Updates VaultMining user state

function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override;

getUtilisation

Returns the utilisation rate of the vault

function getUtilisation() public view virtual returns (UD60x18);

Returns

NameTypeDescription
<none>UD60x18The utilisation rate of the vault

VaultRegistry

Git Source

Inherits: IVaultRegistry, OwnableInternal

Functions

getNumberOfVaults

Gets the total number of vaults in the registry.

function getNumberOfVaults() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of vaults in the registry.

addVault

Adds a vault to the registry.

function addVault(address vault, address asset, bytes32 vaultType, TradeSide side, OptionType optionType)
    external
    onlyOwner;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
assetaddressThe address for the token deposited in the vault.
vaultTypebytes32The type of the vault.
sideTradeSideThe trade side of the vault.
optionTypeOptionTypeThe option type of the vault.

removeVault

Removes a vault from the registry.

function removeVault(address vault) public onlyOwner;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.

isVault

Returns whether the given address is a vault

function isVault(address vault) external view returns (bool);

Parameters

NameTypeDescription
vaultaddressThe address to check

Returns

NameTypeDescription
<none>boolWhether the given address is a vault

updateVault

Updates a vault in the registry.

function updateVault(address vault, address asset, bytes32 vaultType, TradeSide side, OptionType optionType)
    external
    onlyOwner;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
assetaddressThe address for the token deposited in the vault.
vaultTypebytes32The type of the vault.
sideTradeSideThe trade side of the vault.
optionTypeOptionTypeThe option type of the vault.

addSupportedTokenPairs

Adds a set of supported token pairs to the vault.

function addSupportedTokenPairs(address vault, TokenPair[] memory tokenPairs) external onlyOwner;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
tokenPairsTokenPair[]The token pairs to add.

_containsTokenPair

Returns true if tokenPairs contains tokenPair, false otherwise

function _containsTokenPair(TokenPair[] memory tokenPairs, TokenPair memory tokenPair) internal pure returns (bool);

removeSupportedTokenPairs

Removes a set of supported token pairs from the vault.

function removeSupportedTokenPairs(address vault, TokenPair[] memory tokenPairsToRemove) external onlyOwner;

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.
tokenPairsToRemoveTokenPair[]The token pairs to remove.

getVault

Gets the vault at the specified by the proxy address.

function getVault(address vault) external view returns (Vault memory);

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.

Returns

NameTypeDescription
<none>VaultThe vault associated with the proxy address.

getSupportedTokenPairs

Gets the token supports supported for trading within the vault.

function getSupportedTokenPairs(address vault) external view returns (TokenPair[] memory);

Parameters

NameTypeDescription
vaultaddressThe proxy address of the vault.

Returns

NameTypeDescription
<none>TokenPair[]The token pairs supported for trading within the vault.

_getVaultsFromAddressSet

Returns an array of vaults from a set of vault addresses

function _getVaultsFromAddressSet(EnumerableSet.AddressSet storage vaultSet) internal view returns (Vault[] memory);

getVaults

Gets all vaults in the registry.

function getVaults() external view returns (Vault[] memory);

Returns

NameTypeDescription
<none>Vault[]All vaults in the registry.

getVaultsByFilter

Gets all vaults with trade side side and option type optionType.

function getVaultsByFilter(address[] memory assets, TradeSide side, OptionType optionType)
    external
    view
    returns (Vault[] memory);

Parameters

NameTypeDescription
assetsaddress[]The accepted assets (empty list for all assets).
sideTradeSideThe trade side.
optionTypeOptionTypeThe option type.

Returns

NameTypeDescription
<none>Vault[]All vaults meeting all of the passed filter criteria.

getVaultsByAsset

Gets all vaults with asset as their deposit token.

function getVaultsByAsset(address asset) external view returns (Vault[] memory);

Parameters

NameTypeDescription
assetaddressThe desired asset.

Returns

NameTypeDescription
<none>Vault[]All vaults with asset as their deposit token.

getVaultsByTokenPair

Gets all vaults with tokenPair in their trading set.

function getVaultsByTokenPair(TokenPair memory tokenPair) external view returns (Vault[] memory);

Parameters

NameTypeDescription
tokenPairTokenPairThe desired token pair.

Returns

NameTypeDescription
<none>Vault[]All vaults with tokenPair in their trading set.

getVaultsByTradeSide

Gets all vaults with trade side side.

function getVaultsByTradeSide(TradeSide side) external view returns (Vault[] memory);

Parameters

NameTypeDescription
sideTradeSideThe trade side.

Returns

NameTypeDescription
<none>Vault[]All vaults with trade side side.

getVaultsByOptionType

Gets all vaults with option type optionType.

function getVaultsByOptionType(OptionType optionType) external view returns (Vault[] memory);

Parameters

NameTypeDescription
optionTypeOptionTypeThe option type.

Returns

NameTypeDescription
<none>Vault[]All vaults with option type optionType.

getVaultsByType

Gets all the vaults of type vaultType.

function getVaultsByType(bytes32 vaultType) external view returns (Vault[] memory);

Parameters

NameTypeDescription
vaultTypebytes32The vault type.

Returns

NameTypeDescription
<none>Vault[]All the vaults of type vaultType.

getImplementation

Gets the implementation for the vaultType.

function getImplementation(bytes32 vaultType) external view returns (address);

Parameters

NameTypeDescription
vaultTypebytes32The vault type.

Returns

NameTypeDescription
<none>addressThe implementation address.

setImplementation

Sets the implementation for the vaultType.

function setImplementation(bytes32 vaultType, address implementation) external onlyOwner;

Parameters

NameTypeDescription
vaultTypebytes32The vault type.
implementationaddressThe implementation contract address

VaultRegistryStorage

Git Source

State Variables

STORAGE_SLOT

bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VaultRegistry");

Functions

layout

function layout() internal pure returns (Layout storage l);

Structs

Layout

struct Layout {
    EnumerableSet.AddressSet vaultAddresses;
    mapping(bytes32 vaultType => bytes) __deprecated_settings;
    mapping(bytes32 vaultType => address) implementations;
    mapping(address vault => IVaultRegistry.Vault) vaults;
    mapping(address vault => IVaultRegistry.TokenPair[] supported) supportedTokenPairs;
    mapping(bytes32 vaultType => EnumerableSet.AddressSet vaults) vaultsByType;
    mapping(address asset => EnumerableSet.AddressSet vaults) vaultsByAsset;
    mapping(address base => mapping(address quote => mapping(address oracleAdapter => EnumerableSet.AddressSet vaults)))
        vaultsByTokenPair;
    mapping(IVaultRegistry.TradeSide tradeSide => EnumerableSet.AddressSet vaults) vaultsByTradeSide;
    mapping(IVaultRegistry.OptionType optionType => EnumerableSet.AddressSet vaults) vaultsByOptionType;
}

Contents

AggregatorProxyInterface

Git Source

Inherits: AggregatorV2V3Interface

Wrapper interface for the AggregatorProxy contracts

Functions

phaseAggregators

function phaseAggregators(uint16 phaseId) external view returns (address);

phaseId

function phaseId() external view returns (uint16);

proposedAggregator

function proposedAggregator() external view returns (address);

proposedGetRoundData

function proposedGetRoundData(uint80 roundId)
    external
    view
    returns (uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

proposedLatestRoundData

function proposedLatestRoundData()
    external
    view
    returns (uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

aggregator

function aggregator() external view returns (address);