LiquidityPool.sol
The Liquidity Pool holds most core functionality for the Rysk Dynamic Hedging Vault, it is responsible for managing all funds. It uses several libraries and contracts which have been explained in other docs.
Throughout the contract there are conversions between decimals, there are three decimals to be aware of e6 (USDC decimals) or collateral decimals, e8 otoken decimals and e18 share value, eth, and options calculation decimals. Where each decimal type is used is commented in each function.
The contract uses Chainlink Price feed oracles. The contract also makes use of the Portfolio values feed request response oracle and may in the future make use of a volatility feed oracle. These are documented in the oracle documentation.
Most variables and functions if not mentioned here can be fully explained by their natspec in the contracts so have been left out
This variable is an array that stores hedging reactor addresses. Each hedging reactor can be referenced by its index in
rebalancePortfolioDelta
or each hedging reactor is referenced by iterating over the array, for example in completeWithdraw() or getPortfolioDelta()
. When a hedging reactor is added it is added to the last place of the array, when removed the array should be shifted so as not to leave any array elements as zero addresses.There is pause and unpause functionality which pauses all state changing functionality. There is also pause and unpause trading which pauses any options buying or selling activity from the pool. This pause functionality can be executed by Guardians or above.
This is a struct that contains variables that pertain to the min and max call strike which are the minimum and maximum strikes that can be written for calls by the pool and the min and max put strikes. The min and max expiry are also stored which are the minimum and maximum length options that the pool can write. These variables can be updated by management or above and helps with managing pool exposure depending on the market outlook.
These values are used to set the time and price thresholds for when an oracle update becomes stale. For example, if an oracle update was done at 600 and the threshold is 10 if the time is now 611 the oracle update is stale and the pool will not do anything until the oracle is updated again. This is to deal with the value of the pool changing due to price and time movement and thus the liability value and delta value being off.
These are contracts that have the authority to issue, write, and buyback options from the liquidityPool. They must be authorised. This architecture allows for multiple handlers and upgradeability on the handlers.
An explainer of the mutual fund system or how deposits/withdraws/redeems/pauseTradingAndRequest and executeEpochCalculation work can be seen here: Deposit and Withdraw Mechanism
This function uses hedging reactors to hedge off a specified delta. The manager (or above) will specify the delta to hedge and the index of the reactor in the hedgingReactors array. The hedging reactor can be anything that implements the IHedgingReactor interface, it is used for accessing alternate derivatives that can be used for delta hedging. Currently only spot and perps are implemented but any derivative or asset can be implemented in the future.
This function is used by the option registry to update the collateralAllocated in the LiquidityPool when funds are moved around. If the option registry is moving funds back into the LiquidityPool then it will decrease collateralAllocated. If the option registry is moving funds from the LiquidityPool then it will get a safe approval and will increase the collateralAllocated. Collateral allocated should never drop below negative because the balance of option registry should not go up beyond what it is allocated (because it generates no profits from providing collateral)(it can only go down, say if an option gets exercised).
This function is used to settle a vault and move collateral between the registry and the vault when an option expires.
This function is used to get the portfolio delta. This first retrieves the delta from the portfolio value feed oracle (making sure it isnt stale), it then gets the delta from all hedging reactors finally it gets the ephemeralDelta that has been recorded between a request and response.
Reference for implementation:
Reference for implementation:
Contract used as the Dynamic Hedging Vault for storing funds, issuing shares and processing options transactions
Interacts with the OptionRegistry for options behaviour, Interacts with hedging reactors for alternative derivatives Interacts with Handlers for periphary user options interactions. Interacts with Chainlink price feeds throughout. Interacts with Volatility Feed via getImpliedVolatility(), interacts with a chainlink PortfolioValues external adaptor oracle via PortfolioValuesFeed.
immutable variables ///
contract Protocol protocol
address strikeAsset
address underlyingAsset
address collateralAsset
uint256 collateralAllocated
dynamic variables ///
int256 ephemeralLiabilities
int256 ephemeralDelta
uint256 depositEpoch
uint256 withdrawalEpoch
mapping(uint256 => uint256) depositEpochPricePerShare
mapping(uint256 => uint256) withdrawalEpochPricePerShare
mapping(address => struct IAccounting.DepositReceipt) depositReceipts
mapping(address => struct IAccounting.WithdrawalReceipt) withdrawalReceipts
uint256 pendingDeposits
uint256 pendingWithdrawals
uint256 partitionedFunds
uint256 bufferPercentage
governance settable variables ///
address[] hedgingReactors
uint256 collateralCap
uint256 maxDiscount
uint256 bidAskIVSpread
struct Types.OptionParams optionParams
uint256 riskFreeRate
mapping(address => bool) handler
bool isTradingPaused
uint256 maxTimeDeviationThreshold
uint256 maxPriceDeviationThreshold
uint256 belowThresholdGradient
uint256 aboveThresholdGradient
uint256 aboveThresholdYIntercept
uint256 utilizationFunctionThreshold
mapping(address => bool) keeper
uint256 MAX_BPS
constant variables ///
event DepositEpochExecuted(uint256 epoch)
structs && events ///
event WithdrawalEpochExecuted(uint256 epoch)
event Withdraw(address recipient, uint256 amount, uint256 shares)
event Deposit(address recipient, uint256 amount, uint256 epoch)
event Redeem(address recipient, uint256 amount, uint256 epoch)
event InitiateWithdraw(address recipient, uint256 amount, uint256 epoch)
event WriteOption(address series, uint256 amount, uint256 premium, uint256 escrow, address buyer)
event SettleVault(address series, uint256 collateralReturned, uint256 collateralLost, address closer)
event BuybackOption(address series, uint256 amount, uint256 premium, uint256 escrowReturned, address seller)
constructor(address _protocol, address _strikeAsset, address _underlyingAsset, address _collateralAsset, uint256 rfr, string name, string symbol, struct Types.OptionParams _optionParams, address _authority) public
function pause() external
setters ///
function pauseUnpauseTrading(bool _pause) external
function unpause() external
function setHedgingReactorAddress(address _reactorAddress) external
set a new hedging reactor
only governance can call this function
Name | Type | Description |
---|---|---|
_reactorAddress | address | append a new hedging reactor |
function removeHedgingReactorAddress(uint256 _index, bool _override) external
remove a new hedging reactor by index
only governance can call this function
Name | Type | Description |
---|---|---|
_index | uint256 | remove a hedging reactor |
_override | bool | whether to override whether the reactor is wound down (THE REACTOR SHOULD BE WOUND DOWN SEPERATELY) |
function setNewOptionParams(uint128 _newMinCallStrike, uint128 _newMaxCallStrike, uint128 _newMinPutStrike, uint128 _newMaxPutStrike, uint128 _newMinExpiry, uint128 _newMaxExpiry) external
update all optionParam variables for max and min strikes and max and min expiries for options that the DHV can issue
only management or above can call this function
function setBidAskSpread(uint256 _bidAskSpread) external
set the bid ask spread used to price option buying
only management or above can call this function
Name | Type | Description |
---|---|---|
_bidAskSpread | uint256 | the bid ask spread to update to |
function setMaxDiscount(uint256 _maxDiscount) external
set the maximum percentage discount for an option
only management or above can call this function
Name | Type | Description |
---|---|---|
_maxDiscount | uint256 | of the option as a percentage in 1e18 format. ie: 1*e18 == 1% |
function setCollateralCap(uint256 _collateralCap) external
set the maximum collateral amount allowed in the pool
only governance can call this function
Name | Type | Description |
---|---|---|
_collateralCap | uint256 | of the collateral held |
function setBufferPercentage(uint256 _bufferPercentage) external
update the liquidity pool buffer limit
only governance can call this function
Name | Type | Description |
---|---|---|
_bufferPercentage | uint256 | the minimum balance the liquidity pool must have as a percentage of collateral allocated to options. (for 20% enter 2000) |
function setRiskFreeRate(uint256 _riskFreeRate) external
update the liquidity pool risk free rate
Name | Type | Description |
---|---|---|
_riskFreeRate | uint256 | the risk free rate of the market |
function setMaxTimeDeviationThreshold(uint256 _maxTimeDeviationThreshold) external
update the max oracle time deviation threshold
function setMaxPriceDeviationThreshold(uint256 _maxPriceDeviationThreshold) external
update the max oracle price deviation threshold
function changeHandler(address _handler, bool auth) external
change the status of a handler
function setKeeper(address _keeper, bool _auth) external
change the status of a keeper
function setUtilizationSkewParams(uint256 _belowThresholdGradient, uint256 _aboveThresholdGradient, uint256 _utilizationFunctionThreshold) external
@notice sets the parameters for the function that determines the utilization price factor The function is made up of two parts, both linear. The line to the left of the utilisation threshold has a low gradient while the gradient to the right of the threshold is much steeper. The aim of this function is to make options much more expensive near full utilization while not having much effect at low utilizations. @param _belowThresholdGradient the gradient of the function where utiization is below function threshold. e18 @param _aboveThresholdGradient the gradient of the line above the utilization threshold. e18 @param _utilizationFunctionThreshold the percentage utilization above which the function moves from its shallow line to its steep line
function rebalancePortfolioDelta(int256 delta, uint256 reactorIndex) external
function for hedging portfolio delta through external means
Name | Type | Description |
---|---|---|
delta | int256 | the current portfolio delta |
reactorIndex | uint256 | the index of the reactor in the hedgingReactors array to use |
function adjustCollateral(uint256 lpCollateralDifference, bool addToLpBalance) external
adjust the collateral held in a specific vault because of health
called by the option registry only
Name | Type | Description |
---|---|---|
lpCollateralDifference | uint256 | amount of collateral taken from or given to the liquidity pool in collateral decimals |
addToLpBalance | bool | true if collateral is returned to liquidity pool, false if collateral is withdrawn from liquidity pool |
function settleVault(address seriesAddress) external returns (uint256)
closes an oToken vault, returning collateral (minus ITM option expiry value) back to the pool
Name | Type | Description |
---|---|---|
seriesAddress | address | the address of the oToken vault to close |
Name | Type | Description |
---|---|---|
[0] | uint256 | collatReturned the amount of collateral returned to the liquidity pool, assumes in collateral decimals |
function handlerIssue(struct Types.OptionSeries optionSeries) external returns (address)
issue an option
only callable by a handler contract
Name | Type | Description |
---|---|---|
optionSeries | struct Types.OptionSeries | the series detail of the option - strike decimals in e18 |
function handlerWriteOption(struct Types.OptionSeries optionSeries, address seriesAddress, uint256 amount, contract IOptionRegistry optionRegistry, uint256 premium, int256 delta, address recipient) external returns (uint256)
write an option that already exists
only callable by a handler contract
Name | Type | Description |
---|---|---|
optionSeries | struct Types.OptionSeries | the series detail of the option - strike decimals in e8 |
seriesAddress | address | the series address of the oToken |
amount | uint256 | the number of options to write - in e18 |
optionRegistry | contract IOptionRegistry | the registry used for options writing |
premium | uint256 | the premium of the option - in collateral decimals |
delta | int256 | the delta of the option - in e18 |
recipient | address | the receiver of the option |
function handlerIssueAndWriteOption(struct Types.OptionSeries optionSeries, uint256 amount, uint256 premium, int256 delta, address recipient) external returns (uint256, address)
write an option that doesnt exist
only callable by a handler contract
Name | Type | Description |
---|---|---|
optionSeries | struct Types.OptionSeries | the series detail of the option - strike decimals in e18 |
amount | uint256 | the number of options to write - in e18 |
premium | uint256 | the premium of the option - in collateral decimals |
delta | int256 | the delta of the option - in e18 |
recipient | address | the receiver of the option |
function handlerBuybackOption(struct Types.OptionSeries optionSeries, uint256 amount, contract IOptionRegistry optionRegistry, address seriesAddress, uint256 premium, int256 delta, address seller) external returns (uint256)
buy back an option that already exists
only callable by a handler contract
Name | Type | Description |
---|---|---|
optionSeries | struct Types.OptionSeries | the series detail of the option - strike decimals in e8 |
amount | uint256 | the number of options to buyback - in e18 |
optionRegistry | contract IOptionRegistry | the registry used for options writing |
seriesAddress | address | the series address of the oToken |
premium | uint256 | the premium of the option - in collateral decimals |
delta | int256 | the delta of the option - in e18 |
seller | address | the receiver of the option |
function resetEphemeralValues() external
reset the temporary portfolio and delta values that have been changed since the last oracle update
only callable by the portfolio values feed oracle contract
function pauseTradingAndRequest() external returns (bytes32)
reset the temporary portfolio and delta values that have been changed since the last oracle update
this function must be called in order to execute an epoch calculation
function executeEpochCalculation() external
execute the epoch and set all the price per shares
this function must be called in order to execute an epoch calculation and batch a mutual fund epoch
function deposit(uint256 _amount) external returns (bool)
function for adding liquidity to the options liquidity pool
entry point to provide liquidity to dynamic hedging vault
Name | Type | Description |
---|---|---|
_amount | uint256 | amount of the strike asset to deposit |
Name | Type | Description |
---|---|---|
[0] | bool | success |
function redeem(uint256 _shares) external returns (uint256)
function for allowing a user to redeem their shares from a previous epoch
Name | Type | Description |
---|---|---|
_shares | uint256 | the number of shares to redeem |
Name | Type | Description |
---|---|---|
[0] | uint256 | the number of shares actually returned |
function initiateWithdraw(uint256 _shares) external
function for initiating a withdraw request from the pool
entry point to remove liquidity to dynamic hedging vault
Name | Type | Description |
---|---|---|
_shares | uint256 | amount of shares to return |
function completeWithdraw(uint256 _shares) external returns (uint256)
function for completing the withdraw from a pool
entry point to remove liquidity to dynamic hedging vault
Name | Type | Description |
---|---|---|
_shares | uint256 | amount of shares to return |
function _getNormalizedBalance(address asset) internal view returns (uint256 normalizedBalance)
Returning balance in 1e18 format
Name | Type | Description |
---|---|---|
asset | address | address of the asset to get balance and normalize |
Name | Type | Description |
---|---|---|
normalizedBalance | uint256 | balance in 1e18 format |
function getBalance(address asset) public view returns (uint256)
Returning balance in 1e6 format
Name | Type | Description |
---|---|---|
asset | address | address of the asset to get balance |
Name | Type | Description |
---|---|---|
[0] | uint256 | balance of the address accounting for partitionedFunds |
function getExternalDelta() public view returns (int256 externalDelta)
get the delta of the hedging reactors
Name | Type | Description |
---|---|---|
externalDelta | int256 | hedging reactor delta in e18 format |
function getPortfolioDelta() public view returns (int256)
get the delta of the portfolio
Name | Type | Description |
---|---|---|
[0] | int256 | portfolio delta |
function quotePriceWithUtilizationGreeks(struct Types.OptionSeries optionSeries, uint256 amount, bool toBuy) external view returns (uint256 quote, int256 delta)
get the quote price and delta for a given option
Name | Type | Description |
---|---|---|
optionSeries | struct Types.OptionSeries | option type to quote - strike assumed in e18 |
amount | uint256 | the number of options to mint - assumed in e18 |
toBuy | bool | whether the protocol is buying the option |
Name | Type | Description |
---|---|---|
quote | uint256 | the price of the options - returns in e18 |
delta | int256 | the delta of the options - returns in e18 |
function addUtilizationPremium(struct Types.UtilizationState quoteState, struct Types.OptionSeries optionSeries, uint256 amount, bool toBuy) internal view
applies a utilization premium when the protocol is selling options. Stores the utilization price in quoteState.utilizationPrice for use in quotePriceWithUtilizationGreeks
Name | Type | Description |
---|---|---|
quoteState | struct Types.UtilizationState | the struct created in quoteStateWithUtilizationGreeks to store memory variables |
optionSeries | struct Types.OptionSeries | the option type for which we are quoting a price |
amount |