Contract Overview
My Name Tag:
Not Available
TokenTracker:
[ Download CSV Export ]
Latest 25 internal transaction
[ Download CSV Export ]
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Name:
LiquidityPool
Compiler Version
v0.8.9+commit.e5eed63a
Optimization Enabled:
Yes with 200 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./Protocol.sol"; import "./PriceFeed.sol"; import "./VolatilityFeed.sol"; import "./tokens/ERC20.sol"; import "./utils/ReentrancyGuard.sol"; import "./libraries/BlackScholes.sol"; import "./libraries/CustomErrors.sol"; import "./libraries/AccessControl.sol"; import "./libraries/OptionsCompute.sol"; import "./libraries/SafeTransferLib.sol"; import "./interfaces/IAccounting.sol"; import "./interfaces/IOptionRegistry.sol"; import "./interfaces/IHedgingReactor.sol"; import "./interfaces/IPortfolioValuesFeed.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /** * @title Contract used as the Dynamic Hedging Vault for storing funds, issuing shares and processing options transactions * @dev 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. */ contract LiquidityPool is ERC20, AccessControl, ReentrancyGuard, Pausable { using PRBMathSD59x18 for int256; using PRBMathUD60x18 for uint256; /////////////////////////// /// immutable variables /// /////////////////////////// // Protocol management contract Protocol public immutable protocol; // asset that denominates the strike price address public immutable strikeAsset; // asset that is used as the reference asset address public immutable underlyingAsset; // asset that is used for collateral asset address public immutable collateralAsset; ///////////////////////// /// dynamic variables /// ///////////////////////// // amount of collateralAsset allocated as collateral uint256 public collateralAllocated; // ephemeral liabilities of the pool int256 public ephemeralLiabilities; // ephemeral delta of the pool int256 public ephemeralDelta; // epoch of the price per share round for deposits uint256 public depositEpoch; // epoch of the price per share round for withdrawals uint256 public withdrawalEpoch; // epoch PPS for deposits mapping(uint256 => uint256) public depositEpochPricePerShare; // epoch PPS for withdrawals mapping(uint256 => uint256) public withdrawalEpochPricePerShare; // deposit receipts for users mapping(address => IAccounting.DepositReceipt) public depositReceipts; // withdrawal receipts for users mapping(address => IAccounting.WithdrawalReceipt) public withdrawalReceipts; // pending deposits for a round - collateral denominated (collateral decimals) uint256 public pendingDeposits; // pending withdrawals for a round - DHV token e18 denominated uint256 public pendingWithdrawals; // withdrawal amount that has been executed and is pending completion. These funds are to be excluded from all book balances. uint256 public partitionedFunds; ///////////////////////////////////// /// governance settable variables /// ///////////////////////////////////// // buffer of funds to not be used to write new options in case of margin requirements (as percentage - for 20% enter 2000) uint256 public bufferPercentage = 5000; // list of addresses for hedging reactors address[] public hedgingReactors; // max total supply of collateral, denominated in e18 uint256 public collateralCap = type(uint256).max; // Maximum discount that an option tilting factor can discount an option price uint256 public maxDiscount = (PRBMathUD60x18.SCALE * 10) / 100; // As a percentage. Init at 10% // The spread between the bid and ask on the IV skew; // Consider making this it's own volatility skew if more flexibility is needed uint256 public bidAskIVSpread; // option issuance parameters Types.OptionParams public optionParams; // riskFreeRate as a percentage PRBMath Float. IE: 3% -> 0.03 * 10**18 uint256 public riskFreeRate; // handlers who are approved to interact with options functionality mapping(address => bool) public handler; // is the purchase and sale of options paused bool public isTradingPaused; // max time to allow between oracle updates for an underlying and strike uint256 public maxTimeDeviationThreshold = 600; // max price difference to allow between oracle updates for an underlying and strike uint256 public maxPriceDeviationThreshold = 1e18; // variables relating to the utilization skew function: // the gradient of the function where utiization is below function threshold. e18 uint256 public belowThresholdGradient = 0; // 0 // the gradient of the line above the utilization threshold. e18 uint256 public aboveThresholdGradient = 1e18; // 1 // the y-intercept of the line above the threshold. Needed to make the two lines meet at the threshold. Will always be negative but enter the absolute value uint256 public aboveThresholdYIntercept = 6e17; //-0.6 // the percentage utilization above which the function moves from its shallow line to its steep line. e18 uint256 public utilizationFunctionThreshold = 6e17; // 60% // keeper mapping mapping(address => bool) public keeper; ////////////////////////// /// constant variables /// ////////////////////////// // BIPS uint256 private constant MAX_BPS = 10_000; ///////////////////////// /// structs && events /// ///////////////////////// event DepositEpochExecuted(uint256 epoch); 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 RebalancePortfolioDelta(int256 deltaChange); event TradingPaused(); event TradingUnpaused(); 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 memory name, string memory symbol, Types.OptionParams memory _optionParams, address _authority ) ERC20(name, symbol, 18) AccessControl(IAuthority(_authority)) { if (ERC20(_collateralAsset).decimals() > 18) { revert CustomErrors.InvalidDecimals(); } strikeAsset = _strikeAsset; riskFreeRate = rfr; underlyingAsset = _underlyingAsset; collateralAsset = _collateralAsset; protocol = Protocol(_protocol); optionParams = _optionParams; depositEpochPricePerShare[0] = 1e18; withdrawalEpochPricePerShare[0] = 1e18; depositEpoch++; withdrawalEpoch++; } /////////////// /// setters /// /////////////// function pause() external { _onlyGuardian(); _pause(); } function pauseUnpauseTrading(bool _pause) external { _onlyGuardian(); isTradingPaused = _pause; if (_pause) { emit TradingPaused(); } else { emit TradingUnpaused(); } } function unpause() external { _onlyGuardian(); _unpause(); } /** * @notice set a new hedging reactor * @param _reactorAddress append a new hedging reactor * @dev only governance can call this function */ function setHedgingReactorAddress(address _reactorAddress) external { _onlyGovernor(); if (_reactorAddress == address(0)) { revert CustomErrors.InvalidAddress(); } uint256 arrayLength = hedgingReactors.length; for (uint256 i = 0; i < arrayLength; i++) { if (hedgingReactors[i] == _reactorAddress) { revert CustomErrors.ReactorAlreadyExists(); } } hedgingReactors.push(_reactorAddress); SafeTransferLib.safeApprove(ERC20(collateralAsset), _reactorAddress, type(uint256).max); } /** * @notice remove a new hedging reactor by index * @param _index remove a hedging reactor * @param _override whether to override whether the reactor is wound down (THE REACTOR SHOULD BE WOUND DOWN SEPERATELY) * @dev only governance can call this function */ function removeHedgingReactorAddress(uint256 _index, bool _override) external { _onlyGovernor(); address[] memory hedgingReactors_ = hedgingReactors; address reactorAddress = hedgingReactors_[_index]; if (!_override) { IHedgingReactor reactor = IHedgingReactor(reactorAddress); int256 delta = reactor.getDelta(); if (delta != 0) { reactor.hedgeDelta(delta); } reactor.withdraw(type(uint256).max); } SafeTransferLib.safeApprove(ERC20(collateralAsset), reactorAddress, 0); uint256 maxIndex = hedgingReactors_.length - 1; for (uint256 i = _index; i < maxIndex; i++) { hedgingReactors[i] = hedgingReactors_[i + 1]; } hedgingReactors.pop(); } function getHedgingReactors() external view returns (address[] memory) { return hedgingReactors; } /** * @notice update all optionParam variables for max and min strikes and max and * min expiries for options that the DHV can issue * @dev only management or above can call this function */ function setNewOptionParams( uint128 _newMinCallStrike, uint128 _newMaxCallStrike, uint128 _newMinPutStrike, uint128 _newMaxPutStrike, uint128 _newMinExpiry, uint128 _newMaxExpiry ) external { _onlyManager(); optionParams.minCallStrikePrice = _newMinCallStrike; optionParams.maxCallStrikePrice = _newMaxCallStrike; optionParams.minPutStrikePrice = _newMinPutStrike; optionParams.maxPutStrikePrice = _newMaxPutStrike; optionParams.minExpiry = _newMinExpiry; optionParams.maxExpiry = _newMaxExpiry; } /** * @notice set the bid ask spread used to price option buying * @param _bidAskSpread the bid ask spread to update to * @dev only management or above can call this function */ function setBidAskSpread(uint256 _bidAskSpread) external { _onlyManager(); bidAskIVSpread = _bidAskSpread; } /** * @notice set the maximum percentage discount for an option * @param _maxDiscount of the option as a percentage in 1e18 format. ie: 1*e18 == 1% * @dev only management or above can call this function */ function setMaxDiscount(uint256 _maxDiscount) external { _onlyManager(); maxDiscount = _maxDiscount; } /** * @notice set the maximum collateral amount allowed in the pool * @param _collateralCap of the collateral held * @dev only governance can call this function */ function setCollateralCap(uint256 _collateralCap) external { _onlyGovernor(); collateralCap = _collateralCap; } /** * @notice update the liquidity pool buffer limit * @param _bufferPercentage the minimum balance the liquidity pool must have as a percentage of collateral allocated to options. (for 20% enter 2000) * @dev only governance can call this function */ function setBufferPercentage(uint256 _bufferPercentage) external { _onlyGovernor(); bufferPercentage = _bufferPercentage; } /** * @notice update the liquidity pool risk free rate * @param _riskFreeRate the risk free rate of the market */ function setRiskFreeRate(uint256 _riskFreeRate) external { _onlyGovernor(); riskFreeRate = _riskFreeRate; } /** * @notice update the max oracle time deviation threshold */ function setMaxTimeDeviationThreshold(uint256 _maxTimeDeviationThreshold) external { _onlyGovernor(); maxTimeDeviationThreshold = _maxTimeDeviationThreshold; } /** * @notice update the max oracle price deviation threshold */ function setMaxPriceDeviationThreshold(uint256 _maxPriceDeviationThreshold) external { _onlyGovernor(); maxPriceDeviationThreshold = _maxPriceDeviationThreshold; } /** * @notice change the status of a handler */ function changeHandler(address _handler, bool auth) external { _onlyGovernor(); if (_handler == address(0)) { revert CustomErrors.InvalidAddress(); } handler[_handler] = auth; } /** * @notice change the status of a keeper */ function setKeeper(address _keeper, bool _auth) external { _onlyGovernor(); if (_keeper == address(0)) { revert CustomErrors.InvalidAddress(); } keeper[_keeper] = _auth; } /** * @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 setUtilizationSkewParams( uint256 _belowThresholdGradient, uint256 _aboveThresholdGradient, uint256 _utilizationFunctionThreshold ) external { _onlyManager(); belowThresholdGradient = _belowThresholdGradient; aboveThresholdGradient = _aboveThresholdGradient; aboveThresholdYIntercept = _utilizationFunctionThreshold.mul( _aboveThresholdGradient - _belowThresholdGradient // inverted the order of the subtraction to result in a positive uint ); utilizationFunctionThreshold = _utilizationFunctionThreshold; } ////////////////////////////////////////////////////// /// access-controlled state changing functionality /// ////////////////////////////////////////////////////// /** * @notice function for hedging portfolio delta through external means * @param delta the current portfolio delta * @param reactorIndex the index of the reactor in the hedgingReactors array to use */ function rebalancePortfolioDelta(int256 delta, uint256 reactorIndex) external { _onlyManager(); IHedgingReactor(hedgingReactors[reactorIndex]).hedgeDelta(delta); emit RebalancePortfolioDelta(delta); } /** * @notice adjust the collateral held in a specific vault because of health * @param lpCollateralDifference amount of collateral taken from or given to the liquidity pool in collateral decimals * @param addToLpBalance true if collateral is returned to liquidity pool, false if collateral is withdrawn from liquidity pool * @dev called by the option registry only */ function adjustCollateral(uint256 lpCollateralDifference, bool addToLpBalance) external { IOptionRegistry optionRegistry = _getOptionRegistry(); require(msg.sender == address(optionRegistry)); // assumes in collateral decimals if (addToLpBalance) { collateralAllocated -= lpCollateralDifference; } else { SafeTransferLib.safeApprove( ERC20(collateralAsset), address(optionRegistry), lpCollateralDifference ); collateralAllocated += lpCollateralDifference; } } /** * @notice closes an oToken vault, returning collateral (minus ITM option expiry value) back to the pool * @param seriesAddress the address of the oToken vault to close * @return collatReturned the amount of collateral returned to the liquidity pool, assumes in collateral decimals */ function settleVault(address seriesAddress) external returns (uint256) { _isKeeper(); // get number of options in vault and collateral returned to recalculate our position without these options // returns in collat decimals, collat decimals and e8 (, uint256 collatReturned, uint256 collatLost, ) = _getOptionRegistry().settle(seriesAddress); emit SettleVault(seriesAddress, collatReturned, collatLost, msg.sender); // if the vault expired ITM then when settled the oracle will still have accounted for it as a liability. When // the settle happens the liability is wiped off as it is now accounted for in collateralAllocated but because the // oracle doesn't know this yet we need to temporarily reduce the liability value. _adjustVariables(collatReturned, collatLost, 0, false); collateralAllocated -= collatLost; return collatReturned; } /** * @notice issue an option * @param optionSeries the series detail of the option - strike decimals in e18 * @dev only callable by a handler contract */ function handlerIssue(Types.OptionSeries memory optionSeries) external returns (address) { _isHandler(); // series strike in e18 return _issue(optionSeries, _getOptionRegistry()); } /** * @notice write an option that already exists * @param optionSeries the series detail of the option - strike decimals in e8 * @param seriesAddress the series address of the oToken * @param amount the number of options to write - in e18 * @param optionRegistry the registry used for options writing * @param premium the premium of the option - in collateral decimals * @param delta the delta of the option - in e18 * @param recipient the receiver of the option * @dev only callable by a handler contract */ function handlerWriteOption( Types.OptionSeries memory optionSeries, address seriesAddress, uint256 amount, IOptionRegistry optionRegistry, uint256 premium, int256 delta, address recipient ) external returns (uint256) { _isTradingNotPaused(); _isHandler(); return _writeOption( optionSeries, // series strike in e8 seriesAddress, amount, // in e18 optionRegistry, premium, // in collat decimals delta, checkBuffer(), // in e6 recipient ); } /** * @notice write an option that doesnt exist * @param optionSeries the series detail of the option - strike decimals in e18 * @param amount the number of options to write - in e18 * @param premium the premium of the option - in collateral decimals * @param delta the delta of the option - in e18 * @param recipient the receiver of the option * @dev only callable by a handler contract */ function handlerIssueAndWriteOption( Types.OptionSeries memory optionSeries, uint256 amount, uint256 premium, int256 delta, address recipient ) external returns (uint256, address) { _isTradingNotPaused(); _isHandler(); IOptionRegistry optionRegistry = _getOptionRegistry(); // series strike passed in as e18 address seriesAddress = _issue(optionSeries, optionRegistry); // series strike received in e8, retrieved from the option registry instead of // using one in memory because formatStrikePrice might have slightly changed the // strike optionSeries = optionRegistry.getSeriesInfo(seriesAddress); return ( _writeOption( optionSeries, // strike in e8 seriesAddress, amount, // in e18 optionRegistry, premium, // in collat decimals delta, checkBuffer(), // in e6 recipient ), seriesAddress ); } /** * @notice buy back an option that already exists * @param optionSeries the series detail of the option - strike decimals in e8 * @param amount the number of options to buyback - in e18 * @param optionRegistry the registry used for options writing * @param seriesAddress the series address of the oToken * @param premium the premium of the option - in collateral decimals * @param delta the delta of the option - in e18 * @param seller the receiver of the option * @dev only callable by a handler contract */ function handlerBuybackOption( Types.OptionSeries memory optionSeries, uint256 amount, IOptionRegistry optionRegistry, address seriesAddress, uint256 premium, int256 delta, address seller ) external returns (uint256) { _isTradingNotPaused(); _isHandler(); // strike passed in as e8 return _buybackOption(optionSeries, amount, optionRegistry, seriesAddress, premium, delta, seller); } /** * @notice reset the temporary portfolio and delta values that have been changed since the last oracle update * @dev only callable by the portfolio values feed oracle contract */ function resetEphemeralValues() external { require(msg.sender == address(_getPortfolioValuesFeed())); delete ephemeralLiabilities; delete ephemeralDelta; } /** * @notice reset the temporary portfolio and delta values that have been changed since the last oracle update * @dev this function must be called in order to execute an epoch calculation */ function pauseTradingAndRequest() external returns (bytes32) { _isKeeper(); // pause trading isTradingPaused = true; emit TradingPaused(); // make an oracle request return _getPortfolioValuesFeed().requestPortfolioData(underlyingAsset, strikeAsset); } /** * @notice execute the epoch and set all the price per shares * @dev this function must be called in order to execute an epoch calculation and batch a mutual fund epoch */ function executeEpochCalculation() external whenNotPaused { _isKeeper(); if (!isTradingPaused) { revert CustomErrors.TradingNotPaused(); } ( uint256 newPricePerShareDeposit, uint256 newPricePerShareWithdrawal, uint256 sharesToMint, uint256 totalWithdrawAmount, uint256 amountNeeded ) = _getAccounting().executeEpochCalculation(totalSupply, _getAssets(), _getLiabilities()); // deposits always get executed depositEpochPricePerShare[depositEpoch] = newPricePerShareDeposit; delete pendingDeposits; emit DepositEpochExecuted(depositEpoch); depositEpoch++; isTradingPaused = false; emit TradingUnpaused(); _mint(address(this), sharesToMint); // loop through the reactors and move funds if found if (amountNeeded > 0) { address[] memory hedgingReactors_ = hedgingReactors; for (uint8 i = 0; i < hedgingReactors_.length; i++) { amountNeeded -= IHedgingReactor(hedgingReactors_[i]).withdraw(amountNeeded); if (amountNeeded <= 0) { break; } } // if not enough funds in liquidity pool and reactors, dont process withdrawals this epoch if (amountNeeded > 0) { return; } } withdrawalEpochPricePerShare[withdrawalEpoch] = newPricePerShareWithdrawal; partitionedFunds += totalWithdrawAmount; emit WithdrawalEpochExecuted(withdrawalEpoch); _burn(address(this), pendingWithdrawals); delete pendingWithdrawals; withdrawalEpoch++; } ///////////////////////////////////////////// /// external state changing functionality /// ///////////////////////////////////////////// /** * @notice function for adding liquidity to the options liquidity pool * @param _amount amount of the strike asset to deposit * @return success * @dev entry point to provide liquidity to dynamic hedging vault */ function deposit(uint256 _amount) external whenNotPaused nonReentrant returns (bool) { if (_amount == 0) { revert CustomErrors.InvalidAmount(); } (uint256 depositAmount, uint256 unredeemedShares) = _getAccounting().deposit(msg.sender, _amount); emit Deposit(msg.sender, _amount, depositEpoch); // create the deposit receipt depositReceipts[msg.sender] = IAccounting.DepositReceipt({ epoch: uint128(depositEpoch), amount: uint128(depositAmount), unredeemedShares: unredeemedShares }); pendingDeposits += _amount; // Pull in tokens from sender SafeTransferLib.safeTransferFrom(collateralAsset, msg.sender, address(this), _amount); return true; } /** * @notice function for allowing a user to redeem their shares from a previous epoch * @param _shares the number of shares to redeem * @return the number of shares actually returned */ function redeem(uint256 _shares) external nonReentrant returns (uint256) { if (_shares == 0) { revert CustomErrors.InvalidShareAmount(); } return _redeem(_shares); } /** * @notice function for initiating a withdraw request from the pool * @param _shares amount of shares to return * @dev entry point to remove liquidity to dynamic hedging vault */ function initiateWithdraw(uint256 _shares) external whenNotPaused nonReentrant { if (_shares == 0) { revert CustomErrors.InvalidShareAmount(); } IAccounting.DepositReceipt memory depositReceipt = depositReceipts[msg.sender]; if (depositReceipt.amount > 0 || depositReceipt.unredeemedShares > 0) { // redeem so a user can use a completed deposit as shares for an initiation _redeem(type(uint256).max); } IAccounting.WithdrawalReceipt memory withdrawalReceipt = _getAccounting().initiateWithdraw( msg.sender, _shares ); withdrawalReceipts[msg.sender] = withdrawalReceipt; pendingWithdrawals += _shares; emit InitiateWithdraw(msg.sender, _shares, withdrawalEpoch); transfer(address(this), _shares); } /** * @notice function for completing the withdraw from a pool * @dev entry point to remove liquidity to dynamic hedging vault */ function completeWithdraw() external whenNotPaused nonReentrant returns (uint256) { ( uint256 withdrawalAmount, uint256 withdrawalShares, IAccounting.WithdrawalReceipt memory withdrawalReceipt ) = _getAccounting().completeWithdraw(msg.sender); withdrawalReceipts[msg.sender] = withdrawalReceipt; emit Withdraw(msg.sender, withdrawalAmount, withdrawalShares); // these funds are taken from the partitioned funds partitionedFunds -= withdrawalAmount; SafeTransferLib.safeTransfer(ERC20(collateralAsset), msg.sender, withdrawalAmount); return withdrawalAmount; } /////////////////////// /// complex getters /// /////////////////////// /** * @notice Returning balance in 1e18 format * @param asset address of the asset to get balance and normalize * @return normalizedBalance balance in 1e18 format */ function _getNormalizedBalance(address asset) internal view returns (uint256 normalizedBalance) { normalizedBalance = OptionsCompute.convertFromDecimals( ERC20(asset).balanceOf(address(this)) - partitionedFunds, ERC20(asset).decimals() ); } /** * @notice Returning balance in 1e6 format * @param asset address of the asset to get balance * @return balance of the address accounting for partitionedFunds */ function getBalance(address asset) public view returns (uint256) { return ERC20(asset).balanceOf(address(this)) - partitionedFunds; } /** * @notice get the delta of the hedging reactors * @return externalDelta hedging reactor delta in e18 format */ function getExternalDelta() public view returns (int256 externalDelta) { address[] memory hedgingReactors_ = hedgingReactors; for (uint8 i = 0; i < hedgingReactors_.length; i++) { externalDelta += IHedgingReactor(hedgingReactors_[i]).getDelta(); } } /** * @notice get the delta of the portfolio * @return portfolio delta */ function getPortfolioDelta() public view returns (int256) { // assumes in e18 Types.PortfolioValues memory portfolioValues = _getPortfolioValuesFeed().getPortfolioValues( underlyingAsset, strikeAsset ); // check that the portfolio values are acceptable OptionsCompute.validatePortfolioValues( _getUnderlyingPrice(underlyingAsset, strikeAsset), portfolioValues, maxTimeDeviationThreshold, maxPriceDeviationThreshold ); return portfolioValues.delta + getExternalDelta() + ephemeralDelta; } /** * @notice get the quote price and delta for a given option * @param optionSeries option type to quote - strike assumed in e18 * @param amount the number of options to mint - assumed in e18 * @param toBuy whether the protocol is buying the option * @return quote the price of the options - returns in e18 * @return delta the delta of the options - returns in e18 */ function quotePriceWithUtilizationGreeks( Types.OptionSeries memory optionSeries, uint256 amount, bool toBuy ) external view returns (uint256 quote, int256 delta) { // using a struct to get around stack too deep issues Types.UtilizationState memory quoteState; quoteState.underlyingPrice = _getUnderlyingPrice( optionSeries.underlying, optionSeries.strikeAsset ); quoteState.iv = getImpliedVolatility( optionSeries.isPut, quoteState.underlyingPrice, optionSeries.strike, optionSeries.expiration ); (uint256 optionQuote, int256 deltaQuote) = OptionsCompute.quotePriceGreeks( optionSeries, toBuy, bidAskIVSpread, riskFreeRate, quoteState.iv, quoteState.underlyingPrice ); // price of acquiring total amount of options (remains e18 due to PRBMath) quoteState.totalOptionPrice = optionQuote.mul(amount); quoteState.totalDelta = deltaQuote.mul(int256(amount)); // will update quoteState.utilizationPrice addUtilizationPremium(quoteState, optionSeries, amount, toBuy); quote = applyDeltaPremium(quoteState, toBuy); quote = OptionsCompute.convertToCollateralDenominated( quote, quoteState.underlyingPrice, optionSeries ); delta = quoteState.totalDelta; if (quote == 0 || delta == int256(0)) { revert CustomErrors.DeltaQuoteError(quote, delta); } } /** * @notice applies a utilization premium when the protocol is selling options. * Stores the utilization price in quoteState.utilizationPrice for use in quotePriceWithUtilizationGreeks * @param quoteState the struct created in quoteStateWithUtilizationGreeks to store memory variables * @param optionSeries the option type for which we are quoting a price * @param amount the amount of options. e18 * @param toBuy whether we are buying an option. False if selling */ function addUtilizationPremium( Types.UtilizationState memory quoteState, Types.OptionSeries memory optionSeries, uint256 amount, bool toBuy ) internal view { if (!toBuy) { uint256 collateralAllocated_ = collateralAllocated; // if selling options, we want to add the utilization premium // Work out the utilization of the pool as a percentage quoteState.utilizationBefore = collateralAllocated_.div( collateralAllocated_ + getBalance(collateralAsset) ); // assumes strike is e18 // strike is not being used again so we dont care if format changes optionSeries.strike = optionSeries.strike / 1e10; // returns collateral decimals quoteState.collateralToAllocate = _getOptionRegistry().getCollateral(optionSeries, amount); quoteState.utilizationAfter = (quoteState.collateralToAllocate + collateralAllocated_).div( collateralAllocated_ + getBalance(collateralAsset) ); // get the price of the option with the utilization premium added quoteState.utilizationPrice = OptionsCompute.getUtilizationPrice( quoteState.utilizationBefore, quoteState.utilizationAfter, quoteState.totalOptionPrice, utilizationFunctionThreshold, belowThresholdGradient, aboveThresholdGradient, aboveThresholdYIntercept ); } else { // do not use utlilization premium for buybacks quoteState.utilizationPrice = quoteState.totalOptionPrice; } } /** * @notice Applies a discount or premium based on the liquidity pool's delta exposure * Gives discount if the transaction results in a lower delta exposure for the liquidity pool. * Prices option more richly if the transaction results in higher delta exposure for liquidity pool. * @param quoteState the struct created in quoteStateWithUtilizationGreeks to store memory variables * @param toBuy whether we are buying an option. False if selling * @return quote the quote for the option with the delta skew applied */ function applyDeltaPremium(Types.UtilizationState memory quoteState, bool toBuy) internal view returns (uint256 quote) { // portfolio delta before writing option int256 portfolioDelta = getPortfolioDelta(); // subtract totalDelta if buying as pool is taking on the negative of the option's delta int256 newDelta = toBuy ? portfolioDelta + quoteState.totalDelta : portfolioDelta - quoteState.totalDelta; // Is delta moved closer to zero? quoteState.isDecreased = (PRBMathSD59x18.abs(newDelta) - PRBMathSD59x18.abs(portfolioDelta)) < 0; // delta exposure of the portolio per ETH equivalent value the portfolio holds. // This value is only used for tilting so we are only interested in its distance from 0 (its magnitude) uint256 normalizedDelta = uint256(PRBMathSD59x18.abs((portfolioDelta + newDelta).div(2e18))).div( _getNAV().div(quoteState.underlyingPrice) ); // this is the percentage of the option price which is added to or subtracted from option price // according to whether portfolio delta is increased or decreased respectively quoteState.deltaTiltAmount = normalizedDelta > maxDiscount ? maxDiscount : normalizedDelta; if (quoteState.isDecreased) { quote = toBuy ? quoteState.deltaTiltAmount.mul(quoteState.utilizationPrice) + quoteState.utilizationPrice : quoteState.utilizationPrice - quoteState.deltaTiltAmount.mul(quoteState.utilizationPrice); } else { // increase utilization by delta tilt factor for moving delta away from zero quote = toBuy ? quoteState.utilizationPrice - quoteState.deltaTiltAmount.mul(quoteState.utilizationPrice) : quoteState.deltaTiltAmount.mul(quoteState.utilizationPrice) + quoteState.utilizationPrice; } } /////////////////////////// /// non-complex getters /// /////////////////////////// /** * @notice get the current implied volatility from the feed * @param isPut Is the option a call or put? * @param underlyingPrice The underlying price - assumed in e18 * @param strikePrice The strike price of the option - assumed in e18 * @param expiration expiration timestamp of option as a PRBMath Float * @return Implied volatility adjusted for volatility surface - assumed in e18 */ function getImpliedVolatility( bool isPut, uint256 underlyingPrice, uint256 strikePrice, uint256 expiration ) public view returns (uint256) { return _getVolatilityFeed().getImpliedVolatility(isPut, underlyingPrice, strikePrice, expiration); } function getAssets() external view returns (uint256) { return _getAssets(); } function getNAV() external view returns (uint256) { return _getNAV(); } ////////////////////////// /// internal utilities /// ////////////////////////// /** * @notice functionality for allowing a user to redeem their shares from a previous epoch * @param _shares the number of shares to redeem * @return toRedeem the number of shares actually returned */ function _redeem(uint256 _shares) internal returns (uint256) { (uint256 toRedeem, IAccounting.DepositReceipt memory depositReceipt) = _getAccounting().redeem( msg.sender, _shares ); if (toRedeem == 0) { return 0; } depositReceipts[msg.sender] = depositReceipt; allowance[address(this)][msg.sender] = toRedeem; emit Redeem(msg.sender, toRedeem, depositReceipt.epoch); // transfer as the shares will have been minted in the epoch execution transferFrom(address(this), msg.sender, toRedeem); return toRedeem; } /** * @notice get the Net Asset Value * @return Net Asset Value in e18 decimal format */ function _getNAV() internal view returns (uint256) { // equities = assets - liabilities // assets: Any token such as eth usd, collateral sent to OptionRegistry, hedging reactor stuff in e18 // liabilities: Options that we wrote in e18 uint256 assets = _getAssets(); int256 liabilities = _getLiabilities(); // if this ever happens then something has gone very wrong so throw here if (int256(assets) < liabilities) { revert CustomErrors.LiabilitiesGreaterThanAssets(); } return uint256(int256(assets) - liabilities); } /** * @notice get the Asset Value * @return assets Asset Value in e18 decimal format */ function _getAssets() internal view returns (uint256 assets) { // assets: Any token such as eth usd, collateral sent to OptionRegistry, hedging reactor stuff in e18 // liabilities: Options that we wrote in e18 assets = _getNormalizedBalance(collateralAsset) + OptionsCompute.convertFromDecimals(collateralAllocated, ERC20(collateralAsset).decimals()); address[] memory hedgingReactors_ = hedgingReactors; for (uint8 i = 0; i < hedgingReactors_.length; i++) { // should always return value in e18 decimals assets += IHedgingReactor(hedgingReactors_[i]).getPoolDenominatedValue(); } } function _getLiabilities() internal view returns (int256 liabilities) { Types.PortfolioValues memory portfolioValues = _getPortfolioValuesFeed().getPortfolioValues( underlyingAsset, strikeAsset ); // check that the portfolio values are acceptable OptionsCompute.validatePortfolioValues( _getUnderlyingPrice(underlyingAsset, strikeAsset), portfolioValues, maxTimeDeviationThreshold, maxPriceDeviationThreshold ); // ephemeralLiabilities can be +/-, portfolioValues.callPutsValue could be +/- liabilities = portfolioValues.callPutsValue + ephemeralLiabilities; } /** * @notice calculates amount of liquidity that can be used before hitting buffer * @return bufferRemaining the amount of liquidity available before reaching buffer in e6 */ function checkBuffer() public view returns (int256 bufferRemaining) { // calculate max amount of liquidity pool funds that can be used before reaching max buffer allowance uint256 collateralBalance = getBalance(collateralAsset); uint256 collateralBuffer = (collateralAllocated * bufferPercentage) / MAX_BPS; bufferRemaining = int256(collateralBalance) - int256(collateralBuffer); } /** * @notice create the option contract in the options registry * @param optionSeries option type to mint - option series strike in e18 * @param optionRegistry interface for the options issuer * @return series the address of the option series minted */ function _issue(Types.OptionSeries memory optionSeries, IOptionRegistry optionRegistry) internal returns (address series) { // make sure option is being issued with correct assets if (optionSeries.collateral != collateralAsset) { revert CustomErrors.CollateralAssetInvalid(); } if (optionSeries.underlying != underlyingAsset) { revert CustomErrors.UnderlyingAssetInvalid(); } if (optionSeries.strikeAsset != strikeAsset) { revert CustomErrors.StrikeAssetInvalid(); } // cache Types.OptionParams memory optionParams_ = optionParams; // check the expiry is within the allowed bounds if ( block.timestamp + optionParams_.minExpiry > optionSeries.expiration || optionSeries.expiration > block.timestamp + optionParams_.maxExpiry ) { revert CustomErrors.OptionExpiryInvalid(); } // check that the option strike is within the range of the min and max acceptable strikes of calls and puts if (optionSeries.isPut) { if ( optionParams_.minPutStrikePrice > optionSeries.strike || optionSeries.strike > optionParams_.maxPutStrikePrice ) { revert CustomErrors.OptionStrikeInvalid(); } } else { if ( optionParams_.minCallStrikePrice > optionSeries.strike || optionSeries.strike > optionParams_.maxCallStrikePrice ) { revert CustomErrors.OptionStrikeInvalid(); } } // issue the option from the option registry (its characteristics will be stored in the optionsRegistry) series = optionRegistry.issue(optionSeries); if (series == address(0)) { revert CustomErrors.IssuanceFailed(); } } /** * @notice write a number of options for a given OptionSeries * @param optionSeries option type to mint - strike in e8 * @param seriesAddress the address of the options series * @param amount the amount to be written - in e18 * @param optionRegistry the option registry of the pool * @param premium the premium to charge the user - in collateral decimals * @param delta the delta of the option position - in e18 * @param bufferRemaining the amount of buffer that can be used - in e6 * @return the amount that was written */ function _writeOption( Types.OptionSeries memory optionSeries, address seriesAddress, uint256 amount, IOptionRegistry optionRegistry, uint256 premium, int256 delta, int256 bufferRemaining, address recipient ) internal returns (uint256) { // strike decimals come into this function as e8 uint256 collateralAmount = optionRegistry.getCollateral(optionSeries, amount); if (bufferRemaining < int256(collateralAmount)) { revert CustomErrors.MaxLiquidityBufferReached(); } ERC20(collateralAsset).approve(address(optionRegistry), collateralAmount); (, collateralAmount) = optionRegistry.open(seriesAddress, amount, collateralAmount); emit WriteOption(seriesAddress, amount, premium, collateralAmount, recipient); // convert e8 strike to e18 strike optionSeries.strike = uint128( OptionsCompute.convertFromDecimals(optionSeries.strike, ERC20(seriesAddress).decimals()) ); _adjustVariables(collateralAmount, premium, delta, true); SafeTransferLib.safeTransfer( ERC20(seriesAddress), recipient, OptionsCompute.convertToDecimals(amount, ERC20(seriesAddress).decimals()) ); // returns in e18 return amount; } /** * @notice buys a number of options back and burns the tokens * @param optionSeries the option token series to buyback - strike passed in as e8 * @param amount the number of options to buyback expressed in 1e18 * @param optionRegistry the registry * @param seriesAddress the series being sold * @param premium the premium to be sent back to the owner (in collat decimals) * @param delta the delta of the option * @param seller the address * @return the number of options burned in e18 */ function _buybackOption( Types.OptionSeries memory optionSeries, uint256 amount, IOptionRegistry optionRegistry, address seriesAddress, uint256 premium, int256 delta, address seller ) internal returns (uint256) { SafeTransferLib.safeApprove( ERC20(seriesAddress), address(optionRegistry), OptionsCompute.convertToDecimals(amount, ERC20(seriesAddress).decimals()) ); (, uint256 collateralReturned) = optionRegistry.close(seriesAddress, amount); emit BuybackOption(seriesAddress, amount, premium, collateralReturned, seller); // convert e8 strike to e18 strike optionSeries.strike = uint128( OptionsCompute.convertFromDecimals(optionSeries.strike, ERC20(seriesAddress).decimals()) ); _adjustVariables(collateralReturned, premium, delta, false); if (getBalance(collateralAsset) < premium) { revert CustomErrors.WithdrawExceedsLiquidity(); } SafeTransferLib.safeTransfer(ERC20(collateralAsset), seller, premium); return amount; } /** * @notice adjust the variables of the pool * @param collateralAmount the amount of collateral transferred to change on collateral allocated in collateral decimals * @param optionsValue the value of the options in e18 decimals * @param delta the delta of the options in e18 decimals * @param isSale whether the action was an option sale or not */ function _adjustVariables( uint256 collateralAmount, uint256 optionsValue, int256 delta, bool isSale ) internal { if (isSale) { collateralAllocated += collateralAmount; ephemeralLiabilities += int256( OptionsCompute.convertFromDecimals(optionsValue, ERC20(collateralAsset).decimals()) ); ephemeralDelta -= delta; } else { collateralAllocated -= collateralAmount; ephemeralLiabilities -= int256( OptionsCompute.convertFromDecimals(optionsValue, ERC20(collateralAsset).decimals()) ); ephemeralDelta += delta; } } /** * @notice get the volatility feed used by the liquidity pool * @return the volatility feed contract interface */ function _getVolatilityFeed() internal view returns (VolatilityFeed) { return VolatilityFeed(protocol.volatilityFeed()); } /** * @notice get the portfolio values feed used by the liquidity pool * @return the portfolio values feed contract */ function _getPortfolioValuesFeed() internal view returns (IPortfolioValuesFeed) { return IPortfolioValuesFeed(protocol.portfolioValuesFeed()); } /** * @notice get the DHV accounting calculations contract used by the liquidity pool * @return the Accounting contract */ function _getAccounting() internal view returns (IAccounting) { return IAccounting(protocol.accounting()); } /** * @notice get the option registry used for storing and managing the options * @return the option registry contract */ function _getOptionRegistry() internal view returns (IOptionRegistry) { return IOptionRegistry(protocol.optionRegistry()); } /** * @notice get the underlying price with just the underlying asset and strike asset * @param underlying the asset that is used as the reference asset * @param _strikeAsset the asset that the underlying value is denominated in * @return the underlying price */ function _getUnderlyingPrice(address underlying, address _strikeAsset) internal view returns (uint256) { return PriceFeed(protocol.priceFeed()).getNormalizedRate(underlying, _strikeAsset); } function _isTradingNotPaused() internal view { if (isTradingPaused) { revert CustomErrors.TradingPaused(); } } function _isHandler() internal view { if (!handler[msg.sender]) { revert CustomErrors.NotHandler(); } } /// @dev keepers, managers or governors can access function _isKeeper() internal view { if ( !keeper[msg.sender] && msg.sender != authority.governor() && msg.sender != authority.manager() ) { revert CustomErrors.NotKeeper(); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9; import "./interfaces/AggregatorV3Interface.sol"; import "./libraries/AccessControl.sol"; /** * @title Contract used for accessing exchange rates using chainlink price feeds * @dev Interacts with chainlink price feeds and services all contracts in the system for price data. */ contract PriceFeed is AccessControl { ///////////////////////////////////// /// governance settable variables /// ///////////////////////////////////// mapping(address => mapping(address => address)) public priceFeeds; ////////////////////////// /// constant variables /// ////////////////////////// uint8 private constant SCALE_DECIMALS = 18; // seconds since the last price feed update until we deem the data to be stale uint32 private constant STALE_PRICE_DELAY = 3600; constructor(address _authority) AccessControl(IAuthority(_authority)) {} /////////////// /// setters /// /////////////// function addPriceFeed( address underlying, address strike, address feed ) public { _onlyGovernor(); priceFeeds[underlying][strike] = feed; } /////////////////////// /// complex getters /// /////////////////////// function getRate(address underlying, address strike) external view returns (uint256) { address feedAddress = priceFeeds[underlying][strike]; require(feedAddress != address(0), "Price feed does not exist"); AggregatorV3Interface feed = AggregatorV3Interface(feedAddress); (uint80 roundId, int256 rate, , uint256 timestamp, uint80 answeredInRound) = feed .latestRoundData(); require(rate > 0, "ChainLinkPricer: price is lower than 0"); require(timestamp != 0, "ROUND_NOT_COMPLETE"); require(block.timestamp <= timestamp + STALE_PRICE_DELAY, "STALE_PRICE"); require(answeredInRound >= roundId, "STALE_PRICE"); return uint256(rate); } /// @dev get the rate from chainlink and convert it to e18 decimals function getNormalizedRate(address underlying, address strike) external view returns (uint256) { address feedAddress = priceFeeds[underlying][strike]; require(feedAddress != address(0), "Price feed does not exist"); AggregatorV3Interface feed = AggregatorV3Interface(feedAddress); uint8 feedDecimals = feed.decimals(); (uint80 roundId, int256 rate, , uint256 timestamp, uint80 answeredInRound) = feed .latestRoundData(); require(rate > 0, "ChainLinkPricer: price is lower than 0"); require(timestamp != 0, "ROUND_NOT_COMPLETE"); require(block.timestamp <= timestamp + STALE_PRICE_DELAY, "STALE_PRICE"); require(answeredInRound >= roundId, "STALE_PRICE_ROUND"); uint8 difference; if (SCALE_DECIMALS > feedDecimals) { difference = SCALE_DECIMALS - feedDecimals; return uint256(rate) * (10**difference); } difference = feedDecimals - SCALE_DECIMALS; return uint256(rate) / (10**difference); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./libraries/AccessControl.sol"; /** * @title Contract used for storage of important contracts for the liquidity pool */ contract Protocol is AccessControl { //////////////////////// /// static variables /// //////////////////////// address public immutable optionRegistry; ///////////////////////////////////// /// governance settable variables /// ///////////////////////////////////// address public volatilityFeed; address public portfolioValuesFeed; address public accounting; address public priceFeed; constructor( address _optionRegistry, address _priceFeed, address _volatilityFeed, address _portfolioValuesFeed, address _authority ) AccessControl(IAuthority(_authority)) { optionRegistry = _optionRegistry; priceFeed = _priceFeed; volatilityFeed = _volatilityFeed; portfolioValuesFeed = _portfolioValuesFeed; } /////////////// /// setters /// /////////////// function changeVolatilityFeed(address _volFeed) external { _onlyGovernor(); volatilityFeed = _volFeed; } function changePortfolioValuesFeed(address _portfolioValuesFeed) external { _onlyGovernor(); portfolioValuesFeed = _portfolioValuesFeed; } function changeAccounting(address _accounting) external { _onlyGovernor(); accounting= _accounting; } function changePriceFeed(address _priceFeed) external { _onlyGovernor(); priceFeed = _priceFeed; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "prb-math/contracts/PRBMathSD59x18.sol"; import "prb-math/contracts/PRBMathUD60x18.sol"; import { NormalDist } from "./NormalDist.sol"; /** * @title Library used to calculate an option price using Black Scholes */ library BlackScholes { using PRBMathSD59x18 for int256; using PRBMathSD59x18 for int8; using PRBMathUD60x18 for uint256; uint256 private constant ONE_YEAR_SECONDS = 31557600; uint256 private constant ONE = 1000000000000000000; uint256 private constant TWO = 2000000000000000000; struct Intermediates { uint256 d1Denominator; int256 d1; int256 eToNegRT; } function callOptionPrice( int256 d1, int256 d1Denominator, int256 price, int256 strike, int256 eToNegRT ) public pure returns (uint256) { int256 d2 = d1 - d1Denominator; int256 cdfD1 = NormalDist.cdf(d1); int256 cdfD2 = NormalDist.cdf(d2); int256 priceCdf = price.mul(cdfD1); int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2); assert(priceCdf >= strikeBy); return uint256(priceCdf - strikeBy); } function callOptionPriceGreeks( int256 d1, int256 d1Denominator, int256 price, int256 strike, int256 eToNegRT ) public pure returns (uint256 quote, int256 delta) { int256 d2 = d1 - d1Denominator; int256 cdfD1 = NormalDist.cdf(d1); int256 cdfD2 = NormalDist.cdf(d2); int256 priceCdf = price.mul(cdfD1); int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2); assert(priceCdf >= strikeBy); quote = uint256(priceCdf - strikeBy); delta = cdfD1; } function putOptionPriceGreeks( int256 d1, int256 d1Denominator, int256 price, int256 strike, int256 eToNegRT ) public pure returns (uint256 quote, int256 delta) { int256 d2 = d1Denominator - d1; int256 cdfD1 = NormalDist.cdf(-d1); int256 cdfD2 = NormalDist.cdf(d2); int256 priceCdf = price.mul(cdfD1); int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2); assert(strikeBy >= priceCdf); quote = uint256(strikeBy - priceCdf); delta = -cdfD1; } function putOptionPrice( int256 d1, int256 d1Denominator, int256 price, int256 strike, int256 eToNegRT ) public pure returns (uint256) { int256 d2 = d1Denominator - d1; int256 cdfD1 = NormalDist.cdf(-d1); int256 cdfD2 = NormalDist.cdf(d2); int256 priceCdf = price.mul(cdfD1); int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2); assert(strikeBy >= priceCdf); return uint256(strikeBy - priceCdf); } function getTimeStamp() private view returns (uint256) { return block.timestamp; } function getD1( uint256 price, uint256 strike, uint256 time, uint256 vol, uint256 rfr ) private pure returns (int256 d1, uint256 d1Denominator) { uint256 d1Right = (vol.mul(vol).div(TWO) + rfr).mul(time); int256 d1Left = int256(price.div(strike)).ln(); int256 d1Numerator = d1Left + int256(d1Right); d1Denominator = vol.mul(time.sqrt()); d1 = d1Numerator.div(int256(d1Denominator)); } function getIntermediates( uint256 price, uint256 strike, uint256 time, uint256 vol, uint256 rfr ) private pure returns (Intermediates memory) { (int256 d1, uint256 d1Denominator) = getD1(price, strike, time, vol, rfr); return Intermediates({ d1Denominator: d1Denominator, d1: d1, eToNegRT: (int256(rfr).mul(int256(time)).mul(-int256(ONE))).exp() }); } function blackScholesCalc( uint256 price, uint256 strike, uint256 expiration, uint256 vol, uint256 rfr, bool isPut ) public view returns (uint256) { uint256 time = (expiration - getTimeStamp()).div(ONE_YEAR_SECONDS); Intermediates memory i = getIntermediates(price, strike, time, vol, rfr); if (!isPut) { return callOptionPrice( int256(i.d1), int256(i.d1Denominator), int256(price), int256(strike), i.eToNegRT ); } else { return putOptionPrice( int256(i.d1), int256(i.d1Denominator), int256(price), int256(strike), i.eToNegRT ); } } function blackScholesCalcGreeks( uint256 price, uint256 strike, uint256 expiration, uint256 vol, uint256 rfr, bool isPut ) public view returns (uint256 quote, int256 delta) { uint256 time = (expiration - getTimeStamp()).div(ONE_YEAR_SECONDS); Intermediates memory i = getIntermediates(price, strike, time, vol, rfr); if (!isPut) { return callOptionPriceGreeks( int256(i.d1), int256(i.d1Denominator), int256(price), int256(strike), i.eToNegRT ); } else { return putOptionPriceGreeks( int256(i.d1), int256(i.d1Denominator), int256(price), int256(strike), i.eToNegRT ); } } function getDelta( uint256 price, uint256 strike, uint256 expiration, uint256 vol, uint256 rfr, bool isPut ) public view returns (int256) { uint256 time = (expiration - getTimeStamp()).div(ONE_YEAR_SECONDS); (int256 d1, ) = getD1(price, strike, time, vol, rfr); if (!isPut) { return NormalDist.cdf(d1); } else { return -NormalDist.cdf(-d1); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9; import "./libraries/AccessControl.sol"; import "./libraries/CustomErrors.sol"; import "./libraries/SABR.sol"; import "prb-math/contracts/PRBMathSD59x18.sol"; import "prb-math/contracts/PRBMathUD60x18.sol"; /** * @title Contract used as the Dynamic Hedging Vault for storing funds, issuing shares and processing options transactions * @dev Interacts with liquidity pool to feed in volatility data. */ contract VolatilityFeed is AccessControl { using PRBMathSD59x18 for int256; using PRBMathUD60x18 for uint256; ////////////////////////// /// settable variables /// ////////////////////////// // Parameters for the sabr volatility model mapping(uint256 => SABRParams) public sabrParams; // keeper mapping mapping(address => bool) public keeper; // expiry array uint256[] public expiries; ////////////////////////// /// constant variables /// ////////////////////////// // number of seconds in a year used for calculations int256 private constant ONE_YEAR_SECONDS = 31557600; int256 private constant BIPS_SCALE = 1e12; int256 private constant BIPS = 1e6; struct SABRParams { int32 callAlpha; // not bigger or less than an int32 and above 0 int32 callBeta; // greater than 0 and less than or equal to 1 int32 callRho; // between 1 and -1 int32 callVolvol; // not bigger or less than an int32 and above 0 int32 putAlpha; int32 putBeta; int32 putRho; int32 putVolvol; } constructor(address _authority) AccessControl(IAuthority(_authority)) {} /////////////// /// setters /// /////////////// error AlphaError(); error BetaError(); error RhoError(); error VolvolError(); event SabrParamsSet( uint256 indexed _expiry, int32 callAlpha, int32 callBeta, int32 callRho, int32 callVolvol, int32 putAlpha, int32 putBeta, int32 putRho, int32 putVolvol ); /** * @notice set the sabr volatility params * @param _sabrParams set the SABR parameters * @param _expiry the expiry that the SABR parameters represent * @dev only keepers can call this function */ function setSabrParameters(SABRParams memory _sabrParams, uint256 _expiry) external { _isKeeper(); if (_sabrParams.callAlpha <= 0 || _sabrParams.putAlpha <= 0) { revert AlphaError(); } if (_sabrParams.callVolvol <= 0 || _sabrParams.putVolvol <= 0) { revert VolvolError(); } if ( _sabrParams.callBeta <= 0 || _sabrParams.callBeta > BIPS || _sabrParams.putBeta <= 0 || _sabrParams.putBeta > BIPS ) { revert BetaError(); } if ( _sabrParams.callRho <= -BIPS || _sabrParams.callRho >= BIPS || _sabrParams.putRho <= -BIPS || _sabrParams.putRho >= BIPS ) { revert RhoError(); } // if the expiry is not already a registered expiry then add it to the expiry list if(sabrParams[_expiry].callAlpha == 0) { expiries.push(_expiry); } sabrParams[_expiry] = _sabrParams; emit SabrParamsSet( _expiry, _sabrParams.callAlpha, _sabrParams.callBeta, _sabrParams.callRho, _sabrParams.callVolvol, _sabrParams.putAlpha, _sabrParams.putBeta, _sabrParams.putRho, _sabrParams.putVolvol ); } /// @notice update the keepers function setKeeper(address _keeper, bool _auth) external { _onlyGovernor(); keeper[_keeper] = _auth; } /////////////////////// /// complex getters /// /////////////////////// /** * @notice get the current implied volatility from the feed * @param isPut Is the option a call or put? * @param underlyingPrice The underlying price * @param strikePrice The strike price of the option * @param expiration expiration timestamp of option as a PRBMath Float * @return Implied volatility adjusted for volatility surface */ function getImpliedVolatility( bool isPut, uint256 underlyingPrice, uint256 strikePrice, uint256 expiration ) external view returns (uint256) { int256 time = (int256(expiration) - int256(block.timestamp)).div(ONE_YEAR_SECONDS); int256 vol; SABRParams memory sabrParams_ = sabrParams[expiration]; if (sabrParams_.callAlpha == 0) { revert CustomErrors.IVNotFound(); } if (!isPut) { vol = SABR.lognormalVol( int256(strikePrice), int256(underlyingPrice), time, sabrParams_.callAlpha * BIPS_SCALE, sabrParams_.callBeta * BIPS_SCALE, sabrParams_.callRho * BIPS_SCALE, sabrParams_.callVolvol * BIPS_SCALE ); } else { vol = SABR.lognormalVol( int256(strikePrice), int256(underlyingPrice), time, sabrParams_.putAlpha * BIPS_SCALE, sabrParams_.putBeta * BIPS_SCALE, sabrParams_.putRho * BIPS_SCALE, sabrParams_.putVolvol * BIPS_SCALE ); } if (vol <= 0) { revert CustomErrors.IVNotFound(); } return uint256(vol); } /** @notice get the expiry array @return the expiry array */ function getExpiries() external view returns (uint256[] memory) { return expiries; } /// @dev keepers, managers or governors can access function _isKeeper() internal view { if ( !keeper[msg.sender] && msg.sender != authority.governor() && msg.sender != authority.manager() ) { revert CustomErrors.NotKeeper(); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface CustomErrors { error NotKeeper(); error IVNotFound(); error NotHandler(); error VaultExpired(); error InvalidInput(); error InvalidPrice(); error InvalidBuyer(); error InvalidOrder(); error OrderExpired(); error InvalidAmount(); error TradingPaused(); error InvalidAddress(); error IssuanceFailed(); error EpochNotClosed(); error InvalidDecimals(); error TradingNotPaused(); error NotLiquidityPool(); error DeltaNotDecreased(); error NonExistentOtoken(); error OrderExpiryTooLong(); error InvalidShareAmount(); error ExistingWithdrawal(); error TotalSupplyReached(); error StrikeAssetInvalid(); error OptionStrikeInvalid(); error OptionExpiryInvalid(); error NoExistingWithdrawal(); error SpotMovedBeyondRange(); error ReactorAlreadyExists(); error CollateralAssetInvalid(); error UnderlyingAssetInvalid(); error CollateralAmountInvalid(); error WithdrawExceedsLiquidity(); error InsufficientShareBalance(); error MaxLiquidityBufferReached(); error LiabilitiesGreaterThanAssets(); error CustomOrderInsufficientPrice(); error CustomOrderInvalidDeltaValue(); error DeltaQuoteError(uint256 quote, int256 delta); error TimeDeltaExceedsThreshold(uint256 timeDelta); error PriceDeltaExceedsThreshold(uint256 priceDelta); error StrikeAmountExceedsLiquidity(uint256 strikeAmount, uint256 strikeLiquidity); error MinStrikeAmountExceedsLiquidity(uint256 strikeAmount, uint256 strikeAmountMin); error UnderlyingAmountExceedsLiquidity(uint256 underlyingAmount, uint256 underlyingLiquidity); error MinUnderlyingAmountExceedsLiquidity(uint256 underlyingAmount, uint256 underlyingAmountMin); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../interfaces/IAuthority.sol"; error UNAUTHORIZED(); /** * @title Contract used for access control functionality, based off of OlympusDao Access Control */ abstract contract AccessControl { /* ========== EVENTS ========== */ event AuthorityUpdated(IAuthority authority); /* ========== STATE VARIABLES ========== */ IAuthority public authority; /* ========== Constructor ========== */ constructor(IAuthority _authority) { authority = _authority; emit AuthorityUpdated(_authority); } /* ========== GOV ONLY ========== */ function setAuthority(IAuthority _newAuthority) external { _onlyGovernor(); authority = _newAuthority; emit AuthorityUpdated(_newAuthority); } /* ========== INTERNAL CHECKS ========== */ function _onlyGovernor() internal view { if (msg.sender != authority.governor()) revert UNAUTHORIZED(); } function _onlyGuardian() internal view { if (!authority.guardian(msg.sender) && msg.sender != authority.governor()) revert UNAUTHORIZED(); } function _onlyManager() internal view { if (msg.sender != authority.manager() && msg.sender != authority.governor()) revert UNAUTHORIZED(); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./Types.sol"; import "./CustomErrors.sol"; import "./BlackScholes.sol"; import "prb-math/contracts/PRBMathUD60x18.sol"; import "prb-math/contracts/PRBMathSD59x18.sol"; /** * @title Library used for various helper functionality for the Liquidity Pool */ library OptionsCompute { using PRBMathUD60x18 for uint256; using PRBMathSD59x18 for int256; uint8 private constant SCALE_DECIMALS = 18; /// @dev assumes decimals are coming in as e18 function convertToDecimals(uint256 value, uint256 decimals) internal pure returns (uint256) { if (decimals > SCALE_DECIMALS) { revert(); } uint256 difference = SCALE_DECIMALS - decimals; return value / (10**difference); } /// @dev converts from specified decimals to e18 function convertFromDecimals(uint256 value, uint256 decimals) internal pure returns (uint256) { if (decimals > SCALE_DECIMALS) { revert(); } uint256 difference = SCALE_DECIMALS - decimals; return value * (10**difference); } // doesnt allow for interest bearing collateral function convertToCollateralDenominated( uint256 quote, uint256 underlyingPrice, Types.OptionSeries memory optionSeries ) internal pure returns (uint256 convertedQuote) { if (optionSeries.strikeAsset != optionSeries.collateral) { // convert value from strike asset to collateral asset return (quote * 1e18) / underlyingPrice; } else { return quote; } } /** * @dev computes the percentage change between two integers * @param n new value in e18 * @param o old value in e18 * @return pC uint256 the percentage change in e18 */ function calculatePercentageChange(uint256 n, uint256 o) internal pure returns (uint256 pC) { // if new > old then its a percentage increase so do: // ((new - old) * 1e18) / old // if new < old then its a percentage decrease so do: // ((old - new) * 1e18) / old if (n > o) { pC = (n - o).div(o); } else { pC = (o - n).div(o); } } /** * @notice get the latest oracle fed portfolio values and check when they were last updated and make sure this is within a reasonable window in * terms of price and time */ function validatePortfolioValues( uint256 spotPrice, Types.PortfolioValues memory portfolioValues, uint256 maxTimeDeviationThreshold, uint256 maxPriceDeviationThreshold ) public view { uint256 timeDelta = block.timestamp - portfolioValues.timestamp; // If too much time has passed we want to prevent a possible oracle attack if (timeDelta > maxTimeDeviationThreshold) { revert CustomErrors.TimeDeltaExceedsThreshold(timeDelta); } uint256 priceDelta = calculatePercentageChange(spotPrice, portfolioValues.spotPrice); // If price has deviated too much we want to prevent a possible oracle attack if (priceDelta > maxPriceDeviationThreshold) { revert CustomErrors.PriceDeltaExceedsThreshold(priceDelta); } } /** * @notice calculates the utilization price of an option using the liquidity pool's utilisation skew algorithm */ function getUtilizationPrice( uint256 _utilizationBefore, uint256 _utilizationAfter, uint256 _totalOptionPrice, uint256 _utilizationFunctionThreshold, uint256 _belowThresholdGradient, uint256 _aboveThresholdGradient, uint256 _aboveThresholdYIntercept ) internal pure returns (uint256 utilizationPrice) { if ( _utilizationBefore <= _utilizationFunctionThreshold && _utilizationAfter <= _utilizationFunctionThreshold ) { // linear function up to threshold utilization // take average of before and after utilization and multiply the average by belowThresholdGradient uint256 multiplicationFactor = (_utilizationBefore + _utilizationAfter) .mul(_belowThresholdGradient) .div(2e18); return _totalOptionPrice + _totalOptionPrice.mul(multiplicationFactor); } else if ( _utilizationBefore >= _utilizationFunctionThreshold && _utilizationAfter >= _utilizationFunctionThreshold ) { // over threshold utilization the skew factor will follow a steeper line uint256 multiplicationFactor = _aboveThresholdGradient .mul(_utilizationBefore + _utilizationAfter) .div(2e18) - _aboveThresholdYIntercept; return _totalOptionPrice + _totalOptionPrice.mul(multiplicationFactor); } else { // in this case the utilization after is above the threshold and // utilization before is below it. // _utilizationAfter will always be greater than _utilizationBefore // finds the ratio of the distance below the threshold to the distance above the threshold uint256 weightingRatio = (_utilizationFunctionThreshold - _utilizationBefore).div( _utilizationAfter - _utilizationFunctionThreshold ); // finds the average y value on the part of the function below threshold uint256 averageFactorBelow = (_utilizationFunctionThreshold + _utilizationBefore).div(2e18).mul( _belowThresholdGradient ); // finds average y value on part of the function above threshold uint256 averageFactorAbove = (_utilizationAfter + _utilizationFunctionThreshold).div(2e18).mul( _aboveThresholdGradient ) - _aboveThresholdYIntercept; // finds the weighted average of the two above averaged to find the average utilization skew over the range of utilization uint256 multiplicationFactor = (weightingRatio.mul(averageFactorBelow) + averageFactorAbove).div( 1e18 + weightingRatio ); return _totalOptionPrice + _totalOptionPrice.mul(multiplicationFactor); } } /** * @notice get the greeks of a quotePrice for a given optionSeries * @param optionSeries Types.OptionSeries struct for describing the option to price greeks - strike in e18 * @return quote Quote price of the option - in e18 * @return delta delta of the option being priced - in e18 */ function quotePriceGreeks( Types.OptionSeries memory optionSeries, bool isBuying, uint256 bidAskIVSpread, uint256 riskFreeRate, uint256 iv, uint256 underlyingPrice ) internal view returns (uint256 quote, int256 delta) { if (iv == 0) { revert CustomErrors.IVNotFound(); } // reduce IV by a factor of bidAskIVSpread if we are buying the options if (isBuying) { iv = (iv * (1e18 - (bidAskIVSpread))) / 1e18; } // revert CustomErrors.if the expiry is in the past if (optionSeries.expiration <= block.timestamp) { revert CustomErrors.OptionExpiryInvalid(); } (quote, delta) = BlackScholes.blackScholesCalcGreeks( underlyingPrice, optionSeries.strike, optionSeries.expiration, iv, riskFreeRate, optionSeries.isPut ); } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( address tokenAddress, address from, address to, uint256 amount ) internal { ERC20 token = ERC20(tokenAddress); bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.9; /// @title Accounting contract to calculate the dhv token value and handle deposit/withdraw mechanics interface IAccounting { struct DepositReceipt { uint128 epoch; uint128 amount; // collateral decimals uint256 unredeemedShares; // e18 } struct WithdrawalReceipt { uint128 epoch; uint128 shares; // e18 } /** * @notice logic for adding liquidity to the options liquidity pool * @param depositor the address making the deposit * @param _amount amount of the collateral asset to deposit * @return depositAmount the amount to deposit from the round * @return unredeemedShares number of shares held in the deposit receipt that havent been redeemed */ function deposit(address depositor, uint256 _amount) external returns (uint256 depositAmount, uint256 unredeemedShares); /** * @notice logic for allowing a user to redeem their shares from a previous epoch * @param redeemer the address making the deposit * @param shares amount of the collateral asset to deposit * @return toRedeem the amount to actually redeem * @return depositReceipt the updated deposit receipt after the redeem has completed */ function redeem(address redeemer, uint256 shares) external returns (uint256 toRedeem, DepositReceipt memory depositReceipt); /** * @notice logic for accounting a user to initiate a withdraw request from the pool * @param withdrawer the address carrying out the withdrawal * @param shares the amount of shares to withdraw for * @return withdrawalReceipt the new withdrawal receipt to pass to the liquidityPool */ function initiateWithdraw(address withdrawer, uint256 shares) external returns (WithdrawalReceipt memory withdrawalReceipt); /** * @notice logic for accounting a user to complete a withdrawal * @param withdrawer the address carrying out the withdrawal * @return withdrawalAmount the amount of collateral to withdraw * @return withdrawalShares the number of shares to withdraw * @return withdrawalReceipt the new withdrawal receipt to pass to the liquidityPool */ function completeWithdraw(address withdrawer) external returns ( uint256 withdrawalAmount, uint256 withdrawalShares, WithdrawalReceipt memory withdrawalReceipt ); /** * @notice execute the next epoch * @param totalSupply the total number of share tokens * @param assets the amount of collateral assets * @param liabilities the amount of liabilities of the pool * @return newPricePerShareDeposit the price per share for deposits * @return newPricePerShareWithdrawal the price per share for withdrawals * @return sharesToMint the number of shares to mint this epoch * @return totalWithdrawAmount the amount of collateral to set aside for partitioning * @return amountNeeded the amount needed to reach the total withdraw amount if collateral balance of lp is insufficient */ function executeEpochCalculation( uint256 totalSupply, uint256 assets, int256 liabilities ) external view returns ( uint256 newPricePerShareDeposit, uint256 newPricePerShareWithdrawal, uint256 sharesToMint, uint256 totalWithdrawAmount, uint256 amountNeeded ); /** * @notice get the number of shares for a given amount * @param _amount the amount to convert to shares - assumed in collateral decimals * @param assetPerShare the amount of assets received per share * @return shares the number of shares based on the amount - assumed in e18 */ function sharesForAmount(uint256 _amount, uint256 assetPerShare) external view returns (uint256 shares); }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.9; import { Types } from "../libraries/Types.sol"; interface IOptionRegistry { ////////////////////////////////////////////////////// /// access-controlled state changing functionality /// ////////////////////////////////////////////////////// /** * @notice Either retrieves the option token if it already exists, or deploy it * @param optionSeries option series to issue * @return the address of the option */ function issue(Types.OptionSeries memory optionSeries) external returns (address); /** * @notice Open an options contract using collateral from the liquidity pool * @param _series the address of the option token to be created * @param amount the amount of options to deploy * @param collateralAmount the collateral required for the option * @dev only callable by the liquidityPool * @return if the transaction succeeded * @return the amount of collateral taken from the liquidityPool */ function open( address _series, uint256 amount, uint256 collateralAmount ) external returns (bool, uint256); /** * @notice Close an options contract (oToken) before it has expired * @param _series the address of the option token to be burnt * @param amount the amount of options to burn * @dev only callable by the liquidityPool * @return if the transaction succeeded */ function close(address _series, uint256 amount) external returns (bool, uint256); ///////////////////////////////////////////// /// external state changing functionality /// ///////////////////////////////////////////// /** * @notice Settle an options vault * @param _series the address of the option token to be burnt * @return success if the transaction succeeded * @return collatReturned the amount of collateral returned from the vault * @return collatLost the amount of collateral used to pay ITM options on vault settle * @return amountShort number of oTokens that the vault was short * @dev callable by anyone but returns funds to the liquidityPool */ function settle(address _series) external returns ( bool success, uint256 collatReturned, uint256 collatLost, uint256 amountShort ); /////////////////////// /// complex getters /// /////////////////////// /** * @notice Send collateral funds for an option to be minted * @dev series.strike should be scaled by 1e8. * @param series details of the option series * @param amount amount of options to mint * @return amount transferred */ function getCollateral(Types.OptionSeries memory series, uint256 amount) external view returns (uint256); /** * @notice Retrieves the option token if it exists * @param underlying is the address of the underlying asset of the option * @param strikeAsset is the address of the collateral asset of the option * @param expiration is the expiry timestamp of the option * @param isPut the type of option * @param strike is the strike price of the option - 1e18 format * @param collateral is the address of the asset to collateralize the option with * @return the address of the option */ function getOtoken( address underlying, address strikeAsset, uint256 expiration, bool isPut, uint256 strike, address collateral ) external view returns (address); /////////////////////////// /// non-complex getters /// /////////////////////////// function getSeriesInfo(address series) external view returns (Types.OptionSeries memory); function vaultIds(address series) external view returns (uint256); function gammaController() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.9; /// @title Reactors to hedge delta using means outside of the option pricing skew. interface IHedgingReactor { /// @notice Execute a strategy to hedge delta exposure /// @param delta The exposure of the liquidity pool that the reactor needs to hedge against /// @return deltaChange The difference in delta exposure as a result of strategy execution function hedgeDelta(int256 delta) external returns (int256); /// @notice Returns the delta exposure of the reactor function getDelta() external view returns (int256 delta); /// @notice Returns the value of the reactor denominated in the liquidity pool asset /// @return value the value of the reactor in the liquidity pool asset function getPoolDenominatedValue() external view returns (uint256 value); /// @notice Withdraw a given asset from the hedging reactor to the calling liquidity pool. /// @param amount The amount to withdraw /// @return the amount actually withdrawn from the reactor denominated in the liquidity pool asset function withdraw(uint256 amount) external returns (uint256); /// @notice Handle events such as collateralisation rebalancing function update() external returns (uint256); }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.9; import "../libraries/Types.sol"; interface IPortfolioValuesFeed { ///////////////////////////////////////////// /// external state changing functionality /// ///////////////////////////////////////////// /** * @notice Creates a Chainlink request to update portfolio values * data, then multiply by 1000000000000000000 (to remove decimal places from data). * * @return requestId - id of the request */ function requestPortfolioData(address _underlying, address _strike) external returns (bytes32 requestId); function updateStores(Types.OptionSeries memory _optionSeries, int256 _shortExposure, int256 _longExposure, address _seriesAddress) external; /////////////////////////// /// non-complex getters /// /////////////////////////// function getPortfolioValues(address underlying, address strike) external view returns (Types.PortfolioValues memory); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
// SPDX-License-Identifier: AGPL-3.0 pragma solidity >=0.8.0; interface IAuthority { /* ========== EVENTS ========== */ event GovernorPushed(address indexed from, address indexed to); event GuardianPushed(address indexed to); event ManagerPushed(address indexed from, address indexed to); event GovernorPulled(address indexed from, address indexed to); event GuardianRevoked(address indexed to); event ManagerPulled(address indexed from, address indexed to); /* ========== VIEW ========== */ function governor() external view returns (address); function guardian(address _target) external view returns (bool); function manager() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "prb-math/contracts/PRBMathSD59x18.sol"; /** * @title Library used for approximating a normal distribution */ library NormalDist { using PRBMathSD59x18 for int256; int256 private constant ONE = 1000000000000000000; int256 private constant ONE_HALF = 500000000000000000; int256 private constant SQRT_TWO = 1414213562373095048; // z-scores // A1 0.254829592 int256 private constant A1 = 254829592000000000; // A2 -0.284496736 int256 private constant A2 = -284496736000000000; // A3 1.421413741 int256 private constant A3 = 1421413741000000000; // A4 -1.453152027 int256 private constant A4 = -1453152027000000000; // A5 1.061405429 int256 private constant A5 = 1061405429000000000; // P 0.3275911 int256 private constant P = 327591100000000000; function cdf(int256 x) public pure returns (int256) { int256 phiParam = x.div(SQRT_TWO); int256 onePlusPhi = ONE + (phi(phiParam)); return ONE_HALF.mul(onePlusPhi); } function phi(int256 x) public pure returns (int256) { int256 sign = x >= 0 ? ONE : -ONE; int256 abs = x.abs(); // A&S formula 7.1.26 int256 t = ONE.div(ONE + (P.mul(abs))); int256 scoresByT = getScoresFromT(t); int256 eToXs = abs.mul(-ONE).mul(abs).exp(); int256 y = ONE - (scoresByT.mul(eToXs)); return sign.mul(y); } function getScoresFromT(int256 t) public pure returns (int256) { int256 byA5T = A5.mul(t); int256 byA4T = (byA5T + A4).mul(t); int256 byA3T = (byA4T + A3).mul(t); int256 byA2T = (byA3T + A2).mul(t); int256 byA1T = (byA2T + A1).mul(t); return byA1T; } }
// SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; import "./PRBMath.sol"; /// @title PRBMathSD59x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18 /// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have /// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers /// are bound by the minimum and the maximum values permitted by the Solidity type int256. library PRBMathSD59x18 { /// @dev log2(e) as a signed 59.18-decimal fixed-point number. int256 internal constant LOG2_E = 1_442695040888963407; /// @dev Half the SCALE number. int256 internal constant HALF_SCALE = 5e17; /// @dev The maximum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967; /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev The minimum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968; /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev How many trailing decimals can be represented. int256 internal constant SCALE = 1e18; /// INTERNAL FUNCTIONS /// /// @notice Calculate the absolute value of x. /// /// @dev Requirements: /// - x must be greater than MIN_SD59x18. /// /// @param x The number to calculate the absolute value for. /// @param result The absolute value of x. function abs(int256 x) internal pure returns (int256 result) { unchecked { if (x == MIN_SD59x18) { revert PRBMathSD59x18__AbsInputTooSmall(); } result = x < 0 ? -x : x; } } /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number. function avg(int256 x, int256 y) internal pure returns (int256 result) { // The operations can never overflow. unchecked { int256 sum = (x >> 1) + (y >> 1); if (sum < 0) { // If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the // right rounds down to infinity. assembly { result := add(sum, and(or(x, y), 1)) } } else { // If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5 // remainder gets truncated twice. result = sum + (x & y & 1); } } } /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number. function ceil(int256 x) internal pure returns (int256 result) { if (x > MAX_WHOLE_SD59x18) { revert PRBMathSD59x18__CeilOverflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x > 0) { result += SCALE; } } } } /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - All from "PRBMath.mulDiv". /// - None of the inputs can be MIN_SD59x18. /// - The denominator cannot be zero. /// - The result must fit within int256. /// /// Caveats: /// - All from "PRBMath.mulDiv". /// /// @param x The numerator as a signed 59.18-decimal fixed-point number. /// @param y The denominator as a signed 59.18-decimal fixed-point number. /// @param result The quotient as a signed 59.18-decimal fixed-point number. function div(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__DivInputTooSmall(); } // Get hold of the absolute values of x and y. uint256 ax; uint256 ay; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); } // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256. uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__DivOverflow(rAbs); } // Get the signs of x and y. uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result // should be positive. Otherwise, it should be negative. result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (int256 result) { result = 2_718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 133.084258667509499441. /// /// Caveats: /// - All from "exp2". /// - For any x less than -41.446531673892822322, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp(int256 x) internal pure returns (int256 result) { // Without this check, the value passed to "exp2" would be less than -59.794705707972522261. if (x < -41_446531673892822322) { return 0; } // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathSD59x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { int256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - For any x less than -59.794705707972522261, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp2(int256 x) internal pure returns (int256 result) { // This works because 2^(-x) = 1/2^x. if (x < 0) { // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero. if (x < -59_794705707972522261) { return 0; } // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. unchecked { result = 1e36 / exp2(-x); } } else { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathSD59x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE); // Safe to convert the result to int256 directly because the maximum input allowed is 192. result = int256(PRBMath.exp2(x192x64)); } } } /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be greater than or equal to MIN_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number. function floor(int256 x) internal pure returns (int256 result) { if (x < MIN_WHOLE_SD59x18) { revert PRBMathSD59x18__FloorUnderflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x < 0) { result -= SCALE; } } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number. function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } } /// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be greater than or equal to MIN_SD59x18 divided by SCALE. /// - x must be less than or equal to MAX_SD59x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in signed 59.18-decimal fixed-point representation. function fromInt(int256 x) internal pure returns (int256 result) { unchecked { if (x < MIN_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntUnderflow(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntOverflow(x); } result = x * SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_SD59x18, lest it overflows. /// - x * y cannot be negative. /// /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function gm(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. int256 xy = x * y; if (xy / x != y) { revert PRBMathSD59x18__GmOverflow(x, y); } // The product cannot be negative. if (xy < 0) { revert PRBMathSD59x18__GmNegativeProduct(x, y); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = int256(PRBMath.sqrt(uint256(xy))); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as a signed 59.18-decimal fixed-point number. function inv(int256 x) internal pure returns (int256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number. function ln(int256 x) internal pure returns (int256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 195205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as a signed 59.18-decimal fixed-point number. function log10(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } default { result := MAX_SD59x18 } } if (result == MAX_SD59x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= SCALE) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * SCALE; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal /// fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is /// always 1e18. /// /// Requirements: /// - All from "PRBMath.mulDivFixedPoint". /// - None of the inputs can be MIN_SD59x18 /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// /// @param x The multiplicand as a signed 59.18-decimal fixed-point number. /// @param y The multiplier as a signed 59.18-decimal fixed-point number. /// @return result The product as a signed 59.18-decimal fixed-point number. function mul(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__MulInputTooSmall(); } unchecked { uint256 ax; uint256 ay; ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__MulOverflow(rAbs); } uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } } /// @notice Returns PI as a signed 59.18-decimal fixed-point number. function pi() internal pure returns (int256 result) { result = 3_141592653589793238; } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// - z cannot be zero. /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number. /// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number. /// @return result x raised to power y, as a signed 59.18-decimal fixed-point number. function pow(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { result = y == 0 ? SCALE : int256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - All from "abs" and "PRBMath.mulDivFixedPoint". /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - All from "PRBMath.mulDivFixedPoint". /// - Assumes 0^0 is 1. /// /// @param x The base as a signed 59.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as a signed 59.18-decimal fixed-point number. function powu(int256 x, uint256 y) internal pure returns (int256 result) { uint256 xAbs = uint256(abs(x)); // Calculate the first iteration of the loop in advance. uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE); // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs); // Equivalent to "y % 2 == 1" but faster. if (yAux & 1 > 0) { rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs); } } // The result must fit within the 59.18-decimal fixed-point representation. if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__PowuOverflow(rAbs); } // Is the base negative and the exponent an odd number? bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(rAbs) : int256(rAbs); } /// @notice Returns 1 as a signed 59.18-decimal fixed-point number. function scale() internal pure returns (int256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x cannot be negative. /// - x must be less than MAX_SD59x18 / SCALE. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as a signed 59.18-decimal fixed-point . function sqrt(int256 x) internal pure returns (int256 result) { unchecked { if (x < 0) { revert PRBMathSD59x18__SqrtNegativeInput(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = int256(PRBMath.sqrt(uint256(x * SCALE))); } } /// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The signed 59.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toInt(int256 x) internal pure returns (int256 result) { unchecked { result = x / SCALE; } } }
// SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; import "./PRBMath.sol"; /// @title PRBMathUD60x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18 /// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60 /// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the /// maximum values permitted by the Solidity type uint256. library PRBMathUD60x18 { /// @dev Half the SCALE number. uint256 internal constant HALF_SCALE = 5e17; /// @dev log2(e) as an unsigned 60.18-decimal fixed-point number. uint256 internal constant LOG2_E = 1_442695040888963407; /// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935; /// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000; /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number. function avg(uint256 x, uint256 y) internal pure returns (uint256 result) { // The operations can never overflow. unchecked { // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice. result = (x >> 1) + (y >> 1) + (x & y & 1); } } /// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_UD60x18. /// /// @param x The unsigned 60.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number. function ceil(uint256 x) internal pure returns (uint256 result) { if (x > MAX_WHOLE_UD60x18) { revert PRBMathUD60x18__CeilOverflow(x); } assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(x, SCALE) // Equivalent to "SCALE - remainder" but faster. let delta := sub(SCALE, remainder) // Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster. result := add(x, mul(delta, gt(remainder, 0))) } } /// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number. /// /// @dev Uses mulDiv to enable overflow-safe multiplication and division. /// /// Requirements: /// - The denominator cannot be zero. /// /// @param x The numerator as an unsigned 60.18-decimal fixed-point number. /// @param y The denominator as an unsigned 60.18-decimal fixed-point number. /// @param result The quotient as an unsigned 60.18-decimal fixed-point number. function div(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDiv(x, SCALE, y); } /// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (uint256 result) { result = 2_718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 133.084258667509499441. /// /// @param x The exponent as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp(uint256 x) internal pure returns (uint256 result) { // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathUD60x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { uint256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_UD60x18. /// /// @param x The exponent as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathUD60x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (x << 64) / SCALE; // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation. result = PRBMath.exp2(x192x64); } } /// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x. /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// @param x The unsigned 60.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number. function floor(uint256 x) internal pure returns (uint256 result) { assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(x, SCALE) // Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster. result := sub(x, mul(remainder, gt(remainder, 0))) } } /// @notice Yields the excess beyond the floor of x. /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part. /// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number. function frac(uint256 x) internal pure returns (uint256 result) { assembly { result := mod(x, SCALE) } } /// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be less than or equal to MAX_UD60x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in unsigned 60.18-decimal fixed-point representation. function fromUint(uint256 x) internal pure returns (uint256 result) { unchecked { if (x > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__FromUintOverflow(x); } result = x * SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_UD60x18, lest it overflows. /// /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function gm(uint256 x, uint256 y) internal pure returns (uint256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. uint256 xy = x * y; if (xy / x != y) { revert PRBMathUD60x18__GmOverflow(x, y); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = PRBMath.sqrt(xy); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as an unsigned 60.18-decimal fixed-point number. function inv(uint256 x) internal pure returns (uint256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number. function ln(uint256 x) internal pure returns (uint256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 196205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number. function log10(uint256 x) internal pure returns (uint256 result) { if (x < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined // in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) } default { result := MAX_UD60x18 } } if (result == MAX_UD60x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than or equal to SCALE, otherwise the result would be negative. /// /// Caveats: /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number. function log2(uint256 x) internal pure returns (uint256 result) { if (x < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(x); } unchecked { // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(x / SCALE); // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255 and SCALE is 1e18. result = n * SCALE; // This is y = x * 2^(-n). uint256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } } } /// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal /// fixed-point number. /// @dev See the documentation for the "PRBMath.mulDivFixedPoint" function. /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The product as an unsigned 60.18-decimal fixed-point number. function mul(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDivFixedPoint(x, y); } /// @notice Returns PI as an unsigned 60.18-decimal fixed-point number. function pi() internal pure returns (uint256 result) { result = 3_141592653589793238; } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number. /// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number. /// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number. function pow(uint256 x, uint256 y) internal pure returns (uint256 result) { if (x == 0) { result = y == 0 ? SCALE : uint256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - The result must fit within MAX_UD60x18. /// /// Caveats: /// - All from "mul". /// - Assumes 0^0 is 1. /// /// @param x The base as an unsigned 60.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function powu(uint256 x, uint256 y) internal pure returns (uint256 result) { // Calculate the first iteration of the loop in advance. result = y & 1 > 0 ? x : SCALE; // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. for (y >>= 1; y > 0; y >>= 1) { x = PRBMath.mulDivFixedPoint(x, x); // Equivalent to "y % 2 == 1" but faster. if (y & 1 > 0) { result = PRBMath.mulDivFixedPoint(result, x); } } } /// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number. function scale() internal pure returns (uint256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x must be less than MAX_UD60x18 / SCALE. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as an unsigned 60.18-decimal fixed-point . function sqrt(uint256 x) internal pure returns (uint256 result) { unchecked { if (x > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = PRBMath.sqrt(x * SCALE); } } /// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The unsigned 60.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toUint(uint256 x) internal pure returns (uint256 result) { unchecked { result = x / SCALE; } } }
// SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivFixedPointOverflow(uint256 prod1); /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator); /// @notice Emitted when one of the inputs is type(int256).min. error PRBMath__MulDivSignedInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows int256. error PRBMath__MulDivSignedOverflow(uint256 rAbs); /// @notice Emitted when the input is MIN_SD59x18. error PRBMathSD59x18__AbsInputTooSmall(); /// @notice Emitted when ceiling a number overflows SD59x18. error PRBMathSD59x18__CeilOverflow(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__DivInputTooSmall(); /// @notice Emitted when one of the intermediary unsigned results overflows SD59x18. error PRBMathSD59x18__DivOverflow(uint256 rAbs); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathSD59x18__ExpInputTooBig(int256 x); /// @notice Emitted when the input is greater than 192. error PRBMathSD59x18__Exp2InputTooBig(int256 x); /// @notice Emitted when flooring a number underflows SD59x18. error PRBMathSD59x18__FloorUnderflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMathSD59x18__FromIntOverflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMathSD59x18__FromIntUnderflow(int256 x); /// @notice Emitted when the product of the inputs is negative. error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y); /// @notice Emitted when multiplying the inputs overflows SD59x18. error PRBMathSD59x18__GmOverflow(int256 x, int256 y); /// @notice Emitted when the input is less than or equal to zero. error PRBMathSD59x18__LogInputTooSmall(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__MulInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__MulOverflow(uint256 rAbs); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__PowuOverflow(uint256 rAbs); /// @notice Emitted when the input is negative. error PRBMathSD59x18__SqrtNegativeInput(int256 x); /// @notice Emitted when the calculating the square root overflows SD59x18. error PRBMathSD59x18__SqrtOverflow(int256 x); /// @notice Emitted when addition overflows UD60x18. error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y); /// @notice Emitted when ceiling a number overflows UD60x18. error PRBMathUD60x18__CeilOverflow(uint256 x); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathUD60x18__ExpInputTooBig(uint256 x); /// @notice Emitted when the input is greater than 192. error PRBMathUD60x18__Exp2InputTooBig(uint256 x); /// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18. error PRBMathUD60x18__FromUintOverflow(uint256 x); /// @notice Emitted when multiplying the inputs overflows UD60x18. error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y); /// @notice Emitted when the input is less than 1. error PRBMathUD60x18__LogInputTooSmall(uint256 x); /// @notice Emitted when the calculating the square root overflows UD60x18. error PRBMathUD60x18__SqrtOverflow(uint256 x); /// @notice Emitted when subtraction underflows UD60x18. error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y); /// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library /// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point /// representation. When it does not, it is explicitly mentioned in the NatSpec documentation. library PRBMath { /// STRUCTS /// struct SD59x18 { int256 value; } struct UD60x18 { uint256 value; } /// STORAGE /// /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @dev Largest power of two divisor of SCALE. uint256 internal constant SCALE_LPOTD = 262144; /// @dev SCALE inverted mod 2^256. uint256 internal constant SCALE_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// FUNCTIONS /// /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. /// See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^191 and all magic factors are less than 2^65. if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } // We're doing two things at the same time: // // 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191 // rather than 192. // 2. Convert the result to the unsigned 60.18-decimal fixed-point format. // // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n". result *= SCALE; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { result = prod0 / denominator; } return result; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath__MulDivOverflow(prod1, denominator); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. unchecked { // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 lpotdod = denominator & (~denominator + 1); assembly { // Divide denominator by lpotdod. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one. lpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * lpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /// @notice Calculates floor(x*y÷1e18) with full precision. /// /// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of /// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations: /// 1. x * y = type(uint256).max * SCALE /// 2. (x * y) % SCALE >= SCALE / 2 /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 >= SCALE) { revert PRBMath__MulDivFixedPointOverflow(prod1); } uint256 remainder; uint256 roundUpUnit; assembly { remainder := mulmod(x, y, SCALE) roundUpUnit := gt(remainder, 499999999999999999) } if (prod1 == 0) { unchecked { result = (prod0 / SCALE) + roundUpUnit; return result; } } assembly { result := add( mul( or( div(sub(prod0, remainder), SCALE_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)) ), SCALE_INVERSE ), roundUpUnit ) } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - None of the inputs can be type(int256).min. /// - The result must fit within int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. function mulDivSigned( int256 x, int256 y, int256 denominator ) internal pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath__MulDivSignedInputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 ax; uint256 ay; uint256 ad; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); ad = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of (x*y)÷denominator. The result must fit within int256. uint256 rAbs = mulDiv(ax, ay, ad); if (rAbs > uint256(type(int256).max)) { revert PRBMath__MulDivSignedOverflow(rAbs); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs. // If yes, the result should be negative. result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the least power of two that is greater than or equal to sqrt(x). uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "prb-math/contracts/PRBMath.sol"; import "prb-math/contracts/PRBMathSD59x18.sol"; library SABR { using PRBMathSD59x18 for int256; int256 private constant eps = 1e11; struct IntermediateVariables { int256 a; int256 b; int256 c; int256 d; int256 v; int256 w; int256 z; int256 k; int256 f; int256 t; } function lognormalVol( int256 k, int256 f, int256 t, int256 alpha, int256 beta, int256 rho, int256 volvol ) internal pure returns (int256 iv) { // Hagan's 2002 SABR lognormal vol expansion. // negative strikes or forwards if (k <= 0 || f <= 0) { return 0; } IntermediateVariables memory vars; vars.k = k; vars.f = f; vars.t = t; if (beta == 1e18) { vars.a = 0; vars.v = 0; vars.w = 0; } else { vars.a = ((1e18 - beta).pow(2e18)).mul(alpha.pow(2e18)).div( int256(24e18).mul(_fkbeta(vars.f, vars.k, beta)) ); vars.v = ((1e18 - beta).pow(2e18)).mul(_logfk(vars.f, vars.k).powu(2)).div(24e18); vars.w = ((1e18 - beta).pow(4e18)).mul(_logfk(vars.f, vars.k).powu(4)).div(1920e18); } vars.b = int256(25e16).mul(rho).mul(beta).mul(volvol).mul(alpha).div( _fkbeta(vars.f, vars.k, beta).sqrt() ); vars.c = (2e18 - int256(3e18).mul(rho.powu(2))).mul(volvol.pow(2e18)).div(24e18); vars.d = _fkbeta(vars.f, vars.k, beta).sqrt(); vars.z = volvol.mul(_fkbeta(vars.f, vars.k, beta).sqrt()).mul(_logfk(vars.f, vars.k)).div(alpha); // if |z| > eps if (vars.z.abs() > eps) { int256 vz = alpha.mul(vars.z).mul(1e18 + (vars.a + vars.b + vars.c).mul(vars.t)).div( vars.d.mul(1e18 + vars.v + vars.w).mul(_x(rho, vars.z)) ); return vz; // if |z| <= eps } else { int256 v0 = alpha.mul(1e18 + (vars.a + vars.b + vars.c).mul(vars.t)).div( vars.d.mul(1e18 + vars.v + vars.w) ); return v0; } } function _logfk(int256 f, int256 k) internal pure returns (int256) { return (f.div(k)).ln(); } function _fkbeta( int256 f, int256 k, int256 beta ) internal pure returns (int256) { return (f.mul(k)).pow(1e18 - beta); } function _x(int256 rho, int256 z) internal pure returns (int256) { int256 a = (1e18 - 2 * rho.mul(z) + z.powu(2)).sqrt() + z - rho; int256 b = 1e18 - rho; return (a.div(b)).ln(); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; library Types { struct OptionSeries { uint64 expiration; uint128 strike; bool isPut; address underlying; address strikeAsset; address collateral; } struct PortfolioValues { int256 delta; int256 gamma; int256 vega; int256 theta; int256 callPutsValue; uint256 timestamp; uint256 spotPrice; } struct Order { OptionSeries optionSeries; uint256 amount; uint256 price; uint256 orderExpiry; address buyer; address seriesAddress; uint128 lowerSpotMovementRange; uint128 upperSpotMovementRange; bool isBuyBack; } // strike and expiry date range for options struct OptionParams { uint128 minCallStrikePrice; uint128 maxCallStrikePrice; uint128 minPutStrikePrice; uint128 maxPutStrikePrice; uint128 minExpiry; uint128 maxExpiry; } struct UtilizationState { uint256 totalOptionPrice; //e18 int256 totalDelta; // e18 uint256 collateralToAllocate; //collateral decimals uint256 utilizationBefore; // e18 uint256 utilizationAfter; //e18 uint256 utilizationPrice; //e18 bool isDecreased; uint256 deltaTiltAmount; //e18 uint256 underlyingPrice; // strike asset decimals uint256 iv; // e18 } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
{ "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": { "contracts/libraries/BlackScholes.sol": { "BlackScholes": "0x2c215b6bac6a4871c2e58669f0437853da500020" }, "contracts/libraries/OptionsCompute.sol": { "OptionsCompute": "0x303956bcc420b3b74b861874d39bad5d5ee341f0" } } }
[{"inputs":[{"internalType":"address","name":"_protocol","type":"address"},{"internalType":"address","name":"_strikeAsset","type":"address"},{"internalType":"address","name":"_underlyingAsset","type":"address"},{"internalType":"address","name":"_collateralAsset","type":"address"},{"internalType":"uint256","name":"rfr","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"components":[{"internalType":"uint128","name":"minCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minExpiry","type":"uint128"},{"internalType":"uint128","name":"maxExpiry","type":"uint128"}],"internalType":"struct Types.OptionParams","name":"_optionParams","type":"tuple"},{"internalType":"address","name":"_authority","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CollateralAssetInvalid","type":"error"},{"inputs":[{"internalType":"uint256","name":"quote","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"}],"name":"DeltaQuoteError","type":"error"},{"inputs":[],"name":"IVNotFound","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidDecimals","type":"error"},{"inputs":[],"name":"InvalidShareAmount","type":"error"},{"inputs":[],"name":"IssuanceFailed","type":"error"},{"inputs":[],"name":"LiabilitiesGreaterThanAssets","type":"error"},{"inputs":[],"name":"MaxLiquidityBufferReached","type":"error"},{"inputs":[],"name":"NotHandler","type":"error"},{"inputs":[],"name":"NotKeeper","type":"error"},{"inputs":[],"name":"OptionExpiryInvalid","type":"error"},{"inputs":[],"name":"OptionStrikeInvalid","type":"error"},{"inputs":[],"name":"PRBMathSD59x18__AbsInputTooSmall","type":"error"},{"inputs":[],"name":"PRBMathSD59x18__DivInputTooSmall","type":"error"},{"inputs":[{"internalType":"uint256","name":"rAbs","type":"uint256"}],"name":"PRBMathSD59x18__DivOverflow","type":"error"},{"inputs":[],"name":"PRBMathSD59x18__MulInputTooSmall","type":"error"},{"inputs":[{"internalType":"uint256","name":"rAbs","type":"uint256"}],"name":"PRBMathSD59x18__MulOverflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"prod1","type":"uint256"}],"name":"PRBMath__MulDivFixedPointOverflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"prod1","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath__MulDivOverflow","type":"error"},{"inputs":[],"name":"ReactorAlreadyExists","type":"error"},{"inputs":[],"name":"StrikeAssetInvalid","type":"error"},{"inputs":[],"name":"TradingNotPaused","type":"error"},{"inputs":[],"name":"TradingPaused","type":"error"},{"inputs":[],"name":"UNAUTHORIZED","type":"error"},{"inputs":[],"name":"UnderlyingAssetInvalid","type":"error"},{"inputs":[],"name":"WithdrawExceedsLiquidity","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract IAuthority","name":"authority","type":"address"}],"name":"AuthorityUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"series","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"premium","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"escrowReturned","type":"uint256"},{"indexed":false,"internalType":"address","name":"seller","type":"address"}],"name":"BuybackOption","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"DepositEpochExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"InitiateWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int256","name":"deltaChange","type":"int256"}],"name":"RebalancePortfolioDelta","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"series","type":"address"},{"indexed":false,"internalType":"uint256","name":"collateralReturned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collateralLost","type":"uint256"},{"indexed":false,"internalType":"address","name":"closer","type":"address"}],"name":"SettleVault","type":"event"},{"anonymous":false,"inputs":[],"name":"TradingPaused","type":"event"},{"anonymous":false,"inputs":[],"name":"TradingUnpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"WithdrawalEpochExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"series","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"premium","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"escrow","type":"uint256"},{"indexed":false,"internalType":"address","name":"buyer","type":"address"}],"name":"WriteOption","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"aboveThresholdGradient","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"aboveThresholdYIntercept","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"lpCollateralDifference","type":"uint256"},{"internalType":"bool","name":"addToLpBalance","type":"bool"}],"name":"adjustCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"authority","outputs":[{"internalType":"contract IAuthority","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"belowThresholdGradient","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bidAskIVSpread","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bufferPercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_handler","type":"address"},{"internalType":"bool","name":"auth","type":"bool"}],"name":"changeHandler","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"checkBuffer","outputs":[{"internalType":"int256","name":"bufferRemaining","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralAllocated","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"completeWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"depositEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"depositEpochPricePerShare","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"depositReceipts","outputs":[{"internalType":"uint128","name":"epoch","type":"uint128"},{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"uint256","name":"unredeemedShares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ephemeralDelta","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ephemeralLiabilities","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"executeEpochCalculation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"getBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getExternalDelta","outputs":[{"internalType":"int256","name":"externalDelta","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getHedgingReactors","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"uint256","name":"underlyingPrice","type":"uint256"},{"internalType":"uint256","name":"strikePrice","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"}],"name":"getImpliedVolatility","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNAV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPortfolioDelta","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"handler","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"contract IOptionRegistry","name":"optionRegistry","type":"address"},{"internalType":"address","name":"seriesAddress","type":"address"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"address","name":"seller","type":"address"}],"name":"handlerBuybackOption","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"}],"name":"handlerIssue","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"handlerIssueAndWriteOption","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"},{"internalType":"address","name":"seriesAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"contract IOptionRegistry","name":"optionRegistry","type":"address"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"handlerWriteOption","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"hedgingReactors","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"initiateWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isTradingPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"keeper","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxDiscount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxPriceDeviationThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTimeDeviationThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"optionParams","outputs":[{"internalType":"uint128","name":"minCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minExpiry","type":"uint128"},{"internalType":"uint128","name":"maxExpiry","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"partitionedFunds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pauseTradingAndRequest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_pause","type":"bool"}],"name":"pauseUnpauseTrading","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingWithdrawals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"protocol","outputs":[{"internalType":"contract Protocol","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"toBuy","type":"bool"}],"name":"quotePriceWithUtilizationGreeks","outputs":[{"internalType":"uint256","name":"quote","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"uint256","name":"reactorIndex","type":"uint256"}],"name":"rebalancePortfolioDelta","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_index","type":"uint256"},{"internalType":"bool","name":"_override","type":"bool"}],"name":"removeHedgingReactorAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resetEphemeralValues","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"riskFreeRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IAuthority","name":"_newAuthority","type":"address"}],"name":"setAuthority","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bidAskSpread","type":"uint256"}],"name":"setBidAskSpread","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bufferPercentage","type":"uint256"}],"name":"setBufferPercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_collateralCap","type":"uint256"}],"name":"setCollateralCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_reactorAddress","type":"address"}],"name":"setHedgingReactorAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_keeper","type":"address"},{"internalType":"bool","name":"_auth","type":"bool"}],"name":"setKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxDiscount","type":"uint256"}],"name":"setMaxDiscount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxPriceDeviationThreshold","type":"uint256"}],"name":"setMaxPriceDeviationThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxTimeDeviationThreshold","type":"uint256"}],"name":"setMaxTimeDeviationThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"_newMinCallStrike","type":"uint128"},{"internalType":"uint128","name":"_newMaxCallStrike","type":"uint128"},{"internalType":"uint128","name":"_newMinPutStrike","type":"uint128"},{"internalType":"uint128","name":"_newMaxPutStrike","type":"uint128"},{"internalType":"uint128","name":"_newMinExpiry","type":"uint128"},{"internalType":"uint128","name":"_newMaxExpiry","type":"uint128"}],"name":"setNewOptionParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_riskFreeRate","type":"uint256"}],"name":"setRiskFreeRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_belowThresholdGradient","type":"uint256"},{"internalType":"uint256","name":"_aboveThresholdGradient","type":"uint256"},{"internalType":"uint256","name":"_utilizationFunctionThreshold","type":"uint256"}],"name":"setUtilizationSkewParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"seriesAddress","type":"address"}],"name":"settleVault","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"strikeAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"underlyingAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"utilizationFunctionThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"withdrawalEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"withdrawalEpochPricePerShare","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"withdrawalReceipts","outputs":[{"internalType":"uint128","name":"epoch","type":"uint128"},{"internalType":"uint128","name":"shares","type":"uint128"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
610160604052611388601555600019601755606462000028670de0b6b3a7640000600a62000459565b6200003491906200047b565b601855610258602055670de0b6b3a76400006021556000602255670de0b6b3a7640000602355670853a0d2313c0000602455670853a0d2313c00006025553480156200007f57600080fd5b506040516200698e3803806200698e833981016040819052620000a291620005b1565b80848460128260009080519060200190620000bf9291906200039d565b508151620000d59060019060208501906200039d565b5060ff81166080524660a052620000eb62000301565b60c0525050600680546001600160a01b0319166001600160a01b0384169081179091556040519081527f2f658b440c35314f52658ea8a740e05b284cdc84dc9ae01e891f21b8933e7cad915060200160405180910390a15060016007556008805460ff191690556040805163313ce56760e01b815290516012916001600160a01b0389169163313ce56791600480820192602092909190829003018186803b1580156200019757600080fd5b505afa158015620001ac573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001d2919062000734565b60ff161115620001f557604051630692acc560e51b815260040160405180910390fd5b6001600160a01b0388811661010052601d8690558781166101205286811661014052891660e05281516020838101516001600160801b03928316600160801b918416820217601a5560408501516060860151908416908416820217601b55608085015160a086015190841693160291909117601c556000808052670de0b6b3a76400007fe710864318d4a32f37d6ce54cb3fadbef648dd12d8dbdf53973564d56b7f881c819055600f9092527ff4803e074bd026baaf6ed2e288c9515f68c72fb7216eebdd7cae1718a53ec37591909155600c805491620002d68362000760565b9091555050600d8054906000620002ed8362000760565b91905055505050505050505050506200085f565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f6000604051620003359190620007bb565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b828054620003ab906200077e565b90600052602060002090601f016020900481019282620003cf57600085556200041a565b82601f10620003ea57805160ff19168380011785556200041a565b828001600101855582156200041a579182015b828111156200041a578251825591602001919060010190620003fd565b50620004289291506200042c565b5090565b5b808211156200042857600081556001016200042d565b634e487b7160e01b600052601160045260246000fd5b600081600019048311821515161562000476576200047662000443565b500290565b6000826200049957634e487b7160e01b600052601260045260246000fd5b500490565b80516001600160a01b0381168114620004b657600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715620004fc57620004fc620004bb565b604052919050565b600082601f8301126200051657600080fd5b81516001600160401b03811115620005325762000532620004bb565b602062000548601f8301601f19168201620004d1565b82815285828487010111156200055d57600080fd5b60005b838110156200057d57858101830151828201840152820162000560565b838111156200058f5760008385840101525b5095945050505050565b80516001600160801b0381168114620004b657600080fd5b6000806000806000806000806000898b036101c0811215620005d257600080fd5b620005dd8b6200049e565b9950620005ed60208c016200049e565b9850620005fd60408c016200049e565b97506200060d60608c016200049e565b60808c015160a08d015191985096506001600160401b03808211156200063257600080fd5b620006408e838f0162000504565b965060c08d01519150808211156200065757600080fd5b620006658e838f0162000504565b955060c060df19840112156200067a57600080fd5b604051925060c08301915082821081831117156200069c576200069c620004bb565b50604052620006ae60e08c0162000599565b8152620006bf6101008c0162000599565b6020820152620006d36101208c0162000599565b6040820152620006e76101408c0162000599565b6060820152620006fb6101608c0162000599565b60808201526200070f6101808c0162000599565b60a08201529150620007256101a08b016200049e565b90509295985092959850929598565b6000602082840312156200074757600080fd5b815160ff811681146200075957600080fd5b9392505050565b600060001982141562000777576200077762000443565b5060010190565b600181811c908216806200079357607f821691505b60208210811415620007b557634e487b7160e01b600052602260045260246000fd5b50919050565b600080835481600182811c915080831680620007d857607f831692505b6020808410821415620007f957634e487b7160e01b86526022600452602486fd5b818015620008105760018114620008225762000851565b60ff1986168952848901965062000851565b60008a81526020902060005b86811015620008495781548b8201529085019083016200082e565b505084890196505b509498975050505050505050565b60805160a05160c05160e051610100516101205161014051615fed620009a160003960008181610a2701528181610e2f01528181611a9e01528181611c7f01528181612462015281816124d701528181612b1b0152818161336b0152818161340701528181613af401528181613b3c01528181613dfd01528181613eec015281816141270152818161452c015281816148ef015261499a01526000818161084101528181610fdc0152818161111c015281816111e9015281816135720152818161363f015261417d01526000818161059701528181611004015281816111440152818161120a0152818161359a0152818161366001526141d301526000818161096c01528181612e30015281816130b9015281816131ae0152818161330a0152613b73015260006110d8015260006110a8015260006106330152615fed6000f3fe608060405234801561001057600080fd5b50600436106104c25760003560e01c806370a0823111610278578063b908337b1161015c578063dd62ed3e116100ce578063eaae9f4211610092578063eaae9f4214610bb6578063f3cc699314610bc9578063f589826214610bd2578063f60a61bb14610be5578063f756fa2114610bf8578063f8b2cb4f14610c0057600080fd5b8063dd62ed3e14610b1f578063dfef605e14610b4a578063e1ea1cf514610b6d578063e6d1544014610b80578063e8cf860814610b9357600080fd5b8063cda2dd9a11610120578063cda2dd9a14610acc578063d1b9e85314610ad4578063d2bb18e914610ae7578063d505accf14610af0578063db006a7514610b03578063dc1bee0d14610b1657600080fd5b8063b908337b14610a81578063bdb4246114610a8a578063beca03d514610a9d578063bf7e214f14610aa6578063c0e9b16414610ab957600080fd5b8063923e7657116101f5578063a9059cbb116101b9578063a9059cbb14610a0f578063aabaecd614610a22578063ae7ec18c14610a49578063afd3280814610a5c578063b6b55f2514610a65578063b8b89e1b14610a7857600080fd5b8063923e76571461098e57806393fd25ec1461099757806395d89b41146109a05780639649b0a2146109a8578063992006e4146109fc57600080fd5b80637ecebe001161023c5780637ecebe00146108b9578063802aaa5f146108d95780638456cb59146108e25780638adce2b4146108ea5780638ce744261461096757600080fd5b806370a082311461081c5780637158da7c1461083c5780637a9e5e4b146108635780637d462472146108765780637e108d52146108a657600080fd5b80633a5cd401116103aa5780635c074f441161031c57806367a35e47116102e057806367a35e47146107a057806367e4ac2c146107b35780636834a332146107bb5780636cc69817146107ce5780636cf79126146107e157806370183e0a1461080957600080fd5b80635c074f441461070e5780635c975abb146107175780635cb563ec146107225780636719b2ee1461072b5780636724589e1461078d57600080fd5b80634c9eb2ec1161036e5780634c9eb2ec146106b95780634da2df78146106c25780634e952c26146106ca578063522f4a08146106ea57806354db2f73146106f35780635733af2a146106fb57600080fd5b80633a5cd4011461068b5780633b9d7454146106945780633d1d667c1461069c5780633f2306ab146106a45780633f4ba83a146106b157600080fd5b806317d69bc81161044357806326d127f31161040757806326d127f3146106135780632b371ecf1461061b578063313ce5671461062e5780633185d32b1461066757806334b2c0221461067a5780633644e5151461068357600080fd5b806317d69bc81461059257806318160ddd146105d15780631e4bc557146105da57806321950260146105ed57806323b872dd1461060057600080fd5b80630a67daad1161048a5780630a67daad1461052c5780630b4c0ddf1461054c5780630b75503d1461056157806311fad31214610576578063131f13931461058957600080fd5b80630126c606146104c757806301633407146104e257806303c53893146104eb57806306fdde03146104f4578063095ea7b314610509575b600080fd5b6104cf610c13565b6040519081526020015b60405180910390f35b6104cf60195481565b6104cf60225481565b6104fc610c22565b6040516104d991906150ee565b61051c610517366004615158565b610cb0565b60405190151581526020016104d9565b6104cf61053a366004615184565b600f6020526000908152604090205481565b610554610d1d565b6040516104d9919061519d565b61057461056f3660046151f8565b610d7f565b005b610574610584366004615184565b610dd9565b6104cf60255481565b6105b97f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016104d9565b6104cf60025481565b6105746105e8366004615231565b610de6565b6105b96105fb366004615184565b610e72565b61051c61060e366004615256565b610e9c565b6104cf610f7e565b610574610629366004615184565b61108a565b6106557f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff90911681526020016104d9565b610574610675366004615184565b611097565b6104cf60145481565b6104cf6110a4565b6104cf60095481565b6104cf6110fa565b6105746112ab565b601f5461051c9060ff1681565b61057461161d565b6104cf60205481565b61057461162d565b6104cf6106d8366004615184565b600e6020526000908152604090205481565b6104cf600b5481565b6104cf61165e565b6104cf61070936600461537f565b61177d565b6104cf60125481565b60085460ff1661051c565b6104cf60245481565b6107676107393660046153fe565b601060205260009081526040902080546001909101546001600160801b0380831692600160801b9004169083565b604080516001600160801b039485168152939092166020840152908201526060016104d9565b61057461079b36600461541b565b6117ac565b6104cf6107ae36600461549d565b6117e7565b6104cf61188a565b6105746107c9366004615231565b611894565b6105746107dc3660046153fe565b611b8e565b6107f46107ef3660046154d8565b611cab565b604080519283526020830191909152016104d9565b6105b961081736600461551a565b611e09565b6104cf61082a3660046153fe565b60036020526000908152604090205481565b6105b97f000000000000000000000000000000000000000000000000000000000000000081565b6105746108713660046153fe565b611e24565b610889610884366004615536565b611e80565b604080519283526001600160a01b039091166020830152016104d9565b6105746108b4366004615184565b611f4f565b6104cf6108c73660046153fe565b60056020526000908152604090205481565b6104cf600d5481565b61057461212f565b601a54601b54601c54610925926001600160801b0380821693600160801b928390048216938183169391829004831692818116929091041686565b604080516001600160801b03978816815295871660208701529386169385019390935290841660608401528316608083015290911660a082015260c0016104d9565b6105b97f000000000000000000000000000000000000000000000000000000000000000081565b6104cf60235481565b6104cf60155481565b6104fc61213f565b6109dc6109b63660046153fe565b6011602052600090815260409020546001600160801b0380821691600160801b90041682565b604080516001600160801b039384168152929091166020830152016104d9565b6104cf610a0a3660046153fe565b61214c565b61051c610a1d366004615158565b612261565b6105b97f000000000000000000000000000000000000000000000000000000000000000081565b610574610a57366004615184565b6122c7565b6104cf600a5481565b61051c610a73366004615184565b6122d4565b6104cf60185481565b6104cf60215481565b6104cf610a9836600461558e565b612499565b6104cf60135481565b6006546105b9906001600160a01b031681565b610574610ac7366004615184565b6124c2565b6104cf6124cf565b610574610ae23660046151f8565b61252f565b6104cf60175481565b610574610afe3660046155eb565b612589565b6104cf610b11366004615184565b6127da565b6104cf600c5481565b6104cf610b2d36600461565c565b600460209081526000928352604080842090915290825290205481565b61051c610b583660046153fe565b601e6020526000908152604090205460ff1681565b610574610b7b366004615184565b612836565b610574610b8e366004615184565b612843565b61051c610ba13660046153fe565b60266020526000908152604090205460ff1681565b610574610bc436600461568a565b612850565b6104cf601d5481565b610574610be03660046156a7565b6128c8565b610574610bf33660046156c9565b6129a2565b6104cf6129d2565b6104cf610c0e3660046153fe565b612b4d565b6000610c1d612bd5565b905090565b60008054610c2f906156f5565b80601f0160208091040260200160405190810160405280929190818152602001828054610c5b906156f5565b8015610ca85780601f10610c7d57610100808354040283529160200191610ca8565b820191906000526020600020905b815481529060010190602001808311610c8b57829003601f168201915b505050505081565b3360008181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590610d0b9086815260200190565b60405180910390a35060015b92915050565b60606016805480602002602001604051908101604052809291908181526020018280548015610d7557602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610d57575b5050505050905090565b610d87612c19565b6001600160a01b038216610dae5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b03919091166000908152601e60205260409020805460ff1916911515919091179055565b610de1612cd0565b601855565b6000610df0612e2c565b9050336001600160a01b03821614610e0757600080fd5b8115610e2a578260096000828254610e1f9190615746565b90915550610e6d9050565b610e557f00000000000000000000000000000000000000000000000000000000000000008285612ebf565b8260096000828254610e67919061575d565b90915550505b505050565b60168181548110610e8257600080fd5b6000918252602090912001546001600160a01b0316905081565b6001600160a01b03831660009081526004602090815260408083203384529091528120546000198114610ef857610ed38382615746565b6001600160a01b03861660009081526004602090815260408083203384529091529020555b6001600160a01b03851660009081526003602052604081208054859290610f20908490615746565b90915550506001600160a01b0380851660008181526003602052604090819020805487019055519091871690600080516020615f9883398151915290610f699087815260200190565b60405180910390a360019150505b9392505050565b6000610f88612f3d565b601f805460ff191660011790556040517f02b874a66f7edefaaca8e06ecdb0825247542b983cc7c499a3d7f1bb34e7272890600090a1610fc66130b5565b604051625c253960e41b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f00000000000000000000000000000000000000000000000000000000000000008116602483015291909116906305c2539090604401602060405180830381600087803b15801561105257600080fd5b505af1158015611066573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c1d9190615775565b611092612c19565b601555565b61109f612c19565b602155565b60007f000000000000000000000000000000000000000000000000000000000000000046146110d557610c1d613110565b507f000000000000000000000000000000000000000000000000000000000000000090565b6000806111056130b5565b604051634e133d4d60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f0000000000000000000000000000000000000000000000000000000000000000811660248301529190911690634e133d4d9060440160e06040518083038186803b15801561119057600080fd5b505afa1580156111a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111c8919061578e565b905073303956bcc420b3b74b861874d39bad5d5ee341f06348aec70b61122e7f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000006131aa565b836020546021546040518563ffffffff1660e01b81526004016112549493929190615820565b60006040518083038186803b15801561126c57600080fd5b505af4158015611280573d6000803e3d6000fd5b50505050600b5461128f61165e565b825161129b9190615886565b6112a59190615886565b91505090565b6112b36132c0565b6112bb612f3d565b601f5460ff166112de5760405163dd908f1b60e01b815260040160405180910390fd5b60008060008060006112ee613306565b6001600160a01b03166355676bad600254611307613361565b61130f613550565b6040516001600160e01b031960e086901b16815260048101939093526024830191909152604482015260640160a06040518083038186803b15801561135357600080fd5b505afa158015611367573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061138b91906158c7565b9450945094509450945084600e6000600c548152602001908152602001600020819055506012600090557f0f5bb4b5d20dcb8c06151458c2583d0958b5cc6bead1f07a26f7ee1ef1a5ba7d600c546040516113e891815260200190565b60405180910390a1600c805490600061140083615907565b9091555050601f805460ff191690556040517f2185a7ecc28b84536b7b3d3cf472d9215a2bc8f2302d7331cb56db0a44239f3290600090a161144230846136ec565b801561158e57600060168054806020026020016040519081016040528092919081815260200182805480156114a057602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611482575b5050505050905060005b81518160ff16101561157d57818160ff16815181106114cb576114cb615922565b60200260200101516001600160a01b0316632e1a7d4d846040518263ffffffff1660e01b815260040161150091815260200190565b602060405180830381600087803b15801561151a57600080fd5b505af115801561152e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115529190615775565b61155c9084615746565b92506000831161156b5761157d565b8061157581615938565b9150506114aa565b50811561158c57505050505050565b505b600d546000908152600f60205260408120859055601480548492906115b490849061575d565b9091555050600d546040519081527f14605f088644076934e95d93264603055260cbb14ab846609ecd0153ec2842ad9060200160405180910390a16115fb30601354613746565b60006013819055600d80549161161083615907565b919050555050505050505b565b6116256137a8565b61161b613879565b6116356130b5565b6001600160a01b0316336001600160a01b03161461165257600080fd5b6000600a819055600b55565b60008060168054806020026020016040519081016040528092919081815260200182805480156116b757602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611699575b5050505050905060005b81518160ff16101561177857818160ff16815181106116e2576116e2615922565b60200260200101516001600160a01b031663c549176e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561172257600080fd5b505afa158015611736573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061175a9190615775565b6117649084615886565b92508061177081615938565b9150506116c1565b505090565b60006117876138cb565b61178f6138ef565b61179e8888888888888861391f565b90505b979650505050505050565b6117b4612cd0565b6001600160801b03958616600160801b958716860217601a55928516918516840291909117601b55831692160217601c55565b60006117f1613b6f565b6040516367a35e4760e01b815286151560048201526024810186905260448101859052606481018490526001600160a01b0391909116906367a35e479060840160206040518083038186803b15801561184957600080fd5b505afa15801561185d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118819190615775565b95945050505050565b6000610c1d613361565b61189c612c19565b600060168054806020026020016040519081016040528092919081815260200182805480156118f457602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116118d6575b50505050509050600081848151811061190f5761190f615922565b6020026020010151905082611a995760008190506000816001600160a01b031663c549176e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561195e57600080fd5b505afa158015611972573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119969190615775565b90508015611a1a5760405163fbaac11560e01b8152600481018290526001600160a01b0383169063fbaac11590602401602060405180830381600087803b1580156119e057600080fd5b505af11580156119f4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a189190615775565b505b604051632e1a7d4d60e01b815260001960048201526001600160a01b03831690632e1a7d4d90602401602060405180830381600087803b158015611a5d57600080fd5b505af1158015611a71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a959190615775565b5050505b611ac57f0000000000000000000000000000000000000000000000000000000000000000826000612ebf565b600060018351611ad59190615746565b9050845b81811015611b535783611aed82600161575d565b81518110611afd57611afd615922565b602002602001015160168281548110611b1857611b18615922565b600091825260209091200180546001600160a01b0319166001600160a01b039290921691909117905580611b4b81615907565b915050611ad9565b506016805480611b6557611b65615958565b600082815260209020810160001990810180546001600160a01b03191690550190555050505050565b611b96612c19565b6001600160a01b038116611bbd5760405163e6c4247b60e01b815260040160405180910390fd5b60165460005b81811015611c2e57826001600160a01b031660168281548110611be857611be8615922565b6000918252602090912001546001600160a01b03161415611c1c576040516305de9c7760e11b815260040160405180910390fd5b80611c2681615907565b915050611bc3565b50601680546001810182556000919091527fd833147d7dc355ba459fc788f669e58cfaf9dc25ddcd0702e87d69c7b51242890180546001600160a01b0319166001600160a01b038416179055611ca77f000000000000000000000000000000000000000000000000000000000000000083600019612ebf565b5050565b600080611d066040518061014001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581526020016000815260200160008152602001600081525090565b611d18866060015187608001516131aa565b6101008201819052604087015160208801518851611d4a93916001600160801b03169067ffffffffffffffff166117e7565b81610120018181525050600080611d738887601954601d54876101200151886101000151613bca565b9092509050611d828288613d1c565b8352611d8e8188613d28565b6020840152611d9f83898989613ded565b611da98387613f70565b9450611dbb858461010001518a6140d5565b9450826020015193508460001480611dd1575083155b15611dfe576040516330cf3a1360e21b815260048101869052602481018590526044015b60405180910390fd5b505050935093915050565b6000611e136138ef565b610d1782611e1f612e2c565b614123565b611e2c612c19565b600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f2f658b440c35314f52658ea8a740e05b284cdc84dc9ae01e891f21b8933e7cad9060200160405180910390a150565b600080611e8b6138cb565b611e936138ef565b6000611e9d612e2c565b90506000611eab8983614123565b60405163dac9675b60e01b81526001600160a01b0380831660048301529192509083169063dac9675b9060240160c06040518083038186803b158015611ef057600080fd5b505afa158015611f04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f28919061596e565b9850611f4189828a858b8b611f3b6124cf565b8c614462565b999098509650505050505050565b611f576132c0565b60026007541415611f7a5760405162461bcd60e51b8152600401611df590615a27565b600260075580611f9d57604051638c88122d60e01b815260040160405180910390fd5b33600090815260106020908152604091829020825160608101845281546001600160801b038082168352600160801b9091041692810183905260019091015492810192909252151580611ff4575060008160400151115b1561200657612004600019614740565b505b6000612010613306565b60405163625f849b60e11b8152336004820152602481018590526001600160a01b03919091169063c4bf0936906044016040805180830381600087803b15801561205957600080fd5b505af115801561206d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120919190615ad1565b33600090815260116020908152604082208351918401516001600160801b03908116600160801b0292169190911790556013805492935085929091906120d890849061575d565b9091555050600d546040517f0c53c82ad07e2d592d88ece3b066777dd60f1118e2a081b380efc4358f0d9e2a916121129133918791615aed565b60405180910390a16121243084612261565b505060016007555050565b6121376137a8565b61161b61488d565b60018054610c2f906156f5565b6000612156612f3d565b600080612161612e2c565b604051636a256b2960e01b81526001600160a01b0386811660048301529190911690636a256b2990602401608060405180830381600087803b1580156121a657600080fd5b505af11580156121ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121de9190615b0e565b50604080516001600160a01b03891681526020810184905290810182905233606082015291945092507f3c6fbb57d229454c2441564ffff38b57852db9295bb7794d55f399901f5758a9915060800160405180910390a161224282826000806148ca565b80600960008282546122549190615746565b9091555091949350505050565b33600090815260036020526040812080548391908390612282908490615746565b90915550506001600160a01b03831660008181526003602052604090819020805485019055513390600080516020615f9883398151915290610d0b9086815260200190565b6122cf612cd0565b601955565b60006122de6132c0565b600260075414156123015760405162461bcd60e51b8152600401611df590615a27565b6002600755816123245760405163162908e360e11b815260040160405180910390fd5b60008061232f613306565b6040516311f9fbc960e21b8152336004820152602481018690526001600160a01b0391909116906347e7ef24906044016040805180830381600087803b15801561237857600080fd5b505af115801561238c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123b09190615b4d565b915091507f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a153385600c546040516123e993929190615aed565b60405180910390a160408051606081018252600c546001600160801b03908116825284811660208084019182528385018681523360009081526010909252948120935191518316600160801b029190921617825591516001909101556012805486929061245790849061575d565b9091555061248990507f0000000000000000000000000000000000000000000000000000000000000000333087614a26565b6001925050506001600755919050565b60006124a36138cb565b6124ab6138ef565b61179e8888888888886124bc6124cf565b89614462565b6124ca612c19565b602055565b6000806124fb7f0000000000000000000000000000000000000000000000000000000000000000612b4d565b905060006127106015546009546125129190615b71565b61251c9190615ba6565b90506125288183615bba565b9250505090565b612537612c19565b6001600160a01b03821661255e5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b03919091166000908152602660205260409020805460ff1916911515919091179055565b428410156125d95760405162461bcd60e51b815260206004820152601760248201527f5045524d49545f444541444c494e455f455850495245440000000000000000006044820152606401611df5565b60006125e36110a4565b6001600160a01b0389811660008181526005602090815260409182902080546001810190915582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98184015280840194909452938c166060840152608083018b905260a083019390935260c08083018a90528151808403909101815260e08301909152805192019190912061190160f01b6101008301526101028201929092526101228101919091526101420160408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa1580156126fc573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116158015906127325750886001600160a01b0316816001600160a01b0316145b61276f5760405162461bcd60e51b815260206004820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152606401611df5565b6001600160a01b0390811660009081526004602090815260408083208b8516808552908352928190208a905551898152919350918a16917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a350505050505050565b6000600260075414156127ff5760405162461bcd60e51b8152600401611df590615a27565b60026007558161282257604051638c88122d60e01b815260040160405180910390fd5b61282b82614740565b600160075592915050565b61283e612c19565b601d55565b61284b612c19565b601755565b6128586137a8565b601f805460ff1916821580159190911790915561289b576040517f02b874a66f7edefaaca8e06ecdb0825247542b983cc7c499a3d7f1bb34e7272890600090a150565b6040517f2185a7ecc28b84536b7b3d3cf472d9215a2bc8f2302d7331cb56db0a44239f3290600090a15b50565b6128d0612cd0565b601681815481106128e3576128e3615922565b60009182526020909120015460405163fbaac11560e01b8152600481018490526001600160a01b039091169063fbaac11590602401602060405180830381600087803b15801561293257600080fd5b505af1158015612946573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061296a9190615775565b506040518281527faf0f1d052fd7370209dd6c5557bc9c6e0249ea04840a1a09bdc7ac76fb60585d9060200160405180910390a15050565b6129aa612cd0565b602283905560238290556129c86129c18484615746565b8290613d1c565b6024556025555050565b60006129dc6132c0565b600260075414156129ff5760405162461bcd60e51b8152600401611df590615a27565b600260075560008080612a10613306565b60405163bf3b826b60e01b81523360048201526001600160a01b03919091169063bf3b826b90602401608060405180830381600087803b158015612a5357600080fd5b505af1158015612a67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a8b9190615bf9565b336000818152601160209081526040918290208451918501516001600160801b03908116600160801b0292169190911790555193965091945092507ff279e6a1f5e320cca91135676d9cb6e44ca8a08c0b88342bcdb1144f6511b56891612af6919086908690615aed565b60405180910390a18260146000828254612b109190615746565b90915550612b4190507f00000000000000000000000000000000000000000000000000000000000000003385614ac0565b50506001600755919050565b6014546040516370a0823160e01b8152306004820152600091906001600160a01b038416906370a082319060240160206040518083038186803b158015612b9357600080fd5b505afa158015612ba7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bcb9190615775565b610d179190615746565b600080612be0613361565b90506000612bec613550565b905080821215612c0f576040516307e42e3b60e21b815260040160405180910390fd5b6125288183615bba565b600660009054906101000a90046001600160a01b03166001600160a01b0316630c340a246040518163ffffffff1660e01b815260040160206040518083038186803b158015612c6757600080fd5b505afa158015612c7b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c9f9190615c2f565b6001600160a01b0316336001600160a01b03161461161b5760405163075fd2b160e01b815260040160405180910390fd5b600660009054906101000a90046001600160a01b03166001600160a01b031663481c6a756040518163ffffffff1660e01b815260040160206040518083038186803b158015612d1e57600080fd5b505afa158015612d32573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d569190615c2f565b6001600160a01b0316336001600160a01b031614158015612e0e5750600660009054906101000a90046001600160a01b03166001600160a01b0316630c340a246040518163ffffffff1660e01b815260040160206040518083038186803b158015612dc057600080fd5b505afa158015612dd4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612df89190615c2f565b6001600160a01b0316336001600160a01b031614155b1561161b5760405163075fd2b160e01b815260040160405180910390fd5b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633b4567b06040518163ffffffff1660e01b815260040160206040518083038186803b158015612e8757600080fd5b505afa158015612e9b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c1d9190615c2f565b600060405163095ea7b360e01b81526001600160a01b03841660048201528260248201526000806044836000895af1915050612efa81614b39565b612f375760405162461bcd60e51b815260206004820152600e60248201526d1054141493d59157d1905253115160921b6044820152606401611df5565b50505050565b3360009081526026602052604090205460ff16158015612ff45750600660009054906101000a90046001600160a01b03166001600160a01b0316630c340a246040518163ffffffff1660e01b815260040160206040518083038186803b158015612fa657600080fd5b505afa158015612fba573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fde9190615c2f565b6001600160a01b0316336001600160a01b031614155b80156130975750600660009054906101000a90046001600160a01b03166001600160a01b031663481c6a756040518163ffffffff1660e01b815260040160206040518083038186803b15801561304957600080fd5b505afa15801561305d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130819190615c2f565b6001600160a01b0316336001600160a01b031614155b1561161b57604051631ea2564f60e31b815260040160405180910390fd5b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635fb480c96040518163ffffffff1660e01b815260040160206040518083038186803b158015612e8757600080fd5b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60006040516131429190615c4c565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663741bef1a6040518163ffffffff1660e01b815260040160206040518083038186803b15801561320557600080fd5b505afa158015613219573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061323d9190615c2f565b60405163051ce29b60e21b81526001600160a01b038581166004830152848116602483015291909116906314738a6c9060440160206040518083038186803b15801561328857600080fd5b505afa15801561329c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f779190615775565b60085460ff161561161b5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606401611df5565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639624e83e6040518163ffffffff1660e01b815260040160206040518083038186803b158015612e8757600080fd5b60006134026009547f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156133c257600080fd5b505afa1580156133d6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133fa9190615ce8565b60ff16614b80565b61342b7f0000000000000000000000000000000000000000000000000000000000000000614bbc565b613435919061575d565b90506000601680548060200260200160405190810160405280929190818152602001828054801561348f57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613471575b5050505050905060005b81518160ff16101561177857818160ff16815181106134ba576134ba615922565b60200260200101516001600160a01b031663b7aa436d6040518163ffffffff1660e01b815260040160206040518083038186803b1580156134fa57600080fd5b505afa15801561350e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135329190615775565b61353c908461575d565b92508061354881615938565b915050613499565b60008061355b6130b5565b604051634e133d4d60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f0000000000000000000000000000000000000000000000000000000000000000811660248301529190911690634e133d4d9060440160e06040518083038186803b1580156135e657600080fd5b505afa1580156135fa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061361e919061578e565b905073303956bcc420b3b74b861874d39bad5d5ee341f06348aec70b6136847f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000006131aa565b836020546021546040518563ffffffff1660e01b81526004016136aa9493929190615820565b60006040518083038186803b1580156136c257600080fd5b505af41580156136d6573d6000803e3d6000fd5b50505050600a5481608001516112a59190615886565b80600260008282546136fe919061575d565b90915550506001600160a01b038216600081815260036020908152604080832080548601905551848152600080516020615f9883398151915291015b60405180910390a35050565b6001600160a01b0382166000908152600360205260408120805483929061376e908490615746565b90915550506002805482900390556040518181526000906001600160a01b03841690600080516020615f988339815191529060200161373a565b60065460405163794f111b60e11b81523360048201526001600160a01b039091169063f29e22369060240160206040518083038186803b1580156137eb57600080fd5b505afa1580156137ff573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138239190615d05565b158015612e0e5750600660009054906101000a90046001600160a01b03166001600160a01b0316630c340a246040518163ffffffff1660e01b815260040160206040518083038186803b158015612dc057600080fd5b613881614c80565b6008805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b601f5460ff161561161b5760405163015c3a5360e11b815260040160405180910390fd5b336000908152601e602052604090205460ff1661161b57604051634690abc160e11b815260040160405180910390fd5b60006139a885876139a38a896001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561396357600080fd5b505afa158015613977573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061399b9190615ce8565b60ff16614cc9565b612ebf565b60405163e49280cb60e01b81526001600160a01b038681166004830152602482018990526000919088169063e49280cb906044016040805180830381600087803b1580156139f557600080fd5b505af1158015613a09573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a2d9190615d22565b604080516001600160a01b038a81168252602082018d90528183018a9052606082018490528716608082015290519193507fe988243c7383c2c950aab9b716103bb6d91f015900ef405467025fbdc3fe1ecd925081900360a00190a1613ad389602001516001600160801b0316876001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156133c257600080fd5b6001600160801b031660208a0152613aee81868660006148ca565b84613b187f0000000000000000000000000000000000000000000000000000000000000000612b4d565b1015613b375760405163b84beb5d60e01b815260040160405180910390fd5b613b627f00000000000000000000000000000000000000000000000000000000000000008487614ac0565b5095979650505050505050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663128e414b6040518163ffffffff1660e01b815260040160206040518083038186803b158015612e8757600080fd5b60008083613beb576040516304485c2d60e41b815260040160405180910390fd5b8615613c1b57670de0b6b3a7640000613c048782615746565b613c0e9086615b71565b613c189190615ba6565b93505b42886000015167ffffffffffffffff1611613c49576040516366bfac3d60e01b815260040160405180910390fd5b602088015188516040808b0151905163d98ac76960e01b8152600481018790526001600160801b03909316602484015267ffffffffffffffff90911660448301526064820186905260848201879052151560a4820152732c215b6bac6a4871c2e58669f0437853da5000209063d98ac7699060c401604080518083038186803b158015613cd557600080fd5b505af4158015613ce9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d0d9190615b4d565b90999098509650505050505050565b6000610f778383614cfd565b6000600160ff1b831480613d3f5750600160ff1b82145b15613d5d57604051630d01a11b60e21b815260040160405180910390fd5b60008060008512613d6e5784613d73565b846000035b915060008412613d835783613d88565b836000035b90506000613d968383614cfd565b90506001600160ff1b03811115613dc35760405163bf79e8d960e01b815260048101829052602401611df5565b600019808713908613808218600114613ddc5782613de1565b826000035b98975050505050505050565b80613f6357600954613e32613e217f0000000000000000000000000000000000000000000000000000000000000000612b4d565b613e2b908361575d565b8290614dbf565b60608601526020840151613e4c906402540be40090615d50565b6001600160801b03166020850152613e62612e2c565b6001600160a01b0316632e79bf4285856040518363ffffffff1660e01b8152600401613e8f929190615dd3565b60206040518083038186803b158015613ea757600080fd5b505afa158015613ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613edf9190615775565b6040860152613f30613f107f0000000000000000000000000000000000000000000000000000000000000000612b4d565b613f1a908361575d565b828760400151613f2a919061575d565b90614dbf565b6080860181905260608601518651602554602254602354602454613f58969493929190614dd4565b60a086015250612f37565b835160a085015250505050565b600080613f7b6110fa565b9050600083613f98576020850151613f939083615bba565b613fa7565b6020850151613fa79083615886565b90506000613fb483614f1e565b613fbd83614f1e565b613fc79190615bba565b1260c086015261010085015160009061400a90613fe690613f2a612bd5565b613f2a614005671bc16d674ec80000613fff8789615886565b90614f5a565b614f1e565b9050601854811161401b578061401f565b6018545b60e087015260c08601511561407f578461405a5760a086015160e087015161404691613d1c565b8660a001516140559190615746565b614078565b60a086015160e087015161406e9082613d1c565b614078919061575d565b93506140cc565b846140a75760a086015160e08701516140989082613d1c565b6140a2919061575d565b6140c9565b60a086015160e08701516140ba91613d1c565b8660a001516140c99190615746565b93505b50505092915050565b60008160a001516001600160a01b031682608001516001600160a01b03161461411c578261410b85670de0b6b3a7640000615b71565b6141159190615ba6565b9050610f77565b5082610f77565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168360a001516001600160a01b03161461417b57604051639d3b9e0160e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031683606001516001600160a01b0316146141d15760405163bff9e44560e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031683608001516001600160a01b0316146142275760405163b3e8cda760e01b815260040160405180910390fd5b6040805160c081018252601a546001600160801b038082168352600160801b9182900481166020840152601b54808216948401949094529281900483166060830152601c548084166080840181905291900490921660a08201528451909167ffffffffffffffff9091169061429c904261575d565b11806142c9575060a08101516142bb906001600160801b03164261575d565b845167ffffffffffffffff16115b156142e7576040516366bfac3d60e01b815260040160405180910390fd5b8360400151156143555783602001516001600160801b031681604001516001600160801b03161180614332575080606001516001600160801b031684602001516001600160801b0316115b156143505760405163e04ba97560e01b815260040160405180910390fd5b6143b4565b83602001516001600160801b031681600001516001600160801b03161180614396575080602001516001600160801b031684602001516001600160801b0316115b156143b45760405163e04ba97560e01b815260040160405180910390fd5b604051635fb708cf60e01b81526001600160a01b03841690635fb708cf906143e0908790600401615dee565b602060405180830381600087803b1580156143fa57600080fd5b505af115801561440e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144329190615c2f565b91506001600160a01b03821661445b5760405163ecdc661560e01b815260040160405180910390fd5b5092915050565b600080866001600160a01b0316632e79bf428b8a6040518363ffffffff1660e01b8152600401614493929190615dd3565b60206040518083038186803b1580156144ab57600080fd5b505afa1580156144bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144e39190615775565b905080841215614506576040516301b2115160e61b815260040160405180910390fd5b60405163095ea7b360e01b81526001600160a01b038881166004830152602482018390527f0000000000000000000000000000000000000000000000000000000000000000169063095ea7b390604401602060405180830381600087803b15801561457057600080fd5b505af1158015614584573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906145a89190615d05565b506040516389a86ad360e01b81526001600160a01b038816906389a86ad3906145d9908c908c908690600401615aed565b6040805180830381600087803b1580156145f257600080fd5b505af1158015614606573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061462a9190615d22565b604080516001600160a01b038d81168252602082018d90528183018b9052606082018490528716608082015290519193507f807243a06aa6324afb44b093c16090c302133c76a8ce9f9ba4f74cdae3c0f2b0925081900360a00190a16146d08a602001516001600160801b03168a6001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156133c257600080fd5b6001600160801b031660208b01526146eb81878760016148ca565b614732898461472d8b8d6001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561396357600080fd5b614ac0565b509598975050505050505050565b600080600061474d613306565b6040516301e9a69560e41b8152336004820152602481018690526001600160a01b039190911690631e9a695090604401608060405180830381600087803b15801561479757600080fd5b505af11580156147ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906147cf9190615dfc565b9150915081600014156147e6575060009392505050565b3360008181526010602090815260408083208551868401516001600160801b03908116600160801b02918116919091178255868301516001909201919091553084526004835281842085855283529281902086905584518151948552918401869052911682820152517fe5b754fb1abb7f01b499791d0b820ae3b6af3424ac1c59768edb53f4ec31a9299181900360600190a1614884303384610e9c565b50909392505050565b6148956132c0565b6008805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586138ae3390565b801561497b5783600960008282546148e2919061575d565b92505081905550614946837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156133c257600080fd5b600a60008282546149579190615886565b9250508190555081600b60008282546149709190615bba565b90915550612f379050565b836009600082825461498d9190615746565b925050819055506149f1837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156133c257600080fd5b600a6000828254614a029190615bba565b9250508190555081600b6000828254614a1b9190615886565b909155505050505050565b600084905060006040516323b872dd60e01b81526001600160a01b03861660048201526001600160a01b03851660248201528360448201526000806064836000875af1915050614a7581614b39565b614ab85760405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606401611df5565b505050505050565b600060405163a9059cbb60e01b81526001600160a01b03841660048201528260248201526000806044836000895af1915050614afb81614b39565b612f375760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401611df5565b60003d82614b4b57806000803e806000fd5b8060208114614b63578015614b745760009250614b79565b816000803e60005115159250614b79565b600192505b5050919050565b60006012821115614b9057600080fd5b6000614b9d836012615746565b9050614baa81600a615f75565b614bb49085615b71565b949350505050565b6014546040516370a0823160e01b8152306004820152600091610d17916001600160a01b038516906370a082319060240160206040518083038186803b158015614c0557600080fd5b505afa158015614c19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614c3d9190615775565b614c479190615746565b836001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156133c257600080fd5b60085460ff1661161b5760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401611df5565b60006012821115614cd957600080fd5b6000614ce6836012615746565b9050614cf381600a615f75565b614bb49085615ba6565b60008080600019848609848602925082811083820303915050670de0b6b3a76400008110614d415760405163698d9a0160e11b815260048101829052602401611df5565b600080670de0b6b3a76400008688099150506706f05b59d3b1ffff811182614d7b5780670de0b6b3a7640000850401945050505050610d17565b620400008285030493909111909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690201905092915050565b6000610f7783670de0b6b3a764000084615020565b6000848811158015614de65750848711155b15614e2b576000614e0d671bc16d674ec80000613f2a87614e078c8e61575d565b90613d1c565b9050614e198782613d1c565b614e23908861575d565b9150506117a1565b848810158015614e3b5750848710155b15614e6d57600082614e63671bc16d674ec80000613f2a614e5c8c8e61575d565b8890613d1c565b614e0d9190615746565b6000614e86614e7c878a615746565b613f2a8b89615746565b90506000614ea486614e07671bc16d674ec80000613f2a8e8c61575d565b9050600084614ec587614e07671bc16d674ec800008c8f613f2a919061575d565b614ecf9190615746565b90506000614efd614ee885670de0b6b3a764000061575d565b83614ef38787613d1c565b613f2a919061575d565b9050614f098a82613d1c565b614f13908b61575d565b9450505050506117a1565b6000600160ff1b821415614f4557604051631d0742e360e21b815260040160405180910390fd5b60008212614f535781610d17565b5060000390565b6000600160ff1b831480614f715750600160ff1b82145b15614f8f5760405163b3c754a360e01b815260040160405180910390fd5b60008060008512614fa05784614fa5565b846000035b915060008412614fb55783614fba565b836000035b90506000614fd183670de0b6b3a764000084615020565b90506001600160ff1b03811115614ffe57604051637cb4bef560e01b815260048101829052602401611df5565b6000198087139086138082186001146150175782613de1565b613de183615f81565b60008080600019858709858702925082811083820303915050806000141561505b5783828161505157615051615b90565b0492505050610f77565b83811061508557604051631dcf306360e21b81526004810182905260248101859052604401611df5565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600060208083528351808285015260005b8181101561511b578581018301518582016040015282016150ff565b8181111561512d576000604083870101525b50601f01601f1916929092016040019392505050565b6001600160a01b03811681146128c557600080fd5b6000806040838503121561516b57600080fd5b823561517681615143565b946020939093013593505050565b60006020828403121561519657600080fd5b5035919050565b6020808252825182820181905260009190848201906040850190845b818110156151de5783516001600160a01b0316835292840192918401916001016151b9565b50909695505050505050565b80151581146128c557600080fd5b6000806040838503121561520b57600080fd5b823561521681615143565b91506020830135615226816151ea565b809150509250929050565b6000806040838503121561524457600080fd5b823591506020830135615226816151ea565b60008060006060848603121561526b57600080fd5b833561527681615143565b9250602084013561528681615143565b929592945050506040919091013590565b67ffffffffffffffff811681146128c557600080fd5b6001600160801b03811681146128c557600080fd5b600060c082840312156152d457600080fd5b60405160c0810181811067ffffffffffffffff8211171561530557634e487b7160e01b600052604160045260246000fd5b604052905080823561531681615297565b81526020830135615326816152ad565b60208201526040830135615339816151ea565b6040820152606083013561534c81615143565b6060820152608083013561535f81615143565b608082015260a083013561537281615143565b60a0919091015292915050565b6000806000806000806000610180888a03121561539b57600080fd5b6153a589896152c2565b965060c0880135955060e08801356153bc81615143565b94506101008801356153cd81615143565b9350610120880135925061014088013591506101608801356153ee81615143565b8091505092959891949750929550565b60006020828403121561541057600080fd5b8135610f7781615143565b60008060008060008060c0878903121561543457600080fd5b863561543f816152ad565b9550602087013561544f816152ad565b9450604087013561545f816152ad565b9350606087013561546f816152ad565b9250608087013561547f816152ad565b915060a087013561548f816152ad565b809150509295509295509295565b600080600080608085870312156154b357600080fd5b84356154be816151ea565b966020860135965060408601359560600135945092505050565b600080600061010084860312156154ee57600080fd5b6154f885856152c2565b925060c0840135915060e084013561550f816151ea565b809150509250925092565b600060c0828403121561552c57600080fd5b610f7783836152c2565b6000806000806000610140868803121561554f57600080fd5b61555987876152c2565b945060c0860135935060e08601359250610100860135915061012086013561558081615143565b809150509295509295909350565b6000806000806000806000610180888a0312156155aa57600080fd5b6155b489896152c2565b965060c08801356155c481615143565b955060e088013594506101008801356153cd81615143565b60ff811681146128c557600080fd5b600080600080600080600060e0888a03121561560657600080fd5b873561561181615143565b9650602088013561562181615143565b95506040880135945060608801359350608088013561563f816155dc565b9699959850939692959460a0840135945060c09093013592915050565b6000806040838503121561566f57600080fd5b823561567a81615143565b9150602083013561522681615143565b60006020828403121561569c57600080fd5b8135610f77816151ea565b600080604083850312156156ba57600080fd5b50508035926020909101359150565b6000806000606084860312156156de57600080fd5b505081359360208301359350604090920135919050565b600181811c9082168061570957607f821691505b6020821081141561572a57634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b60008282101561575857615758615730565b500390565b6000821982111561577057615770615730565b500190565b60006020828403121561578757600080fd5b5051919050565b600060e082840312156157a057600080fd5b60405160e0810181811067ffffffffffffffff821117156157d157634e487b7160e01b600052604160045260246000fd5b8060405250825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c08201528091505092915050565b60006101408201905085825284516020830152602085015160408301526040850151606083015260608501516080830152608085015160a083015260a085015160c083015260c085015160e0830152836101008301528261012083015295945050505050565b600080821280156001600160ff1b03849003851316156158a8576158a8615730565b600160ff1b83900384128116156158c1576158c1615730565b50500190565b600080600080600060a086880312156158df57600080fd5b5050835160208501516040860151606087015160809097015192989197509594509092509050565b600060001982141561591b5761591b615730565b5060010190565b634e487b7160e01b600052603260045260246000fd5b600060ff821660ff81141561594f5761594f615730565b60010192915050565b634e487b7160e01b600052603160045260246000fd5b600060c0828403121561598057600080fd5b60405160c0810181811067ffffffffffffffff821117156159b157634e487b7160e01b600052604160045260246000fd5b60405282516159bf81615297565b815260208301516159cf816152ad565b602082015260408301516159e2816151ea565b604082015260608301516159f581615143565b60608201526080830151615a0881615143565b608082015260a0830151615a1b81615143565b60a08201529392505050565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b600060408284031215615a7057600080fd5b6040516040810181811067ffffffffffffffff82111715615aa157634e487b7160e01b600052604160045260246000fd5b80604052508091508251615ab4816152ad565b81526020830151615ac4816152ad565b6020919091015292915050565b600060408284031215615ae357600080fd5b610f778383615a5e565b6001600160a01b039390931683526020830191909152604082015260600190565b60008060008060808587031215615b2457600080fd5b8451615b2f816151ea565b60208601516040870151606090970151919890975090945092505050565b60008060408385031215615b6057600080fd5b505080516020909101519092909150565b6000816000190483118215151615615b8b57615b8b615730565b500290565b634e487b7160e01b600052601260045260246000fd5b600082615bb557615bb5615b90565b500490565b60008083128015600160ff1b850184121615615bd857615bd8615730565b6001600160ff1b0384018313811615615bf357615bf3615730565b50500390565b600080600060808486031215615c0e57600080fd5b8351925060208401519150615c268560408601615a5e565b90509250925092565b600060208284031215615c4157600080fd5b8151610f7781615143565b600080835481600182811c915080831680615c6857607f831692505b6020808410821415615c8857634e487b7160e01b86526022600452602486fd5b818015615c9c5760018114615cad57615cda565b60ff19861689528489019650615cda565b60008a81526020902060005b86811015615cd25781548b820152908501908301615cb9565b505084890196505b509498975050505050505050565b600060208284031215615cfa57600080fd5b8151610f77816155dc565b600060208284031215615d1757600080fd5b8151610f77816151ea565b60008060408385031215615d3557600080fd5b8251615d40816151ea565b6020939093015192949293505050565b60006001600160801b0380841680615d6a57615d6a615b90565b92169190910492915050565b805167ffffffffffffffff1682526020808201516001600160801b0316908301526040808201511515908301526060808201516001600160a01b039081169184019190915260808083015182169084015260a09182015116910152565b60e08101615de18285615d76565b8260c08301529392505050565b60c08101610d178284615d76565b6000808284036080811215615e1057600080fd5b835192506060601f1982011215615e2657600080fd5b506040516060810181811067ffffffffffffffff82111715615e5857634e487b7160e01b600052604160045260246000fd5b6040526020840151615e69816152ad565b81526040840151615e79816152ad565b60208201526060939093015160408401525092909150565b600181815b80851115615ecc578160001904821115615eb257615eb2615730565b80851615615ebf57918102915b93841c9390800290615e96565b509250929050565b600082615ee357506001610d17565b81615ef057506000610d17565b8160018114615f065760028114615f1057615f2c565b6001915050610d17565b60ff841115615f2157615f21615730565b50506001821b610d17565b5060208310610133831016604e8410600b8410161715615f4f575081810a610d17565b615f598383615e91565b8060001904821115615f6d57615f6d615730565b029392505050565b6000610f778383615ed4565b6000600160ff1b821415614f5357614f5361573056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220c3798692a393bdb732d180f703c8376d35d403c74717e23c753064dff0e49d2e64736f6c6343000809003300000000000000000000000008674f64dac31f36828b63a4468a3ac3c68db5b2000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc800000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000001b1ae4d6e2ef50000000000000000000000000000000000000000000000000010f0cf064dd5920000000000000000000000000000000000000000000000000001b1ae4d6e2ef50000000000000000000000000000000000000000000000000010f0cf064dd592000000000000000000000000000000000000000000000000000000000000000093a80000000000000000000000000000000000000000000000000000000000076a7000000000000000000000000000c83e447dc7f4045b8717d5321056d4e9e86dcd200000000000000000000000000000000000000000000000000000000000000115279736b20444856204554482f55534443000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a7279555344432d45544800000000000000000000000000000000000000000000
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000008674f64dac31f36828b63a4468a3ac3c68db5b2000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc800000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000001b1ae4d6e2ef50000000000000000000000000000000000000000000000000010f0cf064dd5920000000000000000000000000000000000000000000000000001b1ae4d6e2ef50000000000000000000000000000000000000000000000000010f0cf064dd592000000000000000000000000000000000000000000000000000000000000000093a80000000000000000000000000000000000000000000000000000000000076a7000000000000000000000000000c83e447dc7f4045b8717d5321056d4e9e86dcd200000000000000000000000000000000000000000000000000000000000000115279736b20444856204554482f55534443000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a7279555344432d45544800000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : _protocol (address): 0x08674f64dac31f36828b63a4468a3ac3c68db5b2
Arg [1] : _strikeAsset (address): 0xff970a61a04b1ca14834a43f5de4533ebddb5cc8
Arg [2] : _underlyingAsset (address): 0x82af49447d8a07e3bd95bd0d56f35241523fbab1
Arg [3] : _collateralAsset (address): 0xff970a61a04b1ca14834a43f5de4533ebddb5cc8
Arg [4] : rfr (uint256): 0
Arg [5] : name (string): Rysk DHV ETH/USDC
Arg [6] : symbol (string): ryUSDC-ETH
Arg [7] : _optionParams (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]
Arg [8] : _authority (address): 0x0c83e447dc7f4045b8717d5321056d4e9e86dcd2
-----Encoded View---------------
18 Constructor Arguments found :
Arg [0] : 00000000000000000000000008674f64dac31f36828b63a4468a3ac3c68db5b2
Arg [1] : 000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc8
Arg [2] : 00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1
Arg [3] : 000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc8
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [5] : 00000000000000000000000000000000000000000000000000000000000001c0
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000200
Arg [7] : 00000000000000000000000000000000000000000000001b1ae4d6e2ef500000
Arg [8] : 00000000000000000000000000000000000000000000010f0cf064dd59200000
Arg [9] : 00000000000000000000000000000000000000000000001b1ae4d6e2ef500000
Arg [10] : 00000000000000000000000000000000000000000000010f0cf064dd59200000
Arg [11] : 0000000000000000000000000000000000000000000000000000000000093a80
Arg [12] : 000000000000000000000000000000000000000000000000000000000076a700
Arg [13] : 0000000000000000000000000c83e447dc7f4045b8717d5321056d4e9e86dcd2
Arg [14] : 0000000000000000000000000000000000000000000000000000000000000011
Arg [15] : 5279736b20444856204554482f55534443000000000000000000000000000000
Arg [16] : 000000000000000000000000000000000000000000000000000000000000000a
Arg [17] : 7279555344432d45544800000000000000000000000000000000000000000000
Age | Block | Fee Address | BC Fee Address | Voting Power | Jailed | Incoming |
---|
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.