{ "language": "Solidity", "sources": { "contracts/libraries/VaultLifecycleTreasuryBare.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nimport {SafeMath} from \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {Vault} from \"./Vault.sol\";\nimport {ShareMath} from \"./ShareMath.sol\";\nimport {IStrikeSelection} from \"../interfaces/IRibbon.sol\";\nimport {GnosisAuction} from \"./GnosisAuction.sol\";\nimport {DateTime} from \"./DateTime.sol\";\nimport {\n IOtokenFactory,\n IOtoken,\n IController,\n GammaTypes\n} from \"../interfaces/GammaInterface.sol\";\nimport {IERC20Detailed} from \"../interfaces/IERC20Detailed.sol\";\nimport {IGnosisAuction} from \"../interfaces/IGnosisAuction.sol\";\nimport {SupportsNonCompliantERC20} from \"./SupportsNonCompliantERC20.sol\";\n\nlibrary VaultLifecycleTreasuryBare {\n using SafeMath for uint256;\n using SupportsNonCompliantERC20 for IERC20;\n\n struct CloseParams {\n address OTOKEN_FACTORY;\n address USDC;\n address currentOption;\n uint256 delay;\n uint16 lastStrikeOverrideRound;\n uint256 overriddenStrikePrice;\n uint256 period;\n }\n\n /**\n * @notice Initialization parameters for the vault.\n * @param _owner is the owner of the vault with critical permissions\n * @param _feeRecipient is the address to recieve vault performance and management fees\n * @param _managementFee is the management fee pct.\n * @param _performanceFee is the perfomance fee pct.\n * @param _tokenName is the name of the token\n * @param _tokenSymbol is the symbol of the token\n * @param _optionsPremiumPricer is the address of the contract with the\n black-scholes premium calculation logic\n * @param _strikeSelection is the address of the contract with strike selection logic\n * @param _premiumDiscount is the vault's discount applied to the premium\n * @param _auctionDuration is the duration of the gnosis auction\n * @param _period is the period between each option sales\n */\n struct InitParams {\n address _owner;\n address _keeper;\n address _feeRecipient;\n uint256 _managementFee;\n uint256 _performanceFee;\n string _tokenName;\n string _tokenSymbol;\n address _optionsPremiumPricer;\n address _strikeSelection;\n uint32 _premiumDiscount;\n uint256 _auctionDuration;\n uint256 _period;\n uint256 _maxDepositors;\n uint256 _minDeposit;\n }\n\n /**\n * @notice Sets the next option the vault will be shorting, and calculates its premium for the auction\n * @param strikeSelection is the address of the contract with strike selection logic\n * @param optionsPremiumPricer is the address of the contract with the\n black-scholes premium calculation logic\n * @param premiumDiscount is the vault's discount applied to the premium\n * @param closeParams is the struct with details on previous option and strike selection details\n * @param vaultParams is the struct with vault general data\n * @param vaultState is the struct with vault accounting state\n * @return otokenAddress is the address of the new option\n * @return premium is the premium of the new option\n * @return strikePrice is the strike price of the new option\n * @return delta is the delta of the new option\n */\n function commitAndClose(\n address strikeSelection,\n address optionsPremiumPricer,\n uint256 premiumDiscount,\n CloseParams calldata closeParams,\n Vault.VaultParams storage vaultParams,\n Vault.VaultState storage vaultState\n )\n external\n returns (\n address otokenAddress,\n uint256 premium,\n uint256 strikePrice,\n uint256 delta\n )\n {\n uint256 expiry;\n\n // uninitialized state\n if (closeParams.currentOption == address(0)) {\n expiry = getNextExpiry(block.timestamp, closeParams.period);\n } else {\n expiry = getNextExpiry(\n IOtoken(closeParams.currentOption).expiryTimestamp(),\n closeParams.period\n );\n }\n\n bool isPut = vaultParams.isPut;\n address underlying = vaultParams.underlying;\n address asset = vaultParams.asset;\n\n (strikePrice, delta) = closeParams.lastStrikeOverrideRound ==\n vaultState.round\n ? (closeParams.overriddenStrikePrice, 0)\n : IStrikeSelection(strikeSelection).getStrikePrice(expiry, isPut);\n\n require(strikePrice != 0, \"!strikePrice\");\n\n // retrieve address if option already exists, or deploy it\n otokenAddress = getOrDeployOtoken(\n closeParams,\n vaultParams,\n underlying,\n asset,\n strikePrice,\n expiry,\n isPut\n );\n\n // get the black scholes premium of the option\n premium = optionsPremiumPricer == address(1)\n ? 1\n : GnosisAuction.getOTokenPremiumInStables(\n otokenAddress,\n optionsPremiumPricer,\n premiumDiscount\n );\n\n require(premium > 0, \"!premium\");\n\n return (otokenAddress, premium, strikePrice, delta);\n }\n\n /**\n * @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes\n * @param otokenAddress is the address of the otoken\n * @param vaultParams is the struct with vault general data\n * @param collateralAsset is the address of the collateral asset\n * @param USDC is the address of usdc\n * @param delay is the delay between commitAndClose and rollToNextOption\n */\n function verifyOtoken(\n address otokenAddress,\n Vault.VaultParams storage vaultParams,\n address collateralAsset,\n address USDC,\n uint256 delay\n ) private view {\n require(otokenAddress != address(0), \"!otokenAddress\");\n\n IOtoken otoken = IOtoken(otokenAddress);\n require(otoken.isPut() == vaultParams.isPut, \"Type mismatch\");\n require(\n otoken.underlyingAsset() == vaultParams.underlying,\n \"Wrong underlyingAsset\"\n );\n require(\n otoken.collateralAsset() == collateralAsset,\n \"Wrong collateralAsset\"\n );\n\n // we just assume all options use USDC as the strike\n require(otoken.strikeAsset() == USDC, \"strikeAsset != USDC\");\n\n uint256 readyAt = block.timestamp.add(delay);\n require(otoken.expiryTimestamp() >= readyAt, \"Expiry before delay\");\n }\n\n /**\n * @param currentShareSupply is the supply of the shares invoked with totalSupply()\n * @param asset is the address of the vault's asset\n * @param decimals is the decimals of the asset\n * @param lastQueuedWithdrawAmount is the amount queued for withdrawals from last round\n * @param managementFee is the management fee percent to charge on the AUM\n */\n struct RolloverParams {\n uint256 decimals;\n uint256 totalBalance;\n uint256 currentShareSupply;\n uint256 lastQueuedWithdrawAmount;\n uint256 managementFee;\n }\n\n /**\n * @notice Calculate the shares to mint, new price per share, and\n amount of funds to re-allocate as collateral for the new round\n * @param vaultState is the storage variable vaultState passed from RibbonVault\n * @param params is the rollover parameters passed to compute the next state\n * @return newLockedAmount is the amount of funds to allocate for the new round\n * @return queuedWithdrawAmount is the amount of funds set aside for withdrawal\n * @return newPricePerShare is the price per share of the new round\n * @return mintShares is the amount of shares to mint from deposits\n * @return managementFeeInAsset is the amount of management fee charged by vault\n */\n function rollover(\n Vault.VaultState storage vaultState,\n RolloverParams calldata params\n )\n external\n view\n returns (\n uint256 newLockedAmount,\n uint256 queuedWithdrawAmount,\n uint256 newPricePerShare,\n uint256 mintShares,\n uint256 managementFeeInAsset\n )\n {\n uint256 currentBalance = params.totalBalance;\n uint256 pendingAmount = vaultState.totalPending;\n uint256 queuedWithdrawShares = vaultState.queuedWithdrawShares;\n\n uint256 balanceForVaultFees;\n {\n uint256 pricePerShareBeforeFee =\n ShareMath.pricePerShare(\n params.currentShareSupply,\n currentBalance,\n pendingAmount,\n params.decimals\n );\n\n uint256 queuedWithdrawBeforeFee =\n params.currentShareSupply > 0\n ? ShareMath.sharesToAsset(\n queuedWithdrawShares,\n pricePerShareBeforeFee,\n params.decimals\n )\n : 0;\n\n // Deduct the difference between the newly scheduled withdrawals\n // and the older withdrawals\n // so we can charge them fees before they leave\n uint256 withdrawAmountDiff =\n queuedWithdrawBeforeFee > params.lastQueuedWithdrawAmount\n ? queuedWithdrawBeforeFee.sub(\n params.lastQueuedWithdrawAmount\n )\n : 0;\n\n balanceForVaultFees = currentBalance\n .sub(queuedWithdrawBeforeFee)\n .add(withdrawAmountDiff);\n }\n\n managementFeeInAsset = getManagementFee(\n balanceForVaultFees,\n vaultState.totalPending,\n params.managementFee\n );\n\n // Take into account the fee\n // so we can calculate the newPricePerShare\n currentBalance = currentBalance.sub(managementFeeInAsset);\n\n {\n newPricePerShare = ShareMath.pricePerShare(\n params.currentShareSupply,\n currentBalance,\n pendingAmount,\n params.decimals\n );\n\n // After closing the short, if the options expire in-the-money\n // vault pricePerShare would go down because vault's asset balance decreased.\n // This ensures that the newly-minted shares do not take on the loss.\n mintShares = ShareMath.assetToShares(\n pendingAmount,\n newPricePerShare,\n params.decimals\n );\n\n uint256 newSupply = params.currentShareSupply.add(mintShares);\n\n queuedWithdrawAmount = newSupply > 0\n ? ShareMath.sharesToAsset(\n queuedWithdrawShares,\n newPricePerShare,\n params.decimals\n )\n : 0;\n }\n\n return (\n currentBalance.sub(queuedWithdrawAmount), // new locked balance subtracts the queued withdrawals\n queuedWithdrawAmount,\n newPricePerShare,\n mintShares,\n managementFeeInAsset\n );\n }\n\n /**\n * @notice Creates the actual Opyn short position by depositing collateral and minting otokens\n * @param gammaController is the address of the opyn controller contract\n * @param marginPool is the address of the opyn margin contract which holds the collateral\n * @param oTokenAddress is the address of the otoken to mint\n * @param depositAmount is the amount of collateral to deposit\n * @return the otoken mint amount\n */\n function createShort(\n address gammaController,\n address marginPool,\n address oTokenAddress,\n uint256 depositAmount\n ) external returns (uint256) {\n IController controller = IController(gammaController);\n uint256 newVaultID =\n (controller.getAccountVaultCounter(address(this))).add(1);\n\n // An otoken's collateralAsset is the vault's `asset`\n // So in the context of performing Opyn short operations we call them collateralAsset\n IOtoken oToken = IOtoken(oTokenAddress);\n address collateralAsset = oToken.collateralAsset();\n\n uint256 collateralDecimals =\n uint256(IERC20Detailed(collateralAsset).decimals());\n uint256 mintAmount;\n\n if (oToken.isPut()) {\n // For minting puts, there will be instances where the full depositAmount will not be used for minting.\n // This is because of an issue with precision.\n //\n // For ETH put options, we are calculating the mintAmount (10**8 decimals) using\n // the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down.\n // As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens.\n //\n // For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens.\n // We retain the dust in the vault so the calling contract can withdraw the\n // actual locked amount + dust at settlement.\n //\n // To test this behavior, we can console.log\n // MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault)\n // to see how much dust (or excess collateral) is left behind.\n mintAmount = depositAmount\n .mul(10**Vault.OTOKEN_DECIMALS)\n .mul(10**18) // we use 10**18 to give extra precision\n .div(oToken.strikePrice().mul(10**(10 + collateralDecimals)));\n } else {\n mintAmount = depositAmount;\n\n if (collateralDecimals > 8) {\n uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals\n if (mintAmount > scaleBy) {\n mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8\n }\n }\n }\n\n // double approve to fix non-compliant ERC20s\n IERC20 collateralToken = IERC20(collateralAsset);\n collateralToken.safeApproveNonCompliant(marginPool, depositAmount);\n\n IController.ActionArgs[] memory actions =\n new IController.ActionArgs[](3);\n\n actions[0] = IController.ActionArgs(\n IController.ActionType.OpenVault,\n address(this), // owner\n address(this), // receiver\n address(0), // asset, otoken\n newVaultID, // vaultId\n 0, // amount\n 0, //index\n \"\" //data\n );\n\n actions[1] = IController.ActionArgs(\n IController.ActionType.DepositCollateral,\n address(this), // owner\n address(this), // address to transfer from\n collateralAsset, // deposited asset\n newVaultID, // vaultId\n depositAmount, // amount\n 0, //index\n \"\" //data\n );\n\n actions[2] = IController.ActionArgs(\n IController.ActionType.MintShortOption,\n address(this), // owner\n address(this), // address to transfer to\n oTokenAddress, // option address\n newVaultID, // vaultId\n mintAmount, // amount\n 0, //index\n \"\" //data\n );\n\n controller.operate(actions);\n\n return mintAmount;\n }\n\n /**\n * @notice Close the existing short otoken position. Currently this implementation is simple.\n * It closes the most recent vault opened by the contract. This assumes that the contract will\n * only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by\n calling SettleVault action, this assumption should hold.\n * @param gammaController is the address of the opyn controller contract\n * @return amount of collateral redeemed from the vault\n */\n function settleShort(address gammaController) external returns (uint256) {\n IController controller = IController(gammaController);\n\n // gets the currently active vault ID\n uint256 vaultID = controller.getAccountVaultCounter(address(this));\n\n GammaTypes.Vault memory vault =\n controller.getVault(address(this), vaultID);\n\n require(vault.shortOtokens.length > 0, \"No short\");\n\n // An otoken's collateralAsset is the vault's `asset`\n // So in the context of performing Opyn short operations we call them collateralAsset\n IERC20 collateralToken = IERC20(vault.collateralAssets[0]);\n\n // The short position has been previously closed, or all the otokens have been burned.\n // So we return early.\n if (address(collateralToken) == address(0)) {\n return 0;\n }\n\n // This is equivalent to doing IERC20(vault.asset).balanceOf(address(this))\n uint256 startCollateralBalance =\n collateralToken.balanceOf(address(this));\n\n // If it is after expiry, we need to settle the short position using the normal way\n // Delete the vault and withdraw all remaining collateral from the vault\n IController.ActionArgs[] memory actions =\n new IController.ActionArgs[](1);\n\n actions[0] = IController.ActionArgs(\n IController.ActionType.SettleVault,\n address(this), // owner\n address(this), // address to transfer to\n address(0), // not used\n vaultID, // vaultId\n 0, // not used\n 0, // not used\n \"\" // not used\n );\n\n controller.operate(actions);\n\n uint256 endCollateralBalance = collateralToken.balanceOf(address(this));\n\n return endCollateralBalance.sub(startCollateralBalance);\n }\n\n /**\n * @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple.\n * It calls the `Redeem` action to claim the payout.\n * @param gammaController is the address of the opyn controller contract\n * @param oldOption is the address of the old option\n * @param asset is the address of the vault's asset\n * @return amount of asset received by exercising the option\n */\n function settleLong(\n address gammaController,\n address oldOption,\n address asset\n ) external returns (uint256) {\n IController controller = IController(gammaController);\n\n uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this));\n\n if (controller.getPayout(oldOption, oldOptionBalance) == 0) {\n return 0;\n }\n\n uint256 startAssetBalance = IERC20(asset).balanceOf(address(this));\n\n // If it is after expiry, we need to redeem the profits\n IController.ActionArgs[] memory actions =\n new IController.ActionArgs[](1);\n\n actions[0] = IController.ActionArgs(\n IController.ActionType.Redeem,\n address(0), // not used\n address(this), // address to send profits to\n oldOption, // address of otoken\n 0, // not used\n oldOptionBalance, // otoken balance\n 0, // not used\n \"\" // not used\n );\n\n controller.operate(actions);\n\n uint256 endAssetBalance = IERC20(asset).balanceOf(address(this));\n\n return endAssetBalance.sub(startAssetBalance);\n }\n\n /**\n * @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple.\n * It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will\n * only have a single vault open at any given time.\n * @param gammaController is the address of the opyn controller contract\n * @param currentOption is the address of the current option\n * @return amount of collateral redeemed by burning otokens\n */\n function burnOtokens(address gammaController, address currentOption)\n external\n returns (uint256)\n {\n uint256 numOTokensToBurn =\n IERC20(currentOption).balanceOf(address(this));\n\n require(numOTokensToBurn > 0, \"No oTokens to burn\");\n\n IController controller = IController(gammaController);\n\n // gets the currently active vault ID\n uint256 vaultID = controller.getAccountVaultCounter(address(this));\n\n GammaTypes.Vault memory vault =\n controller.getVault(address(this), vaultID);\n\n require(vault.shortOtokens.length > 0, \"No short\");\n\n IERC20 collateralToken = IERC20(vault.collateralAssets[0]);\n\n uint256 startCollateralBalance =\n collateralToken.balanceOf(address(this));\n\n // Burning `amount` of oTokens from the ribbon vault,\n // then withdrawing the corresponding collateral amount from the vault\n IController.ActionArgs[] memory actions =\n new IController.ActionArgs[](2);\n\n actions[0] = IController.ActionArgs(\n IController.ActionType.BurnShortOption,\n address(this), // owner\n address(this), // address to transfer from\n address(vault.shortOtokens[0]), // otoken address\n vaultID, // vaultId\n numOTokensToBurn, // amount\n 0, //index\n \"\" //data\n );\n\n actions[1] = IController.ActionArgs(\n IController.ActionType.WithdrawCollateral,\n address(this), // owner\n address(this), // address to transfer to\n address(collateralToken), // withdrawn asset\n vaultID, // vaultId\n vault.collateralAmounts[0].mul(numOTokensToBurn).div(\n vault.shortAmounts[0]\n ), // amount\n 0, //index\n \"\" //data\n );\n\n controller.operate(actions);\n\n uint256 endCollateralBalance = collateralToken.balanceOf(address(this));\n\n return endCollateralBalance.sub(startCollateralBalance);\n }\n\n /**\n * @notice Calculates the management fee for this week's round\n * @param currentBalance is the balance of funds held on the vault after closing short\n * @param pendingAmount is the pending deposit amount\n * @param managementFeePercent is the management fee pct.\n * @return managementFeeInAsset is the management fee\n */\n function getManagementFee(\n uint256 currentBalance,\n uint256 pendingAmount,\n uint256 managementFeePercent\n ) internal pure returns (uint256 managementFeeInAsset) {\n // At the first round, currentBalance=0, pendingAmount>0\n // so we just do not charge anything on the first round\n uint256 lockedBalanceSansPending =\n currentBalance > pendingAmount\n ? currentBalance.sub(pendingAmount)\n : 0;\n\n uint256 _managementFeeInAsset;\n\n // Always charge management fee regardless of whether the vault is\n // making a profit from the previous options sale\n _managementFeeInAsset = managementFeePercent > 0\n ? lockedBalanceSansPending.mul(managementFeePercent).div(\n 100 * Vault.FEE_MULTIPLIER\n )\n : 0;\n\n return _managementFeeInAsset;\n }\n\n /**\n * @notice Either retrieves the option token if it already exists, or deploy it\n * @param closeParams is the struct with details on previous option and strike selection details\n * @param vaultParams is the struct with vault general data\n * @param underlying is the address of the underlying asset of the option\n * @param collateralAsset is the address of the collateral asset of the option\n * @param strikePrice is the strike price of the option\n * @param expiry is the expiry timestamp of the option\n * @param isPut is whether the option is a put\n * @return the address of the option\n */\n function getOrDeployOtoken(\n CloseParams calldata closeParams,\n Vault.VaultParams storage vaultParams,\n address underlying,\n address collateralAsset,\n uint256 strikePrice,\n uint256 expiry,\n bool isPut\n ) internal returns (address) {\n IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY);\n\n address otokenFromFactory =\n factory.getOtoken(\n underlying,\n closeParams.USDC,\n collateralAsset,\n strikePrice,\n expiry,\n isPut\n );\n\n if (otokenFromFactory != address(0)) {\n return otokenFromFactory;\n }\n\n address otoken =\n factory.createOtoken(\n underlying,\n closeParams.USDC,\n collateralAsset,\n strikePrice,\n expiry,\n isPut\n );\n\n verifyOtoken(\n otoken,\n vaultParams,\n collateralAsset,\n closeParams.USDC,\n closeParams.delay\n );\n\n return otoken;\n }\n\n /**\n * @notice Starts the gnosis auction\n * @param auctionDetails is the struct with all the custom parameters of the auction\n * @return the auction id of the newly created auction\n */\n function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails)\n external\n returns (uint256)\n {\n return GnosisAuction.startAuction(auctionDetails);\n }\n\n /**\n * @notice Settles the gnosis auction\n * @param gnosisEasyAuction is the contract address of Gnosis easy auction protocol\n * @param auctionID is the auction ID of the gnosis easy auction\n */\n function settleAuction(address gnosisEasyAuction, uint256 auctionID)\n internal\n {\n IGnosisAuction(gnosisEasyAuction).settleAuction(auctionID);\n }\n\n /**\n * @notice Places a bid in an auction\n * @param bidDetails is the struct with all the details of the\n bid including the auction's id and how much to bid\n */\n function placeBid(GnosisAuction.BidDetails calldata bidDetails)\n external\n returns (\n uint256 sellAmount,\n uint256 buyAmount,\n uint64 userId\n )\n {\n return GnosisAuction.placeBid(bidDetails);\n }\n\n /**\n * @notice Claims the oTokens belonging to the vault\n * @param auctionSellOrder is the sell order of the bid\n * @param gnosisEasyAuction is the address of the gnosis auction contract\n holding custody to the funds\n * @param counterpartyThetaVault is the address of the counterparty theta\n vault of this delta vault\n */\n function claimAuctionOtokens(\n Vault.AuctionSellOrder calldata auctionSellOrder,\n address gnosisEasyAuction,\n address counterpartyThetaVault\n ) external {\n GnosisAuction.claimAuctionOtokens(\n auctionSellOrder,\n gnosisEasyAuction,\n counterpartyThetaVault\n );\n }\n\n /**\n * @notice Verify the constructor params satisfy requirements\n * @param _initParams is the initialization parameter including owner, keeper, etc.\n * @param _vaultParams is the struct with vault general data\n */\n function verifyInitializerParams(\n InitParams calldata _initParams,\n Vault.VaultParams calldata _vaultParams,\n uint256 _min_auction_duration\n ) external pure {\n require(_initParams._owner != address(0), \"!_owner\");\n require(_initParams._keeper != address(0), \"!_keeper\");\n require(_initParams._feeRecipient != address(0), \"!_feeRecipient\");\n require(\n _initParams._performanceFee < 100 * Vault.FEE_MULTIPLIER,\n \"performanceFee >= 100%\"\n );\n require(\n _initParams._managementFee < 100 * Vault.FEE_MULTIPLIER,\n \"managementFee >= 100%\"\n );\n require(bytes(_initParams._tokenName).length > 0, \"!_tokenName\");\n require(bytes(_initParams._tokenSymbol).length > 0, \"!_tokenSymbol\");\n require(\n (_initParams._period == 7) ||\n (_initParams._period == 14) ||\n (_initParams._period == 30) ||\n (_initParams._period == 90) ||\n (_initParams._period == 180),\n \"!_period\"\n );\n require(\n _initParams._optionsPremiumPricer != address(0),\n \"!_optionsPremiumPricer\"\n );\n require(\n _initParams._strikeSelection != address(0),\n \"!_strikeSelection\"\n );\n require(\n _initParams._premiumDiscount > 0 &&\n _initParams._premiumDiscount <\n 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER,\n \"!_premiumDiscount\"\n );\n require(\n _initParams._auctionDuration >= _min_auction_duration,\n \"!_auctionDuration\"\n );\n require(_initParams._maxDepositors > 0, \"!_maxDepositors\");\n require(_initParams._minDeposit > 0, \"!_minDeposit\");\n\n require(_vaultParams.asset != address(0), \"!asset\");\n require(_vaultParams.underlying != address(0), \"!underlying\");\n require(_vaultParams.minimumSupply > 0, \"!minimumSupply\");\n require(_vaultParams.cap > 0, \"!cap\");\n require(\n _vaultParams.cap > _vaultParams.minimumSupply,\n \"cap has to be higher than minimumSupply\"\n );\n }\n\n /**\n * @notice Gets the next options expiry timestamp, this function should be called\n when there is sufficient guard to ensure valid period\n * @param timestamp is the expiry timestamp of the current option\n * @param period is no. of days in between option sales. Available periods are: \n * 7(1w), 14(2w), 30(1m), 90(3m), 180(6m)\n */\n function getNextExpiry(uint256 timestamp, uint256 period)\n internal\n pure\n returns (uint256 nextExpiry)\n {\n if (period == 7) {\n nextExpiry = DateTime.getNextFriday(timestamp);\n nextExpiry = nextExpiry <= timestamp\n ? nextExpiry + 1 weeks\n : nextExpiry;\n } else if (period == 14) {\n nextExpiry = DateTime.getNextFriday(timestamp);\n nextExpiry = nextExpiry <= timestamp\n ? nextExpiry + 2 weeks\n : nextExpiry;\n } else if (period == 30) {\n nextExpiry = DateTime.getMonthLastFriday(timestamp);\n nextExpiry = nextExpiry <= timestamp\n ? DateTime.getMonthLastFriday(nextExpiry + 1 weeks)\n : nextExpiry;\n } else if (period == 90) {\n nextExpiry = DateTime.getQuarterLastFriday(timestamp);\n nextExpiry = nextExpiry <= timestamp\n ? DateTime.getQuarterLastFriday(nextExpiry + 1 weeks)\n : nextExpiry;\n } else if (period == 180) {\n nextExpiry = DateTime.getBiannualLastFriday(timestamp);\n nextExpiry = nextExpiry <= timestamp\n ? DateTime.getBiannualLastFriday(nextExpiry + 1 weeks)\n : nextExpiry;\n }\n\n nextExpiry = nextExpiry - (nextExpiry % (24 hours)) + (8 hours);\n }\n}\n" }, "@openzeppelin/contracts/utils/math/SafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n// CAUTION\n// This version of SafeMath should only be used with Solidity 0.8 or later,\n// because it relies on the compiler's built in overflow checks.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations.\n *\n * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler\n * now has built in overflow checking.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n return a + b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n return a * b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator.\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b <= a, errorMessage);\n return a - b;\n }\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b > 0, errorMessage);\n return a / b;\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b > 0, errorMessage);\n return a % b;\n }\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" }, "contracts/libraries/Vault.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nlibrary Vault {\n /************************************************\n * IMMUTABLES & CONSTANTS\n ***********************************************/\n\n // Fees are 6-decimal places. For example: 20 * 10**6 = 20%\n uint256 internal constant FEE_MULTIPLIER = 10**6;\n\n // Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount.\n uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10;\n\n // Otokens have 8 decimal places.\n uint256 internal constant OTOKEN_DECIMALS = 8;\n\n // Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10%\n uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2;\n\n // Placeholder uint value to prevent cold writes\n uint256 internal constant PLACEHOLDER_UINT = 1;\n\n struct VaultParams {\n // Option type the vault is selling\n bool isPut;\n // Token decimals for vault shares\n uint8 decimals;\n // Asset used in Theta / Delta Vault\n address asset;\n // Underlying asset of the options sold by vault\n address underlying;\n // Minimum supply of the vault shares issued, for ETH it's 10**10\n uint56 minimumSupply;\n // Vault cap\n uint104 cap;\n }\n\n struct OptionState {\n // Option that the vault is shorting / longing in the next cycle\n address nextOption;\n // Option that the vault is currently shorting / longing\n address currentOption;\n // The timestamp when the `nextOption` can be used by the vault\n uint32 nextOptionReadyAt;\n }\n\n struct VaultState {\n // 32 byte slot 1\n // Current round number. `round` represents the number of `period`s elapsed.\n uint16 round;\n // Amount that is currently locked for selling options\n uint104 lockedAmount;\n // Amount that was locked for selling options in the previous round\n // used for calculating performance fee deduction\n uint104 lastLockedAmount;\n // 32 byte slot 2\n // Stores the total tally of how much of `asset` there is\n // to be used to mint rTHETA tokens\n uint128 totalPending;\n // Total amount of queued withdrawal shares from previous rounds (doesn't include the current round)\n uint128 queuedWithdrawShares;\n }\n\n struct DepositReceipt {\n // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.\n uint16 round;\n // Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit\n uint104 amount;\n // Unredeemed shares balance\n uint128 unredeemedShares;\n }\n\n struct Withdrawal {\n // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.\n uint16 round;\n // Number of shares withdrawn\n uint128 shares;\n }\n\n struct AuctionSellOrder {\n // Amount of `asset` token offered in auction\n uint96 sellAmount;\n // Amount of oToken requested in auction\n uint96 buyAmount;\n // User Id of delta vault in latest gnosis auction\n uint64 userId;\n }\n}\n" }, "contracts/libraries/ShareMath.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nimport {SafeMath} from \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\nimport {Vault} from \"./Vault.sol\";\n\nlibrary ShareMath {\n using SafeMath for uint256;\n\n uint256 internal constant PLACEHOLDER_UINT = 1;\n\n function assetToShares(\n uint256 assetAmount,\n uint256 assetPerShare,\n uint256 decimals\n ) internal pure returns (uint256) {\n // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet\n // which should never happen.\n // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.\n require(assetPerShare > PLACEHOLDER_UINT, \"Invalid assetPerShare\");\n\n return assetAmount.mul(10**decimals).div(assetPerShare);\n }\n\n function sharesToAsset(\n uint256 shares,\n uint256 assetPerShare,\n uint256 decimals\n ) internal pure returns (uint256) {\n // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet\n // which should never happen.\n // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.\n require(assetPerShare > PLACEHOLDER_UINT, \"Invalid assetPerShare\");\n\n return shares.mul(assetPerShare).div(10**decimals);\n }\n\n /**\n * @notice Returns the shares unredeemed by the user given their DepositReceipt\n * @param depositReceipt is the user's deposit receipt\n * @param currentRound is the `round` stored on the vault\n * @param assetPerShare is the price in asset per share\n * @param decimals is the number of decimals the asset/shares use\n * @return unredeemedShares is the user's virtual balance of shares that are owed\n */\n function getSharesFromReceipt(\n Vault.DepositReceipt memory depositReceipt,\n uint256 currentRound,\n uint256 assetPerShare,\n uint256 decimals\n ) internal pure returns (uint256 unredeemedShares) {\n if (depositReceipt.round > 0 && depositReceipt.round < currentRound) {\n uint256 sharesFromRound =\n assetToShares(depositReceipt.amount, assetPerShare, decimals);\n\n return\n uint256(depositReceipt.unredeemedShares).add(sharesFromRound);\n }\n return depositReceipt.unredeemedShares;\n }\n\n function pricePerShare(\n uint256 totalSupply,\n uint256 totalBalance,\n uint256 pendingAmount,\n uint256 decimals\n ) internal pure returns (uint256) {\n uint256 singleShare = 10**decimals;\n return\n totalSupply > 0\n ? singleShare.mul(totalBalance.sub(pendingAmount)).div(\n totalSupply\n )\n : singleShare;\n }\n\n /************************************************\n * HELPERS\n ***********************************************/\n\n function assertUint104(uint256 num) internal pure {\n require(num <= type(uint104).max, \"Overflow uint104\");\n }\n\n function assertUint128(uint256 num) internal pure {\n require(num <= type(uint128).max, \"Overflow uint128\");\n }\n}\n" }, "contracts/interfaces/IRibbon.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\nimport {Vault} from \"../libraries/Vault.sol\";\n\ninterface IRibbonVault {\n function deposit(uint256 amount) external;\n\n function depositETH() external payable;\n\n function cap() external view returns (uint256);\n\n function depositFor(uint256 amount, address creditor) external;\n\n function vaultParams() external view returns (Vault.VaultParams memory);\n}\n\ninterface IStrikeSelection {\n function getStrikePrice(uint256 expiryTimestamp, bool isPut)\n external\n view\n returns (uint256, uint256);\n\n function delta() external view returns (uint256);\n}\n\ninterface IOptionsPremiumPricer {\n function getPremium(\n uint256 strikePrice,\n uint256 timeToExpiry,\n bool isPut\n ) external view returns (uint256);\n\n function getPremiumInStables(\n uint256 strikePrice,\n uint256 timeToExpiry,\n bool isPut\n ) external view returns (uint256);\n\n function getOptionDelta(\n uint256 spotPrice,\n uint256 strikePrice,\n uint256 volatility,\n uint256 expiryTimestamp\n ) external view returns (uint256 delta);\n\n function getUnderlyingPrice() external view returns (uint256);\n\n function priceOracle() external view returns (address);\n\n function volatilityOracle() external view returns (address);\n\n function optionId() external view returns (bytes32);\n}\n" }, "contracts/libraries/GnosisAuction.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nimport {SafeMath} from \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {\n SafeERC20\n} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {DSMath} from \"../vendor/DSMath.sol\";\nimport {IGnosisAuction} from \"../interfaces/IGnosisAuction.sol\";\nimport {IOtoken} from \"../interfaces/GammaInterface.sol\";\nimport {IOptionsPremiumPricer} from \"../interfaces/IRibbon.sol\";\nimport {Vault} from \"./Vault.sol\";\nimport {IRibbonThetaVault} from \"../interfaces/IRibbonThetaVault.sol\";\n\nlibrary GnosisAuction {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n event InitiateGnosisAuction(\n address indexed auctioningToken,\n address indexed biddingToken,\n uint256 auctionCounter,\n address indexed manager\n );\n\n event PlaceAuctionBid(\n uint256 auctionId,\n address indexed auctioningToken,\n uint256 sellAmount,\n uint256 buyAmount,\n address indexed bidder\n );\n\n struct AuctionDetails {\n address oTokenAddress;\n address gnosisEasyAuction;\n address asset;\n uint256 assetDecimals;\n uint256 oTokenPremium;\n uint256 duration;\n }\n\n struct BidDetails {\n address oTokenAddress;\n address gnosisEasyAuction;\n address asset;\n uint256 assetDecimals;\n uint256 auctionId;\n uint256 lockedBalance;\n uint256 optionAllocation;\n uint256 optionPremium;\n address bidder;\n }\n\n function startAuction(AuctionDetails calldata auctionDetails)\n internal\n returns (uint256 auctionID)\n {\n uint256 oTokenSellAmount =\n getOTokenSellAmount(auctionDetails.oTokenAddress);\n require(oTokenSellAmount > 0, \"No otokens to sell\");\n\n IERC20(auctionDetails.oTokenAddress).safeApprove(\n auctionDetails.gnosisEasyAuction,\n IERC20(auctionDetails.oTokenAddress).balanceOf(address(this))\n );\n\n // minBidAmount is total oTokens to sell * premium per oToken\n // shift decimals to correspond to decimals of USDC for puts\n // and underlying for calls\n uint256 minBidAmount =\n DSMath.wmul(\n oTokenSellAmount.mul(10**10),\n auctionDetails.oTokenPremium\n );\n\n minBidAmount = auctionDetails.assetDecimals > 18\n ? minBidAmount.mul(10**(auctionDetails.assetDecimals.sub(18)))\n : minBidAmount.div(\n 10**(uint256(18).sub(auctionDetails.assetDecimals))\n );\n\n require(\n minBidAmount <= type(uint96).max,\n \"optionPremium * oTokenSellAmount > type(uint96) max value!\"\n );\n\n uint256 auctionEnd = block.timestamp.add(auctionDetails.duration);\n\n auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction)\n .initiateAuction(\n // address of oToken we minted and are selling\n auctionDetails.oTokenAddress,\n // address of asset we want in exchange for oTokens. Should match vault `asset`\n auctionDetails.asset,\n // orders can be cancelled at any time during the auction\n auctionEnd,\n // order will last for `duration`\n auctionEnd,\n // we are selling all of the otokens minus a fee taken by gnosis\n uint96(oTokenSellAmount),\n // the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price\n uint96(minBidAmount),\n // the minimum bidding amount must be 1 * 10 ** -assetDecimals\n 1,\n // the min funding threshold\n 0,\n // no atomic closure\n false,\n // access manager contract\n address(0),\n // bytes for storing info like a whitelist for who can bid\n bytes(\"\")\n );\n\n emit InitiateGnosisAuction(\n auctionDetails.oTokenAddress,\n auctionDetails.asset,\n auctionID,\n msg.sender\n );\n }\n\n function placeBid(BidDetails calldata bidDetails)\n internal\n returns (\n uint256 sellAmount,\n uint256 buyAmount,\n uint64 userId\n )\n {\n // calculate how much to allocate\n sellAmount = bidDetails\n .lockedBalance\n .mul(bidDetails.optionAllocation)\n .div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER);\n\n // divide the `asset` sellAmount by the target premium per oToken to\n // get the number of oTokens to buy (8 decimals)\n buyAmount = sellAmount\n .mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS)))\n .div(bidDetails.optionPremium)\n .div(10**bidDetails.assetDecimals);\n\n require(\n sellAmount <= type(uint96).max,\n \"sellAmount > type(uint96) max value!\"\n );\n require(\n buyAmount <= type(uint96).max,\n \"buyAmount > type(uint96) max value!\"\n );\n\n // approve that amount\n IERC20(bidDetails.asset).safeApprove(\n bidDetails.gnosisEasyAuction,\n sellAmount\n );\n\n uint96[] memory _minBuyAmounts = new uint96[](1);\n uint96[] memory _sellAmounts = new uint96[](1);\n bytes32[] memory _prevSellOrders = new bytes32[](1);\n _minBuyAmounts[0] = uint96(buyAmount);\n _sellAmounts[0] = uint96(sellAmount);\n _prevSellOrders[\n 0\n ] = 0x0000000000000000000000000000000000000000000000000000000000000001;\n\n // place sell order with that amount\n userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders(\n bidDetails.auctionId,\n _minBuyAmounts,\n _sellAmounts,\n _prevSellOrders,\n \"0x\"\n );\n\n emit PlaceAuctionBid(\n bidDetails.auctionId,\n bidDetails.oTokenAddress,\n sellAmount,\n buyAmount,\n bidDetails.bidder\n );\n\n return (sellAmount, buyAmount, userId);\n }\n\n function claimAuctionOtokens(\n Vault.AuctionSellOrder calldata auctionSellOrder,\n address gnosisEasyAuction,\n address counterpartyThetaVault\n ) internal {\n bytes32 order =\n encodeOrder(\n auctionSellOrder.userId,\n auctionSellOrder.buyAmount,\n auctionSellOrder.sellAmount\n );\n bytes32[] memory orders = new bytes32[](1);\n orders[0] = order;\n IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder(\n IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(),\n orders\n );\n }\n\n function getOTokenSellAmount(address oTokenAddress)\n internal\n view\n returns (uint256)\n {\n // We take our current oToken balance. That will be our sell amount\n // but otokens will be transferred to gnosis.\n uint256 oTokenSellAmount =\n IERC20(oTokenAddress).balanceOf(address(this));\n\n require(\n oTokenSellAmount <= type(uint96).max,\n \"oTokenSellAmount > type(uint96) max value!\"\n );\n\n return oTokenSellAmount;\n }\n\n function getOTokenPremiumInStables(\n address oTokenAddress,\n address optionsPremiumPricer,\n uint256 premiumDiscount\n ) internal view returns (uint256) {\n IOtoken newOToken = IOtoken(oTokenAddress);\n IOptionsPremiumPricer premiumPricer =\n IOptionsPremiumPricer(optionsPremiumPricer);\n\n // Apply black-scholes formula (from rvol library) to option given its features\n // and get price for 100 contracts denominated USDC for both call and put options\n uint256 optionPremium =\n premiumPricer.getPremiumInStables(\n newOToken.strikePrice(),\n newOToken.expiryTimestamp(),\n newOToken.isPut()\n );\n\n // Apply a discount to incentivize arbitraguers\n optionPremium = optionPremium.mul(premiumDiscount).div(\n 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER\n );\n\n require(\n optionPremium <= type(uint96).max,\n \"optionPremium > type(uint96) max value!\"\n );\n\n return optionPremium;\n }\n\n function encodeOrder(\n uint64 userId,\n uint96 buyAmount,\n uint96 sellAmount\n ) internal pure returns (bytes32) {\n return\n bytes32(\n (uint256(userId) << 192) +\n (uint256(buyAmount) << 96) +\n uint256(sellAmount)\n );\n }\n}\n" }, "contracts/libraries/DateTime.sol": { "content": "// SPDX-License-Identifier: MIT\n// Source: https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n// ----------------------------------------------------------------------------\n\npragma solidity =0.8.4;\n\nlibrary DateTime {\n uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant SECONDS_PER_HOUR = 60 * 60;\n uint256 constant SECONDS_PER_MINUTE = 60;\n int256 constant OFFSET19700101 = 2440588;\n\n uint256 constant DOW_MON = 1;\n uint256 constant DOW_TUE = 2;\n uint256 constant DOW_WED = 3;\n uint256 constant DOW_THU = 4;\n uint256 constant DOW_FRI = 5;\n uint256 constant DOW_SAT = 6;\n uint256 constant DOW_SUN = 7;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days =\n _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function isLeapYear(uint256 timestamp)\n internal\n pure\n returns (bool leapYear)\n {\n (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) internal pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function getDaysInMonth(uint256 timestamp)\n internal\n pure\n returns (uint256 daysInMonth)\n {\n (uint256 year, uint256 month, ) =\n _daysToDate(timestamp / SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month)\n internal\n pure\n returns (uint256 daysInMonth)\n {\n if (\n month == 1 ||\n month == 3 ||\n month == 5 ||\n month == 7 ||\n month == 8 ||\n month == 10 ||\n month == 12\n ) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp)\n internal\n pure\n returns (uint256 dayOfWeek)\n {\n uint256 _days = timestamp / SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;\n }\n\n /**\n * @notice Gets the Friday of the same week\n * @param timestamp is the given date and time\n * @return the Friday of the same week in unix time\n */\n function getThisWeekFriday(uint256 timestamp)\n internal\n pure\n returns (uint256)\n {\n return timestamp + 5 days - getDayOfWeek(timestamp) * 1 days;\n }\n\n /**\n * @notice Gets the next friday after the given date and time\n * @param timestamp is the given date and time\n * @return the next friday after the given date and time\n */\n function getNextFriday(uint256 timestamp) internal pure returns (uint256) {\n uint256 friday = getThisWeekFriday(timestamp);\n return friday >= timestamp ? friday : friday + 1 weeks;\n }\n\n /**\n * @notice Gets the last day of the month\n * @param timestamp is the given date and time\n * @return the last day of the same month in unix time\n */\n function getLastDayOfMonth(uint256 timestamp)\n internal\n pure\n returns (uint256)\n {\n return\n timestampFromDate(getYear(timestamp), getMonth(timestamp) + 1, 1) -\n 1 days;\n }\n\n /**\n * @notice Gets the last Friday of the month\n * @param timestamp is the given date and time\n * @return the last Friday of the same month in unix time\n */\n function getMonthLastFriday(uint256 timestamp)\n internal\n pure\n returns (uint256)\n {\n uint256 lastDay = getLastDayOfMonth(timestamp);\n uint256 friday = getThisWeekFriday(lastDay);\n\n return friday > lastDay ? friday - 1 weeks : friday;\n }\n\n /**\n * @notice Gets the last Friday of the quarter\n * @param timestamp is the given date and time\n * @return the last Friday of the quarter in unix time\n */\n function getQuarterLastFriday(uint256 timestamp)\n internal\n pure\n returns (uint256)\n {\n uint256 month = getMonth(timestamp);\n uint256 quarterMonth =\n (month <= 3) ? 3 : (month <= 6) ? 6 : (month <= 9) ? 9 : 12;\n\n uint256 quarterDate =\n timestampFromDate(getYear(timestamp), quarterMonth, 1);\n\n return getMonthLastFriday(quarterDate);\n }\n\n /**\n * @notice Gets the last Friday of the half-year\n * @param timestamp is the given date and time\n * @return the last friday of the half-year\n */\n function getBiannualLastFriday(uint256 timestamp)\n internal\n pure\n returns (uint256)\n {\n uint256 month = getMonth(timestamp);\n uint256 biannualMonth = (month <= 6) ? 6 : 12;\n\n uint256 biannualDate =\n timestampFromDate(getYear(timestamp), biannualMonth, 1);\n\n return getMonthLastFriday(biannualDate);\n }\n}\n" }, "contracts/interfaces/GammaInterface.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nlibrary GammaTypes {\n // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.\n struct Vault {\n // addresses of oTokens a user has shorted (i.e. written) against this vault\n address[] shortOtokens;\n // addresses of oTokens a user has bought and deposited in this vault\n // user can be long oTokens without opening a vault (e.g. by buying on a DEX)\n // generally, long oTokens will be 'deposited' in vaults to act as collateral\n // in order to write oTokens against (i.e. in spreads)\n address[] longOtokens;\n // addresses of other ERC-20s a user has deposited as collateral in this vault\n address[] collateralAssets;\n // quantity of oTokens minted/written for each oToken address in shortOtokens\n uint256[] shortAmounts;\n // quantity of oTokens owned and held in the vault for each oToken address in longOtokens\n uint256[] longAmounts;\n // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets\n uint256[] collateralAmounts;\n }\n}\n\ninterface IOtoken {\n function underlyingAsset() external view returns (address);\n\n function strikeAsset() external view returns (address);\n\n function collateralAsset() external view returns (address);\n\n function strikePrice() external view returns (uint256);\n\n function expiryTimestamp() external view returns (uint256);\n\n function isPut() external view returns (bool);\n}\n\ninterface IOtokenFactory {\n function getOtoken(\n address _underlyingAsset,\n address _strikeAsset,\n address _collateralAsset,\n uint256 _strikePrice,\n uint256 _expiry,\n bool _isPut\n ) external view returns (address);\n\n function createOtoken(\n address _underlyingAsset,\n address _strikeAsset,\n address _collateralAsset,\n uint256 _strikePrice,\n uint256 _expiry,\n bool _isPut\n ) external returns (address);\n\n function getTargetOtokenAddress(\n address _underlyingAsset,\n address _strikeAsset,\n address _collateralAsset,\n uint256 _strikePrice,\n uint256 _expiry,\n bool _isPut\n ) external view returns (address);\n\n event OtokenCreated(\n address tokenAddress,\n address creator,\n address indexed underlying,\n address indexed strike,\n address indexed collateral,\n uint256 strikePrice,\n uint256 expiry,\n bool isPut\n );\n}\n\ninterface IController {\n // possible actions that can be performed\n enum ActionType {\n OpenVault,\n MintShortOption,\n BurnShortOption,\n DepositLongOption,\n WithdrawLongOption,\n DepositCollateral,\n WithdrawCollateral,\n SettleVault,\n Redeem,\n Call,\n Liquidate\n }\n\n struct ActionArgs {\n // type of action that is being performed on the system\n ActionType actionType;\n // address of the account owner\n address owner;\n // address which we move assets from or to (depending on the action type)\n address secondAddress;\n // asset that is to be transfered\n address asset;\n // index of the vault that is to be modified (if any)\n uint256 vaultId;\n // amount of asset that is to be transfered\n uint256 amount;\n // each vault can hold multiple short / long / collateral assets\n // but we are restricting the scope to only 1 of each in this version\n // in future versions this would be the index of the short / long / collateral asset that needs to be modified\n uint256 index;\n // any other data that needs to be passed in for arbitrary function calls\n bytes data;\n }\n\n struct RedeemArgs {\n // address to which we pay out the oToken proceeds\n address receiver;\n // oToken that is to be redeemed\n address otoken;\n // amount of oTokens that is to be redeemed\n uint256 amount;\n }\n\n function getPayout(address _otoken, uint256 _amount)\n external\n view\n returns (uint256);\n\n function operate(ActionArgs[] calldata _actions) external;\n\n function getAccountVaultCounter(address owner)\n external\n view\n returns (uint256);\n\n function oracle() external view returns (address);\n\n function getVault(address _owner, uint256 _vaultId)\n external\n view\n returns (GammaTypes.Vault memory);\n\n function getProceed(address _owner, uint256 _vaultId)\n external\n view\n returns (uint256);\n\n function isSettlementAllowed(\n address _underlying,\n address _strike,\n address _collateral,\n uint256 _expiry\n ) external view returns (bool);\n}\n\ninterface IOracle {\n function setAssetPricer(address _asset, address _pricer) external;\n\n function updateAssetPricer(address _asset, address _pricer) external;\n\n function getPrice(address _asset) external view returns (uint256);\n}\n" }, "contracts/interfaces/IERC20Detailed.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IERC20Detailed is IERC20 {\n function decimals() external view returns (uint8);\n\n function symbol() external view returns (string calldata);\n\n function name() external view returns (string calldata);\n}\n" }, "contracts/interfaces/IGnosisAuction.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nlibrary AuctionType {\n struct AuctionData {\n IERC20 auctioningToken;\n IERC20 biddingToken;\n uint256 orderCancellationEndDate;\n uint256 auctionEndDate;\n bytes32 initialAuctionOrder;\n uint256 minimumBiddingAmountPerOrder;\n uint256 interimSumBidAmount;\n bytes32 interimOrder;\n bytes32 clearingPriceOrder;\n uint96 volumeClearingPriceOrder;\n bool minFundingThresholdNotReached;\n bool isAtomicClosureAllowed;\n uint256 feeNumerator;\n uint256 minFundingThreshold;\n }\n}\n\ninterface IGnosisAuction {\n function initiateAuction(\n address _auctioningToken,\n address _biddingToken,\n uint256 orderCancellationEndDate,\n uint256 auctionEndDate,\n uint96 _auctionedSellAmount,\n uint96 _minBuyAmount,\n uint256 minimumBiddingAmountPerOrder,\n uint256 minFundingThreshold,\n bool isAtomicClosureAllowed,\n address accessManagerContract,\n bytes memory accessManagerContractData\n ) external returns (uint256);\n\n function auctionCounter() external view returns (uint256);\n\n function auctionData(uint256 auctionId)\n external\n view\n returns (AuctionType.AuctionData memory);\n\n function auctionAccessManager(uint256 auctionId)\n external\n view\n returns (address);\n\n function auctionAccessData(uint256 auctionId)\n external\n view\n returns (bytes memory);\n\n function FEE_DENOMINATOR() external view returns (uint256);\n\n function feeNumerator() external view returns (uint256);\n\n function settleAuction(uint256 auctionId) external returns (bytes32);\n\n function placeSellOrders(\n uint256 auctionId,\n uint96[] memory _minBuyAmounts,\n uint96[] memory _sellAmounts,\n bytes32[] memory _prevSellOrders,\n bytes calldata allowListCallData\n ) external returns (uint64);\n\n function claimFromParticipantOrder(\n uint256 auctionId,\n bytes32[] memory orders\n ) external returns (uint256, uint256);\n}\n" }, "contracts/libraries/SupportsNonCompliantERC20.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {\n SafeERC20\n} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\n/**\n * This library supports ERC20s that have quirks in their behavior.\n * One such ERC20 is USDT, which requires allowance to be 0 before calling approve.\n * We plan to update this library with ERC20s that display such idiosyncratic behavior.\n */\nlibrary SupportsNonCompliantERC20 {\n address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;\n\n function safeApproveNonCompliant(\n IERC20 token,\n address spender,\n uint256 amount\n ) internal {\n if (address(token) == USDT) {\n SafeERC20.safeApprove(token, spender, 0);\n }\n SafeERC20.safeApprove(token, spender, amount);\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "contracts/vendor/DSMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\n/// math.sol -- mixin for inline numerical wizardry\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity >0.4.13;\n\nlibrary DSMath {\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x + y) >= x, \"ds-math-add-overflow\");\n }\n\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x - y) <= x, \"ds-math-sub-underflow\");\n }\n\n function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require(y == 0 || (z = x * y) / y == x, \"ds-math-mul-overflow\");\n }\n\n function min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n return x <= y ? x : y;\n }\n\n function max(uint256 x, uint256 y) internal pure returns (uint256 z) {\n return x >= y ? x : y;\n }\n\n function imin(int256 x, int256 y) internal pure returns (int256 z) {\n return x <= y ? x : y;\n }\n\n function imax(int256 x, int256 y) internal pure returns (int256 z) {\n return x >= y ? x : y;\n }\n\n uint256 constant WAD = 10**18;\n uint256 constant RAY = 10**27;\n\n //rounds to zero if x*y < WAD / 2\n function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = add(mul(x, y), WAD / 2) / WAD;\n }\n\n //rounds to zero if x*y < WAD / 2\n function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = add(mul(x, y), RAY / 2) / RAY;\n }\n\n //rounds to zero if x*y < WAD / 2\n function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = add(mul(x, WAD), y / 2) / y;\n }\n\n //rounds to zero if x*y < RAY / 2\n function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = add(mul(x, RAY), y / 2) / y;\n }\n\n // This famous algorithm is called \"exponentiation by squaring\"\n // and calculates x^n with x as fixed-point and n as regular unsigned.\n //\n // It's O(log n), instead of O(n) for naive repeated multiplication.\n //\n // These facts are why it works:\n //\n // If n is even, then x^n = (x^2)^(n/2).\n // If n is odd, then x^n = x * x^(n-1),\n // and applying the equation for even x gives\n // x^n = x * (x^2)^((n-1) / 2).\n //\n // Also, EVM division is flooring and\n // floor[(n-1) / 2] = floor[n / 2].\n //\n function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {\n z = n % 2 != 0 ? x : RAY;\n\n for (n /= 2; n != 0; n /= 2) {\n x = rmul(x, x);\n\n if (n % 2 != 0) {\n z = rmul(z, x);\n }\n }\n }\n}\n" }, "contracts/interfaces/IRibbonThetaVault.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.4;\n\nimport {Vault} from \"../libraries/Vault.sol\";\n\ninterface IRibbonThetaVault {\n function currentOption() external view returns (address);\n\n function nextOption() external view returns (address);\n\n function vaultParams() external view returns (Vault.VaultParams memory);\n\n function vaultState() external view returns (Vault.VaultState memory);\n\n function optionState() external view returns (Vault.OptionState memory);\n\n function optionAuctionID() external view returns (uint256);\n\n function pricePerShare() external view returns (uint256);\n\n function roundPricePerShare(uint256) external view returns (uint256);\n\n function depositFor(uint256 amount, address creditor) external;\n\n function initiateWithdraw(uint256 numShares) external;\n\n function completeWithdraw() external;\n\n function maxRedeem() external;\n\n function depositYieldTokenFor(uint256 amount, address creditor) external;\n\n function symbol() external view returns (string calldata);\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} } }