Premia - Next-Generation Options AMM
https://premia.finance
Deployments
Deployment | Arbitrum | Arbitrum Goerli | Arbitrum 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:
Key | Description | Required for |
---|---|---|
API_KEY_ALCHEMY | Alchemy API key for node connectivity | Tests + deployments |
API_KEY_ARBISCAN | Arbiscan API key for source code verification | Contracts verification |
PKEY_DEPLOYER_MAIN | contract deployer private key for production use on mainnets | Mainnet deployment |
PKEY_DEPLOYER_TEST | contract deployer private key for test/development use on testnets | Testnet deployment |
PKEY_PROPOSER_MAIN | Safe multi-sig transaction proposer private key for production use on mainnets | Mainnet deployment |
PKEY_PROPOSER_TEST | Safe multi-sig transaction proposer private key for test/development use on testnets | Testnet 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
- chainlink
- FeedRegistry
- FeedRegistryStorage
- IFeedRegistry
- IOracleAdapter
- IPriceRepository
- OracleAdapter
- PriceRepository
- PriceRepositoryStorage
- Tokens
- Tokens constants
Contents
ChainlinkAdapter
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
Name | Type | Description |
---|---|---|
tokenA | address | One of the pair's tokens |
tokenB | address | The other of the pair's tokens |
Returns
Name | Type | Description |
---|---|---|
isCached | bool | True if the pair has been cached, false otherwise |
hasPath | bool | True 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
Name | Type | Description |
---|---|---|
tokenA | address | One of the pair's tokens |
tokenB | address | The 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
Name | Type | Description |
---|---|---|
tokenIn | address | The exchange token (base token) |
tokenOut | address | The token to quote against (quote token) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
tokenIn | address | The exchange token (base token) |
tokenOut | address | The token to quote against (quote token) |
target | uint256 | Reference timestamp of the quote |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | Historical 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
Name | Type | Description |
---|---|---|
token | address | The token from where the pricing path starts |
Returns
Name | Type | Description |
---|---|---|
adapterType | AdapterType | The type of adapter |
path | address[][] | The path required to convert the token to ETH |
decimals | uint8[] | 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
Name | Type | Description |
---|---|---|
tokenA | address | One of the pair's tokens |
tokenB | address | The other of the pair's tokens |
Returns
Name | Type | Description |
---|---|---|
<none> | PricingPath | The 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
Name | Type | Description |
---|---|---|
args | FeedMappingArgs[] | 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
Name | Type | Description |
---|---|---|
token | address | The exchange token (ERC20 token) |
denomination | address | The Chainlink token denomination to quote against (ETH, BTC, or USD) |
timestamp | uint256 | Reference timestamp (in seconds) |
price | UD60x18 | The 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
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
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
Name | Type | Description |
---|---|---|
tokenA | address | One of the pair's tokens |
tokenB | address | The other of the pair's tokens |
Returns
Name | Type | Description |
---|---|---|
<none> | PricingPath | The 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
Name | Type | Description |
---|---|---|
tokenA | address | One of the pair's tokens |
tokenB | address | The other of the pair's tokens |
path | PricingPath | The 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
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
Name | Type | Description |
---|---|---|
args | FeedMappingArgs[] | 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
Name | Type | Description |
---|---|---|
token | address | The exchange token (ERC20 token) |
denomination | address | The Chainlink token denomination to quote against (ETH, BTC, or USD) |
Returns
Name | Type | Description |
---|---|---|
<none> | address | The 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
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
Functions
batchRegisterFeedMappings
Registers mappings of ERC20 token, and denomination (ETH, BTC, or USD) to feed
function batchRegisterFeedMappings(FeedMappingArgs[] memory args) external;
Parameters
Name | Type | Description |
---|---|---|
args | FeedMappingArgs[] | 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
Name | Type | Description |
---|---|---|
token | address | The exchange token (ERC20 token) |
denomination | address | The Chainlink token denomination to quote against (ETH, BTC, or USD) |
Returns
Name | Type | Description |
---|---|---|
<none> | address | The feed address |
Events
FeedMappingsRegistered
Emitted when new price feed mappings are registered
event FeedMappingsRegistered(FeedMappingArgs[] args);
Parameters
Name | Type | Description |
---|---|---|
args | FeedMappingArgs[] | The arguments for the new mappings |
Structs
FeedMappingArgs
struct FeedMappingArgs {
address token;
address denomination;
address feed;
}
IOracleAdapter
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
Name | Type | Description |
---|---|---|
tokenA | address | One of the pair's tokens |
tokenB | address | The other of the pair's tokens |
Returns
Name | Type | Description |
---|---|---|
isCached | bool | True if the pair has been cached, false otherwise |
hasPath | bool | True 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
Name | Type | Description |
---|---|---|
tokenA | address | One of the pair's tokens |
tokenB | address | The 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
Name | Type | Description |
---|---|---|
tokenIn | address | The exchange token (base token) |
tokenOut | address | The token to quote against (quote token) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
tokenIn | address | The exchange token (base token) |
tokenOut | address | The token to quote against (quote token) |
target | uint256 | Reference timestamp of the quote |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | Historical 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
Name | Type | Description |
---|---|---|
token | address | The token from where the pricing path starts |
Returns
Name | Type | Description |
---|---|---|
adapterType | AdapterType | The type of adapter |
path | address[][] | The path required to convert the token to ETH |
decimals | uint8[] | 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
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
Name | Type | Description |
---|---|---|
token | address | The exchange token (ERC20 token) |
denomination | address | The Chainlink token denomination to quote against (ETH, BTC, or USD) |
timestamp | uint256 | Reference timestamp (in seconds) |
price | UD60x18 | The amount of token denominated in denomination (18 decimals) |
Events
PriceUpdate
event PriceUpdate(address indexed token, address indexed denomination, uint256 timestamp, UD60x18 price);
OracleAdapter
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
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
Name | Type | Description |
---|---|---|
token | address | The exchange token (ERC20 token) |
denomination | address | The Chainlink token denomination to quote against (ETH, BTC, or USD) |
timestamp | uint256 | Reference timestamp (in seconds) |
price | UD60x18 | The 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
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
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
FOREX_DECIMALS
uint8 constant FOREX_DECIMALS = 8;
ETH_DECIMALS
uint8 constant ETH_DECIMALS = 18;
Contents
- IPoolFactory
- IPoolFactoryDeployer
- IPoolFactoryEvents
- PoolFactory
- PoolFactoryDeployer
- PoolFactoryProxy
- PoolFactoryStorage
IPoolFactory
Inherits: IPoolFactoryEvents
Functions
isPool
Returns whether the given address is a pool
function isPool(address contractAddress) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
contractAddress | address | The address to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
k | PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
pool | address | The pool address |
isDeployed | bool | Whether the pool has been deployed |
deployPool
Deploy a new option pool
function deployPool(PoolKey calldata k) external payable returns (address poolAddress);
Parameters
Name | Type | Description |
---|---|---|
k | PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
poolAddress | address | The address of the deployed pool |
initializationFee
DEPRECATED: Calculates the initialization fee for a pool
function initializationFee(PoolKey calldata k) external view returns (UD60x18);
Parameters
Name | Type | Description |
---|---|---|
k | PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Functions
deployPool
Deploy a new option pool
function deployPool(IPoolFactory.PoolKey calldata k) external returns (address poolAddress);
Parameters
Name | Type | Description |
---|---|---|
k | IPoolFactory.PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
poolAddress | address | The 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
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
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
Name | Type | Description |
---|---|---|
contractAddress | address | The address to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
k | PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
pool | address | The pool address |
isDeployed | bool | Whether 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
Name | Type | Description |
---|---|---|
k | PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
poolAddress | address | The 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
Name | Type | Description |
---|---|---|
k | IPoolFactory.PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
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
Name | Type | Description |
---|---|---|
k | IPoolFactory.PoolKey | The pool key |
Returns
Name | Type | Description |
---|---|---|
poolAddress | address | The 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
Inherits: ProxyUpgradeableOwnable
Functions
constructor
constructor(address implementation) ProxyUpgradeableOwnable(implementation);
PoolFactoryStorage
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
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
Name | Type | Description |
---|---|---|
dstChainId | uint16 | The destination chain identifier |
destination | bytes | The address on destination chain (in bytes). address length/format may vary by chains |
payload | bytes | A custom bytes payload to send to the destination contract |
refundAddress | address payable | If the source transaction is cheaper than the amount of value passed, refund the additional amount to this address |
zroPaymentAddress | address | The address of the ZRO token holder who would pay for the transaction |
adapterParams | bytes | Parameters 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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The source chain identifier |
srcAddress | bytes | The source contract (as bytes) at the source chain |
dstAddress | address | The address on destination chain |
nonce | uint64 | The unbound message ordering nonce |
gasLimit | uint256 | The gas limit for external contract execution |
payload | bytes | Verified 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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The source chain identifier |
srcAddress | bytes | The 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
Name | Type | Description |
---|---|---|
dstChainId | uint16 | |
srcAddress | address | The 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
Name | Type | Description |
---|---|---|
dstChainId | uint16 | The destination chain identifier |
userApplication | address | The user app address on this EVM chain |
payload | bytes | The custom message to send over LayerZero |
payInZRO | bool | If false, user app pays the protocol fee in native token |
adapterParam | bytes | Parameters 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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The source chain identifier |
srcAddress | bytes | The source chain contract address |
payload | bytes | The 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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The source chain identifier |
srcAddress | bytes | The source chain contract address |
getSendLibraryAddress
Query if the libraryAddress is valid for sending msgs.
function getSendLibraryAddress(address userApplication) external view returns (address);
Parameters
Name | Type | Description |
---|---|---|
userApplication | address | The 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
Name | Type | Description |
---|---|---|
userApplication | address | The 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
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
version | uint16 | Messaging library version |
chainId | uint16 | The chainId for the pending config change |
userApplication | address | The contract address of the user application |
configType | uint256 | Type 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
Name | Type | Description |
---|---|---|
userApplication | address | The contract address of the user application |
getReceiveVersion
Get the lzReceive() LayerZero messaging library version
function getReceiveVersion(address userApplication) external view returns (uint16);
Parameters
Name | Type | Description |
---|---|---|
userApplication | address | The contract address of the user application |
ILayerZeroReceiver
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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The source endpoint identifier |
srcAddress | bytes | The source sending contract address from the source chain |
nonce | uint64 | The ordered message nonce |
payload | bytes | The signed payload is the UA bytes has encoded to be sent |
ILayerZeroUserApplicationConfig
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
Name | Type | Description |
---|---|---|
version | uint16 | Messaging library version |
chainId | uint16 | The chainId for the pending config change |
configType | uint256 | Type of configuration. every messaging library has its own convention. |
config | bytes | Configuration in the bytes. can encode arbitrary content. |
setSendVersion
Set the send() LayerZero messaging library version to version
function setSendVersion(uint16 version) external;
Parameters
Name | Type | Description |
---|---|---|
version | uint16 | New messaging library version |
setReceiveVersion
Set the lzReceive() LayerZero messaging library version to version
function setReceiveVersion(uint16 version) external;
Parameters
Name | Type | Description |
---|---|---|
version | uint16 | NMew 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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The chainId of the source chain |
srcAddress | bytes | The contract address of the source contract at the source chain |
Contents
LzApp
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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The source endpoint identifier |
srcAddress | bytes | The source sending contract address from the source chain |
nonce | uint64 | The ordered message nonce |
payload | bytes | The 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
Name | Type | Description |
---|---|---|
version | uint16 | Messaging library version |
chainId | uint16 | The chainId for the pending config change |
configType | uint256 | Type of configuration. every messaging library has its own convention. |
config | bytes | Configuration in the bytes. can encode arbitrary content. |
setSendVersion
Set the send() LayerZero messaging library version to version
function setSendVersion(uint16 version) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
version | uint16 | New messaging library version |
setReceiveVersion
Set the lzReceive() LayerZero messaging library version to version
function setReceiveVersion(uint16 version) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
version | uint16 | NMew 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
Name | Type | Description |
---|---|---|
srcChainId | uint16 | The chainId of the source chain |
srcAddress | bytes | The 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
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
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
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
Inherits: IOFTCore, ISolidStateERC20
Interface of the OFT standard
Errors
OFT_InsufficientAllowance
error OFT_InsufficientAllowance();
IOFTCore
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
Name | Type | Description |
---|---|---|
dstChainId | uint16 | L0 defined chain id to send tokens too |
toAddress | bytes | Dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain |
amount | uint256 | Amount of the tokens to transfer |
useZro | bool | Indicates to use zro to pay L0 fees |
adapterParams | bytes | Flexible 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
Name | Type | Description |
---|---|---|
from | address | The owner of token |
dstChainId | uint16 | The destination chain identifier |
toAddress | bytes | Can be any size depending on the dstChainId . |
amount | uint256 | The quantity of tokens in wei |
refundAddress | address payable | The address LayerZero refunds if too much message fee is sent |
zroPaymentAddress | address | Set to address(0x0) if not paying in ZRO (LayerZero Token) |
adapterParams | bytes | Flexible 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
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
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
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
Inherits: ProxyUpgradeableOwnable, ERC165BaseInternal
Functions
constructor
constructor(address implementation) ProxyUpgradeableOwnable(implementation);
Contents
BytesLib
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
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
Name | Type | Description |
---|---|---|
_target | address | The address to call |
_gas | uint256 | The amount of gas to forward to the remote contract |
_maxCopy | uint16 | The maximum number of bytes of returndata to copy to memory. |
_calldata | bytes | The data to send to the remote contract |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | success 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
Name | Type | Description |
---|---|---|
_target | address | The address to call |
_gas | uint256 | The amount of gas to forward to the remote contract |
_maxCopy | uint16 | The maximum number of bytes of returndata to copy to memory. |
_calldata | bytes | The data to send to the remote contract |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | success 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
Name | Type | Description |
---|---|---|
_newSelector | bytes4 | The new 4-byte selector |
_buf | bytes | The encoded contract args |
Contents
- ArrayUtils
- Constants
- DoublyLinkedListUD60x18
- EnumerableSetUD60x18
- IPosition
- IPricing
- OptionMath
- OptionMathExternal
- PRBMathExtra
- PoolName
- Position
- Pricing
- SD49x28
- SD49x28_Mul_InputTooSmall
- SD49x28_Mul_Overflow
- SD49x28_Div_InputTooSmall
- SD49x28_Div_Overflow
- SD49x28_IntoUD50x28_Underflow
- SD49x28_Abs_MinSD49x28
- eq
- uncheckedAdd
- or
- wrap
- gte
- add
- uncheckedSub
- intoUD50x28
- isZero
- lt
- and2
- uncheckedUnary
- unwrap
- and
- rshift
- lte
- neq
- intoSD59x18
- unary
- intoUD60x18
- sd49x28
- gt
- abs
- lshift
- sub
- avg
- not
- mod
- mul
- xor
- div
- SD49x28 constants
- UD50x28
- UD50x28_IntoSD49x28_Overflow
- mul
- gt
- avg
- intoUD60x18
- wrap
- and
- lt
- neq
- lshift
- isZero
- uncheckedAdd
- rshift
- sub
- xor
- eq
- ud50x28
- and2
- not
- add
- mod
- div
- unwrap
- lte
- intoSD49x28
- gte
- or
- uncheckedSub
- UD50x28 constants
ArrayUtils
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
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
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
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
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
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
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
Name | Type | Description |
---|---|---|
x | SD59x18 | The input to the normal CDF (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
result | SD59x18 | The 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
Name | Type | Description |
---|---|---|
x | SD59x18 | input value to evaluate the normal CDF on, F(Z<=x) (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
result | SD59x18 | The 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
Name | Type | Description |
---|---|---|
x | SD59x18 | Number to get PDF for (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
z | SD59x18 | z-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
Name | Type | Description |
---|---|---|
x | SD59x18 | Input value (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | result 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
Name | Type | Description |
---|---|---|
spot | UD60x18 | The spot price. (18 decimals) |
strike | UD60x18 | The strike price of the option. (18 decimals) |
timeToMaturity | UD60x18 | The time until the option expires. (18 decimals) |
volAnnualized | UD60x18 | The percentage volatility of the geometric Brownian motion. (18 decimals) |
riskFreeRate | UD60x18 | The rate of the risk-less asset, i.e. the risk-free interest rate. (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
d1 | SD59x18 | The term d1 from the Black-Scholes formula. (18 decimals) |
d2 | SD59x18 | The 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
Name | Type | Description |
---|---|---|
spot | UD60x18 | Spot price |
strike | UD60x18 | Strike price |
timeToMaturity | UD60x18 | Duration of option contract (in years) |
volAnnualized | UD60x18 | Annualized volatility |
riskFreeRate | UD60x18 | |
isCall | bool | whether to price "call" or "put" option |
Returns
Name | Type | Description |
---|---|---|
<none> | SD59x18 | price 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
Name | Type | Description |
---|---|---|
spot | UD60x18 | Spot price (18 decimals) |
strike | UD60x18 | Strike price (18 decimals) |
timeToMaturity | UD60x18 | Duration of option contract (in years) (18 decimals) |
volAnnualized | UD60x18 | Annualized volatility (18 decimals) |
riskFreeRate | UD60x18 | The risk-free rate (18 decimals) |
isCall | bool | whether to price "call" or "put" option |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | price 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
Name | Type | Description |
---|---|---|
maturity | uint256 | The maturity timestamp of the option |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
maturity | uint256 | The maturity timestamp of the option |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
maturity | uint256 | The maturity timestamp of the option |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
maturity | uint256 | The maturity timestamp of the option |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | Time to maturity in seconds |
calculateStrikeInterval
Calculates the strike interval for strike
function calculateStrikeInterval(UD60x18 strike) internal pure returns (UD60x18);
Parameters
Name | Type | Description |
---|---|---|
strike | UD60x18 | The price to calculate strike interval for (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The strike interval (18 decimals) |
roundToStrikeInterval
Rounds strike
using the calculated strike interval
function roundToStrikeInterval(UD60x18 strike) internal pure returns (UD60x18);
Parameters
Name | Type | Description |
---|---|---|
strike | UD60x18 | The price to round (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
value | uint256 | The value to convert |
inputDecimals | uint8 | The amount of decimals the input value has |
targetDecimals | uint8 | The amount of decimals to convert to |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
value | int256 | The value to convert |
inputDecimals | uint8 | The amount of decimals the input value has |
targetDecimals | uint8 | The amount of decimals to convert to |
Returns
Name | Type | Description |
---|---|---|
<none> | int256 | The converted value |
fromTokenDecimals
Converts a number with decimals
, to a UD60x18 type
function fromTokenDecimals(uint256 value, uint8 decimals) internal pure returns (UD60x18);
Parameters
Name | Type | Description |
---|---|---|
value | uint256 | The value to convert |
decimals | uint8 | The amount of decimals the value has |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
value | UD60x18 | The value to convert |
decimals | uint8 | The amount of decimals the value has |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
value | UD60x18 | The value to convert |
decimals | uint8 | The amount of decimals the value has |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The truncated UD60x18 number |
countSignificantDigits
Counts the number of significant digits in a UD60x18 number
function countSignificantDigits(UD60x18 value) internal pure returns (uint8);
Parameters
Name | Type | Description |
---|---|---|
value | UD60x18 | The value to count the significant digits of |
Returns
Name | Type | Description |
---|---|---|
<none> | uint8 | The number of significant digits |
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
Name | Type | Description |
---|---|---|
utilisation | UD60x18 | The utilisation after some collateral is utilised |
duration | UD60x18 | The time since last trade (hours) |
alpha | UD60x18 | (needs to be filled in) |
minCLevel | UD60x18 | The minimum C-level |
maxCLevel | UD60x18 | The maximum C-level |
decayRate | UD60x18 | The decay rate of the C-level back down to minimum level (decay/hour) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
utilisationBefore | UD60x18 | The utilisation before some collateral is utilised. |
utilisationAfter | UD60x18 | The utilisation after some collateral is utilised |
duration | UD60x18 | The time since last trade (hours) |
alpha | UD60x18 | (needs to be filled in) |
minCLevel | UD60x18 | The minimum C-level |
maxCLevel | UD60x18 | The maximum C-level |
decayRate | UD60x18 | The decay rate of the C-level back down to minimum level (decay/hour) |
Returns
Name | Type | Description |
---|---|---|
cLevel | UD60x18 | The 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
Functions
optionDelta
Calculate option delta
function optionDelta(
UD60x18 spot,
UD60x18 strike,
UD60x18 timeToMaturity,
UD60x18 volAnnualized,
UD60x18 riskFreeRate,
bool isCall
) public pure returns (SD59x18);
Parameters
Name | Type | Description |
---|---|---|
spot | UD60x18 | Spot price |
strike | UD60x18 | Strike price |
timeToMaturity | UD60x18 | Duration of option contract (in years) |
volAnnualized | UD60x18 | Annualized volatility |
riskFreeRate | UD60x18 | |
isCall | bool | whether to price "call" or "put" option |
Returns
Name | Type | Description |
---|---|---|
<none> | SD59x18 | price 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
Name | Type | Description |
---|---|---|
spot | UD60x18 | Spot price (18 decimals) |
strike | UD60x18 | Strike price (18 decimals) |
timeToMaturity | UD60x18 | Duration of option contract (in years) (18 decimals) |
volAnnualized | UD60x18 | Annualized volatility (18 decimals) |
riskFreeRate | UD60x18 | The risk-free rate (18 decimals) |
isCall | bool | whether to price "call" or "put" option |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | price 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
Name | Type | Description |
---|---|---|
utilisation | UD60x18 | The utilisation after some collateral is utilised |
duration | UD60x18 | The time since last trade (hours) |
alpha | UD60x18 | (needs to be filled in) |
minCLevel | UD60x18 | The minimum C-level |
maxCLevel | UD60x18 | The maximum C-level |
decayRate | UD60x18 | The decay rate of the C-level back down to minimum level (decay/hour) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
utilisationBefore | UD60x18 | The utilisation before some collateral is utilised. |
utilisationAfter | UD60x18 | The utilisation after some collateral is utilised |
duration | UD60x18 | The time since last trade (hours) |
alpha | UD60x18 | (needs to be filled in) |
minCLevel | UD60x18 | The minimum C-level |
maxCLevel | UD60x18 | The maximum C-level |
decayRate | UD60x18 | The decay rate of the C-level back down to minimum level (decay/hour) |
Returns
Name | Type | Description |
---|---|---|
cLevel | UD60x18 | The C-level corresponding to the geo-mean of the utilisation value before and after collateral is utilised. |
PRBMathExtra
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
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
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
Name | Type | Description |
---|---|---|
self | Key | |
strike | UD60x18 | The strike of the option (18 decimals) |
isCall | bool |
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
Name | Type | Description |
---|---|---|
_collateral | UD60x18 | |
strike | UD60x18 | The strike price (18 decimals) |
isCall | bool |
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
Name | Type | Description |
---|---|---|
_contracts | UD60x18 | |
strike | UD60x18 | The strike price (18 decimals) |
isCall | bool |
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
Name | Type | Description |
---|---|---|
_collateral | UD50x28 | |
strike | UD60x18 | The strike price (18 decimals) |
isCall | bool |
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
Name | Type | Description |
---|---|---|
_contracts | UD50x28 | |
strike | UD60x18 | The strike price (18 decimals) |
isCall | bool |
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
Name | Type | Description |
---|---|---|
self | KeyInternal | |
size | UD60x18 | The 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
Name | Type | Description |
---|---|---|
self | KeyInternal | The internal position key |
size | UD60x18 | The contract amount (18 decimals) |
price | UD50x28 | The 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
Name | Type | Description |
---|---|---|
self | KeyInternal | |
size | UD60x18 | The contract amount (18 decimals) |
price | UD50x28 | The 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
Name | Type | Description |
---|---|---|
self | KeyInternal | |
size | UD60x18 | The contract amount (18 decimals) |
price | UD50x28 | The 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
Name | Type | Description |
---|---|---|
self | KeyInternal | |
size | UD60x18 | The contract amount (18 decimals) |
price | UD50x28 | The 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
Name | Type | Description |
---|---|---|
self | KeyInternal | |
size | UD60x18 | The contract amount (18 decimals) |
price | UD50x28 | The 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
Name | Type | Description |
---|---|---|
self | KeyInternal | |
currentBalance | UD60x18 | The current balance of tokens (18 decimals) |
amount | SD59x18 | The number of tokens deposited or withdrawn (18 decimals) |
price | UD50x28 | The current market price, used to compute the change in collateral, long and shorts due to the change in tokens (28 decimals) |
Returns
Name | Type | Description |
---|---|---|
delta | Delta | Absolute 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
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
type SD49x28 is int256;
SD49x28_Mul_InputTooSmall
error SD49x28_Mul_InputTooSmall();
SD49x28_Mul_Overflow
error SD49x28_Mul_Overflow(SD49x28 x, SD49x28 y);
SD49x28_Div_InputTooSmall
error SD49x28_Div_InputTooSmall();
SD49x28_Div_Overflow
error SD49x28_Div_Overflow(SD49x28 x, SD49x28 y);
SD49x28_IntoUD50x28_Underflow
error SD49x28_IntoUD50x28_Underflow(SD49x28 x);
SD49x28_Abs_MinSD49x28
error SD49x28_Abs_MinSD49x28();
eq
Implements the equal (=) operation in the SD49x28 type.
function eq(SD49x28 x, SD49x28 y) pure returns (bool result);
uncheckedAdd
Implements the unchecked addition operation (+) in the SD49x28 type.
function uncheckedAdd(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
or
Implements the OR (|) bitwise operation in the SD49x28 type.
function or(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
wrap
Wraps a int256 number into the SD49x28 value type.
function wrap(int256 x) pure returns (SD49x28 result);
gte
Implements the greater than or equal to operation (>=) in the SD49x28 type.
function gte(SD49x28 x, SD49x28 y) pure returns (bool result);
add
Implements the checked addition operation (+) in the SD49x28 type.
function add(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
uncheckedSub
Implements the unchecked subtraction operation (-) in the SD49x28 type.
function uncheckedSub(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
intoUD50x28
Casts an SD49x28 number into UD50x28.
*Requirements:
- x must be positive.*
function intoUD50x28(SD49x28 x) pure returns (UD50x28 result);
isZero
Implements a zero comparison check function in the SD49x28 type.
function isZero(SD49x28 x) pure returns (bool result);
lt
Implements the lower than operation (<) in the SD49x28 type.
function lt(SD49x28 x, SD49x28 y) pure returns (bool result);
and2
Implements the AND (&) bitwise operation in the SD49x28 type.
function and2(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
uncheckedUnary
Implements the unchecked unary minus operation (-) in the SD49x28 type.
function uncheckedUnary(SD49x28 x) pure returns (SD49x28 result);
unwrap
Unwraps a SD49x28 number into int256.
function unwrap(SD49x28 x) pure returns (int256 result);
and
Implements the AND (&) bitwise operation in the SD49x28 type.
function and(SD49x28 x, int256 bits) pure returns (SD49x28 result);
rshift
Implements the right shift operation (>>) in the SD49x28 type.
function rshift(SD49x28 x, uint256 bits) pure returns (SD49x28 result);
lte
Implements the lower than or equal to operation (<=) in the SD49x28 type.
function lte(SD49x28 x, SD49x28 y) pure returns (bool result);
neq
Implements the not equal operation (!=) in the SD49x28 type.
function neq(SD49x28 x, SD49x28 y) pure returns (bool result);
intoSD59x18
function intoSD59x18(SD49x28 x) pure returns (SD59x18 result);
unary
Implements the checked unary minus operation (-) in the SD49x28 type.
function unary(SD49x28 x) pure returns (SD49x28 result);
intoUD60x18
function intoUD60x18(SD49x28 x) pure returns (UD60x18 result);
sd49x28
function sd49x28(int256 x) pure returns (SD49x28 result);
gt
Implements the greater than operation (>) in the SD49x28 type.
function gt(SD49x28 x, SD49x28 y) pure returns (bool result);
abs
Calculates the absolute value of x.
*Requirements:
- x must be greater than
MIN_SD49x28
.*
function abs(SD49x28 x) pure returns (SD49x28 result);
Parameters
Name | Type | Description |
---|---|---|
x | SD49x28 | The SD49x28 number for which to calculate the absolute value. |
lshift
Implements the left shift operation (<<) in the SD49x28 type.
function lshift(SD49x28 x, uint256 bits) pure returns (SD49x28 result);
sub
Implements the checked subtraction operation (-) in the SD49x28 type.
function sub(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
avg
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
Name | Type | Description |
---|---|---|
x | SD49x28 | The first operand as an SD49x28 number. |
y | SD49x28 | The second operand as an SD49x28 number. |
Returns
Name | Type | Description |
---|---|---|
result | SD49x28 | The arithmetic average as an SD49x28 number. |
not
Implements the NOT (~) bitwise operation in the SD49x28 type.
function not(SD49x28 x) pure returns (SD49x28 result);
mod
Implements the unchecked modulo operation (%) in the SD49x28 type.
function mod(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
mul
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
Name | Type | Description |
---|---|---|
x | SD49x28 | The multiplicand as an SD49x28 number. |
y | SD49x28 | The multiplier as an SD49x28 number. |
Returns
Name | Type | Description |
---|---|---|
result | SD49x28 | The product as an SD49x28 number. |
xor
Implements the XOR (^) bitwise operation in the SD49x28 type.
function xor(SD49x28 x, SD49x28 y) pure returns (SD49x28 result);
div
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
Name | Type | Description |
---|---|---|
x | SD49x28 | The numerator as an SD49x28 number. |
y | SD49x28 | The denominator as an SD49x28 number. |
Constants
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
type UD50x28 is uint256;
UD50x28_IntoSD49x28_Overflow
error UD50x28_IntoSD49x28_Overflow(UD50x28 x);
mul
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
Name | Type | Description |
---|---|---|
x | UD50x28 | The multiplicand as a UD50x28 number. |
y | UD50x28 | The multiplier as a UD50x28 number. |
Returns
Name | Type | Description |
---|---|---|
result | UD50x28 | The product as a UD50x28 number. |
gt
Implements the greater than operation (>) in the UD50x28 type.
function gt(UD50x28 x, UD50x28 y) pure returns (bool result);
avg
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:
- AND x and y.
- Calculate half of XOR x and y.
- 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
Name | Type | Description |
---|---|---|
x | UD50x28 | The first operand as a UD50x28 number. |
y | UD50x28 | The second operand as a UD50x28 number. |
Returns
Name | Type | Description |
---|---|---|
result | UD50x28 | The arithmetic average as a UD50x28 number. |
intoUD60x18
function intoUD60x18(UD50x28 x) pure returns (UD60x18 result);
wrap
Wraps a uint256 number into the UD50x28 value type.
function wrap(uint256 x) pure returns (UD50x28 result);
and
Implements the AND (&) bitwise operation in the UD50x28 type.
function and(UD50x28 x, uint256 bits) pure returns (UD50x28 result);
lt
Implements the lower than operation (<) in the UD50x28 type.
function lt(UD50x28 x, UD50x28 y) pure returns (bool result);
neq
Implements the not equal operation (!=) in the UD50x28 type.
function neq(UD50x28 x, UD50x28 y) pure returns (bool result);
lshift
Implements the left shift operation (<<) in the UD50x28 type.
function lshift(UD50x28 x, uint256 bits) pure returns (UD50x28 result);
isZero
Implements a zero comparison check function in the UD50x28 type.
function isZero(UD50x28 x) pure returns (bool result);
uncheckedAdd
Implements the unchecked addition operation (+) in the UD50x28 type.
function uncheckedAdd(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
rshift
Implements the right shift operation (>>) in the UD50x28 type.
function rshift(UD50x28 x, uint256 bits) pure returns (UD50x28 result);
sub
Implements the checked subtraction operation (-) in the UD50x28 type.
function sub(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
xor
Implements the XOR (^) bitwise operation in the UD50x28 type.
function xor(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
eq
Implements the equal operation (==) in the UD50x28 type.
function eq(UD50x28 x, UD50x28 y) pure returns (bool result);
ud50x28
function ud50x28(uint256 x) pure returns (UD50x28 result);
and2
Implements the AND (&) bitwise operation in the UD50x28 type.
function and2(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
not
Implements the NOT (~) bitwise operation in the UD50x28 type.
function not(UD50x28 x) pure returns (UD50x28 result);
add
Implements the checked addition operation (+) in the UD50x28 type.
function add(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
mod
Implements the checked modulo operation (%) in the UD50x28 type.
function mod(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
div
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
Name | Type | Description |
---|---|---|
x | UD50x28 | The numerator as a UD50x28 number. |
y | UD50x28 | The denominator as a UD50x28 number. |
unwrap
Unwraps a UD50x28 number into uint256.
function unwrap(UD50x28 x) pure returns (uint256 result);
lte
Implements the lower than or equal to operation (<=) in the UD50x28 type.
function lte(UD50x28 x, UD50x28 y) pure returns (bool result);
intoSD49x28
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);
gte
Implements the greater than or equal to operation (>=) in the UD50x28 type.
function gte(UD50x28 x, UD50x28 y) pure returns (bool result);
or
Implements the OR (|) bitwise operation in the UD50x28 type.
function or(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
uncheckedSub
Implements the unchecked subtraction operation (-) in the UD50x28 type.
function uncheckedSub(UD50x28 x, UD50x28 y) pure returns (UD50x28 result);
Constants
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
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
Name | Type | Description |
---|---|---|
user | address | The 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
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
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
Name | Type | Description |
---|---|---|
<none> | address | implementation address |
getImplementation
get address of implementation contract
function getImplementation() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | implementation address |
DualMiningStorage
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
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
Name | Type | Description |
---|---|---|
user | address | The 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
- IOptionPSFactory
- OptionPS
- OptionPSFactory
- OptionPSFactoryStorage
- OptionPSProxy
- OptionPSStorage
IOptionPS
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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
longReceiver | address | the address that will receive the long tokens |
contractSize | UD60x18 | number 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | number 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
contractSize | UD60x18 | number of long tokens to exercise (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
totalExerciseCost | uint256 | the total amount of exerciseToken to pay, including fee (exerciseToken decimals) |
fee | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
contractSize | UD60x18 | number of long tokens to exercise (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | amount 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | amount 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | number of long tokens to settle (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
exerciseValue | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | number of short tokens to settle (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
collateralAmount | uint256 | the amount of collateral transferred to the caller (base for calls, quote for puts) |
exerciseTokenAmount | uint256 | the 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
Name | Type | Description |
---|---|---|
<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
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
Name | Type | Description |
---|---|---|
args | OptionPSArgs | The arguments used to deploy the proxy |
Returns
Name | Type | Description |
---|---|---|
proxy | address | The proxy address |
isDeployed | bool | Whether 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
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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
longReceiver | address | the address that will receive the long tokens |
contractSize | UD60x18 | number 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | number 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
contractSize | UD60x18 | number of long tokens to exercise (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
totalExerciseCost | uint256 | the total amount of exerciseToken to pay, including fee (exerciseToken decimals) |
fee | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
contractSize | UD60x18 | number of long tokens to exercise (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | amount 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | amount 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | number of long tokens to settle (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
exerciseValue | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
contractSize | UD60x18 | number of short tokens to settle (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
collateralAmount | uint256 | the amount of collateral transferred to the caller (base for calls, quote for puts) |
exerciseTokenAmount | uint256 | the 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
Name | Type | Description |
---|---|---|
<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
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
Name | Type | Description |
---|---|---|
args | OptionPSArgs | The arguments used to deploy the proxy |
Returns
Name | Type | Description |
---|---|---|
proxy | address | The proxy address |
isDeployed | bool | Whether the proxy is deployed |
deployProxy
Deploy a new proxy
function deployProxy(OptionPSArgs calldata args) external nonReentrant returns (address proxy);
OptionPSFactoryStorage
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
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
Name | Type | Description |
---|---|---|
<none> | address | implementation address |
receive
receive() external payable;
OptionPSStorage
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
- IOptionRewardFactory
- OptionReward
- OptionRewardFactory
- OptionRewardFactoryStorage
- OptionRewardProxy
- OptionRewardStorage
IOptionReward
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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
underwrite
Underwrite an option
function underwrite(address longReceiver, UD60x18 contractSize) external;
Parameters
Name | Type | Description |
---|---|---|
longReceiver | address | the address that will receive the long tokens |
contractSize | UD60x18 | number 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
Returns
Name | Type | Description |
---|---|---|
baseAmount | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the 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
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
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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
underwrite
Underwrite an option
function underwrite(address longReceiver, UD60x18 contractSize) external nonReentrant;
Parameters
Name | Type | Description |
---|---|---|
longReceiver | address | the address that will receive the long tokens |
contractSize | UD60x18 | number 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the option maturity timestamp |
Returns
Name | Type | Description |
---|---|---|
baseAmount | uint256 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the 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
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
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
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
Name | Type | Description |
---|---|---|
<none> | address | implementation address |
receive
receive() external payable;
OptionRewardStorage
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
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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the 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
Name | Type | Description |
---|---|---|
vaults | address[] | The vaults for which to trigger allocation of pending rewards |
amount | UD60x18 | The 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
Name | Type | Description |
---|---|---|
user | address | The user to update |
newUserShares | UD60x18 | The new amount of shares for the user |
newTotalShares | UD60x18 | The new amount of total shares for the vault |
utilisationRate | UD60x18 | DEPRECATED: 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
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
Name | Type | Description |
---|---|---|
strike | UD60x18 | the option strike price (18 decimals) |
maturity | uint64 | the 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
Name | Type | Description |
---|---|---|
vaults | address[] | The vaults for which to trigger allocation of pending rewards |
amount | UD60x18 | The 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
Name | Type | Description |
---|---|---|
user | address | The user to update |
newUserShares | UD60x18 | The new amount of shares for the user |
newTotalShares | UD60x18 | The 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
Name | Type | Description |
---|---|---|
user | address | The user to update |
vault | address |
_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
Inherits: ProxyUpgradeableOwnable
Functions
constructor
constructor(address implementation, UD60x18 rewardsPerYear) ProxyUpgradeableOwnable(implementation);
VaultMiningStorage
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
Functions
addRewards
Add rewards to the mining contract
function addRewards(uint256 amount) external;
IPaymentSplitter
Functions
pay
function pay(uint256 baseAmount, uint256 quoteAmount) external;
PaymentSplitter
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
Name | Type | Description |
---|---|---|
premiaAmount | uint256 | Amount of PREMIA to send back to mining contract |
usdcAmount | uint256 | Amount of USDC to send to vxPREMIA staking contract |
Contents
IVolatilityOracle
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
Name | Type | Description |
---|---|---|
params | int256[5] | Parameters of IV model to pack |
Returns
Name | Type | Description |
---|---|---|
result | bytes32 | The 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
Name | Type | Description |
---|---|---|
input | bytes32 | Packed IV model parameters to unpack |
Returns
Name | Type | Description |
---|---|---|
params | int256[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
Name | Type | Description |
---|---|---|
tokens | address[] | List of the base tokens |
tau | bytes32[] | List of maturities |
theta | bytes32[] | List of ATM total implied variance curves |
psi | bytes32[] | List of ATM skew curves |
rho | bytes32[] | List of rho curves |
riskFreeRate | UD60x18 | The risk-free rate |
getParams
Get the IV model parameters of a token pair
function getParams(address token) external view returns (VolatilityOracleStorage.Update memory);
Parameters
Name | Type | Description |
---|---|---|
token | address | The token address |
Returns
Name | Type | Description |
---|---|---|
<none> | VolatilityOracleStorage.Update | The IV model parameters |
getParamsUnpacked
Get unpacked IV model parameters
function getParamsUnpacked(address token) external view returns (VolatilityOracleStorage.Params memory);
Parameters
Name | Type | Description |
---|---|---|
token | address | The token address |
Returns
Name | Type | Description |
---|---|---|
<none> | VolatilityOracleStorage.Params | The 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
Name | Type | Description |
---|---|---|
token | address | The token address |
spot | UD60x18 | The spot price of the token |
strike | UD60x18 | The strike price of the option |
timeToMaturity | UD60x18 | The time until maturity (denominated in years) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
token | address | The token address |
spot | UD60x18 | The spot price of the token |
strike | UD60x18[] | The strike price of the option |
timeToMaturity | UD60x18[] | The time until maturity (denominated in years) |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
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
Name | Type | Description |
---|---|---|
params | int256[5] | Parameters of IV model to pack |
Returns
Name | Type | Description |
---|---|---|
result | bytes32 | The 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
Name | Type | Description |
---|---|---|
input | bytes32 | Packed IV model parameters to unpack |
Returns
Name | Type | Description |
---|---|---|
params | int256[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
Name | Type | Description |
---|---|---|
tokens | address[] | List of the base tokens |
tau | bytes32[] | List of maturities |
theta | bytes32[] | List of ATM total implied variance curves |
psi | bytes32[] | List of ATM skew curves |
rho | bytes32[] | List of rho curves |
riskFreeRate | UD60x18 | The risk-free rate |
getParams
Get the IV model parameters of a token pair
function getParams(address token) external view returns (VolatilityOracleStorage.Update memory);
Parameters
Name | Type | Description |
---|---|---|
token | address | The token address |
Returns
Name | Type | Description |
---|---|---|
<none> | VolatilityOracleStorage.Update | The IV model parameters |
getParamsUnpacked
Get unpacked IV model parameters
function getParamsUnpacked(address token) external view returns (VolatilityOracleStorage.Params memory);
Parameters
Name | Type | Description |
---|---|---|
token | address | The token address |
Returns
Name | Type | Description |
---|---|---|
<none> | VolatilityOracleStorage.Params | The 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
Name | Type | Description |
---|---|---|
arr | SD59x18[5] | The array of cutoff points that define the intervals |
value | SD59x18 | The value to find the interval for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
src | int256[5] | The array to be converted |
Returns
Name | Type | Description |
---|---|---|
tgt | SD59x18[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
Name | Type | Description |
---|---|---|
token | address | The token address |
spot | UD60x18 | The spot price of the token |
strike | UD60x18 | The strike price of the option |
timeToMaturity | UD60x18 | The time until maturity (denominated in years) |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
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
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
- IPoolBase
- IPoolCore
- IPoolDepositWithdraw
- IPoolEvents
- IPoolInternal
- IPoolTrade
- PoolBase
- PoolCore
- PoolDepositWithdraw
- PoolInternal
- PoolProxy
- PoolStorage
- PoolTrade
IPool
Inherits: IPoolBase, IPoolCore, IPoolDepositWithdraw, IPoolEvents, IPoolTrade
IPoolBase
Inherits: IERC1155Base, IERC1155Enumerable, IMulticall
Functions
name
get token collection name
function name() external view returns (string memory);
Returns
Name | Type | Description |
---|---|---|
<none> | string | collection name |
Errors
Pool__UseTransferPositionToTransferLPTokens
error Pool__UseTransferPositionToTransferLPTokens();
IPoolCore
Inherits: IPoolInternal
Functions
marketPrice
Get the current market price as normalized price
function marketPrice() external view returns (UD60x18);
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
taker | address | The taker of a trade |
size | UD60x18 | The size of a trade (number of contracts) (18 decimals) |
premium | uint256 | The total cost of option(s) for a purchase (poolToken decimals) |
isPremiumNormalized | bool | Whether 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) |
isOrderbook | bool | Whether the fee is for the fillQuoteOB function or not |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
taker | address | The taker of a trade |
size | UD60x18 | The size of a trade (number of contracts) (18 decimals) |
premium | UD60x18 | The total cost of option(s) for a purchase (18 decimals) |
isPremiumNormalized | bool | Whether 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) |
isOrderbook | bool | Whether the fee is for the fillQuoteOB function or not |
strike | UD60x18 | The strike of the option (18 decimals) |
isCallPool | bool | Whether the pool is a call pool or not |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
base | address | Address of base token |
quote | address | Address of quote token |
oracleAdapter | address | Address of oracle adapter |
strike | UD60x18 | The strike of the option (18 decimals) |
maturity | uint256 | The maturity timestamp of the option |
isCallPool | bool | Whether 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
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
underwriter | address | The underwriter of the option (Collateral will be taken from this address, and it will receive the short token) |
longReceiver | address | The address which will receive the long token |
size | UD60x18 | The number of contracts being underwritten (18 decimals) |
referrer | address | The 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
Name | Type | Description |
---|---|---|
size | UD60x18 | The 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
Name | Type | Description |
---|---|---|
owner | address | The owner of the shorts/longs to annihilate |
size | UD60x18 | The size to annihilate (18 decimals) |
exercise
Exercises all long options held by caller
function exercise() external returns (uint256 exerciseValue, uint256 exerciseFee);
Returns
Name | Type | Description |
---|---|---|
exerciseValue | uint256 | The exercise value as amount of collateral paid out to long holder (poolToken decimals) |
exerciseFee | uint256 | The 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
Name | Type | Description |
---|---|---|
holders | address[] | The holders of the contracts |
costPerHolder | uint256 | The cost charged by the authorized operator, per option holder (poolToken decimals) |
Returns
Name | Type | Description |
---|---|---|
exerciseValues | uint256[] | 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) |
exerciseFees | uint256[] | The fees paid to protocol (poolToken decimals) |
settle
Settles all short options held by caller
function settle() external returns (uint256 collateral);
Returns
Name | Type | Description |
---|---|---|
collateral | uint256 | The 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
Name | Type | Description |
---|---|---|
holders | address[] | The holders of the contracts |
costPerHolder | uint256 | The cost charged by the authorized operator, per option holder (poolToken decimals) |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
Returns
Name | Type | Description |
---|---|---|
collateral | uint256 | The 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
Name | Type | Description |
---|---|---|
p | Position.Key[] | The position keys |
costPerHolder | uint256 | The cost charged by the authorized operator, per position holder (poolToken decimals) |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
srcP | Position.Key | The position key |
newOwner | address | The new owner |
newOperator | address | The new operator |
size | UD60x18 | The 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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
lower | UD60x18 | Lower bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals) |
upper | UD60x18 | Upper 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
Name | Type | Description |
---|---|---|
<none> | uint256[] | tokenIds The list of existing tokenIds |
IPoolDepositWithdraw
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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
belowLower | UD60x18 | The 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) |
belowUpper | UD60x18 | The 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) |
size | UD60x18 | The position size to deposit (18 decimals) |
minMarketPrice | UD60x18 | Min market price, as normalized value. (If below, tx will revert) (18 decimals) |
maxMarketPrice | UD60x18 | Max market price, as normalized value. (If above, tx will revert) (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
belowLower | UD60x18 | The 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) |
belowUpper | UD60x18 | The 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) |
size | UD60x18 | The position size to deposit (18 decimals) |
minMarketPrice | UD60x18 | Min market price, as normalized value. (If below, tx will revert) (18 decimals) |
maxMarketPrice | UD60x18 | Max market price, as normalized value. (If above, tx will revert) (18 decimals) |
isBidIfStrandedMarketPrice | bool | Whether this is a bid or ask order when the market price is stranded (This argument doesnt matter if market price is not stranded) |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
size | UD60x18 | The position size to withdraw (18 decimals) |
minMarketPrice | UD60x18 | Min market price, as normalized value. (If below, tx will revert) (18 decimals) |
maxMarketPrice | UD60x18 | Max market price, as normalized value. (If above, tx will revert) (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
lower | UD60x18 | The lower bound of the range (18 decimals) |
upper | UD60x18 | The upper bound of the range (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
nearestBelowLower | UD60x18 | The nearest tick below lower (18 decimals) |
nearestBelowUpper | UD60x18 | The nearest tick below upper (18 decimals) |
IPoolEvents
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
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
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
Name | Type | Description |
---|---|---|
taker | address | The taker of the trade |
size | UD60x18 | The number of contracts being traded (18 decimals) |
isBuy | bool | Whether the taker is buying or selling |
Returns
Name | Type | Description |
---|---|---|
premiumNet | uint256 | The premium which has to be paid to complete the trade (Net of fees) (poolToken decimals) |
takerFee | uint256 | The 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
Name | Type | Description |
---|---|---|
quoteOB | QuoteOB | The OB quote given by the provider |
size | UD60x18 | The size to fill from the OB quote (18 decimals) |
signature | Signature | secp256k1 'r', 's', and 'v' value |
referrer | address | The referrer of the user filling the OB quote |
Returns
Name | Type | Description |
---|---|---|
premiumTaker | uint256 | The premium paid or received by the taker for the trade (poolToken decimals) |
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
size | UD60x18 | The number of contracts being traded (18 decimals) |
isBuy | bool | Whether the taker is buying or selling |
premiumLimit | uint256 | Tx will revert if total premium is above this value when buying, or below this value when selling. (poolToken decimals) |
referrer | address | The referrer of the user doing the trade |
Returns
Name | Type | Description |
---|---|---|
totalPremium | uint256 | The premium paid or received by the taker for the trade (poolToken decimals) |
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
hashes | bytes32[] | 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
Name | Type | Description |
---|---|---|
user | address | The address of the user that will call the fillQuoteOB function to fill the OB quote |
quoteOB | QuoteOB | The OB quote to check |
size | UD60x18 | Size to fill from the OB quote (18 decimals) |
sig | Signature | secp256k1 Signature |
getQuoteOBFilledAmount
Returns the size already filled for a given OB quote
function getQuoteOBFilledAmount(address provider, bytes32 quoteOBHash) external view returns (UD60x18);
Parameters
Name | Type | Description |
---|---|---|
provider | address | Provider of the OB quote |
quoteOBHash | bytes32 | Hash of the OB quote |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The size already filled (18 decimals) |
PoolBase
Inherits: IPoolBase, ERC1155Base, ERC1155Enumerable, ERC165Base, Multicall
Functions
name
get token collection name
function name() external view returns (string memory);
Returns
Name | Type | Description |
---|---|---|
<none> | string | collection 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
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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
taker | address | The taker of a trade |
size | UD60x18 | The size of a trade (number of contracts) (18 decimals) |
premium | uint256 | The total cost of option(s) for a purchase (poolToken decimals) |
isPremiumNormalized | bool | Whether 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) |
isOrderbook | bool | Whether the fee is for the fillQuoteOB function or not |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
taker | address | The taker of a trade |
size | UD60x18 | The size of a trade (number of contracts) (18 decimals) |
premium | UD60x18 | The total cost of option(s) for a purchase (18 decimals) |
isPremiumNormalized | bool | Whether 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) |
isOrderbook | bool | Whether the fee is for the fillQuoteOB function or not |
strike | UD60x18 | The strike of the option (18 decimals) |
isCallPool | bool | Whether the pool is a call pool or not |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
base | address | Address of base token |
quote | address | Address of quote token |
oracleAdapter | address | Address of oracle adapter |
strike | UD60x18 | The strike of the option (18 decimals) |
maturity | uint256 | The maturity timestamp of the option |
isCallPool | bool | Whether 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
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
underwriter | address | The underwriter of the option (Collateral will be taken from this address, and it will receive the short token) |
longReceiver | address | The address which will receive the long token |
size | UD60x18 | The number of contracts being underwritten (18 decimals) |
referrer | address | The 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
Name | Type | Description |
---|---|---|
size | UD60x18 | The 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
Name | Type | Description |
---|---|---|
account | address | |
size | UD60x18 | The size to annihilate (18 decimals) |
exercise
Exercises all long options held by caller
function exercise() external nonReentrant returns (uint256 exerciseValue, uint256 exerciseFee);
Returns
Name | Type | Description |
---|---|---|
exerciseValue | uint256 | The exercise value as amount of collateral paid out to long holder (poolToken decimals) |
exerciseFee | uint256 | The 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
Name | Type | Description |
---|---|---|
holders | address[] | The holders of the contracts |
costPerHolder | uint256 | The cost charged by the authorized operator, per option holder (poolToken decimals) |
Returns
Name | Type | Description |
---|---|---|
exerciseValues | uint256[] | 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) |
exerciseFees | uint256[] | The fees paid to protocol (poolToken decimals) |
settle
Settles all short options held by caller
function settle() external nonReentrant returns (uint256 collateral);
Returns
Name | Type | Description |
---|---|---|
collateral | uint256 | The 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
Name | Type | Description |
---|---|---|
holders | address[] | The holders of the contracts |
costPerHolder | uint256 | The cost charged by the authorized operator, per option holder (poolToken decimals) |
Returns
Name | Type | Description |
---|---|---|
collateral | 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 nonReentrant returns (uint256 collateral);
Parameters
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
Returns
Name | Type | Description |
---|---|---|
collateral | uint256 | The 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
Name | Type | Description |
---|---|---|
p | Position.Key[] | The position keys |
costPerHolder | uint256 | The cost charged by the authorized operator, per position holder (poolToken decimals) |
Returns
Name | Type | Description |
---|---|---|
collateral | 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
nonReentrant;
Parameters
Name | Type | Description |
---|---|---|
srcP | Position.Key | The position key |
newOwner | address | The new owner |
newOperator | address | The new operator |
size | UD60x18 | The 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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
lower | UD60x18 | Lower bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals) |
upper | UD60x18 | Upper 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
Name | Type | Description |
---|---|---|
<none> | uint256[] | tokenIds The list of existing tokenIds |
PoolDepositWithdraw
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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
belowLower | UD60x18 | The 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) |
belowUpper | UD60x18 | The 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) |
size | UD60x18 | The position size to deposit (18 decimals) |
minMarketPrice | UD60x18 | Min market price, as normalized value. (If below, tx will revert) (18 decimals) |
maxMarketPrice | UD60x18 | Max market price, as normalized value. (If above, tx will revert) (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
belowLower | UD60x18 | The 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) |
belowUpper | UD60x18 | The 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) |
size | UD60x18 | The position size to deposit (18 decimals) |
minMarketPrice | UD60x18 | Min market price, as normalized value. (If below, tx will revert) (18 decimals) |
maxMarketPrice | UD60x18 | Max market price, as normalized value. (If above, tx will revert) (18 decimals) |
isBidIfStrandedMarketPrice | bool |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
p | Position.Key | The position key |
size | UD60x18 | The position size to withdraw (18 decimals) |
minMarketPrice | UD60x18 | Min market price, as normalized value. (If below, tx will revert) (18 decimals) |
maxMarketPrice | UD60x18 | Max market price, as normalized value. (If above, tx will revert) (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
lower | UD60x18 | The lower bound of the range (18 decimals) |
upper | UD60x18 | The upper bound of the range (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
nearestBelowLower | UD60x18 | The nearest tick below lower (18 decimals) |
nearestBelowUpper | UD60x18 | The nearest tick below upper (18 decimals) |
PoolInternal
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
Name | Type | Description |
---|---|---|
taker | address | The taker of a trade |
size | UD60x18 | The size of a trade (number of contracts) (18 decimals) |
premium | UD60x18 | The total cost of option(s) for a purchase (18 decimals) |
isPremiumNormalized | bool | Whether 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) |
strike | UD60x18 | The strike of the option (18 decimals) |
isCallPool | bool | Whether the pool is a call pool or not |
isOrderbook | bool | Whether the fee is for the fillQuoteOB function or not |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
taker | address | The taker of a trade |
size | UD60x18 | The size of a trade (number of contracts) (18 decimals) |
intrinsicValue | UD60x18 | Total intrinsic value of all the contracts exercised, denormalized (18 decimals) |
strike | UD60x18 | The strike of the option (18 decimals) |
isCallPool | bool | Whether the pool is a call pool or not |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
taker | address | The taker of the trade |
size | UD60x18 | The number of contracts being traded (18 decimals) |
isBuy | bool | Whether the taker is buying or selling |
Returns
Name | Type | Description |
---|---|---|
totalNetPremium | uint256 | The premium which has to be paid to complete the trade (Net of fees) (poolToken decimals) |
totalTakerFee | uint256 | The 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
Name | Type | Description |
---|---|---|
p | Position.KeyInternal | The position to claim fees for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
p | Position.KeyInternal | The position key |
args | DepositArgsInternal | The deposit parameters |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
p | Position.KeyInternal | The position key |
args | DepositArgsInternal | The deposit parameters |
isBidIfStrandedMarketPrice | bool | Whether this is a bid or ask order when the market price is stranded (This argument doesnt matter if market price is not stranded) |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
p | Position.KeyInternal | The position key |
size | UD60x18 | The position size to withdraw (18 decimals) |
minMarketPrice | UD60x18 | Min market price, as normalized value. (If below, tx will revert) (18 decimals) |
maxMarketPrice | UD60x18 | Max market price, as normalized value. (If above, tx will revert) (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
args | TradeArgsInternal | Trade parameters |
Returns
Name | Type | Description |
---|---|---|
premiumWithFees | uint256 | The premium paid or received by the taker for the trade (poolToken decimals) |
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
args | FillQuoteOBArgsInternal | The fillQuoteOB parameters |
quoteOB | QuoteOB | The OB quote given by the provider |
Returns
Name | Type | Description |
---|---|---|
premiumTaker | uint256 | The premium paid by the taker (poolToken decimals) |
deltaTaker | Position.Delta | The 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
Name | Type | Description |
---|---|---|
srcP | Position.KeyInternal | The position key |
newOwner | address | The new owner of the transferred liquidity |
newOperator | address | The new operator of the transferred liquidity |
size | UD60x18 |
_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
Name | Type | Description |
---|---|---|
holder | address | The holder of the contracts |
costPerHolder | UD60x18 | The cost charged by the authorized operator, per option holder (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
exerciseValue | uint256 | The amount of collateral resulting from the exercise, ignoring costs applied during automatic exercise (poolToken decimals) |
exerciseFee | uint256 | The amount of fees paid to the protocol during exercise (18 decimals) |
success | bool | Whether 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
Name | Type | Description |
---|---|---|
holder | address | The holder of the contracts |
costPerHolder | UD60x18 | The cost charged by the authorized operator, per option holder (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
collateral | uint256 | The amount of collateral resulting from the settlement, ignoring costs applied during automatic settlement (poolToken decimals) |
success | bool | Whether 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
Name | Type | Description |
---|---|---|
p | Position.KeyInternal | The position key |
costPerHolder | UD60x18 | The cost charged by the authorized operator, per position holder (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
collateral | uint256 | The amount of collateral resulting from the settlement, ignoring costs applied during automatic settlement (poolToken decimals) |
success | bool | Whether 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
Name | Type | Description |
---|---|---|
price | UD60x18 | The price of the Tick (18 decimals) |
priceBelow | UD60x18 | The price of the nearest Tick below (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
<none> | Tick | tick 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
Name | Type | Description |
---|---|---|
isBuy | bool | Whether 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
Name | Type | Description |
---|---|---|
lower | UD60x18 | Lower bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals) |
upper | UD60x18 | Upper 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
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
Name | Type | Description |
---|---|---|
<none> | address | implementation address |
PoolStorage
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
Name | Type | Description |
---|---|---|
l | Layout | |
value | UD60x18 | The value that should be rounded down |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | Returns 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
Name | Type | Description |
---|---|---|
l | Layout | |
value | UD60x18 | The value that should be rounded down |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | Returns 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
Name | Type | Description |
---|---|---|
l | Layout | |
value | SD59x18 | The value that should be rounded down |
Returns
Name | Type | Description |
---|---|---|
<none> | SD59x18 | Returns 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
Name | Type | Description |
---|---|---|
l | Layout | |
value | UD60x18 | The value that should be rounded up |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | Returns 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
Name | Type | Description |
---|---|---|
l | Layout | |
value | UD60x18 | The value that should be rounded up |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | Returns 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
Name | Type | Description |
---|---|---|
operator | address | The current operator of the position |
lower | UD60x18 | The lower bound normalized option price (18 decimals) |
upper | UD60x18 | The upper bound normalized option price (18 decimals) |
orderType | Position.OrderType |
Returns
Name | Type | Description |
---|---|---|
tokenId | uint256 | token 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
Name | Type | Description |
---|---|---|
tokenId | uint256 | token id |
Returns
Name | Type | Description |
---|---|---|
version | uint8 | The version of LP token, used to know how to decode it, if upgrades are made |
operator | address | The current operator of the position |
lower | UD60x18 | The lower bound normalized option price (18 decimals) |
upper | UD60x18 | The upper bound normalized option price (18 decimals) |
orderType | Position.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
Name | Type | Description |
---|---|---|
token | IERC20 | IERC20 token that is intended to be sent. |
to | address | Recipient address of the tokens. |
value | uint256 | The 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
Name | Type | Description |
---|---|---|
token | IERC20 | IERC20 token that is intended to be sent. |
to | address | Recipient address of the tokens. |
value | UD60x18 | The 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
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
Name | Type | Description |
---|---|---|
taker | address | The taker of the trade |
size | UD60x18 | The number of contracts being traded (18 decimals) |
isBuy | bool | Whether the taker is buying or selling |
Returns
Name | Type | Description |
---|---|---|
premiumNet | uint256 | The premium which has to be paid to complete the trade (Net of fees) (poolToken decimals) |
takerFee | uint256 | The 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
Name | Type | Description |
---|---|---|
quoteOB | QuoteOB | The OB quote given by the provider |
size | UD60x18 | The size to fill from the OB quote (18 decimals) |
signature | Signature | secp256k1 'r', 's', and 'v' value |
referrer | address | The referrer of the user filling the OB quote |
Returns
Name | Type | Description |
---|---|---|
premiumTaker | uint256 | The premium paid or received by the taker for the trade (poolToken decimals) |
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
size | UD60x18 | The number of contracts being traded (18 decimals) |
isBuy | bool | Whether the taker is buying or selling |
premiumLimit | uint256 | Tx will revert if total premium is above this value when buying, or below this value when selling. (poolToken decimals) |
referrer | address | The referrer of the user doing the trade |
Returns
Name | Type | Description |
---|---|---|
totalPremium | uint256 | The premium paid or received by the taker for the trade (poolToken decimals) |
delta | Position.Delta | The 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
Name | Type | Description |
---|---|---|
hashes | bytes32[] | 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
Name | Type | Description |
---|---|---|
user | address | The address of the user that will call the fillQuoteOB function to fill the OB quote |
quoteOB | QuoteOB | The OB quote to check |
size | UD60x18 | Size to fill from the OB quote (18 decimals) |
sig | Signature | secp256k1 Signature |
getQuoteOBFilledAmount
Returns the size already filled for a given OB quote
function getQuoteOBFilledAmount(address provider, bytes32 quoteOBHash) external view returns (UD60x18);
Parameters
Name | Type | Description |
---|---|---|
provider | address | Provider of the OB quote |
quoteOBHash | bytes32 | Hash of the OB quote |
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The size already filled (18 decimals) |
maxFlashLoan
The amount of currency available to be lent.
function maxFlashLoan(address token) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
token | address | The loan currency. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
token | address | The loan currency. |
amount | uint256 | The amount of tokens lent. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
receiver | IERC3156FlashBorrower | The receiver of the tokens in the loan, and the receiver of the callback. |
token | address | The loan currency. |
amount | uint256 | The amount of tokens lent. |
data | bytes | Arbitrary 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
- IProxyUpgradeableOwnable
- Premia
- ProxyManager
- ProxyManagerStorage
- ProxyUpgradeableOwnable
- ProxyUpgradeableOwnableStorage
IProxyManager
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
Functions
getImplementation
Return the implementation address of the proxy
function getImplementation() external view returns (address);
Premia
Inherits: SolidStateDiamond
based on the EIP2535 Diamond standard
ProxyManager
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
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
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
Name | Type | Description |
---|---|---|
<none> | address | implementation 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
Name | Type | Description |
---|---|---|
implementation | address | address 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
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
Functions
getReferrer
Returns the address of the referrer for a given user
function getReferrer(address user) external view returns (address referrer);
Parameters
Name | Type | Description |
---|---|---|
user | address | The address of the user |
Returns
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
getRebateTier
Returns the rebate tier for a given referrer
function getRebateTier(address referrer) external view returns (RebateTier tier);
Parameters
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
Returns
Name | Type | Description |
---|---|---|
tier | RebateTier | The rebate tier |
getRebatePercents
Returns the primary and secondary rebate percents
function getRebatePercents()
external
view
returns (UD60x18[] memory primaryRebatePercents, UD60x18 secondaryRebatePercent);
Returns
Name | Type | Description |
---|---|---|
primaryRebatePercents | UD60x18[] | The primary rebate percents (18 decimals) |
secondaryRebatePercent | UD60x18 | The 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
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
Returns
Name | Type | Description |
---|---|---|
primaryRebatePercent | UD60x18 | The primary rebate percent (18 decimals) |
secondaryRebatePercent | UD60x18 | The 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
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
Returns
Name | Type | Description |
---|---|---|
tokens | address[] | The tokens for which the referrer has rebates |
rebates | uint256[] | 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
Name | Type | Description |
---|---|---|
user | address | The address of the user |
referrer | address | The address of the referrer |
tradingFee | UD60x18 | The trading fee (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
primaryRebate | UD60x18 | The primary rebate amount (18 decimals) |
secondaryRebate | UD60x18 | The 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
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
tier | RebateTier | The rebate tier |
setPrimaryRebatePercent
Sets the primary rebate percents - caller must be owner
function setPrimaryRebatePercent(UD60x18 percent, RebateTier tier) external;
Parameters
Name | Type | Description |
---|---|---|
percent | UD60x18 | The primary rebate percent (18 decimals) |
tier | RebateTier | The rebate tier |
setSecondaryRebatePercent
Sets the secondary rebate percent - caller must be owner
function setSecondaryRebatePercent(UD60x18 percent) external;
Parameters
Name | Type | Description |
---|---|---|
percent | UD60x18 | The 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
Name | Type | Description |
---|---|---|
user | address | The address of the user |
referrer | address | The address of the primary referrer |
token | address | The address of the token |
primaryRebate | UD60x18 | The primary rebate amount (18 decimals) |
secondaryRebate | UD60x18 | The secondary rebate amount (18 decimals) |
claimRebate
Claims the rebates for the msg.sender
function claimRebate(address[] memory tokens) external;
Parameters
Name | Type | Description |
---|---|---|
tokens | address[] | 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
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
Name | Type | Description |
---|---|---|
user | address | The address of the user |
Returns
Name | Type | Description |
---|---|---|
<none> | address | referrer The address of the referrer |
getRebateTier
Returns the rebate tier for a given referrer
function getRebateTier(address referrer) public view returns (RebateTier);
Parameters
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
Returns
Name | Type | Description |
---|---|---|
<none> | RebateTier | tier The rebate tier |
getRebatePercents
Returns the primary and secondary rebate percents
function getRebatePercents()
external
view
returns (UD60x18[] memory primaryRebatePercents, UD60x18 secondaryRebatePercent);
Returns
Name | Type | Description |
---|---|---|
primaryRebatePercents | UD60x18[] | The primary rebate percents (18 decimals) |
secondaryRebatePercent | UD60x18 | The 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
Name | Type | Description |
---|---|---|
primaryRebatePercents | UD60x18 | The primary rebate percents (18 decimals) |
secondaryRebatePercent | UD60x18 | The 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
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
user | address | The address of the user |
referrer | address | The address of the referrer |
tradingFee | UD60x18 | The trading fee (18 decimals) |
Returns
Name | Type | Description |
---|---|---|
primaryRebate | UD60x18 | The primary rebate amount (18 decimals) |
secondaryRebate | UD60x18 | The 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
Name | Type | Description |
---|---|---|
referrer | address | The address of the referrer |
tier | RebateTier | The rebate tier |
setPrimaryRebatePercent
Sets the primary rebate percents - caller must be owner
function setPrimaryRebatePercent(UD60x18 percent, RebateTier tier) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
percent | UD60x18 | The primary rebate percent (18 decimals) |
tier | RebateTier | The rebate tier |
setSecondaryRebatePercent
Sets the secondary rebate percent - caller must be owner
function setSecondaryRebatePercent(UD60x18 percent) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
percent | UD60x18 | The 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
Name | Type | Description |
---|---|---|
user | address | The address of the user |
referrer | address | The address of the primary referrer |
token | address | The address of the token |
primaryRebate | UD60x18 | The primary rebate amount (18 decimals) |
secondaryRebate | UD60x18 | The secondary rebate amount (18 decimals) |
claimRebate
Claims the rebates for the msg.sender
function claimRebate(address[] memory tokens) external nonReentrant;
Parameters
Name | Type | Description |
---|---|---|
tokens | address[] | 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
Inherits: ProxyUpgradeableOwnable
Functions
constructor
constructor(address implementation) ProxyUpgradeableOwnable(implementation);
ReferralStorage
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
Functions
addWhitelistedRelayers
Add relayers to the whitelist so that they can add price updates
function addWhitelistedRelayers(address[] calldata relayers) external;
Parameters
Name | Type | Description |
---|---|---|
relayers | address[] | 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
Name | Type | Description |
---|---|---|
relayers | address[] | The addresses to remove from the whitelist |
getWhitelistedRelayers
Get the list of whitelisted relayers
function getWhitelistedRelayers() external view returns (address[] memory relayers);
Returns
Name | Type | Description |
---|---|---|
relayers | address[] | 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
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
Name | Type | Description |
---|---|---|
relayers | address[] | 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
Name | Type | Description |
---|---|---|
relayers | address[] | The addresses to remove from the whitelist |
getWhitelistedRelayers
Get the list of whitelisted relayers
function getWhitelistedRelayers() external view virtual returns (address[] memory relayers);
Returns
Name | Type | Description |
---|---|---|
relayers | address[] | The list of whitelisted relayers |
_revertIfNotWhitelistedRelayer
Revert if relayer
is not whitelisted
function _revertIfNotWhitelistedRelayer(address relayer) internal view;
RelayerAccessManagerStorage
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
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
Name | Type | Description |
---|---|---|
token | address | Address of token to transfer |
from | address | Address to transfer tokens from |
to | address | Address to transfer tokens to |
amount | uint256 | Amount of tokens to transfer |
IERC20Router
Functions
safeTransferFrom
Transfers tokens - caller must be an authorized pool
function safeTransferFrom(address token, address from, address to, uint256 amount) external;
Parameters
Name | Type | Description |
---|---|---|
token | address | Address of token to transfer |
from | address | Address to transfer tokens from |
to | address | Address to transfer tokens to |
amount | uint256 | Amount of tokens to transfer |
Errors
ERC20Router__NotAuthorized
error ERC20Router__NotAuthorized();
Contents
IUserSettings
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
Name | Type | Description |
---|---|---|
user | address | The user who grants authorization |
operator | address | The operator who is granted authorization |
action | Action | The action operator is authorized to perform |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
user | address | The user who grants authorization |
operator | address | The operator who is granted authorization |
Returns
Name | Type | Description |
---|---|---|
actions | Action[] | All available actions a user may grant authorization to operator for |
authorization | bool[] | 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
Name | Type | Description |
---|---|---|
operator | address | The operator who is granted authorization |
actions | Action[] | The actions to modify authorization state for |
authorization | bool[] | 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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
amount | UD60x18 | The 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
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
Name | Type | Description |
---|---|---|
user | address | The user who grants authorization |
operator | address | The operator who is granted authorization |
action | Action | The action operator is authorized to perform |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
user | address | The user who grants authorization |
operator | address | The operator who is granted authorization |
Returns
Name | Type | Description |
---|---|---|
actions | Action[] | All available actions a user may grant authorization to operator for |
authorization | bool[] | 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
Name | Type | Description |
---|---|---|
operator | address | The operator who is granted authorization |
actions | Action[] | The actions to modify authorization state for |
authorization | bool[] | 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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
amount | UD60x18 | The users authorized cost in the ERC20 Native token (WETH, WFTM, etc) (18 decimals) |
UserSettingsStorage
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
- FeeConverterStorage
- IFeeConverter
- IPoolV2ProxyManager
- IPremiaStaking
- IVxPremia
- PremiaStaking
- PremiaStakingStorage
- VxPremia
- VxPremiaProxy
- VxPremiaStorage
FeeConverter
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
Name | Type | Description |
---|---|---|
exchangeHelper | address | exchange helper address |
getTreasury
get the treasury address and treasuryShare
function getTreasury() external view returns (address treasury, UD60x18 treasuryShare);
Returns
Name | Type | Description |
---|---|---|
treasury | address | treasury address |
treasuryShare | UD60x18 | treasury 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
Name | Type | Description |
---|---|---|
account | address | The account for which to set new authorization status |
isAuthorized | bool | Whether 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
Name | Type | Description |
---|---|---|
sourceToken | address | address of token to convert |
callee | address | exchange address to call to execute the trade. |
allowanceTarget | address | address for which to set allowance for the trade |
data | bytes | calldata 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
Name | Type | Description |
---|---|---|
vault | address | address of the ERC4626 vault to redeem from |
shareAmount | uint256 | quantity of shares to redeem |
Returns
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity of assets received |
FeeConverterStorage
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
Functions
getExchangeHelper
get the exchange helper address
function getExchangeHelper() external view returns (address exchangeHelper);
Returns
Name | Type | Description |
---|---|---|
exchangeHelper | address | exchange helper address |
getTreasury
get the treasury address and treasuryShare
function getTreasury() external view returns (address treasury, UD60x18 treasuryShare);
Returns
Name | Type | Description |
---|---|---|
treasury | address | treasury address |
treasuryShare | UD60x18 | treasury 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
Name | Type | Description |
---|---|---|
sourceToken | address | address of token to convert |
callee | address | exchange address to call to execute the trade. |
allowanceTarget | address | address for which to set allowance for the trade |
data | bytes | calldata to execute the trade |
redeem
Redeem shares from an ERC4626 vault
function redeem(address vault, uint256 shareAmount) external returns (uint256 assetAmount);
Parameters
Name | Type | Description |
---|---|---|
vault | address | address of the ERC4626 vault to redeem from |
shareAmount | uint256 | quantity of shares to redeem |
Returns
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity 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
Functions
getPoolList
function getPoolList() external view returns (address[] memory);
IPremiaStaking
Inherits: IERC2612, IOFT
Functions
getRewardToken
Returns the reward token address
function getRewardToken() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | The reward token address |
addRewards
add premia tokens as available tokens to be distributed as rewards
function addRewards(uint256 amount) external;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | amount 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
Name | Type | Description |
---|---|---|
rewards | uint256 | amount of tokens not yet distributed as rewards |
unstakeRewards | uint256 | amount 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
Name | Type | Description |
---|---|---|
<none> | uint256 | amount 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
Name | Type | Description |
---|---|---|
amount | uint256 | pending withdrawal amount |
startDate | uint256 | start timestamp of withdrawal |
unlockDate | uint256 | timestamp at which withdrawal becomes available |
getAvailablePremiaAmount
get the amount of PREMIA available for withdrawal
function getAvailablePremiaAmount() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | amount 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of xPremia to stake |
period | uint64 | The lockup period (in seconds) |
deadline | uint256 | Deadline after which permit will fail |
v | uint8 | V |
r | bytes32 | R |
s | bytes32 | S |
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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of xPremia to stake |
period | uint64 | The lockup period (in seconds) |
updateLock
update vxPremia lock
function updateLock(uint64 period) external;
Parameters
Name | Type | Description |
---|---|---|
period | uint64 | The 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
Name | Type | Description |
---|---|---|
s | IPremiaStaking.SwapArgs | swap arguments |
stakePeriod | uint64 | The 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
Name | Type | Description |
---|---|---|
user | address | User for which to calculate pending rewards |
Returns
Name | Type | Description |
---|---|---|
reward | uint256 | amount of pending rewards from protocol fees (in REWARD_TOKEN) |
unstakeReward | uint256 | amount 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
Name | Type | Description |
---|---|---|
amount | uint256 | the amount of vxPremia to unstake |
getEarlyUnstakeFee
get early unstake fee for given user
function getEarlyUnstakeFee(address user) external view returns (uint256 feePercentage);
Parameters
Name | Type | Description |
---|---|---|
user | address | address of the user |
Returns
Name | Type | Description |
---|---|---|
feePercentage | uint256 | % 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
Name | Type | Description |
---|---|---|
amount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
user | address | The user from which to query the stake amount |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
user | address | The _user for which the discount is for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | Percentage of protocol fee discount Ex : 1e17 = 10% fee discount |
getStakeLevels
Get stake levels
function getStakeLevels() external pure returns (StakeLevel[] memory);
Returns
Name | Type | Description |
---|---|---|
<none> | StakeLevel[] | Stake levels Ex : 25e16 = -25% |
getStakePeriodMultiplier
Get stake period multiplier
function getStakePeriodMultiplier(uint256 period) external pure returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
period | uint256 | The duration (in seconds) for which tokens are locked |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
user | address | The user address for which to get staking infos |
Returns
Name | Type | Description |
---|---|---|
<none> | PremiaStakingStorage.UserInfo | The 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
Inherits: IPremiaStaking
Functions
getPoolVotes
get total votes for specific pools
function getPoolVotes(VoteVersion version, bytes calldata target) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
version | VoteVersion | version of target (used to know how to decode data) |
target | bytes | ABI encoded target of the votes |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | total votes for specific pool |
getUserVotes
get votes of user
function getUserVotes(address user) external view returns (VxPremiaStorage.Vote[] memory);
Parameters
Name | Type | Description |
---|---|---|
user | address | user from which to get votes |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
votes | VxPremiaStorage.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
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
Name | Type | Description |
---|---|---|
<none> | address | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | amount 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
Name | Type | Description |
---|---|---|
rewards | uint256 | amount of tokens not yet distributed as rewards |
unstakeRewards | uint256 | amount 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
Name | Type | Description |
---|---|---|
<none> | uint256 | amount 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of xPremia to stake |
period | uint64 | The lockup period (in seconds) |
deadline | uint256 | Deadline after which permit will fail |
v | uint8 | V |
r | bytes32 | R |
s | bytes32 | S |
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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of xPremia to stake |
period | uint64 | The lockup period (in seconds) |
updateLock
update vxPremia lock
function updateLock(uint64 period) external nonReentrant;
Parameters
Name | Type | Description |
---|---|---|
period | uint64 | The 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
Name | Type | Description |
---|---|---|
s | IPremiaStaking.SwapArgs | swap arguments |
stakePeriod | uint64 | The 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
Name | Type | Description |
---|---|---|
user | address | User for which to calculate pending rewards |
Returns
Name | Type | Description |
---|---|---|
reward | uint256 | amount of pending rewards from protocol fees (in REWARD_TOKEN) |
unstakeReward | uint256 | amount 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
Name | Type | Description |
---|---|---|
amount | uint256 | the amount of vxPremia to unstake |
getEarlyUnstakeFee
get early unstake fee for given user
function getEarlyUnstakeFee(address user) public view returns (uint256 feePercentage);
Parameters
Name | Type | Description |
---|---|---|
user | address | address of the user |
Returns
Name | Type | Description |
---|---|---|
feePercentage | uint256 | % 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
Name | Type | Description |
---|---|---|
amount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
user | address | The user from which to query the stake amount |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
user | address | The _user for which the discount is for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | Percentage 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
Name | Type | Description |
---|---|---|
user | address | The user address for which to get staking infos |
Returns
Name | Type | Description |
---|---|---|
<none> | PremiaStakingStorage.UserInfo | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | pending withdrawal amount |
startDate | uint256 | start timestamp of withdrawal |
unlockDate | uint256 | timestamp 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
Name | Type | Description |
---|---|---|
stakeLevels | IPremiaStaking.StakeLevel[] | Stake levels Ex : 25e16 = -25% |
getStakePeriodMultiplier
Get stake period multiplier
function getStakePeriodMultiplier(uint256 period) public pure returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
period | uint256 | The duration (in seconds) for which tokens are locked |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | amount of PREMIA available for withdrawal |
Structs
UpdateArgsInternal
struct UpdateArgsInternal {
address user;
uint256 balance;
uint256 oldPower;
uint256 newPower;
uint256 reward;
uint256 unstakeReward;
}
PremiaStakingStorage
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
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
Name | Type | Description |
---|---|---|
version | VoteVersion | version of target (used to know how to decode data) |
target | bytes | ABI encoded target of the votes |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | total votes for specific pool |
getUserVotes
get votes of user
function getUserVotes(address user) external view returns (VxPremiaStorage.Vote[] memory);
Parameters
Name | Type | Description |
---|---|---|
user | address | user from which to get votes |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
votes | VxPremiaStorage.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
Inherits: ProxyUpgradeableOwnable, ERC20MetadataInternal
Functions
constructor
constructor(address implementation) ProxyUpgradeableOwnable(implementation);
VxPremiaStorage
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
- IExchangeHelper
- IPremiaAirdrip
- IRewardDistributor
- Placeholder
- PremiaAirdrip
- PremiaAirdripStorage
- RewardDistributor
ExchangeHelper
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
Name | Type | Description |
---|---|---|
sourceToken | address | source token to pull into this address |
targetToken | address | target token to buy |
sourceTokenAmount | uint256 | amount of source token to start the trade |
callee | address | exchange address to call to execute the trade. |
allowanceTarget | address | address for which to set allowance for the trade |
data | bytes | calldata to execute the trade |
refundAddress | address | address that un-used source token goes to |
Returns
Name | Type | Description |
---|---|---|
amountOut | uint256 | quantity of targetToken yielded by swap |
sourceLeft | uint256 | quantity of sourceToken left and refunded to refundAddress |
IExchangeHelper
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
Name | Type | Description |
---|---|---|
sourceToken | address | source token to pull into this address |
targetToken | address | target token to buy |
sourceTokenAmount | uint256 | amount of source token to start the trade |
callee | address | exchange address to call to execute the trade. |
allowanceTarget | address | address for which to set allowance for the trade |
data | bytes | calldata to execute the trade |
refundAddress | address | address that un-used source token goes to |
Returns
Name | Type | Description |
---|---|---|
amountOut | uint256 | quantity of targetToken yielded by swap |
sourceLeft | uint256 | quantity of sourceToken left and refunded to refundAddress |
IPremiaAirdrip
Functions
initialize
Initializes the airdrip contract by pulling $PREMIA tokens from msg.sender and setting state variables
function initialize(User[] memory users, bool initialized) external;
Parameters
Name | Type | Description |
---|---|---|
users | User[] | The users that will receive the premia tokens |
initialized | bool | Whether the contract initialization is complete |
claim
Claims the premia tokens for the user.
function claim() external;
previewTotalAllocationAmount
Returns the total allocation amount (throughout entire vesting period)
function previewTotalAllocationAmount(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total allocation amount |
previewClaimableAmount
Returns the amount claimable since the last claim was made (or the vesting start)
function previewClaimableAmount(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The claimable amount |
previewClaimRemaining
Returns the remaining amount claimable (throughout entire vesting period)
function previewClaimRemaining(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The remaining claimable amount |
previewClaimedAmount
Returns the amount claimed
function previewClaimedAmount(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The claimed amount |
Events
Initialized
event Initialized(bool initialized, UD60x18 premiaPerInfluence, UD60x18 totalInfluence);
Claimed
event Claimed(address indexed user, uint256 amount, uint256 totalClaimed, uint256 totalRemaining);
Errors
PremiaAirdrip__ArrayEmpty
error PremiaAirdrip__ArrayEmpty();
PremiaAirdrip__Initialized
error PremiaAirdrip__Initialized();
PremiaAirdrip__InvalidUser
error PremiaAirdrip__InvalidUser(address user, UD60x18 influence);
PremiaAirdrip__NotClaimable
error PremiaAirdrip__NotClaimable(uint256 lastClaim, uint256 blockTimestamp);
PremiaAirdrip__NotInitialized
error PremiaAirdrip__NotInitialized();
PremiaAirdrip__NotVested
error PremiaAirdrip__NotVested(uint256 vestingStart, uint256 blockTimestamp);
PremiaAirdrip__UserAlreadyExists
error PremiaAirdrip__UserAlreadyExists(address user);
PremiaAirdrip__ZeroAmountClaimable
error PremiaAirdrip__ZeroAmountClaimable();
Structs
User
struct User {
address addr;
UD60x18 influence;
}
IRewardDistributor
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
Placeholder contract that can be used to deploy a proxy without initial implementation
Functions
placeholder
function placeholder() external;
PremiaAirdrip
Inherits: IPremiaAirdrip, OwnableInternal, ReentrancyGuard
State Variables
PREMIA
premia token interface
IERC20 public constant PREMIA = IERC20(0x51fC0f6660482Ea73330E414eFd7808811a57Fa2);
TOTAL_ALLOCATION
total allocation of premia distributed over the vesting period
UD60x18 public constant TOTAL_ALLOCATION = UD60x18.wrap(2_000_000e18);
VESTING_DURATION
duration of time premia is distributed
uint256 public constant VESTING_DURATION = 365 days;
VESTING_START
uint256 public constant VESTING_START = 1723708800;
Functions
initialize
Initializes the airdrip contract by pulling $PREMIA tokens from msg.sender and setting state variables
function initialize(User[] memory users, bool initialized) external nonReentrant onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
users | User[] | The users that will receive the premia tokens |
initialized | bool | Whether the contract initialization is complete |
claim
Claims the premia tokens for the user.
function claim() external nonReentrant;
_calculateClaimAmount
function _calculateClaimAmount(PremiaAirdripStorage.Layout storage l, address user, uint256 lastClaim)
internal
view
returns (uint256);
previewTotalAllocationAmount
Returns the total allocation amount (throughout entire vesting period)
function previewTotalAllocationAmount(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total allocation amount |
previewClaimableAmount
Returns the amount claimable since the last claim was made (or the vesting start)
function previewClaimableAmount(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The claimable amount |
previewClaimRemaining
Returns the remaining amount claimable (throughout entire vesting period)
function previewClaimRemaining(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The remaining claimable amount |
previewClaimedAmount
Returns the amount claimed
function previewClaimedAmount(address user) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The claimed amount |
_previewTotalAllocationAmount
function _previewTotalAllocationAmount(PremiaAirdripStorage.Layout storage l, address user)
internal
view
returns (UD60x18);
_previewClaimRemaining
function _previewClaimRemaining(PremiaAirdripStorage.Layout storage l, address user) internal view returns (uint256);
PremiaAirdripStorage
State Variables
STORAGE_SLOT
bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PremiaAirdrip");
Functions
layout
function layout() internal pure returns (Layout storage l);
Structs
Layout
struct Layout {
bool initialized;
UD60x18 premiaPerInfluence;
UD60x18 totalInfluence;
mapping(address user => UD60x18 influence) influence;
mapping(address user => uint256 claimed) claimed;
mapping(address user => uint256 lastClaim) lastClaim;
}
RewardDistributor
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
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
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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The utilisation rate of the vault |
updateSettings
Updates the vault settings
function updateSettings(bytes memory settings) external;
Parameters
Name | Type | Description |
---|---|---|
settings | bytes | Encoding 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
Name | Type | Description |
---|---|---|
<none> | uint256 | total managed asset amount |
_getSpotPrice
Gets the spot price at the current time
function _getSpotPrice() internal view virtual returns (UD60x18);
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
vars | LockedSpreadInternal | The 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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity of assets to convert |
Returns
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity of shares to convert |
Returns
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
caller | address | |
receiver | address | recipient of shares resulting from deposit |
assetAmount | uint256 | quantity of assets to deposit |
shareAmount | uint256 | |
assetAmountOffset | uint256 | |
shareAmountOffset | uint256 |
_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
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity of assets to deposit |
receiver | address | recipient of shares resulting from deposit |
Returns
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity of shares to mint |
Returns
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity of shares to mint |
receiver | address | recipient of shares resulting from deposit |
Returns
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
owner | address | holder of shares to be redeemed |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | maxShares 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
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity of shares to redeem |
receiver | address | recipient of assets resulting from withdrawal |
owner | address | holder of shares to be redeemed |
Returns
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
owner | address | holder of shares to be redeemed |
Returns
Name | Type | Description |
---|---|---|
withdrawableAssets | uint256 | maxAssets 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
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity of assets to withdraw |
Returns
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
assetAmount | uint256 | quantity of assets to withdraw |
receiver | address | recipient of assets resulting from withdrawal |
owner | address | holder of shares to be redeemed |
Returns
Name | Type | Description |
---|---|---|
shareAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
receiver | address | recipient of shares resulting from deposit |
assetAmount | uint256 | quantity of assets being deposited |
shareAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
owner | address | holder of shares to be redeemed |
assetAmount | uint256 | quantity of assets being withdrawn |
shareAmount | uint256 | quantity 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
Name | Type | Description |
---|---|---|
l | UnderwriterVaultStorage.Layout | |
isBuy | bool | Whether this is a buy or a sell |
strike | UD60x18 | The strike price of the option. |
maturity | uint256 | The maturity of the option. |
size | UD60x18 | The amount of contracts. |
spread | UD60x18 | The spread added on to the premium due to C-level |
premium | UD60x18 | The 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
Name | Type | Description |
---|---|---|
l | UnderwriterVaultStorage.Layout | |
strike | UD60x18 | The strike price for the pool |
maturity | uint256 | The maturity for the pool |
Returns
Name | Type | Description |
---|---|---|
<none> | address | The 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
Name | Type | Description |
---|---|---|
totalAssets | UD60x18 | the total assets post settlement |
totalLockedAssets | UD60x18 | the 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);
_truncateTradeSize
Truncates the trade size (18 decimals) by the number of significant digits in the strike price
function _truncateTradeSize(UD60x18 size, UD60x18 strike) internal pure returns (UD60x18);
getQuote
Returns the trade quote premium
function getQuote(IPoolFactory.PoolKey calldata poolKey, UD60x18 size, bool isBuy, address taker)
external
view
returns (uint256 premium);
Parameters
Name | Type | Description |
---|---|---|
poolKey | IPoolFactory.PoolKey | The option pool key |
size | UD60x18 | The size of the trade |
isBuy | bool | Whether the trade is a buy or sell |
taker | address | The address of the taker |
Returns
Name | Type | Description |
---|---|---|
premium | uint256 | The 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
Name | Type | Description |
---|---|---|
poolKey | IPoolFactory.PoolKey | The option pool key |
size | UD60x18 | The size of the trade |
isBuy | bool | Whether the trade is a buy or sell |
premiumLimit | uint256 | The premium limit of the trade |
referrer | address | The address of the referrer |
_settleMaturity
Settles all options that are on a single maturity
function _settleMaturity(UnderwriterVaultStorage.Layout storage l, uint256 maturity) internal;
Parameters
Name | Type | Description |
---|---|---|
l | UnderwriterVaultStorage.Layout | |
maturity | uint256 | The 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
Name | Type | Description |
---|---|---|
l | UnderwriterVaultStorage.Layout | Contains stored parameters of the vault, including the managementFeeRate and the lastManagementFeeTimestamp |
timestamp | uint256 | The block's current timestamp. |
Returns
Name | Type | Description |
---|---|---|
managementFeeInShares | UD60x18 | Returns 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
Name | Type | Description |
---|---|---|
size | UD60x18 | The amount of contracts |
_revertIfZeroShares
Ensures that a share amount is non zero.
function _revertIfZeroShares(uint256 shares) internal pure;
Parameters
Name | Type | Description |
---|---|---|
shares | uint256 | The amount of shares |
_revertIfZeroAsset
Ensures that an asset amount is non zero.
function _revertIfZeroAsset(uint256 amount) internal pure;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of assets |
_revertIfAddressZero
Ensures that an address is non zero.
function _revertIfAddressZero(address addr) internal pure;
Parameters
Name | Type | Description |
---|---|---|
addr | address | The address to check |
_revertIfMaximumAmountExceeded
Ensures that an amount is not above maximum
function _revertIfMaximumAmountExceeded(UD60x18 maximum, UD60x18 amount) internal pure;
Parameters
Name | Type | Description |
---|---|---|
maximum | UD60x18 | The maximum amount |
amount | UD60x18 | The amount to check |
_revertIfNotTradeableWithVault
Ensures that an option is tradeable with the vault.
function _revertIfNotTradeableWithVault(bool isCallVault, bool isCallOption) internal pure;
Parameters
Name | Type | Description |
---|---|---|
isCallVault | bool | Whether the vault is a call or put vault. |
isCallOption | bool | Whether 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | The strike price of the option. |
maturity | uint256 | The 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
Name | Type | Description |
---|---|---|
strike | UD60x18 | The strike price. |
size | UD60x18 | The amount of contracts. |
availableAssets | UD60x18 | The 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
Name | Type | Description |
---|---|---|
value | UD60x18 | The observed value of the variable. |
minimum | UD60x18 | The minimum value the variable can be. |
maximum | UD60x18 | The 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
Name | Type | Description |
---|---|---|
value | UD60x18 | The observed value of the variable. |
minimum | UD60x18 | The minimum value the variable can be. |
maximum | UD60x18 | The 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
Name | Type | Description |
---|---|---|
totalPremium | UD60x18 | The total premium of the trade |
premiumLimit | UD60x18 | The premium limit of the trade |
isBuy | bool | Whether 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
Name | Type | Description |
---|---|---|
l | UnderwriterVaultStorage.Layout | |
maturity | uint256 | The maturity. |
strike | UD60x18 | The strike price. |
size | UD60x18 | The amount of contracts. |
_revertIfSellIsDisabled
Ensures that the vault can't buy-to-close unless it is enabled.
function _revertIfSellIsDisabled(bool enableSell) internal pure;
Parameters
Name | Type | Description |
---|---|---|
enableSell | bool | Whether sell is enabled or not. |
UnderwriterVaultProxy
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
Name | Type | Description |
---|---|---|
<none> | address | implementation address |
getImplementation
get address of implementation contract
function getImplementation() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | implementation address |
UnderwriterVaultStorage
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
Name | Type | Description |
---|---|---|
l | Layout | |
timestamp | uint256 | The given timestamp |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
l | Layout | |
timestamp | uint256 | The given timestamp |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
l | Layout | |
strike | UD60x18 | The strike price of the listing |
maturity | uint256 | The maturity of the listing |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | If 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
Name | Type | Description |
---|---|---|
l | Layout | |
strike | UD60x18 | The strike price of the listing |
maturity | uint256 | The maturity of the listing |
removeListing
Removes a listing from internal data structures
function removeListing(Layout storage l, UD60x18 strike, uint256 maturity) internal;
Parameters
Name | Type | Description |
---|---|---|
l | Layout | |
strike | UD60x18 | The strike price of the listing |
maturity | uint256 | The 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
Inherits: ISolidStateERC4626
Functions
updateSettings
Updates the vault settings
function updateSettings(bytes memory settings) external;
Parameters
Name | Type | Description |
---|---|---|
settings | bytes | Encoding 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
Name | Type | Description |
---|---|---|
poolKey | IPoolFactory.PoolKey | The option pool key |
size | UD60x18 | The size of the trade |
isBuy | bool | Whether the trade is a buy or sell |
taker | address | The address of the taker |
Returns
Name | Type | Description |
---|---|---|
premium | uint256 | The 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
Name | Type | Description |
---|---|---|
poolKey | IPoolFactory.PoolKey | The option pool key |
size | UD60x18 | The size of the trade |
isBuy | bool | Whether the trade is a buy or sell |
premiumLimit | uint256 | The premium limit of the trade |
referrer | address | The address of the referrer |
getUtilisation
Returns the utilisation rate of the vault
function getUtilisation() external view returns (UD60x18);
Returns
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The 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
Functions
getNumberOfVaults
Gets the total number of vaults in the registry.
function getNumberOfVaults() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
asset | address | The address for the token deposited in the vault. |
vaultType | bytes32 | The type of the vault. |
side | TradeSide | The trade side of the vault. |
optionType | OptionType | The option type of the vault. |
removeVault
Removes a vault from the registry.
function removeVault(address vault) external;
Parameters
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
isVault
Returns whether the given address is a vault
function isVault(address vault) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
vault | address | The address to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
asset | address | The address for the token deposited in the vault. |
vaultType | bytes32 | The type of the vault. |
side | TradeSide | The trade side of the vault. |
optionType | OptionType | The 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
tokenPairs | TokenPair[] | 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
tokenPairsToRemove | TokenPair[] | 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
Returns
Name | Type | Description |
---|---|---|
<none> | Vault | The 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
assets | address[] | The accepted assets (empty list for all assets). |
side | TradeSide | The trade side. |
optionType | OptionType | The option type. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
asset | address | The desired asset. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
tokenPair | TokenPair | The desired token pair. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
side | TradeSide | The trade side. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
optionType | OptionType | The option type. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
vaultType | bytes32 | The vault type. |
Returns
Name | Type | Description |
---|---|---|
<none> | Vault[] | All the vaults of type vaultType . |
getImplementation
Gets the implementation for the vaultType.
function getImplementation(bytes32 vaultType) external view returns (address);
Parameters
Name | Type | Description |
---|---|---|
vaultType | bytes32 | The vault type. |
Returns
Name | Type | Description |
---|---|---|
<none> | address | The implementation address. |
setImplementation
Sets the implementation for the vaultType.
function setImplementation(bytes32 vaultType, address implementation) external;
Parameters
Name | Type | Description |
---|---|---|
vaultType | bytes32 | The vault type. |
implementation | address | The 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
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
Name | Type | Description |
---|---|---|
<none> | UD60x18 | The utilisation rate of the vault |
VaultRegistry
Inherits: IVaultRegistry, OwnableInternal
Functions
getNumberOfVaults
Gets the total number of vaults in the registry.
function getNumberOfVaults() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
asset | address | The address for the token deposited in the vault. |
vaultType | bytes32 | The type of the vault. |
side | TradeSide | The trade side of the vault. |
optionType | OptionType | The option type of the vault. |
removeVault
Removes a vault from the registry.
function removeVault(address vault) public onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
isVault
Returns whether the given address is a vault
function isVault(address vault) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
vault | address | The address to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
asset | address | The address for the token deposited in the vault. |
vaultType | bytes32 | The type of the vault. |
side | TradeSide | The trade side of the vault. |
optionType | OptionType | The 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
tokenPairs | TokenPair[] | 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
tokenPairsToRemove | TokenPair[] | 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
Returns
Name | Type | Description |
---|---|---|
<none> | Vault | The 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
Name | Type | Description |
---|---|---|
vault | address | The proxy address of the vault. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
assets | address[] | The accepted assets (empty list for all assets). |
side | TradeSide | The trade side. |
optionType | OptionType | The option type. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
asset | address | The desired asset. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
tokenPair | TokenPair | The desired token pair. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
side | TradeSide | The trade side. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
optionType | OptionType | The option type. |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
vaultType | bytes32 | The vault type. |
Returns
Name | Type | Description |
---|---|---|
<none> | Vault[] | All the vaults of type vaultType . |
getImplementation
Gets the implementation for the vaultType.
function getImplementation(bytes32 vaultType) external view returns (address);
Parameters
Name | Type | Description |
---|---|---|
vaultType | bytes32 | The vault type. |
Returns
Name | Type | Description |
---|---|---|
<none> | address | The implementation address. |
setImplementation
Sets the implementation for the vaultType.
function setImplementation(bytes32 vaultType, address implementation) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
vaultType | bytes32 | The vault type. |
implementation | address | The implementation contract address |
VaultRegistryStorage
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
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);