zellic-audit
Initial commit
f998fcd
raw
history blame
237 kB
{
"language": "Solidity",
"sources": {
"@yield-protocol/yieldspace-tv/src/Pool/Modules/PoolEuler.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.15;\n\nimport \"../Pool.sol\";\nimport \"../../interfaces/IEToken.sol\";\n\n/*\n\n __ ___ _ _\n \\ \\ / (_) | | | |\n \\ \\_/ / _ ___| | __| |\n \\ / | |/ _ \\ |/ _` |\n | | | | __/ | (_| |\n |_| |_|\\___|_|\\__,_|\n yieldprotocol.com\n\n ██████╗ ██████╗ ██████╗ ██╗ ███████╗██╗ ██╗██╗ ███████╗██████╗\n ██╔══██╗██╔═══██╗██╔═══██╗██║ ██╔════╝██║ ██║██║ ██╔════╝██╔══██╗\n ██████╔╝██║ ██║██║ ██║██║ █████╗ ██║ ██║██║ █████╗ ██████╔╝\n ██╔═══╝ ██║ ██║██║ ██║██║ ██╔══╝ ██║ ██║██║ ██╔══╝ ██╔══██╗\n ██║ ╚██████╔╝╚██████╔╝███████╗███████╗╚██████╔╝███████╗███████╗██║ ██║\n ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝\n\n*/\n\n/// Module for using non-4626 compliant Euler etokens as base for the Yield Protocol Pool.sol AMM contract.\n/// Adapted from: https://docs.euler.finance/developers/integration-guide\n/// @dev Since Euler \"eTokens\" are not currently ERC4626 compliant, this contract inherits the Yield Pool\n/// contract and overwrites the functions that are unique to Euler.\n/// @title PoolEuler.sol\n/// @dev Deploy pool with Euler Pool contract and associated fyToken.\n/// @author @devtooligan\ncontract PoolEuler is Pool {\n using MinimalTransferHelper for IERC20Like;\n using CastU256U104 for uint256;\n using CastU256U128 for uint256;\n\n constructor(\n address euler_, // The main Euler contract address\n address eToken_,\n address fyToken_,\n int128 ts_,\n uint16 g1Fee_\n ) Pool(eToken_, fyToken_, ts_, g1Fee_) {\n // Approve the main Euler contract to take base from the Pool, used on `deposit`.\n _getBaseAsset(eToken_).approve(euler_, type(uint256).max);\n }\n\n /// **This function is intentionally empty to overwrite the Pool._approveSharesToken fn.**\n /// This is normally used by Pool.constructor give max approval to sharesToken, but Euler tokens require approval\n /// of the main Euler contract -- not of the individual sharesToken contracts. The required approval is given above\n /// in the constructor.\n function _approveSharesToken(IERC20Like baseToken_, address sharesToken_) internal virtual override {}\n\n /// This is used by the constructor to set the base asset token as immutable.\n function _getBaseAsset(address sharesToken_) internal virtual override returns (IERC20Like) {\n return IERC20Like(address(IEToken(sharesToken_).underlyingAsset()));\n }\n\n /// Returns the base token current price.\n /// This function should be overriden by modules.\n /// @dev Euler tokens are all 18 decimals.\n /// @return The price of 1 share of a Euler token in terms of its underlying base asset with base asset decimals.\n function _getCurrentSharePrice() internal view virtual override returns (uint256) {\n // The return is in the decimals of the underlying.\n return IEToken(address(sharesToken)).convertBalanceToUnderlying(1e18);\n }\n\n /// Returns the shares balance TODO: lots of notes\n /// The decimals of the shares amount returned is adjusted to match the decimals of the baseToken\n function _getSharesBalance() internal view virtual override returns (uint104) {\n return (sharesToken.balanceOf(address(this)) / scaleFactor).u104();\n }\n\n /// Internal function for wrapping base asset tokens.\n /// @param receiver The address the wrapped tokens should be sent.\n /// @return shares The amount of wrapped tokens that are sent to the receiver.\n function _wrap(address receiver) internal virtual override returns (uint256 shares) {\n uint256 baseOut = baseToken.balanceOf(address(this));\n if (baseOut == 0) return 0;\n\n IEToken(address(sharesToken)).deposit(0, baseOut); // first param is subaccount, 0 for primary\n shares = _getSharesBalance() - sharesCached; // this includes any shares in pool previously\n if (receiver != address(this)) {\n sharesToken.safeTransfer(receiver, shares);\n }\n }\n\n /// Internal function to preview how many shares will be received when depositing a given amount of assets.\n /// @param assets The amount of base asset tokens to preview the deposit in native decimals.\n /// @return shares The amount of shares that would be returned from depositing (converted to base decimals).\n function _wrapPreview(uint256 assets) internal view virtual override returns (uint256 shares) {\n shares = IEToken(address(sharesToken)).convertUnderlyingToBalance(assets) / scaleFactor;\n }\n\n /// Internal function for unwrapping unaccounted for base in this contract.\n /// @param receiver The address the wrapped tokens should be sent.\n /// @return assets The amount of assets sent to the receiver in native decimals.\n function _unwrap(address receiver) internal virtual override returns (uint256 assets) {\n uint256 surplus = _getSharesBalance() - sharesCached;\n if (surplus == 0) return 0;\n // convert to base\n assets = _unwrapPreview(surplus);\n IEToken(address(sharesToken)).withdraw(0, assets); // first param is subaccount, 0 for primary\n\n if (receiver != address(this)) {\n baseToken.safeTransfer(receiver, baseToken.balanceOf(address(this)));\n }\n }\n\n /// Internal function to preview how many base tokens will be received when unwrapping a given amount of shares.\n /// @dev NOTE: eToken contracts are all 18 decimals. Because Pool.sol expects share tokens to use the same decimals\n /// as the base taken, when shares balance is needed, we convert the result of shares.balanceOf() to the base\n /// decimals via the overridden _getSharesBalance(). Therefore, this _unwrapPreview() expects to receive share\n /// amounts which have already been converted to base decimals. However, the eToken convertBalanceToUnderlying()\n /// used in this fn requires share amounts in 18 decimals so we scale the shareAmount back up to fp18 and pass\n /// as a parameter. Fortunately, the return value from the convertBalanceToUnderlying() is in base decimals so\n /// we don't have to do any further conversions, yay.\n /// @param sharesInBaseDecimals The amount of shares to preview a redemption (converted to base decimals).\n /// @return assets The amount of base asset tokens that would be returned from redeeming (in base decimals).\n function _unwrapPreview(uint256 sharesInBaseDecimals) internal view virtual override returns (uint256 assets) {\n assets = IEToken(address(sharesToken)).convertBalanceToUnderlying(sharesInBaseDecimals * scaleFactor);\n }\n\n /// Retrieve any shares tokens not accounted for in the cache.\n /// @param to Address of the recipient of the shares tokens.\n /// @return retrieved The amount of shares tokens sent (in eToken decimals -- 18).\n function retrieveShares(address to) external virtual override returns (uint128 retrieved) {\n // sharesCached is stored by Yield with the same decimals as the underlying base, but actually the Euler\n // eTokens are always fp18. So we scale up the sharesCached and subtract from real eToken balance.\n retrieved = (sharesToken.balanceOf(address(this)) - (sharesCached * scaleFactor)).u128();\n sharesToken.safeTransfer(to, retrieved);\n // Now the current balances match the cache, so no need to update the TWAR\n }\n}\n"
},
"@yield-protocol/yieldspace-tv/src/Pool/Pool.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.15;\nimport \"./PoolImports.sol\"; /*\n\n __ ___ _ _\n \\ \\ / (_) | | | | ██████╗ ██████╗ ██████╗ ██╗ ███████╗ ██████╗ ██╗\n \\ \\_/ / _ ___| | __| | ██╔══██╗██╔═══██╗██╔═══██╗██║ ██╔════╝██╔═══██╗██║\n \\ / | |/ _ \\ |/ _` | ██████╔╝██║ ██║██║ ██║██║ ███████╗██║ ██║██║\n | | | | __/ | (_| | ██╔═══╝ ██║ ██║██║ ██║██║ ╚════██║██║ ██║██║\n |_| |_|\\___|_|\\__,_| ██║ ╚██████╔╝╚██████╔╝███████╗██╗███████║╚██████╔╝███████╗\n yieldprotocol.com ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝ ╚═════╝ ╚══════╝\n\n ┌─────────┐\n │no │\n │lifeguard│\n └─┬─────┬─┘ ==+\n be cool, stay in pool │ │ =======+\n _____│_____│______ |+\n \\ .-'\"___________________`-.|+\n ( .'\" '-.)+\n |`-..__________________..-'|+\n | |+\n .-:::::::::::-. | |+ ┌──────────────┐\n .:::::::::::::::::. | --- --- |+ │$ $│\n : _______ __ __ : .| (o) (o) |+. │ ┌────────────┴─┐\n :: | || | | |:: /`| |+'\\ │ │$ $│\n ::: | ___|| |_| |::: / /| [ |+\\ \\ │$│ ┌────────────┴─┐\n ::: | |___ | |::: / / | ---------- |+ \\ \\ └─┤ │$ ERC4626 $│\n ::: | ___||_ _|:::.-\" ; \\ \\________/ /+ \\ \"--/│$│ Tokenized │\n ::: | | | | ::),.-' `-..__________________..-' += `---=└─┤ Vault Shares │\n :: |___| |___| ::=/ | | | | │$ $│\n : TOKEN : | | | | └──────────────┘\n `:::::::::::::::::' | | | |\n `-:::::::::::-' +----+ +----+\n `'''''''` _..._|____| |____| _..._\n .` \"-. `% | | %` .-\" `.\n / \\ .: :. / \\\n '-..___|_..=:` `-:=.._|___..-'\n*/\n\n/// A Yieldspace AMM implementation for pools which provide liquidity and trading of fyTokens vs base tokens.\n/// **The base tokens in this implementation are converted to ERC4626 compliant tokenized vault shares.**\n/// See whitepaper and derived formulas: https://hackmd.io/lRZ4mgdrRgOpxZQXqKYlFw\n//\n// Useful terminology:\n// base - Example: DAI. The underlying token of the fyToken. Sometimes referred to as \"asset\" or \"base\".\n// shares - Example: yvDAI. Upon receipt, base is deposited (wrapped) in a tokenized vault.\n// c - Current price of shares in terms of base (in 64.64 bit)\n// mu - also called c0 is the initial c of shares at contract deployment\n// Reserves are tracked in shares * mu for consistency.\n//\n/// @title Pool.sol\n/// @dev Uses ABDK 64.64 mathlib for precision and reduced gas.\n/// @author Adapted by @devtooligan from original work by @alcueca and UniswapV2. Maths and whitepaper by @aniemerg.\ncontract Pool is PoolEvents, IPool, ERC20Permit, AccessControl {\n /* LIBRARIES\n *****************************************************************************************************************/\n\n using WDiv for uint256;\n using RDiv for uint256;\n using Math64x64 for int128;\n using Math64x64 for uint256;\n using CastU128I128 for uint128;\n using CastU128U104 for uint128;\n using CastU256U104 for uint256;\n using CastU256U128 for uint256;\n using CastU256I256 for uint256;\n using MinimalTransferHelper for IMaturingToken;\n using MinimalTransferHelper for IERC20Like;\n\n /* MODIFIERS\n *****************************************************************************************************************/\n\n /// Trading can only be done before maturity.\n modifier beforeMaturity() {\n if (block.timestamp >= maturity) revert AfterMaturity();\n _;\n }\n\n /* IMMUTABLES\n *****************************************************************************************************************/\n\n /// The fyToken for the corresponding base token. Ex. yvDAI's fyToken will be fyDAI. Even though we convert base\n /// in this contract to a wrapped tokenized vault (e.g. Yearn Vault Dai), the fyToken is still payable in\n /// the base token upon maturity.\n IMaturingToken public immutable fyToken;\n\n /// This pool accepts a pair of base and fyToken tokens.\n /// When these are deposited into a tokenized vault they become shares.\n /// It is an ERC20 token.\n IERC20Like public immutable baseToken;\n\n /// Decimals of base tokens (fyToken, lp token, and usually the sharesToken).\n uint256 public immutable baseDecimals;\n\n /// When base comes into this contract it is deposited into a 3rd party tokenized vault in return for shares.\n /// @dev For most of this contract, only the ERC20 functionality of the shares token is required. As such, shares\n /// are cast as \"IERC20Like\" and when that 4626 functionality is needed, they are recast as IERC4626.\n /// This wei, modules for non-4626 compliant base tokens can import this contract and override 4626 specific fn's.\n IERC20Like public immutable sharesToken;\n\n /// Time stretch == 1 / seconds in x years where x varies per contract (64.64)\n int128 public immutable ts;\n\n /// The normalization coefficient, the initial c value or price per 1 share of base (64.64)\n int128 public immutable mu;\n\n /// Pool's maturity date (not 64.64)\n uint32 public immutable maturity;\n\n /// Used to scale up to 18 decimals (not 64.64)\n uint96 public immutable scaleFactor;\n\n /* STRUCTS\n *****************************************************************************************************************/\n\n struct Cache {\n uint16 g1Fee;\n uint104 sharesCached;\n uint104 fyTokenCached;\n uint32 blockTimestampLast;\n }\n\n /* STORAGE\n *****************************************************************************************************************/\n\n // The following 4 vars use one storage slot and can be retrieved in a Cache struct with getCache()\n\n /// This number is used to calculate the fees for buying/selling fyTokens.\n /// @dev This is a fp4 that represents a ratio out 1, where 1 is represented by 10000.\n uint16 public g1Fee;\n\n /// Shares reserves, cached.\n uint104 internal sharesCached;\n\n /// fyToken reserves, cached.\n uint104 internal fyTokenCached;\n\n /// block.timestamp of last time reserve caches were updated.\n uint32 internal blockTimestampLast;\n\n /// This is a LAGGING, time weighted sum of the fyToken:shares reserves ratio measured in ratio seconds.\n /// @dev Footgun 🔫 alert! Be careful, this number is probably not what you need and it should normally be\n /// considered with blockTimestampLast. For consumption as a TWAR observation, use currentCumulativeRatio().\n /// In future pools, this function's visibility may be changed to internal.\n /// @return a fixed point factor with 27 decimals (ray).\n uint256 public cumulativeRatioLast;\n\n /* CONSTRUCTOR FUNCTIONS\n *****************************************************************************************************************/\n constructor(\n address sharesToken_, // address of shares token\n address fyToken_, // address of fyToken\n int128 ts_, // time stretch(64.64)\n uint16 g1Fee_ // fees (in bps) when buying fyToken\n )\n ERC20Permit(\n string(abi.encodePacked(IERC20Like(fyToken_).name(), \" LP\")),\n string(abi.encodePacked(IERC20Like(fyToken_).symbol(), \"LP\")),\n IERC20Like(fyToken_).decimals()\n )\n {\n /* __ __ __ ___ __ __ ___ __ __\n / ` / \\ |\\ | /__` | |__) | | / ` | / \\ |__)\n \\__, \\__/ | \\| .__/ | | \\ \\__/ \\__, | \\__/ | \\ */\n\n // Set maturity with check to make sure its not 2107 yet.\n uint256 maturity_ = IMaturingToken(fyToken_).maturity();\n if (maturity_ > uint256(type(uint32).max)) revert MaturityOverflow();\n maturity = uint32(maturity_);\n\n // Set sharesToken.\n sharesToken = IERC20Like(sharesToken_);\n\n // Cache baseToken to save loads of SLOADs.\n IERC20Like baseToken_ = _getBaseAsset(sharesToken_);\n\n // Call approve hook for sharesToken.\n _approveSharesToken(baseToken_, sharesToken_);\n\n // NOTE: LP tokens, baseToken and fyToken should have the same decimals. Within this core contract, it is\n // presumed that sharesToken also has the same decimals. If this is not the case, a separate module must be\n // used to overwrite _getSharesBalance() and other affected functions (see PoolEuler.sol for example).\n baseDecimals = baseToken_.decimals();\n\n // Set other immutables.\n baseToken = baseToken_;\n fyToken = IMaturingToken(fyToken_);\n ts = ts_;\n scaleFactor = uint96(10**(18 - uint96(baseDecimals))); // No more than 18 decimals allowed, reverts on underflow.\n\n // Set mu with check for 0.\n if ((mu = _getC()) == 0) {\n revert MuCannotBeZero();\n }\n\n // Set g1Fee state variable with out of bounds check.\n if ((g1Fee = g1Fee_) > 10000) revert InvalidFee(g1Fee_);\n emit FeesSet(g1Fee_);\n }\n\n /// This is used by the constructor to give max approval to sharesToken.\n /// @dev This should be overridden by modules if needed.\n function _approveSharesToken(IERC20Like baseToken_, address sharesToken_) internal virtual {\n bool success = baseToken_.approve(sharesToken_, type(uint256).max);\n if (!success) {\n revert ApproveFailed();\n }\n }\n\n /// This is used by the constructor to set the base token as immutable.\n /// @dev This should be overridden by modules.\n /// We use the IERC20Like interface, but this should be an ERC20 asset per EIP4626.\n function _getBaseAsset(address sharesToken_) internal virtual returns (IERC20Like) {\n return IERC20Like(address(IERC4626(sharesToken_).asset()));\n }\n\n /* LIQUIDITY FUNCTIONS\n\n ┌─────────────────────────────────────────────────┐\n │ mint, new life. gm! │\n │ buy, sell, mint more, trade, trade -- stop │\n │ mature, burn. gg~ │\n │ │\n │ \"Watashinojinsei (My Life)\" - haiku by Poolie │\n └─────────────────────────────────────────────────┘\n\n *****************************************************************************************************************/\n\n /*mint\n v\n ___ \\ /\n |_ \\_/ ┌───────────────────────────────┐\n | | │ │ ` _......._ ' gm!\n \\│ │/ .-:::::::::::-.\n │ \\│ │/ ` : __ ____ : /\n └───────────────► │ mint │ :: / / / __ \\::\n │ │ ──────▶ _ :: / / / /_/ /:: _\n ┌───────────────► │ │ :: / /___/ ____/ ::\n │ /│ │\\ ::/_____/_/ ::\n /│ │\\ ' : : `\n B A S E │ \\(^o^)/ │ `-:::::::::::-'\n │ Pool.sol │ , `'''''''` .\n └───────────────────────────────┘\n / \\\n ^\n */\n /// Mint liquidity tokens in exchange for adding base and fyToken\n /// The amount of liquidity tokens to mint is calculated from the amount of unaccounted for fyToken in this contract.\n /// A proportional amount of asset tokens need to be present in this contract, also unaccounted for.\n /// @dev _totalSupply > 0 check important here to prevent unauthorized initialization.\n /// @param to Wallet receiving the minted liquidity tokens.\n /// @param remainder Wallet receiving any surplus base.\n /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18).\n /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18).\n /// @return baseIn The amount of base found in the contract that was used for the mint.\n /// @return fyTokenIn The amount of fyToken found that was used for the mint\n /// @return lpTokensMinted The amount of LP tokens minted.\n function mint(\n address to,\n address remainder,\n uint256 minRatio,\n uint256 maxRatio\n )\n external\n virtual\n override\n returns (\n uint256 baseIn,\n uint256 fyTokenIn,\n uint256 lpTokensMinted\n )\n {\n if (_totalSupply == 0) revert NotInitialized();\n\n (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, remainder, 0, minRatio, maxRatio);\n }\n\n // ╦┌┐┌┬┌┬┐┬┌─┐┬ ┬┌─┐┌─┐ ╔═╗┌─┐┌─┐┬\n // ║││││ │ │├─┤│ │┌─┘├┤ ╠═╝│ ││ ││\n // ╩┘└┘┴ ┴ ┴┴ ┴┴─┘┴└─┘└─┘ ╩ └─┘└─┘┴─┘\n /// @dev This is the exact same as mint() but with auth added and skip the supply > 0 check\n /// and checks instead that supply == 0.\n /// This intialize mechanism is different than UniV2. Tokens addresses are added at contract creation.\n /// This pool is considered initialized after the first LP token is minted.\n /// @param to Wallet receiving the minted liquidity tokens.\n /// @return baseIn The amount of base found that was used for the mint.\n /// @return fyTokenIn The amount of fyToken found that was used for the mint\n /// @return lpTokensMinted The amount of LP tokens minted.\n function init(address to)\n external\n virtual\n auth\n returns (\n uint256 baseIn,\n uint256 fyTokenIn,\n uint256 lpTokensMinted\n )\n {\n if (_totalSupply != 0) revert Initialized();\n\n // address(this) used for the remainder, but actually this parameter is not used at all in this case because\n // there will never be any left over base in this case\n (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, address(this), 0, 0, type(uint256).max);\n\n emit gm();\n }\n\n /* mintWithBase\n V\n ┌───────────────────────────────┐ \\ /\n │ │ ` _......._ ' gm!\n \\│ │/ .-:::::::::::-.\n \\│ │/ ` : __ ____ : /\n │ mintWithBase │ :: / / / __ \\::\n B A S E ──────► │ │ ──────▶ _ :: / / / /_/ /:: _\n │ │ :: / /___/ ____/ ::\n /│ │\\ ::/_____/_/ ::\n /│ │\\ ' : : `\n │ \\(^o^)/ │ `-:::::::::::-'\n │ Pool.sol │ , `'''''''` .\n └───────────────────────────────┘ / \\\n ^\n */\n /// Mint liquidity tokens in exchange for adding only base.\n /// The amount of liquidity tokens is calculated from the amount of fyToken to buy from the pool.\n /// The base tokens need to be previously transferred and present in this contract.\n /// @dev _totalSupply > 0 check important here to prevent minting before initialization.\n /// @param to Wallet receiving the minted liquidity tokens.\n /// @param remainder Wallet receiving any leftover base at the end.\n /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool, from this we calculate how much base it will be taken in.\n /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18).\n /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18).\n /// @return baseIn The amount of base found that was used for the mint.\n /// @return fyTokenIn The amount of fyToken found that was used for the mint\n /// @return lpTokensMinted The amount of LP tokens minted.\n function mintWithBase(\n address to,\n address remainder,\n uint256 fyTokenToBuy,\n uint256 minRatio,\n uint256 maxRatio\n )\n external\n virtual\n override\n returns (\n uint256 baseIn,\n uint256 fyTokenIn,\n uint256 lpTokensMinted\n )\n {\n if (_totalSupply == 0) revert NotInitialized();\n (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, remainder, fyTokenToBuy, minRatio, maxRatio);\n }\n\n /// This is the internal function called by the external mint functions.\n /// Mint liquidity tokens, with an optional internal trade to buy fyToken beforehand.\n /// The amount of liquidity tokens is calculated from the amount of fyTokenToBuy from the pool,\n /// plus the amount of extra, unaccounted for fyToken in this contract.\n /// The base tokens also need to be previously transferred and present in this contract.\n /// Only usable before maturity.\n /// @dev Warning: This fn does not check if supply > 0 like the external functions do.\n /// This function overloads the ERC20._mint(address, uint) function.\n /// @param to Wallet receiving the minted liquidity tokens.\n /// @param remainder Wallet receiving any surplus base.\n /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool.\n /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18).\n /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18).\n /// @return baseIn The amount of base found that was used for the mint.\n /// @return fyTokenIn The amount of fyToken found that was used for the mint\n /// @return lpTokensMinted The amount of LP tokens minted.\n function _mint(\n address to,\n address remainder,\n uint256 fyTokenToBuy,\n uint256 minRatio,\n uint256 maxRatio\n )\n internal\n beforeMaturity\n returns (\n uint256 baseIn,\n uint256 fyTokenIn,\n uint256 lpTokensMinted\n )\n {\n // Wrap all base found in this contract.\n baseIn = baseToken.balanceOf(address(this));\n\n _wrap(address(this));\n\n // Gather data\n uint256 supply = _totalSupply;\n Cache memory cache = _getCache();\n uint256 realFYTokenCached_ = cache.fyTokenCached - supply; // The fyToken cache includes the virtual fyToken, equal to the supply\n uint256 sharesBalance = _getSharesBalance();\n\n // Check the burn wasn't sandwiched\n if (realFYTokenCached_ != 0) {\n if (\n uint256(cache.sharesCached).wdiv(realFYTokenCached_) < minRatio ||\n uint256(cache.sharesCached).wdiv(realFYTokenCached_) > maxRatio\n ) revert SlippageDuringMint(uint256(cache.sharesCached).wdiv(realFYTokenCached_), minRatio, maxRatio);\n } else if (maxRatio < type(uint256).max) {\n revert SlippageDuringMint(type(uint256).max, minRatio, maxRatio);\n }\n\n // Calculate token amounts\n uint256 sharesIn;\n if (supply == 0) {\n // **First mint**\n // Initialize at 1 pool token\n sharesIn = sharesBalance;\n lpTokensMinted = _mulMu(sharesIn);\n } else if (realFYTokenCached_ == 0) {\n // Edge case, no fyToken in the Pool after initialization\n sharesIn = sharesBalance - cache.sharesCached;\n lpTokensMinted = (supply * sharesIn) / cache.sharesCached;\n } else {\n // There is an optional virtual trade before the mint\n uint256 sharesToSell;\n if (fyTokenToBuy != 0) {\n sharesToSell = _buyFYTokenPreview(\n fyTokenToBuy.u128(),\n cache.sharesCached,\n cache.fyTokenCached,\n _computeG1(cache.g1Fee)\n );\n }\n\n // We use all the available fyTokens, plus optional virtual trade. Surplus is in base tokens.\n fyTokenIn = fyToken.balanceOf(address(this)) - realFYTokenCached_;\n lpTokensMinted = (supply * (fyTokenToBuy + fyTokenIn)) / (realFYTokenCached_ - fyTokenToBuy);\n\n sharesIn = sharesToSell + ((cache.sharesCached + sharesToSell) * lpTokensMinted) / supply;\n\n if ((sharesBalance - cache.sharesCached) < sharesIn) {\n revert NotEnoughBaseIn(_unwrapPreview(sharesBalance - cache.sharesCached), _unwrapPreview(sharesIn));\n }\n }\n\n // Update TWAR\n _update(\n (cache.sharesCached + sharesIn).u128(),\n (cache.fyTokenCached + fyTokenIn + lpTokensMinted).u128(), // Include \"virtual\" fyToken from new minted LP tokens\n cache.sharesCached,\n cache.fyTokenCached\n );\n\n // Execute mint\n _mint(to, lpTokensMinted);\n\n // Return any unused base tokens\n if (sharesBalance > cache.sharesCached + sharesIn) _unwrap(remainder);\n\n // confirm new virtual fyToken balance is not less than new supply\n if ((cache.fyTokenCached + fyTokenIn + lpTokensMinted) < supply + lpTokensMinted) {\n revert FYTokenCachedBadState();\n }\n\n emit Liquidity(\n maturity,\n msg.sender,\n to,\n address(0),\n -(baseIn.i256()),\n -(fyTokenIn.i256()),\n lpTokensMinted.i256()\n );\n }\n\n /* burn\n ( (\n ) (\n ( (| (| )\n ) )\\/ ( \\/(( ( gg ___\n (( / ))\\))))\\ ┌~~~~~~► |_ \\_/\n )\\( | ) │ | |\n /: | __ ____/: │\n :: / / / __ \\:: ───┤\n :: / / / /_/ /:: │\n :: / /___/ ____/ :: └~~~~~~► B A S E\n ::/_____/_/ ::\n : :\n `-:::::::::::-'\n `'''''''`\n */\n /// Burn liquidity tokens in exchange for base and fyToken.\n /// The liquidity tokens need to be previously tranfsferred to this contract.\n /// @param baseTo Wallet receiving the base tokens.\n /// @param fyTokenTo Wallet receiving the fyTokens.\n /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18).\n /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18).\n /// @return lpTokensBurned The amount of LP tokens burned.\n /// @return baseOut The amount of base tokens received.\n /// @return fyTokenOut The amount of fyTokens received.\n function burn(\n address baseTo,\n address fyTokenTo,\n uint256 minRatio,\n uint256 maxRatio\n )\n external\n virtual\n override\n returns (\n uint256 lpTokensBurned,\n uint256 baseOut,\n uint256 fyTokenOut\n )\n {\n (lpTokensBurned, baseOut, fyTokenOut) = _burn(baseTo, fyTokenTo, false, minRatio, maxRatio);\n }\n\n /* burnForBase\n\n ( (\n ) (\n ( (| (| )\n ) )\\/ ( \\/(( ( gg\n (( / ))\\))))\\\n )\\( | )\n /: | __ ____/:\n :: / / / __ \\:: ~~~~~~~► B A S E\n :: / / / /_/ /::\n :: / /___/ ____/ ::\n ::/_____/_/ ::\n : :\n `-:::::::::::-'\n `'''''''`\n */\n /// Burn liquidity tokens in exchange for base.\n /// The liquidity provider needs to have called `pool.approve`.\n /// Only usable before maturity.\n /// @param to Wallet receiving the base and fyToken.\n /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18).\n /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18).\n /// @return lpTokensBurned The amount of lp tokens burned.\n /// @return baseOut The amount of base tokens returned.\n function burnForBase(\n address to,\n uint256 minRatio,\n uint256 maxRatio\n ) external virtual override beforeMaturity returns (uint256 lpTokensBurned, uint256 baseOut) {\n (lpTokensBurned, baseOut, ) = _burn(to, address(0), true, minRatio, maxRatio);\n }\n\n /// Burn liquidity tokens in exchange for base.\n /// The liquidity provider needs to have called `pool.approve`.\n /// @dev This function overloads the ERC20._burn(address, uint) function.\n /// @param baseTo Wallet receiving the base.\n /// @param fyTokenTo Wallet receiving the fyToken.\n /// @param tradeToBase Whether the resulting fyToken should be traded for base tokens.\n /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18).\n /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18).\n /// @return lpTokensBurned The amount of pool tokens burned.\n /// @return baseOut The amount of base tokens returned.\n /// @return fyTokenOut The amount of fyTokens returned.\n function _burn(\n address baseTo,\n address fyTokenTo,\n bool tradeToBase,\n uint256 minRatio,\n uint256 maxRatio\n )\n internal\n returns (\n uint256 lpTokensBurned,\n uint256 baseOut,\n uint256 fyTokenOut\n )\n {\n // Gather data\n lpTokensBurned = _balanceOf[address(this)];\n uint256 supply = _totalSupply;\n\n Cache memory cache = _getCache();\n uint96 scaleFactor_ = scaleFactor;\n\n // The fyToken cache includes the virtual fyToken, equal to the supply.\n uint256 realFYTokenCached_ = cache.fyTokenCached - supply;\n\n // Check the burn wasn't sandwiched\n if (realFYTokenCached_ != 0) {\n if (\n (uint256(cache.sharesCached).wdiv(realFYTokenCached_) < minRatio) ||\n (uint256(cache.sharesCached).wdiv(realFYTokenCached_) > maxRatio)\n ) {\n revert SlippageDuringBurn(uint256(cache.sharesCached).wdiv(realFYTokenCached_), minRatio, maxRatio);\n }\n }\n\n // Calculate trade\n uint256 sharesOut = (lpTokensBurned * cache.sharesCached) / supply;\n fyTokenOut = (lpTokensBurned * realFYTokenCached_) / supply;\n\n if (tradeToBase) {\n sharesOut +=\n YieldMath.sharesOutForFYTokenIn( // This is a virtual sell\n (cache.sharesCached - sharesOut.u128()) * scaleFactor_, // Cache, minus virtual burn\n (cache.fyTokenCached - fyTokenOut.u128()) * scaleFactor_, // Cache, minus virtual burn\n fyTokenOut.u128() * scaleFactor_, // Sell the virtual fyToken obtained\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n _computeG2(cache.g1Fee),\n _getC(),\n mu\n ) /\n scaleFactor_;\n fyTokenOut = 0;\n }\n\n // Update TWAR\n _update(\n (cache.sharesCached - sharesOut).u128(),\n (cache.fyTokenCached - fyTokenOut - lpTokensBurned).u128(), // Exclude \"virtual\" fyToken from new minted LP tokens\n cache.sharesCached,\n cache.fyTokenCached\n );\n\n // Burn and transfer\n _burn(address(this), lpTokensBurned); // This is calling the actual ERC20 _burn.\n baseOut = _unwrap(baseTo);\n\n if (fyTokenOut != 0) fyToken.safeTransfer(fyTokenTo, fyTokenOut);\n\n // confirm new virtual fyToken balance is not less than new supply\n if ((cache.fyTokenCached - fyTokenOut - lpTokensBurned) < supply - lpTokensBurned) {\n revert FYTokenCachedBadState();\n }\n\n emit Liquidity(\n maturity,\n msg.sender,\n baseTo,\n fyTokenTo,\n baseOut.i256(),\n fyTokenOut.i256(),\n -(lpTokensBurned.i256())\n );\n\n if (supply == lpTokensBurned && block.timestamp >= maturity) {\n emit gg();\n }\n }\n\n /* TRADING FUNCTIONS\n ****************************************************************************************************************/\n\n /* buyBase\n\n I want to buy `uint128 baseOut` worth of base tokens.\n _______ I've transferred you some fyTokens -- that should be enough.\n / GUY \\ .:::::::::::::::::.\n (^^^| \\=========== : _______ __ __ : ┌─────────┐\n \\(\\/ | _ _ | :: | || | | |:: │no │\n \\ \\ (. o o | ::: | ___|| |_| |::: │lifeguard│\n \\ \\ | ~ | ::: | |___ | |::: └─┬─────┬─┘ ==+\n \\ \\ \\ == / ::: | ___||_ _|:: ok guy │ │ =======+\n \\ \\___| |___ ::: | | | | ::: _____│_____│______ |+\n \\ / \\__/ \\ :: |___| |___| :: .-'\"___________________`-.|+\n \\ \\ : : ( .'\" '-.)+\n --| GUY |\\_/\\ / `:::::::::::::::::' |`-..__________________..-'|+\n | | \\ \\/ / `-:::::::::::-' | |+\n | | \\ / `'''''''` | |+\n | | \\_/ | --- --- |+\n |______| | (o ) (o ) |+\n |__GG__| ┌──────────────┐ /`| |+\n | | │$ $│ / /| [ |+\n | | | │ B A S E │ / / | ---------- |+\n | | _| │ baseOut │\\.-\" ; \\ \\________/ /+\n | | | │$ $│),.-' `-..__________________..-' +=\n | | | └──────────────┘ | | | |\n ( ( | | | | |\n | | | | | | |\n | | | T----T T----T\n _| | | _..._L____J L____J _..._\n (_____[__) .` \"-. `% | | %` .-\" `.\n / \\ .: :. / \\\n '-..___|_..=:` `-:=.._|___..-'\n */\n /// Buy base with fyToken.\n /// The trader needs to have transferred in the necessary amount of fyTokens in advance.\n /// @param to Wallet receiving the base being bought.\n /// @param baseOut Amount of base being bought that will be deposited in `to` wallet.\n /// @param max This has been deprecated and was left in for backwards compatibility.\n /// @return fyTokenIn Amount of fyToken that will be taken from caller.\n function buyBase(\n address to,\n uint128 baseOut,\n uint128 max\n ) external virtual override returns (uint128 fyTokenIn) {\n // Calculate trade and cache values\n uint128 fyTokenBalance = _getFYTokenBalance();\n Cache memory cache = _getCache();\n\n uint128 sharesOut = _wrapPreview(baseOut).u128();\n fyTokenIn = _buyBasePreview(sharesOut, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee));\n\n // Checks\n if (fyTokenBalance - cache.fyTokenCached < fyTokenIn) {\n revert NotEnoughFYTokenIn(fyTokenBalance - cache.fyTokenCached, fyTokenIn);\n }\n\n // Update TWAR\n _update(\n cache.sharesCached - sharesOut,\n cache.fyTokenCached + fyTokenIn,\n cache.sharesCached,\n cache.fyTokenCached\n );\n\n // Transfer\n _unwrap(to);\n\n emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128()));\n }\n\n /// Returns how much fyToken would be required to buy `baseOut` base.\n /// @dev Note: This fn takes baseOut as a param while the internal fn takes sharesOut.\n /// @param baseOut Amount of base hypothetically desired.\n /// @return fyTokenIn Amount of fyToken hypothetically required.\n function buyBasePreview(uint128 baseOut) external view virtual override returns (uint128 fyTokenIn) {\n Cache memory cache = _getCache();\n fyTokenIn = _buyBasePreview(\n _wrapPreview(baseOut).u128(),\n cache.sharesCached,\n cache.fyTokenCached,\n _computeG2(cache.g1Fee)\n );\n }\n\n /// Returns how much fyToken would be required to buy `sharesOut`.\n /// @dev Note: This fn takes sharesOut as a param while the external fn takes baseOut.\n function _buyBasePreview(\n uint128 sharesOut,\n uint104 sharesBalance,\n uint104 fyTokenBalance,\n int128 g2_\n ) internal view beforeMaturity returns (uint128 fyTokenIn) {\n uint96 scaleFactor_ = scaleFactor;\n fyTokenIn =\n YieldMath.fyTokenInForSharesOut(\n sharesBalance * scaleFactor_,\n fyTokenBalance * scaleFactor_,\n sharesOut * scaleFactor_,\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n g2_,\n _getC(),\n mu\n ) /\n scaleFactor_;\n }\n\n /*buyFYToken\n\n I want to buy `uint128 fyTokenOut` worth of fyTokens.\n _______ I've transferred you some base tokens -- that should be enough.\n / GUY \\ ┌─────────┐\n (^^^| \\=========== ┌──────────────┐ │no │\n \\(\\/ | _ _ | │$ $│ │lifeguard│\n \\ \\ (. o o | │ ┌────────────┴─┐ └─┬─────┬─┘ ==+\n \\ \\ | ~ | │ │$ $│ hmm, let's see here │ │ =======+\n \\ \\ \\ == / │ │ B A S E │ _____│_____│______ |+\n \\ \\___| |___ │$│ │ .-'\"___________________`-.|+\n \\ / \\__/ \\ └─┤$ $│ ( .'\" '-.)+\n \\ \\ └──────────────┘ |`-..__________________..-'|+\n --| GUY |\\_/\\ / / | |+\n | | \\ \\/ / | |+\n | | \\ / _......._ /`| --- --- |+\n | | \\_/ .-:::::::::::-. / /| (o ) (o ) |+\n |______| .:::::::::::::::::. / / | |+\n |__GG__| : _______ __ __ : _.-\" ; | [ |+\n | | :: | || | | |::),.-' | ---------- |+\n | | | ::: | ___|| |_| |:::/ \\ \\________/ /+\n | | _| ::: | |___ | |::: `-..__________________..-' +=\n | | | ::: | ___||_ _|::: | | | |\n | | | ::: | | | | ::: | | | |\n ( ( | :: |___| |___| :: | | | |\n | | | : fyTokenOut : T----T T----T\n | | | `:::::::::::::::::' _..._L____J L____J _..._\n _| | | `-:::::::::::-' .` \"-. `% | | %` .-\" `.\n (_____[__) `'''''''` / \\ .: :. / \\\n '-..___|_..=:` `-:=.._|___..-'\n */\n /// Buy fyToken with base.\n /// The trader needs to have transferred in the correct amount of base tokens in advance.\n /// @param to Wallet receiving the fyToken being bought.\n /// @param fyTokenOut Amount of fyToken being bought that will be deposited in `to` wallet.\n /// @param max This has been deprecated and was left in for backwards compatibility.\n /// @return baseIn Amount of base that will be used.\n function buyFYToken(\n address to,\n uint128 fyTokenOut,\n uint128 max\n ) external virtual override returns (uint128 baseIn) {\n // Wrap any base assets found in contract.\n _wrap(address(this));\n\n // Calculate trade\n uint128 sharesBalance = _getSharesBalance();\n Cache memory cache = _getCache();\n uint128 sharesIn = _buyFYTokenPreview(\n fyTokenOut,\n cache.sharesCached,\n cache.fyTokenCached,\n _computeG1(cache.g1Fee)\n );\n baseIn = _unwrapPreview(sharesIn).u128();\n\n // Checks\n if (sharesBalance - cache.sharesCached < sharesIn)\n revert NotEnoughBaseIn(_unwrapPreview(sharesBalance - cache.sharesCached), baseIn);\n\n // Update TWAR\n _update(\n cache.sharesCached + sharesIn,\n cache.fyTokenCached - fyTokenOut,\n cache.sharesCached,\n cache.fyTokenCached\n );\n\n // Transfer\n fyToken.safeTransfer(to, fyTokenOut);\n\n // confirm new virtual fyToken balance is not less than new supply\n if ((cache.fyTokenCached - fyTokenOut) < _totalSupply) {\n revert FYTokenCachedBadState();\n }\n\n emit Trade(maturity, msg.sender, to, -(baseIn.i128()), fyTokenOut.i128());\n }\n\n /// Returns how much base would be required to buy `fyTokenOut`.\n /// @param fyTokenOut Amount of fyToken hypothetically desired.\n /// @dev Note: This returns an amount in base. The internal fn returns amount of shares.\n /// @return baseIn Amount of base hypothetically required.\n function buyFYTokenPreview(uint128 fyTokenOut) external view virtual override returns (uint128 baseIn) {\n Cache memory cache = _getCache();\n uint128 sharesIn = _buyFYTokenPreview(\n fyTokenOut,\n cache.sharesCached,\n cache.fyTokenCached,\n _computeG1(cache.g1Fee)\n );\n\n baseIn = _unwrapPreview(sharesIn).u128();\n }\n\n /// Returns how many shares are required to buy `fyTokenOut` fyTokens.\n /// @dev Note: This returns an amount in shares. The external fn returns amount of base.\n function _buyFYTokenPreview(\n uint128 fyTokenOut,\n uint128 sharesBalance,\n uint128 fyTokenBalance,\n int128 g1_\n ) internal view beforeMaturity returns (uint128 sharesIn) {\n uint96 scaleFactor_ = scaleFactor;\n\n sharesIn =\n YieldMath.sharesInForFYTokenOut(\n sharesBalance * scaleFactor_,\n fyTokenBalance * scaleFactor_,\n fyTokenOut * scaleFactor_,\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n g1_,\n _getC(),\n mu\n ) /\n scaleFactor_;\n\n uint128 newSharesMulMu = _mulMu(sharesBalance + sharesIn).u128();\n if ((fyTokenBalance - fyTokenOut) < newSharesMulMu) {\n revert NegativeInterestRatesNotAllowed(fyTokenBalance - fyTokenOut, newSharesMulMu);\n }\n }\n\n /* sellBase\n\n I've transfered you some base tokens.\n _______ Can you swap them for fyTokens?\n / GUY \\ ┌─────────┐\n (^^^| \\=========== ┌──────────────┐ │no │\n \\(\\/ | _ _ | │$ $│ │lifeguard│\n \\ \\ (. o o | │ ┌────────────┴─┐ └─┬─────┬─┘ ==+\n \\ \\ | ~ | │ │$ $│ can │ │ =======+\n \\ \\ \\ == / │ │ │ _____│_____│______ |+\n \\ \\___| |___ │$│ baseIn │ .-'\"___________________`-.|+\n \\ / \\__/ \\ └─┤$ $│ ( .'\" '-.)+\n \\ \\ ( └──────────────┘ |`-..__________________..-'|+\n --| GUY |\\_/\\ / / | |+\n | | \\ \\/ / | |+\n | | \\ / _......._ /`| --- --- |+\n | | \\_/ .-:::::::::::-. / /| (o ) (o ) |+\n |______| .:::::::::::::::::. / / | |+\n |__GG__| : _______ __ __ : _.-\" ; | [ |+\n | | :: | || | | |::),.-' | ---------- |+\n | | | ::: | ___|| |_| |:::/ \\ \\________/ /+\n | | _| ::: | |___ | |::: `-..__________________..-' +=\n | | | ::: | ___||_ _|::: | | | |\n | | | ::: | | | | ::: | | | |\n ( ( | :: |___| |___| :: | | | |\n | | | : ???? : T----T T----T\n | | | `:::::::::::::::::' _..._L____J L____J _..._\n _| | | `-:::::::::::-' .` \"-. `% | | %` .-\" `.\n (_____[__) `'''''''` / \\ .: :. / \\\n '-..___|_..=:` `-:=.._|___..-'\n */\n /// Sell base for fyToken.\n /// The trader needs to have transferred the amount of base to sell to the pool before calling this fn.\n /// @param to Wallet receiving the fyToken being bought.\n /// @param min Minimum accepted amount of fyToken.\n /// @return fyTokenOut Amount of fyToken that will be deposited on `to` wallet.\n function sellBase(address to, uint128 min) external virtual override returns (uint128 fyTokenOut) {\n // Wrap any base assets found in contract.\n _wrap(address(this));\n\n // Calculate trade\n Cache memory cache = _getCache();\n uint104 sharesBalance = _getSharesBalance();\n uint128 sharesIn = sharesBalance - cache.sharesCached;\n fyTokenOut = _sellBasePreview(sharesIn, cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee));\n\n // Check slippage\n if (fyTokenOut < min) revert SlippageDuringSellBase(fyTokenOut, min);\n\n // Update TWAR\n _update(sharesBalance, cache.fyTokenCached - fyTokenOut, cache.sharesCached, cache.fyTokenCached);\n\n // Transfer\n fyToken.safeTransfer(to, fyTokenOut);\n\n // confirm new virtual fyToken balance is not less than new supply\n if ((cache.fyTokenCached - fyTokenOut) < _totalSupply) {\n revert FYTokenCachedBadState();\n }\n\n emit Trade(maturity, msg.sender, to, -(_unwrapPreview(sharesIn).u128().i128()), fyTokenOut.i128());\n }\n\n /// Returns how much fyToken would be obtained by selling `baseIn`.\n /// @dev Note: This external fn takes baseIn while the internal fn takes sharesIn.\n /// @param baseIn Amount of base hypothetically sold.\n /// @return fyTokenOut Amount of fyToken hypothetically bought.\n function sellBasePreview(uint128 baseIn) external view virtual override returns (uint128 fyTokenOut) {\n Cache memory cache = _getCache();\n fyTokenOut = _sellBasePreview(\n _wrapPreview(baseIn).u128(),\n cache.sharesCached,\n cache.fyTokenCached,\n _computeG1(cache.g1Fee)\n );\n }\n\n /// Returns how much fyToken would be obtained by selling `sharesIn`.\n /// @dev Note: This internal fn takes sharesIn while the external fn takes baseIn.\n function _sellBasePreview(\n uint128 sharesIn,\n uint104 sharesBalance,\n uint104 fyTokenBalance,\n int128 g1_\n ) internal view beforeMaturity returns (uint128 fyTokenOut) {\n uint96 scaleFactor_ = scaleFactor;\n fyTokenOut =\n YieldMath.fyTokenOutForSharesIn(\n sharesBalance * scaleFactor_,\n fyTokenBalance * scaleFactor_,\n sharesIn * scaleFactor_,\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n g1_,\n _getC(),\n mu\n ) /\n scaleFactor_;\n\n uint128 newSharesMulMu = _mulMu(sharesBalance + sharesIn).u128();\n if ((fyTokenBalance - fyTokenOut) < newSharesMulMu) {\n revert NegativeInterestRatesNotAllowed(fyTokenBalance - fyTokenOut, newSharesMulMu);\n }\n }\n\n /*sellFYToken\n I've transferred you some fyTokens.\n _______ Can you swap them for base?\n / GUY \\ .:::::::::::::::::.\n (^^^| \\=========== : _______ __ __ : ┌─────────┐\n \\(\\/ | _ _ | :: | || | | |:: │no │\n \\ \\ (. o o | ::: | ___|| |_| |::: │lifeguard│\n \\ \\ | ~ | ::: | |___ | |::: └─┬─────┬─┘ ==+\n \\ \\ \\ == / ::: | ___||_ _|::: lfg │ │ =======+\n \\ \\___| |___ ::: | | | | ::: _____│_____│______ |+\n \\ / \\__/ \\ :: |___| |___| :: .-'\"___________________`-.|+\n \\ \\ : fyTokenIn : ( .'\" '-.)+\n --| GUY |\\_/\\ / `:::::::::::::::::' |`-..__________________..-'|+\n | | \\ \\/ / `-:::::::::::-' | |+\n | | \\ / `'''''''` | |+\n | | \\_/ | --- --- |+\n |______| | (o ) (o ) |+\n |__GG__| ┌──────────────┐ /`| |+\n | | │$ $│ / /| [ |+\n | | | │ B A S E │ / / | ---------- |+\n | | _| │ ???? │\\.-\" ; \\ \\________/ /+\n | | | │$ $│),.-' `-..__________________..-' +=\n | | | └──────────────┘ | | | |\n ( ( | | | | |\n | | | | | | |\n | | | T----T T----T\n _| | | _..._L____J L____J _..._\n (_____[__) .` \"-. `% | | %` .-\" `.\n / \\ .: :. / \\\n '-..___|_..=:` `-:=.._|___..-'\n */\n /// Sell fyToken for base.\n /// The trader needs to have transferred the amount of fyToken to sell to the pool before in the same transaction.\n /// @param to Wallet receiving the base being bought.\n /// @param min Minimum accepted amount of base.\n /// @return baseOut Amount of base that will be deposited on `to` wallet.\n function sellFYToken(address to, uint128 min) external virtual override returns (uint128 baseOut) {\n // Calculate trade\n Cache memory cache = _getCache();\n uint104 fyTokenBalance = _getFYTokenBalance();\n uint128 fyTokenIn = fyTokenBalance - cache.fyTokenCached;\n uint128 sharesOut = _sellFYTokenPreview(\n fyTokenIn,\n cache.sharesCached,\n cache.fyTokenCached,\n _computeG2(cache.g1Fee)\n );\n\n // Update TWAR\n _update(cache.sharesCached - sharesOut, fyTokenBalance, cache.sharesCached, cache.fyTokenCached);\n\n // Transfer\n baseOut = _unwrap(to).u128();\n\n // Check slippage\n if (baseOut < min) revert SlippageDuringSellFYToken(baseOut, min);\n\n emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128()));\n }\n\n /// Returns how much base would be obtained by selling `fyTokenIn` fyToken.\n /// @dev Note: This external fn returns baseOut while the internal fn returns sharesOut.\n /// @param fyTokenIn Amount of fyToken hypothetically sold.\n /// @return baseOut Amount of base hypothetically bought.\n function sellFYTokenPreview(uint128 fyTokenIn) public view virtual returns (uint128 baseOut) {\n Cache memory cache = _getCache();\n uint128 sharesOut = _sellFYTokenPreview(\n fyTokenIn,\n cache.sharesCached,\n cache.fyTokenCached,\n _computeG2(cache.g1Fee)\n );\n baseOut = _unwrapPreview(sharesOut).u128();\n }\n\n /// Returns how much shares would be obtained by selling `fyTokenIn` fyToken.\n /// @dev Note: This internal fn returns sharesOut while the external fn returns baseOut.\n function _sellFYTokenPreview(\n uint128 fyTokenIn,\n uint104 sharesBalance,\n uint104 fyTokenBalance,\n int128 g2_\n ) internal view beforeMaturity returns (uint128 sharesOut) {\n uint96 scaleFactor_ = scaleFactor;\n\n sharesOut =\n YieldMath.sharesOutForFYTokenIn(\n sharesBalance * scaleFactor_,\n fyTokenBalance * scaleFactor_,\n fyTokenIn * scaleFactor_,\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n g2_,\n _getC(),\n mu\n ) /\n scaleFactor_;\n }\n\n /* LIQUIDITY FUNCTIONS\n ****************************************************************************************************************/\n\n /// @inheritdoc IPool\n function maxFYTokenIn() public view override returns (uint128 fyTokenIn) {\n uint96 scaleFactor_ = scaleFactor;\n Cache memory cache = _getCache();\n fyTokenIn =\n YieldMath.maxFYTokenIn(\n cache.sharesCached * scaleFactor_,\n cache.fyTokenCached * scaleFactor_,\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n _computeG2(cache.g1Fee),\n _getC(),\n mu\n ) /\n scaleFactor_;\n }\n\n /// @inheritdoc IPool\n function maxFYTokenOut() public view override returns (uint128 fyTokenOut) {\n uint96 scaleFactor_ = scaleFactor;\n Cache memory cache = _getCache();\n fyTokenOut =\n YieldMath.maxFYTokenOut(\n cache.sharesCached * scaleFactor_,\n cache.fyTokenCached * scaleFactor_,\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n _computeG1(cache.g1Fee),\n _getC(),\n mu\n ) /\n scaleFactor_;\n }\n\n /// @inheritdoc IPool\n function maxBaseIn() public view override returns (uint128 baseIn) {\n uint96 scaleFactor_ = scaleFactor;\n Cache memory cache = _getCache();\n uint128 sharesIn = ((YieldMath.maxSharesIn(\n cache.sharesCached * scaleFactor_,\n cache.fyTokenCached * scaleFactor_,\n maturity - uint32(block.timestamp), // This can't be called after maturity\n ts,\n _computeG1(cache.g1Fee),\n _getC(),\n mu\n ) / 1e8) * 1e8) / scaleFactor_; // Shave 8 wei/decimals to deal with precision issues on the decimal functions\n\n baseIn = _unwrapPreview(sharesIn).u128();\n }\n\n /// @inheritdoc IPool\n function maxBaseOut() public view override returns (uint128 baseOut) {\n uint128 sharesOut = _getCache().sharesCached;\n baseOut = _unwrapPreview(sharesOut).u128();\n }\n\n /// @inheritdoc IPool\n function invariant() public view override returns (uint128 result) {\n uint96 scaleFactor_ = scaleFactor;\n Cache memory cache = _getCache();\n result =\n YieldMath.invariant(\n cache.sharesCached * scaleFactor_,\n cache.fyTokenCached * scaleFactor_,\n _totalSupply * scaleFactor_,\n maturity - uint32(block.timestamp),\n ts,\n _computeG2(cache.g1Fee),\n _getC(),\n mu\n ) /\n scaleFactor_;\n }\n\n /* WRAPPING FUNCTIONS\n ****************************************************************************************************************/\n\n /// Wraps any base asset tokens found in the contract, converting them to base tokenized vault shares.\n /// @dev This is provided as a convenience and uses the 4626 deposit method.\n /// @param receiver The address to which the wrapped tokens will be sent.\n /// @return shares The amount of wrapped tokens sent to the receiver.\n function wrap(address receiver) external returns (uint256 shares) {\n shares = _wrap(receiver);\n }\n\n /// Internal function for wrapping base tokens whichwraps the entire balance of base found in this contract.\n /// @dev This should be overridden by modules.\n /// @param receiver The address the wrapped tokens should be sent.\n /// @return shares The amount of wrapped tokens that are sent to the receiver.\n function _wrap(address receiver) internal virtual returns (uint256 shares) {\n uint256 assets = baseToken.balanceOf(address(this));\n if (assets == 0) {\n shares = 0;\n } else {\n shares = IERC4626(address(sharesToken)).deposit(assets, receiver);\n }\n }\n\n /// Preview how many shares will be received when depositing a given amount of base.\n /// @dev This should be overridden by modules.\n /// @param assets The amount of base tokens to preview the deposit.\n /// @return shares The amount of shares that would be returned from depositing.\n function wrapPreview(uint256 assets) external view returns (uint256 shares) {\n shares = _wrapPreview(assets);\n }\n\n /// Internal function to preview how many shares will be received when depositing a given amount of assets.\n /// @param assets The amount of base tokens to preview the deposit.\n /// @return shares The amount of shares that would be returned from depositing.\n function _wrapPreview(uint256 assets) internal view virtual returns (uint256 shares) {\n if (assets == 0) {\n shares = 0;\n } else {\n shares = IERC4626(address(sharesToken)).previewDeposit(assets);\n }\n }\n\n /// Unwraps base shares found unaccounted for in this contract, converting them to the base assets.\n /// @dev This is provided as a convenience and uses the 4626 redeem method.\n /// @param receiver The address to which the assets will be sent.\n /// @return assets The amount of asset tokens sent to the receiver.\n function unwrap(address receiver) external returns (uint256 assets) {\n assets = _unwrap(receiver);\n }\n\n /// Internal function for unwrapping unaccounted for base in this contract.\n /// @dev This should be overridden by modules.\n /// @param receiver The address the wrapped tokens should be sent.\n /// @return assets The amount of base assets sent to the receiver.\n function _unwrap(address receiver) internal virtual returns (uint256 assets) {\n uint256 surplus = _getSharesBalance() - sharesCached;\n if (surplus == 0) {\n assets = 0;\n } else {\n // The third param of the 4626 redeem fn, `owner`, is always this contract address.\n assets = IERC4626(address(sharesToken)).redeem(surplus, receiver, address(this));\n }\n }\n\n /// Preview how many asset tokens will be received when unwrapping a given amount of shares.\n /// @param shares The amount of shares to preview a redemption.\n /// @return assets The amount of base tokens that would be returned from redeeming.\n function unwrapPreview(uint256 shares) external view returns (uint256 assets) {\n assets = _unwrapPreview(shares);\n }\n\n /// Internal function to preview how base asset tokens will be received when unwrapping a given amount of shares.\n /// @dev This should be overridden by modules.\n /// @param shares The amount of shares to preview a redemption.\n /// @return assets The amount of base tokens that would be returned from redeeming.\n function _unwrapPreview(uint256 shares) internal view virtual returns (uint256 assets) {\n if (shares == 0) {\n assets = 0;\n } else {\n assets = IERC4626(address(sharesToken)).previewRedeem(shares);\n }\n }\n\n /* BALANCES MANAGEMENT AND ADMINISTRATIVE FUNCTIONS\n Note: The sync() function has been discontinued and removed.\n *****************************************************************************************************************/\n /*\n _____________________________________\n |o o o o o o o o o o o o o o o o o|\n |o o o o o o o o o o o o o o o o o|\n ||_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_||\n || | | | | | | | | | | | | | | | ||\n |o o o o o o o o o o o o o o o o o|\n |o o o o o o o o o o o o o o o o o|\n |o o o o o o o o o o o o o o o o o|\n |o o o o o o o o o o o o o o o o o|\n _|o_o_o_o_o_o_o_o_o_o_o_o_o_o_o_o_o|_\n \"Poolie's Abacus\" - ejm */\n\n /// Calculates cumulative ratio as of current timestamp. Can be consumed for TWAR observations.\n /// @dev See UniV2 implmentation: https://tinyurl.com/UniV2currentCumulativePrice\n /// @return currentCumulativeRatio_ is the cumulative ratio up to the current timestamp as ray.\n /// @return blockTimestampCurrent is the current block timestamp that the currentCumulativeRatio was computed with.\n function currentCumulativeRatio()\n external\n view\n virtual\n returns (uint256 currentCumulativeRatio_, uint256 blockTimestampCurrent)\n {\n blockTimestampCurrent = block.timestamp;\n uint256 timeElapsed;\n unchecked {\n timeElapsed = blockTimestampCurrent - blockTimestampLast;\n }\n\n // Multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals\n currentCumulativeRatio_ = cumulativeRatioLast + (fyTokenCached * timeElapsed).rdiv(_mulMu(sharesCached));\n }\n\n /// Update cached values and, on the first call per block, update cumulativeRatioLast.\n /// cumulativeRatioLast is a LAGGING, time weighted sum of the reserves ratio which is updated as follows:\n ///\n /// cumulativeRatioLast += old fyTokenReserves / old baseReserves * seconds elapsed since blockTimestampLast\n ///\n /// NOTE: baseReserves is calculated as mu * sharesReserves\n ///\n /// Example:\n /// First mint creates a ratio of 1:1.\n /// 300 seconds later a trade occurs:\n /// - cumulativeRatioLast is updated: 0 + 1/1 * 300 == 300\n /// - sharesCached and fyTokenCached are updated with the new reserves amounts.\n /// - This causes the ratio to skew to 1.1 / 1.\n /// 200 seconds later another trade occurs:\n /// - NOTE: During this 200 seconds, cumulativeRatioLast == 300, which represents the \"last\" updated amount.\n /// - cumulativeRatioLast is updated: 300 + 1.1 / 1 * 200 == 520\n /// - sharesCached and fyTokenCached updated accordingly...etc.\n ///\n /// @dev See UniV2 implmentation: https://tinyurl.com/UniV2UpdateCumulativePrice\n function _update(\n uint128 sharesBalance,\n uint128 fyBalance,\n uint104 sharesCached_,\n uint104 fyTokenCached_\n ) internal {\n // No need to update and spend gas on SSTORE if reserves haven't changed.\n if (sharesBalance == sharesCached_ && fyBalance == fyTokenCached_) return;\n\n uint32 blockTimestamp = uint32(block.timestamp);\n uint256 timeElapsed = blockTimestamp - blockTimestampLast; // reverts on underflow\n\n uint256 oldCumulativeRatioLast = cumulativeRatioLast;\n uint256 newCumulativeRatioLast = oldCumulativeRatioLast;\n if (timeElapsed > 0 && fyTokenCached_ > 0 && sharesCached_ > 0) {\n // Multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals\n newCumulativeRatioLast += (fyTokenCached_ * timeElapsed).rdiv(_mulMu(sharesCached_));\n }\n\n blockTimestampLast = blockTimestamp;\n cumulativeRatioLast = newCumulativeRatioLast;\n\n // Update the reserves caches\n uint104 newSharesCached = sharesBalance.u104();\n uint104 newFYTokenCached = fyBalance.u104();\n\n sharesCached = newSharesCached;\n fyTokenCached = newFYTokenCached;\n\n emit Sync(newSharesCached, newFYTokenCached, newCumulativeRatioLast);\n }\n\n /// Exposes the 64.64 factor used for determining fees.\n /// A value of 1 (in 64.64) means no fees. g1 < 1 because it is used when selling base shares to the pool.\n /// @dev Converts state var cache.g1Fee(fp4) to a 64bit divided by 10,000\n /// Useful for external contracts that need to perform calculations related to pool.\n /// @return a 64bit factor used for applying fees when buying fyToken/selling base.\n function g1() external view returns (int128) {\n Cache memory cache = _getCache();\n return _computeG1(cache.g1Fee);\n }\n\n /// Returns the ratio of net proceeds after fees, for buying fyToken\n function _computeG1(uint16 g1Fee_) internal pure returns (int128) {\n return uint256(g1Fee_).divu(10000);\n }\n\n /// Exposes the 64.64 factor used for determining fees.\n /// A value of 1 means no fees. g2 > 1 because it is used when selling fyToken to the pool.\n /// @dev Calculated by dividing 10,000 by state var cache.g1Fee(fp4) and converting to 64bit.\n /// Useful for external contracts that need to perform calculations related to pool.\n /// @return a 64bit factor used for applying fees when selling fyToken/buying base.\n function g2() external view returns (int128) {\n Cache memory cache = _getCache();\n return _computeG2(cache.g1Fee);\n }\n\n /// Returns the ratio of net proceeds after fees, for selling fyToken\n function _computeG2(uint16 g1Fee_) internal pure returns (int128) {\n // Divide 1 (64.64) by g1\n return uint256(10000).divu(g1Fee_);\n }\n\n /// Returns the shares balance with the same decimals as the underlying base asset.\n /// @dev NOTE: If the decimals of the share token does not match the base token, then the amount of shares returned\n /// will be adjusted to match the decimals of the base token.\n /// @return The current balance of the pool's shares tokens as uint128 for consistency with other functions.\n function getSharesBalance() external view returns (uint128) {\n return _getSharesBalance();\n }\n\n /// Returns the shares balance\n /// @dev NOTE: The decimals returned here must match the decimals of the base token. If not, then this fn should\n // be overriden by modules.\n function _getSharesBalance() internal view virtual returns (uint104) {\n return sharesToken.balanceOf(address(this)).u104();\n }\n\n /// Returns the base balance.\n /// @dev Returns uint128 for backwards compatibility\n /// @return The current balance of the pool's base tokens.\n function getBaseBalance() external view returns (uint128) {\n return _getBaseBalance().u128();\n }\n\n /// Returns the base balance\n function _getBaseBalance() internal view virtual returns (uint256) {\n return (_getSharesBalance() * _getCurrentSharePrice()) / 10**baseDecimals;\n }\n\n /// Returns the base token current price.\n /// @return The price of 1 share of a tokenized vault token in terms of its base cast as uint256.\n function getCurrentSharePrice() external view returns (uint256) {\n return _getCurrentSharePrice();\n }\n\n /// Returns the base token current price.\n /// @dev This assumes the shares, base, and lp tokens all use the same decimals.\n /// This function should be overriden by modules.\n /// @return The price of 1 share of a tokenized vault token in terms of its base asset cast as uint256.\n function _getCurrentSharePrice() internal view virtual returns (uint256) {\n uint256 scalar = 10**baseDecimals;\n return IERC4626(address(sharesToken)).convertToAssets(scalar);\n }\n\n /// Returns current price of 1 share in 64bit.\n /// Useful for external contracts that need to perform calculations related to pool.\n /// @return The current price (as determined by the token) scalled to 18 digits and converted to 64.64.\n function getC() external view returns (int128) {\n return _getC();\n }\n\n /// Returns the c based on the current price\n function _getC() internal view returns (int128) {\n return (_getCurrentSharePrice() * scaleFactor).divu(1e18);\n }\n\n /// Returns the all storage vars except for cumulativeRatioLast\n /// @return Cached shares token balance.\n /// @return Cached virtual FY token balance which is the actual balance plus the pool token supply.\n /// @return Timestamp that balances were last cached.\n /// @return g1Fee This is a fp4 number where 10_000 is 1.\n function getCache()\n public\n view\n virtual\n returns (\n uint104,\n uint104,\n uint32,\n uint16\n )\n {\n return (sharesCached, fyTokenCached, blockTimestampLast, g1Fee);\n }\n\n /// Returns the all storage vars except for cumulativeRatioLast\n /// @dev This returns the same info as external getCache but uses a struct to help with stack too deep.\n /// @return cache A struct containing:\n /// g1Fee a fp4 number where 10_000 is 1.\n /// Cached base token balance.\n /// Cached virtual FY token balance which is the actual balance plus the pool token supply.\n /// Timestamp that balances were last cached.\n\n function _getCache() internal view virtual returns (Cache memory cache) {\n cache = Cache(g1Fee, sharesCached, fyTokenCached, blockTimestampLast);\n }\n\n /// The \"virtual\" fyToken balance, which is the actual balance plus the pool token supply.\n /// @dev For more explanation about using the LP tokens as part of the virtual reserves see:\n /// https://hackmd.io/lRZ4mgdrRgOpxZQXqKYlFw\n /// Returns uint128 for backwards compatibility\n /// @return The current balance of the pool's fyTokens plus the current balance of the pool's\n /// total supply of LP tokens as a uint104\n function getFYTokenBalance() public view virtual override returns (uint128) {\n return _getFYTokenBalance();\n }\n\n /// Returns the \"virtual\" fyToken balance, which is the real balance plus the pool token supply.\n function _getFYTokenBalance() internal view returns (uint104) {\n return (fyToken.balanceOf(address(this)) + _totalSupply).u104();\n }\n\n /// Returns mu multipled by given amount.\n /// @param amount Amount as standard fp number.\n /// @return product Return standard fp number retaining decimals of provided amount.\n function _mulMu(uint256 amount) internal view returns (uint256 product) {\n product = mu.mulu(amount);\n }\n\n /// Retrieve any shares tokens not accounted for in the cache.\n /// @param to Address of the recipient of the shares tokens.\n /// @return retrieved The amount of shares tokens sent.\n function retrieveShares(address to) external virtual override returns (uint128 retrieved) {\n retrieved = _getSharesBalance() - sharesCached; // Cache can never be above balances\n sharesToken.safeTransfer(to, retrieved);\n }\n\n /// Retrieve all base tokens found in this contract.\n /// @param to Address of the recipient of the base tokens.\n /// @return retrieved The amount of base tokens sent.\n function retrieveBase(address to) external virtual override returns (uint128 retrieved) {\n // This and most other pools do not keep any baseTokens, so retrieve everything.\n // Note: For PoolNonTv, baseToken == sharesToken so must override this fn.\n retrieved = baseToken.balanceOf(address(this)).u128();\n baseToken.safeTransfer(to, retrieved);\n }\n\n /// Retrieve any fyTokens not accounted for in the cache.\n /// @param to Address of the recipient of the fyTokens.\n /// @return retrieved The amount of fyTokens sent.\n function retrieveFYToken(address to) external virtual override returns (uint128 retrieved) {\n // related: https://twitter.com/transmissions11/status/1505994136389754880?s=20&t=1H6gvzl7DJLBxXqnhTuOVw\n retrieved = _getFYTokenBalance() - fyTokenCached; // Cache can never be above balances\n fyToken.safeTransfer(to, retrieved);\n // Now the balances match the cache, so no need to update the TWAR\n }\n\n /// Sets g1 as an fp4, g1 <= 1.0\n /// @dev These numbers are converted to 64.64 and used to calculate g1 by dividing them, or g2 from 1/g1\n function setFees(uint16 g1Fee_) public auth {\n if (g1Fee_ > 10000) {\n revert InvalidFee(g1Fee_);\n }\n g1Fee = g1Fee_;\n emit FeesSet(g1Fee_);\n }\n\n /// Returns baseToken.\n /// @dev This has been deprecated and may be removed in future pools.\n /// @return baseToken The base token for this pool. The base of the shares and the fyToken.\n function base() external view returns (IERC20) {\n // Returns IERC20 instead of IERC20Like (IERC20Metadata) for backwards compatability.\n return IERC20(address(baseToken));\n }\n}\n"
},
"@yield-protocol/yieldspace-tv/src/interfaces/IEToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.15;\nimport \"@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol\";\nimport \"@yield-protocol/utils-v2/contracts/token/IERC20.sol\";\n\ninterface IEToken is IERC20, IERC20Metadata {\n\n /// @notice Convert an eToken balance to an underlying amount, taking into account current exchange rate\n /// @param balance eToken balance, in internal book-keeping units (18 decimals)\n /// @return Amount in underlying units, (same decimals as underlying token)\n function convertBalanceToUnderlying(uint balance) external view returns (uint);\n\n\n /// @notice Convert an underlying amount to an eToken balance, taking into account current exchange rate\n /// @param underlyingAmount Amount in underlying units (same decimals as underlying token)\n /// @return eToken balance, in internal book-keeping units (18 decimals)\n function convertUnderlyingToBalance(uint underlyingAmount) external view returns (uint);\n\n /// @notice Transfer underlying tokens from sender to the Euler pool, and increase account's eTokens.\n /// @param subAccountId 0 for primary, 1-255 for a sub-account.\n /// @param amount In underlying units (use max uint256 for full underlying token balance).\n /// subAccountId is the id of optional subaccounts that can be used by the depositor.\n function deposit(uint subAccountId, uint amount) external;\n\n function underlyingAsset() external view returns (address);\n\n /// @notice Transfer underlying tokens from Euler pool to sender, and decrease account's eTokens\n /// @param subAccountId 0 for primary, 1-255 for a sub-account\n /// @param amount In underlying units (use max uint256 for full pool balance)\n function withdraw(uint subAccountId, uint amount) external;\n\n}\n"
},
"@yield-protocol/yieldspace-tv/src/Pool/PoolImports.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.15;\n\nimport \"./PoolEvents.sol\";\nimport \"./PoolErrors.sol\";\n\nimport {CastU256U128} from \"@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol\";\nimport {CastU256U104} from \"@yield-protocol/utils-v2/contracts/cast/CastU256U104.sol\";\nimport {CastU256I256} from \"@yield-protocol/utils-v2/contracts/cast/CastU256I256.sol\";\nimport {CastU128U104} from \"@yield-protocol/utils-v2/contracts/cast/CastU128U104.sol\";\nimport {CastU128I128} from \"@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol\";\n\nimport {Exp64x64} from \"../Exp64x64.sol\";\nimport {Math64x64} from \"../Math64x64.sol\";\nimport {YieldMath} from \"../YieldMath.sol\";\nimport {WDiv} from \"@yield-protocol/utils-v2/contracts/math/WDiv.sol\";\nimport {RDiv} from \"@yield-protocol/utils-v2/contracts/math/RDiv.sol\";\n\nimport {IPool} from \"../interfaces/IPool.sol\";\nimport {IERC4626} from \"../interfaces/IERC4626.sol\";\nimport {IMaturingToken} from \"../interfaces/IMaturingToken.sol\";\nimport {ERC20Permit} from \"@yield-protocol/utils-v2/contracts/token/ERC20Permit.sol\";\nimport {AccessControl} from \"@yield-protocol/utils-v2/contracts/access/AccessControl.sol\";\nimport {ERC20, IERC20Metadata as IERC20Like, IERC20} from \"@yield-protocol/utils-v2/contracts/token/ERC20.sol\";\nimport {MinimalTransferHelper} from \"@yield-protocol/utils-v2/contracts/token/MinimalTransferHelper.sol\";\n"
},
"@yield-protocol/yieldspace-tv/src/Math64x64.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity >=0.8.15; /*\n __ ___ _ _\n \\ \\ / (_) | | | | ███╗ ███╗ █████╗ ████████╗██╗ ██╗ ██████╗ ██╗ ██╗██╗ ██╗ ██████╗ ██╗ ██╗\n \\ \\_/ / _ ___| | __| | ████╗ ████║██╔══██╗╚══██╔══╝██║ ██║██╔════╝ ██║ ██║╚██╗██╔╝██╔════╝ ██║ ██║\n \\ / | |/ _ \\ |/ _` | ██╔████╔██║███████║ ██║ ███████║███████╗ ███████║ ╚███╔╝ ███████╗ ███████║\n | | | | __/ | (_| | ██║╚██╔╝██║██╔══██║ ██║ ██╔══██║██╔═══██╗╚════██║ ██╔██╗ ██╔═══██╗╚════██║\n |_| |_|\\___|_|\\__,_| ██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║╚██████╔╝ ██║██╔╝ ██╗╚██████╔╝ ██║\n yieldprotocol.com ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝\n*/\n\n/// Smart contract library of mathematical functions operating with signed\n/// 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n/// basically a simple fraction whose numerator is signed 128-bit integer and\n/// denominator is 2^64. As long as denominator is always the same, there is no\n/// need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n/// represented by int128 type holding only the numerator.\n/// @title Math64x64.sol\n/// @author Mikhail Vladimirov - ABDK Consulting\n/// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol\nlibrary Math64x64 {\n /* CONVERTERS\n ******************************************************************************************************************/\n /*\n * Minimum value signed 64.64-bit fixed point number may have.\n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have.\n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /// @dev Convert signed 256-bit integer number into signed 64.64-bit fixed point\n /// number. Revert on overflow.\n /// @param x signed 256-bit integer number\n /// @return signed 64.64-bit fixed point number\n function fromInt(int256 x) internal pure returns (int128) {\n unchecked {\n require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128(x << 64);\n }\n }\n\n /// @dev Convert signed 64.64 fixed point number into signed 64-bit integer number rounding down.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64-bit integer number\n function toInt(int128 x) internal pure returns (int64) {\n unchecked {\n return int64(x >> 64);\n }\n }\n\n /// @dev Convert unsigned 256-bit integer number into signed 64.64-bit fixed point number. Revert on overflow.\n /// @param x unsigned 256-bit integer number\n /// @return signed 64.64-bit fixed point number\n function fromUInt(uint256 x) internal pure returns (int128) {\n unchecked {\n require(x <= 0x7FFFFFFFFFFFFFFF);\n return int128(int256(x << 64));\n }\n }\n\n /// @dev Convert signed 64.64 fixed point number into unsigned 64-bit integer number rounding down.\n /// Reverts on underflow.\n /// @param x signed 64.64-bit fixed point number\n /// @return unsigned 64-bit integer number\n function toUInt(int128 x) internal pure returns (uint64) {\n unchecked {\n require(x >= 0);\n return uint64(uint128(x >> 64));\n }\n }\n\n /// @dev Convert signed 128.128 fixed point number into signed 64.64-bit fixed point number rounding down.\n /// Reverts on overflow.\n /// @param x signed 128.128-bin fixed point number\n /// @return signed 64.64-bit fixed point number\n function from128x128(int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require(result >= MIN_64x64 && result <= MAX_64x64);\n return int128(result);\n }\n }\n\n /// @dev Convert signed 64.64 fixed point number into signed 128.128 fixed point number.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 128.128 fixed point number\n function to128x128(int128 x) internal pure returns (int256) {\n unchecked {\n return int256(x) << 64;\n }\n }\n\n /* OPERATIONS\n ******************************************************************************************************************/\n\n /// @dev Calculate x + y. Revert on overflow.\n /// @param x signed 64.64-bit fixed point number\n /// @param y signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function add(int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require(result >= MIN_64x64 && result <= MAX_64x64);\n return int128(result);\n }\n }\n\n /// @dev Calculate x - y. Revert on overflow.\n /// @param x signed 64.64-bit fixed point number\n /// @param y signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function sub(int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require(result >= MIN_64x64 && result <= MAX_64x64);\n return int128(result);\n }\n }\n\n /// @dev Calculate x///y rounding down. Revert on overflow.\n /// @param x signed 64.64-bit fixed point number\n /// @param y signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function mul(int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = (int256(x) * y) >> 64;\n require(result >= MIN_64x64 && result <= MAX_64x64);\n return int128(result);\n }\n }\n\n /// @dev Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n /// number and y is signed 256-bit integer number. Revert on overflow.\n /// @param x signed 64.64 fixed point number\n /// @param y signed 256-bit integer number\n /// @return signed 256-bit integer number\n function muli(int128 x, int256 y) internal pure returns (int256) {\n //NOTE: This reverts if y == type(int128).min\n unchecked {\n if (x == MIN_64x64) {\n require(\n y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000\n );\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu(x, uint256(y));\n if (negativeResult) {\n require(absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256(absoluteResult); // We rely on overflow behavior here\n } else {\n require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256(absoluteResult);\n }\n }\n }\n }\n\n /// @dev Calculate x * y rounding down, where x is signed 64.64 fixed point number\n /// and y is unsigned 256-bit integer number. Revert on overflow.\n /// @param x signed 64.64 fixed point number\n /// @param y unsigned 256-bit integer number\n /// @return unsigned 256-bit integer number\n function mulu(int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require(x >= 0);\n\n uint256 lo = (uint256(int256(x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256(int256(x)) * (y >> 128);\n\n require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /// @dev Calculate x / y rounding towards zero. Revert on overflow or when y is zero.\n /// @param x signed 64.64-bit fixed point number\n /// @param y signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function div(int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require(y != 0);\n int256 result = (int256(x) << 64) / y;\n require(result >= MIN_64x64 && result <= MAX_64x64);\n return int128(result);\n }\n }\n\n /// @dev Calculate x / y rounding towards zero, where x and y are signed 256-bit\n /// integer numbers. Revert on overflow or when y is zero.\n /// @param x signed 256-bit integer number\n /// @param y signed 256-bit integer number\n /// @return signed 64.64-bit fixed point number\n function divi(int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require(y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu(uint256(x), uint256(y));\n if (negativeResult) {\n require(absoluteResult <= 0x80000000000000000000000000000000);\n return -int128(absoluteResult); // We rely on overflow behavior here\n } else {\n require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128(absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /// @dev Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n /// integer numbers. Revert on overflow or when y is zero.\n /// @param x unsigned 256-bit integer number\n /// @param y unsigned 256-bit integer number\n /// @return signed 64.64-bit fixed point number\n function divu(uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require(y != 0);\n uint128 result = divuu(x, y);\n require(result <= uint128(MAX_64x64));\n return int128(result);\n }\n }\n\n /// @dev Calculate -x. Revert on overflow.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function neg(int128 x) internal pure returns (int128) {\n unchecked {\n require(x != MIN_64x64);\n return -x;\n }\n }\n\n /// @dev Calculate |x|. Revert on overflow.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function abs(int128 x) internal pure returns (int128) {\n unchecked {\n require(x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /// @dev Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n ///zero.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function inv(int128 x) internal pure returns (int128) {\n unchecked {\n require(x != 0);\n int256 result = int256(0x100000000000000000000000000000000) / x;\n require(result >= MIN_64x64 && result <= MAX_64x64);\n return int128(result);\n }\n }\n\n /// @dev Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n /// @param x signed 64.64-bit fixed point number\n /// @param y signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function avg(int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128((int256(x) + int256(y)) >> 1);\n }\n }\n\n /// @dev Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n /// Revert on overflow or in case x * y is negative.\n /// @param x signed 64.64-bit fixed point number\n /// @param y signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function gavg(int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256(x) * int256(y);\n require(m >= 0);\n require(m < 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128(sqrtu(uint256(m)));\n }\n }\n\n /// @dev Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n /// and y is unsigned 256-bit integer number. Revert on overflow.\n /// also see:https://hackmd.io/gbnqA3gCTR6z-F0HHTxF-A#33-Normalized-Fractional-Exponentiation\n /// @param x signed 64.64-bit fixed point number\n /// @param y uint256 value\n /// @return signed 64.64-bit fixed point number\n function pow(int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128(x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = (absResult * absX) >> 127;\n }\n absX = (absX * absX) >> 127;\n\n if (y & 0x2 != 0) {\n absResult = (absResult * absX) >> 127;\n }\n absX = (absX * absX) >> 127;\n\n if (y & 0x4 != 0) {\n absResult = (absResult * absX) >> 127;\n }\n absX = (absX * absX) >> 127;\n\n if (y & 0x8 != 0) {\n absResult = (absResult * absX) >> 127;\n }\n absX = (absX * absX) >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) {\n absX <<= 32;\n absXShift -= 32;\n }\n if (absX < 0x10000000000000000000000000000) {\n absX <<= 16;\n absXShift -= 16;\n }\n if (absX < 0x1000000000000000000000000000000) {\n absX <<= 8;\n absXShift -= 8;\n }\n if (absX < 0x10000000000000000000000000000000) {\n absX <<= 4;\n absXShift -= 4;\n }\n if (absX < 0x40000000000000000000000000000000) {\n absX <<= 2;\n absXShift -= 2;\n }\n if (absX < 0x80000000000000000000000000000000) {\n absX <<= 1;\n absXShift -= 1;\n }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require(absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = (absResult * absX) >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = (absX * absX) >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require(resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256(absResult) : int256(absResult);\n require(result >= MIN_64x64 && result <= MAX_64x64);\n return int128(result);\n }\n }\n\n /// @dev Calculate sqrt (x) rounding down. Revert if x < 0.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function sqrt(int128 x) internal pure returns (int128) {\n unchecked {\n require(x >= 0);\n return int128(sqrtu(uint256(int256(x)) << 64));\n }\n }\n\n /// @dev Calculate binary logarithm of x. Revert if x <= 0.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function log_2(int128 x) internal pure returns (int128) {\n unchecked {\n require(x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) {\n xc >>= 64;\n msb += 64;\n }\n if (xc >= 0x100000000) {\n xc >>= 32;\n msb += 32;\n }\n if (xc >= 0x10000) {\n xc >>= 16;\n msb += 16;\n }\n if (xc >= 0x100) {\n xc >>= 8;\n msb += 8;\n }\n if (xc >= 0x10) {\n xc >>= 4;\n msb += 4;\n }\n if (xc >= 0x4) {\n xc >>= 2;\n msb += 2;\n }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = (msb - 64) << 64;\n uint256 ux = uint256(int256(x)) << uint256(127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256(b);\n }\n\n return int128(result);\n }\n }\n\n /// @dev Calculate natural logarithm of x. Revert if x <= 0.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function ln(int128 x) internal pure returns (int128) {\n unchecked {\n require(x > 0);\n\n return int128(int256((uint256(int256(log_2(x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128));\n }\n }\n\n /// @dev Calculate binary exponent of x. Revert on overflow.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function exp_2(int128 x) internal pure returns (int128) {\n unchecked {\n require(x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;\n if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;\n if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;\n if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;\n if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;\n if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;\n if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;\n if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;\n if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;\n if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;\n if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;\n if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;\n if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;\n if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;\n if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128;\n if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;\n if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;\n if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;\n if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;\n if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;\n if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;\n if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;\n if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;\n if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;\n if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;\n if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;\n if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;\n if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;\n if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;\n if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;\n if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;\n if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;\n if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;\n if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;\n if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;\n if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;\n if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;\n if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;\n if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;\n if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;\n if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;\n if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;\n if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;\n if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;\n if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;\n if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;\n if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;\n if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;\n if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;\n if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;\n if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;\n if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;\n if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;\n if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;\n if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;\n if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;\n if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;\n if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;\n if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;\n if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;\n if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;\n if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;\n if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;\n if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;\n\n result >>= uint256(int256(63 - (x >> 64)));\n require(result <= uint256(int256(MAX_64x64)));\n\n return int128(int256(result));\n }\n }\n\n /// @dev Calculate natural exponent of x. Revert on overflow.\n /// @param x signed 64.64-bit fixed point number\n /// @return signed 64.64-bit fixed point number\n function exp(int128 x) internal pure returns (int128) {\n unchecked {\n require(x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2(int128((int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128));\n }\n }\n\n /// @dev Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n /// integer numbers. Revert on overflow or when y is zero.\n /// @param x unsigned 256-bit integer number\n /// @param y unsigned 256-bit integer number\n /// @return unsigned 64.64-bit fixed point number\n function divuu(uint256 x, uint256 y) internal pure returns (uint128) {\n // ^^ changed visibility from private to internal for testing\n unchecked {\n require(y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) {\n xc >>= 32;\n msb += 32;\n }\n if (xc >= 0x10000) {\n xc >>= 16;\n msb += 16;\n }\n if (xc >= 0x100) {\n xc >>= 8;\n msb += 8;\n }\n if (xc >= 0x10) {\n xc >>= 4;\n msb += 4;\n }\n if (xc >= 0x4) {\n xc >>= 2;\n msb += 2;\n }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);\n require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert(xh == hi >> 128);\n\n result += xl / y;\n }\n\n require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128(result);\n }\n }\n\n /// @dev Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer number.\n /// @param x unsigned 256-bit integer number\n /// @return unsigned 128-bit integer number\n function sqrtu(uint256 x) internal pure returns (uint128) {\n // ^^ changed visibility from private to internal for testing\n\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) {\n xx >>= 128;\n r <<= 64;\n }\n if (xx >= 0x10000000000000000) {\n xx >>= 64;\n r <<= 32;\n }\n if (xx >= 0x100000000) {\n xx >>= 32;\n r <<= 16;\n }\n if (xx >= 0x10000) {\n xx >>= 16;\n r <<= 8;\n }\n if (xx >= 0x100) {\n xx >>= 8;\n r <<= 4;\n }\n if (xx >= 0x10) {\n xx >>= 4;\n r <<= 2;\n }\n if (xx >= 0x8) {\n r <<= 1;\n }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128(r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@yield-protocol/yieldspace-tv/src/Exp64x64.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity >=0.8.15; /*\n __ ___ _ _\n \\ \\ / (_) | | | | ███████╗██╗ ██╗██████╗ ██████╗ ██╗ ██╗██╗ ██╗ ██████╗ ██╗ ██╗\n \\ \\_/ / _ ___| | __| | ██╔════╝╚██╗██╔╝██╔══██╗██╔════╝ ██║ ██║╚██╗██╔╝██╔════╝ ██║ ██║\n \\ / | |/ _ \\ |/ _` | █████╗ ╚███╔╝ ██████╔╝███████╗ ███████║ ╚███╔╝ ███████╗ ███████║\n | | | | __/ | (_| | ██╔══╝ ██╔██╗ ██╔═══╝ ██╔═══██╗╚════██║ ██╔██╗ ██╔═══██╗╚════██║\n |_| |_|\\___|_|\\__,_| ███████╗██╔╝ ██╗██║ ╚██████╔╝ ██║██╔╝ ██╗╚██████╔╝ ██║\n yieldprotocol.com ╚══════╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝\n Gas optimized math library custom-built by ABDK -- Copyright © 2019 */\n\nimport \"./Math64x64.sol\";\n\nlibrary Exp64x64 {\n using Math64x64 for int128;\n\n /// @dev Raises a 64.64 number to the power of another 64.64 number\n /// x^y = 2^(y*log_2(x))\n /// https://ethereum.stackexchange.com/questions/79903/exponential-function-with-fractional-numbers\n function pow(int128 x, int128 y) internal pure returns (int128) {\n return y.mul(x.log_2()).exp_2();\n }\n\n\n /* Mikhail Vladimirov, [Jul 6, 2022 at 12:26:12 PM (Jul 6, 2022 at 12:28:29 PM)]:\n In simple words, when have an n-bits wide number x and raise it to a power α, then the result would be α*n bits wide. This, if α<1, the result will loose precision, and if α>1, the result could exceed range.\n\n So, the pow function multiplies the result by 2^(n * (1 - α)). We have:\n\n x ∈ [0; 2^n)\n x^α ∈ [0; 2^(α*n))\n x^α * 2^(n * (1 - α)) ∈ [0; 2^(α*n) * 2^(n * (1 - α))) = [0; 2^(α*n + n * (1 - α))) = [0; 2^(n * (α + (1 - α)))) = [0; 2^n)\n\n So the normalization returns the result back into the proper range.\n\n Now note, that:\n\n pow (pow (x, α), 1/α) =\n pow (x^α * 2^(n * (1 -α)) , 1/α) =\n (x^α * 2^(n * (1 -α)))^(1/α) * 2^(n * (1 -1/α)) =\n x^(α * (1/α)) * 2^(n * (1 -α) * (1/α)) * 2^(n * (1 -1/α)) =\n x * 2^(n * (1/α -1)) * 2^(n * (1 -1/α)) =\n x * 2^(n * (1/α -1) + n * (1 -1/α)) =\n x\n\n So, for formulas that look like:\n\n (a x^α + b y^α + ...)^(1/α)\n\n The pow function could be used instead of normal power. */\n /// @dev Raise given number x into power specified as a simple fraction y/z and then\n /// multiply the result by the normalization factor 2^(128 /// (1 - y/z)).\n /// Revert if z is zero, or if both x and y are zeros.\n /// @param x number to raise into given power y/z -- integer\n /// @param y numerator of the power to raise x into -- 64.64\n /// @param z denominator of the power to raise x into -- 64.64\n /// @return x raised into power y/z and then multiplied by 2^(128 * (1 - y/z)) -- integer\n function pow(\n uint128 x,\n uint128 y,\n uint128 z\n ) internal pure returns (uint128) {\n unchecked {\n require(z != 0);\n\n if (x == 0) {\n require(y != 0);\n return 0;\n } else {\n uint256 l = (uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - log_2(x)) * y) / z;\n if (l > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return 0;\n else return pow_2(uint128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - l));\n }\n }\n }\n\n /// @dev Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert\n /// in case x is zero.\n /// @param x number to calculate base 2 logarithm of\n /// @return base 2 logarithm of x, multiplied by 2^121\n function log_2(uint128 x) internal pure returns (uint128) {\n unchecked {\n require(x != 0);\n\n uint256 b = x;\n\n uint256 l = 0xFE000000000000000000000000000000;\n\n if (b < 0x10000000000000000) {\n l -= 0x80000000000000000000000000000000;\n b <<= 64;\n }\n if (b < 0x1000000000000000000000000) {\n l -= 0x40000000000000000000000000000000;\n b <<= 32;\n }\n if (b < 0x10000000000000000000000000000) {\n l -= 0x20000000000000000000000000000000;\n b <<= 16;\n }\n if (b < 0x1000000000000000000000000000000) {\n l -= 0x10000000000000000000000000000000;\n b <<= 8;\n }\n if (b < 0x10000000000000000000000000000000) {\n l -= 0x8000000000000000000000000000000;\n b <<= 4;\n }\n if (b < 0x40000000000000000000000000000000) {\n l -= 0x4000000000000000000000000000000;\n b <<= 2;\n }\n if (b < 0x80000000000000000000000000000000) {\n l -= 0x2000000000000000000000000000000;\n b <<= 1;\n }\n\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x1000000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x800000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x400000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x200000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x100000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x80000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x40000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x20000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x10000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x8000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x4000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x2000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x1000000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x800000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x400000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x200000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x100000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x80000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x40000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x20000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x10000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x8000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x4000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x2000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x1000000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x800000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x400000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x200000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x100000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x80000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x40000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x20000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x10000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x8000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x4000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x2000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x1000000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x800000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x400000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x200000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x100000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x80000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x40000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x20000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x10000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x8000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x4000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x2000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x1000000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x800000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x400000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x200000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x100000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x80000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x40000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x20000000000000000;\n }\n b = (b * b) >> 127;\n if (b >= 0x100000000000000000000000000000000) {\n b >>= 1;\n l |= 0x10000000000000000;\n } /*\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2;}\n b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) l |= 0x1; */\n\n return uint128(l);\n }\n }\n\n /// @dev Calculate 2 raised into given power.\n /// @param x power to raise 2 into, multiplied by 2^121\n /// @return 2 raised into given power\n function pow_2(uint128 x) internal pure returns (uint128) {\n unchecked {\n uint256 r = 0x80000000000000000000000000000000;\n if (x & 0x1000000000000000000000000000000 > 0) r = (r * 0xb504f333f9de6484597d89b3754abe9f) >> 127;\n if (x & 0x800000000000000000000000000000 > 0) r = (r * 0x9837f0518db8a96f46ad23182e42f6f6) >> 127;\n if (x & 0x400000000000000000000000000000 > 0) r = (r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90) >> 127;\n if (x & 0x200000000000000000000000000000 > 0) r = (r * 0x85aac367cc487b14c5c95b8c2154c1b2) >> 127;\n if (x & 0x100000000000000000000000000000 > 0) r = (r * 0x82cd8698ac2ba1d73e2a475b46520bff) >> 127;\n if (x & 0x80000000000000000000000000000 > 0) r = (r * 0x8164d1f3bc0307737be56527bd14def4) >> 127;\n if (x & 0x40000000000000000000000000000 > 0) r = (r * 0x80b1ed4fd999ab6c25335719b6e6fd20) >> 127;\n if (x & 0x20000000000000000000000000000 > 0) r = (r * 0x8058d7d2d5e5f6b094d589f608ee4aa2) >> 127;\n if (x & 0x10000000000000000000000000000 > 0) r = (r * 0x802c6436d0e04f50ff8ce94a6797b3ce) >> 127;\n if (x & 0x8000000000000000000000000000 > 0) r = (r * 0x8016302f174676283690dfe44d11d008) >> 127;\n if (x & 0x4000000000000000000000000000 > 0) r = (r * 0x800b179c82028fd0945e54e2ae18f2f0) >> 127;\n if (x & 0x2000000000000000000000000000 > 0) r = (r * 0x80058baf7fee3b5d1c718b38e549cb93) >> 127;\n if (x & 0x1000000000000000000000000000 > 0) r = (r * 0x8002c5d00fdcfcb6b6566a58c048be1f) >> 127;\n if (x & 0x800000000000000000000000000 > 0) r = (r * 0x800162e61bed4a48e84c2e1a463473d9) >> 127;\n if (x & 0x400000000000000000000000000 > 0) r = (r * 0x8000b17292f702a3aa22beacca949013) >> 127;\n if (x & 0x200000000000000000000000000 > 0) r = (r * 0x800058b92abbae02030c5fa5256f41fe) >> 127;\n if (x & 0x100000000000000000000000000 > 0) r = (r * 0x80002c5c8dade4d71776c0f4dbea67d6) >> 127;\n if (x & 0x80000000000000000000000000 > 0) r = (r * 0x8000162e44eaf636526be456600bdbe4) >> 127;\n if (x & 0x40000000000000000000000000 > 0) r = (r * 0x80000b1721fa7c188307016c1cd4e8b6) >> 127;\n if (x & 0x20000000000000000000000000 > 0) r = (r * 0x8000058b90de7e4cecfc487503488bb1) >> 127;\n if (x & 0x10000000000000000000000000 > 0) r = (r * 0x800002c5c8678f36cbfce50a6de60b14) >> 127;\n if (x & 0x8000000000000000000000000 > 0) r = (r * 0x80000162e431db9f80b2347b5d62e516) >> 127;\n if (x & 0x4000000000000000000000000 > 0) r = (r * 0x800000b1721872d0c7b08cf1e0114152) >> 127;\n if (x & 0x2000000000000000000000000 > 0) r = (r * 0x80000058b90c1aa8a5c3736cb77e8dff) >> 127;\n if (x & 0x1000000000000000000000000 > 0) r = (r * 0x8000002c5c8605a4635f2efc2362d978) >> 127;\n if (x & 0x800000000000000000000000 > 0) r = (r * 0x800000162e4300e635cf4a109e3939bd) >> 127;\n if (x & 0x400000000000000000000000 > 0) r = (r * 0x8000000b17217ff81bef9c551590cf83) >> 127;\n if (x & 0x200000000000000000000000 > 0) r = (r * 0x800000058b90bfdd4e39cd52c0cfa27c) >> 127;\n if (x & 0x100000000000000000000000 > 0) r = (r * 0x80000002c5c85fe6f72d669e0e76e411) >> 127;\n if (x & 0x80000000000000000000000 > 0) r = (r * 0x8000000162e42ff18f9ad35186d0df28) >> 127;\n if (x & 0x40000000000000000000000 > 0) r = (r * 0x80000000b17217f84cce71aa0dcfffe7) >> 127;\n if (x & 0x20000000000000000000000 > 0) r = (r * 0x8000000058b90bfc07a77ad56ed22aaa) >> 127;\n if (x & 0x10000000000000000000000 > 0) r = (r * 0x800000002c5c85fdfc23cdead40da8d6) >> 127;\n if (x & 0x8000000000000000000000 > 0) r = (r * 0x80000000162e42fefc25eb1571853a66) >> 127;\n if (x & 0x4000000000000000000000 > 0) r = (r * 0x800000000b17217f7d97f692baacded5) >> 127;\n if (x & 0x2000000000000000000000 > 0) r = (r * 0x80000000058b90bfbead3b8b5dd254d7) >> 127;\n if (x & 0x1000000000000000000000 > 0) r = (r * 0x8000000002c5c85fdf4eedd62f084e67) >> 127;\n if (x & 0x800000000000000000000 > 0) r = (r * 0x800000000162e42fefa58aef378bf586) >> 127;\n if (x & 0x400000000000000000000 > 0) r = (r * 0x8000000000b17217f7d24a78a3c7ef02) >> 127;\n if (x & 0x200000000000000000000 > 0) r = (r * 0x800000000058b90bfbe9067c93e474a6) >> 127;\n if (x & 0x100000000000000000000 > 0) r = (r * 0x80000000002c5c85fdf47b8e5a72599f) >> 127;\n if (x & 0x80000000000000000000 > 0) r = (r * 0x8000000000162e42fefa3bdb315934a2) >> 127;\n if (x & 0x40000000000000000000 > 0) r = (r * 0x80000000000b17217f7d1d7299b49c46) >> 127;\n if (x & 0x20000000000000000000 > 0) r = (r * 0x8000000000058b90bfbe8e9a8d1c4ea0) >> 127;\n if (x & 0x10000000000000000000 > 0) r = (r * 0x800000000002c5c85fdf4745969ea76f) >> 127;\n if (x & 0x8000000000000000000 > 0) r = (r * 0x80000000000162e42fefa3a0df5373bf) >> 127;\n if (x & 0x4000000000000000000 > 0) r = (r * 0x800000000000b17217f7d1cff4aac1e1) >> 127;\n if (x & 0x2000000000000000000 > 0) r = (r * 0x80000000000058b90bfbe8e7db95a2f1) >> 127;\n if (x & 0x1000000000000000000 > 0) r = (r * 0x8000000000002c5c85fdf473e61ae1f8) >> 127;\n if (x & 0x800000000000000000 > 0) r = (r * 0x800000000000162e42fefa39f121751c) >> 127;\n if (x & 0x400000000000000000 > 0) r = (r * 0x8000000000000b17217f7d1cf815bb96) >> 127;\n if (x & 0x200000000000000000 > 0) r = (r * 0x800000000000058b90bfbe8e7bec1e0d) >> 127;\n if (x & 0x100000000000000000 > 0) r = (r * 0x80000000000002c5c85fdf473dee5f17) >> 127;\n if (x & 0x80000000000000000 > 0) r = (r * 0x8000000000000162e42fefa39ef5438f) >> 127;\n if (x & 0x40000000000000000 > 0) r = (r * 0x80000000000000b17217f7d1cf7a26c8) >> 127;\n if (x & 0x20000000000000000 > 0) r = (r * 0x8000000000000058b90bfbe8e7bcf4a4) >> 127;\n if (x & 0x10000000000000000 > 0) r = (r * 0x800000000000002c5c85fdf473de72a2) >> 127; /*\n if(x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127;\n if(x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127;\n if(x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127;\n if(x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127;\n if(x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127;\n if(x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127;\n if(x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127;\n if(x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127;\n if(x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127;\n if(x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127;\n if(x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127;\n if(x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127;\n if(x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127;\n if(x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127;\n if(x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127;\n if(x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127;\n if(x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127;\n if(x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127;\n if(x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127;\n if(x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127;\n if(x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127;\n if(x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127;\n if(x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127;\n if(x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127;\n if(x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127;\n if(x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127;\n if(x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127;\n if(x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127;\n if(x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127;\n if(x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127;\n if(x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127;\n if(x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127;\n if(x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127;\n if(x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127;\n if(x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127;\n if(x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127;\n if(x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127;\n if(x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127;\n if(x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127;\n if(x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127;\n if(x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127;\n if(x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127;\n if(x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127;\n if(x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127;\n if(x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127;\n if(x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127;\n if(x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127;\n if(x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127;\n if(x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127;\n if(x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127;\n if(x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127;\n if(x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127;\n if(x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127;\n if(x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127;\n if(x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127;\n if(x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127;\n if(x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127;\n if(x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127;\n if(x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127;\n if(x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127;\n if(x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127;\n if(x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127;\n if(x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127;\n if(x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127; */\n\n r >>= 127 - (x >> 121);\n\n return uint128(r);\n }\n }\n}\n"
},
"@yield-protocol/utils-v2/contracts/cast/CastU256U104.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n\nlibrary CastU256U104 {\n /// @dev Safely cast an uint256 to an uint104\n function u104(uint256 x) internal pure returns (uint104 y) {\n require (x <= type(uint104).max, \"Cast overflow\");\n y = uint104(x);\n }\n}"
},
"@yield-protocol/yieldspace-tv/src/YieldMath.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity >=0.8.15;\n/*\n __ ___ _ _\n \\ \\ / (_) | | | | ██╗ ██╗██╗███████╗██╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗\n \\ \\_/ / _ ___| | __| | ╚██╗ ██╔╝██║██╔════╝██║ ██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║\n \\ / | |/ _ \\ |/ _` | ╚████╔╝ ██║█████╗ ██║ ██║ ██║██╔████╔██║███████║ ██║ ███████║\n | | | | __/ | (_| | ╚██╔╝ ██║██╔══╝ ██║ ██║ ██║██║╚██╔╝██║██╔══██║ ██║ ██╔══██║\n |_| |_|\\___|_|\\__,_| ██║ ██║███████╗███████╗██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║\n yieldprotocol.com ╚═╝ ╚═╝╚══════╝╚══════╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n*/\n\nimport {Exp64x64} from \"./Exp64x64.sol\";\nimport {Math64x64} from \"./Math64x64.sol\";\nimport {CastU256U128} from \"@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol\";\nimport {CastU128I128} from \"@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol\";\n\n/// Ethereum smart contract library implementing Yield Math model with yield bearing tokens.\n/// @dev see Mikhail Vladimirov (ABDK) explanations of the math: https://hackmd.io/gbnqA3gCTR6z-F0HHTxF-A#Yield-Math\nlibrary YieldMath {\n using Math64x64 for int128;\n using Math64x64 for uint128;\n using Math64x64 for int256;\n using Math64x64 for uint256;\n using Exp64x64 for uint128;\n using Exp64x64 for int128;\n using CastU256U128 for uint256;\n using CastU128I128 for uint128;\n\n uint128 public constant WAD = 1e18;\n uint128 public constant ONE = 0x10000000000000000; // In 64.64\n uint256 public constant MAX = type(uint128).max; // Used for overflow checks\n\n /* CORE FUNCTIONS\n ******************************************************************************************************************/\n\n /* ----------------------------------------------------------------------------------------------------------------\n ┌───────────────────────────────┐ .-:::::::::::-.\n ┌──────────────┐ │ │ .:::::::::::::::::.\n │$ $│ \\│ │/ : _______ __ __ :\n │ ┌────────────┴─┐ \\│ │/ :: | || | | |::\n │ │$ $│ │ fyTokenOutForSharesIn │ ::: | ___|| |_| |:::\n │$│ ┌────────────┴─┐ ────────▶ │ │ ────────▶ ::: | |___ | |:::\n └─┤ │$ $│ │ │ ::: | ___||_ _|:::\n │$│ `sharesIn` │ /│ │\\ ::: | | | | :::\n └─┤ │ /│ │\\ :: |___| |___| ::\n │$ $│ │ \\(^o^)/ │ : ???? :\n └──────────────┘ │ YieldMath │ `:::::::::::::::::'\n └───────────────────────────────┘ `-:::::::::::-'\n */\n /// Calculates the amount of fyToken a user would get for given amount of shares.\n /// https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n /// @param sharesReserves yield bearing vault shares reserve amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param sharesIn shares amount to be traded\n /// @param timeTillMaturity time till maturity in seconds e.g. 90 days in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds\n /// @param g fee coefficient, multiplied by 2^64 -- sb under 1.0 for selling shares to pool\n /// @param c price of shares in terms of their base, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- starts as c at initialization\n /// @return fyTokenOut the amount of fyToken a user would get for given amount of shares\n function fyTokenOutForSharesIn(\n uint128 sharesReserves, // z\n uint128 fyTokenReserves, // x\n uint128 sharesIn, // x == Δz\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128) {\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n\n uint128 a = _computeA(timeTillMaturity, k, g);\n\n uint256 sum;\n {\n /* https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n\n y = fyToken reserves\n z = shares reserves\n x = Δz (sharesIn)\n\n y - ( sum )^( invA )\n y - (( Za ) + ( Ya ) - ( Zxa ) )^( invA )\n Δy = y - ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz + μx)^(1-t) )^(1 / (1 - t))\n\n */\n uint256 normalizedSharesReserves;\n require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, \"YieldMath: Rate overflow (nsr)\");\n\n // za = c/μ * (normalizedSharesReserves ** a)\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 za;\n require(\n (za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,\n \"YieldMath: Rate overflow (za)\"\n );\n\n // ya = fyTokenReserves ** a\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 ya = fyTokenReserves.pow(a, ONE);\n\n // normalizedSharesIn = μ * sharesIn\n uint256 normalizedSharesIn;\n require((normalizedSharesIn = mu.mulu(sharesIn)) <= MAX, \"YieldMath: Rate overflow (nsi)\");\n\n // zx = normalizedSharesReserves + sharesIn * μ\n uint256 zx;\n require((zx = normalizedSharesReserves + normalizedSharesIn) <= MAX, \"YieldMath: Too many shares in\");\n\n // zxa = c/μ * zx ** a\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 zxa;\n require((zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE))) <= MAX, \"YieldMath: Rate overflow (zxa)\");\n\n sum = za + ya - zxa;\n\n require(sum <= (za + ya), \"YieldMath: Sum underflow\");\n }\n\n // result = fyTokenReserves - (sum ** (1/a))\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 fyTokenOut;\n require(\n (fyTokenOut = uint256(fyTokenReserves) - sum.u128().pow(ONE, a)) <= MAX,\n \"YieldMath: Rounding error\"\n );\n\n require(fyTokenOut <= fyTokenReserves, \"YieldMath: > fyToken reserves\");\n\n return uint128(fyTokenOut);\n }\n }\n\n /* ----------------------------------------------------------------------------------------------------------------\n .-:::::::::::-. ┌───────────────────────────────┐\n .:::::::::::::::::. │ │\n : _______ __ __ : \\│ │/ ┌──────────────┐\n :: | || | | |:: \\│ │/ │$ $│\n ::: | ___|| |_| |::: │ sharesOutForFYTokenIn │ │ ┌────────────┴─┐\n ::: | |___ | |::: ────────▶ │ │ ────────▶ │ │$ $│\n ::: | ___||_ _|::: │ │ │$│ ┌────────────┴─┐\n ::: | | | | ::: /│ │\\ └─┤ │$ $│\n :: |___| |___| :: /│ │\\ │$│ SHARES │\n : `fyTokenIn` : │ \\(^o^)/ │ └─┤ ???? │\n `:::::::::::::::::' │ YieldMath │ │$ $│\n `-:::::::::::-' └───────────────────────────────┘ └──────────────┘\n */\n /// Calculates the amount of shares a user would get for certain amount of fyToken.\n /// @param sharesReserves shares reserves amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param fyTokenIn fyToken amount to be traded\n /// @param timeTillMaturity time till maturity in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64\n /// @param g fee coefficient, multiplied by 2^64\n /// @param c price of shares in terms of Dai, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- starts as c at initialization\n /// @return amount of Shares a user would get for given amount of fyToken\n function sharesOutForFYTokenIn(\n uint128 sharesReserves,\n uint128 fyTokenReserves,\n uint128 fyTokenIn,\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128) {\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n return\n _sharesOutForFYTokenIn(\n sharesReserves,\n fyTokenReserves,\n fyTokenIn,\n _computeA(timeTillMaturity, k, g),\n c,\n mu\n );\n }\n }\n\n /// @dev Splitting sharesOutForFYTokenIn in two functions to avoid stack depth limits.\n function _sharesOutForFYTokenIn(\n uint128 sharesReserves,\n uint128 fyTokenReserves,\n uint128 fyTokenIn,\n uint128 a,\n int128 c,\n int128 mu\n ) private pure returns (uint128) {\n /* https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n\n y = fyToken reserves\n z = shares reserves\n x = Δy (fyTokenIn)\n\n z - ( rightTerm )\n z - (invMu) * ( Za ) + ( Ya ) - ( Yxa ) / (c / μ) )^( invA )\n Δz = z - 1/μ * ( ( (c / μ) * (μz)^(1-t) + y^(1-t) - (y + x)^(1-t) ) / (c / μ) )^(1 / (1 - t))\n\n */\n unchecked {\n // normalizedSharesReserves = μ * sharesReserves\n uint256 normalizedSharesReserves;\n require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, \"YieldMath: Rate overflow (nsr)\");\n\n uint128 rightTerm;\n {\n uint256 zaYaYxa;\n {\n // za = c/μ * (normalizedSharesReserves ** a)\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 za;\n require(\n (za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,\n \"YieldMath: Rate overflow (za)\"\n );\n\n // ya = fyTokenReserves ** a\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 ya = fyTokenReserves.pow(a, ONE);\n\n // yxa = (fyTokenReserves + x) ** a # x is aka Δy\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 yxa = (fyTokenReserves + fyTokenIn).pow(a, ONE);\n\n require((zaYaYxa = (za + ya - yxa)) <= MAX, \"YieldMath: Rate overflow (yxa)\");\n }\n\n rightTerm = uint128( // Cast zaYaYxa/(c/μ).pow(1/a).div(μ) from int128 to uint128 - always positive\n int128( // Cast zaYaYxa/(c/μ).pow(1/a) from uint128 to int128 - always < zaYaYxa/(c/μ)\n uint128( // Cast zaYaYxa/(c/μ) from int128 to uint128 - always positive\n zaYaYxa.divu(uint128(c.div(mu))) // Cast c/μ from int128 to uint128 - always positive\n ).pow(uint128(ONE), a) // Cast 2^64 from int128 to uint128 - always positive\n ).div(mu)\n );\n }\n require(rightTerm <= sharesReserves, \"YieldMath: Rate underflow\");\n\n return sharesReserves - rightTerm;\n }\n }\n\n /* ----------------------------------------------------------------------------------------------------------------\n .-:::::::::::-. ┌───────────────────────────────┐\n .:::::::::::::::::. │ │ ┌──────────────┐\n : _______ __ __ : \\│ │/ │$ $│\n :: | || | | |:: \\│ │/ │ ┌────────────┴─┐\n ::: | ___|| |_| |::: │ fyTokenInForSharesOut │ │ │$ $│\n ::: | |___ | |::: ────────▶ │ │ ────────▶ │$│ ┌────────────┴─┐\n ::: | ___||_ _|::: │ │ └─┤ │$ $│\n ::: | | | | ::: /│ │\\ │$│ │\n :: |___| |___| :: /│ │\\ └─┤ `sharesOut` │\n : ???? : │ \\(^o^)/ │ │$ $│\n `:::::::::::::::::' │ YieldMath │ └──────────────┘\n `-:::::::::::-' └───────────────────────────────┘\n */\n /// Calculates the amount of fyToken a user could sell for given amount of Shares.\n /// @param sharesReserves shares reserves amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param sharesOut Shares amount to be traded\n /// @param timeTillMaturity time till maturity in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64\n /// @param g fee coefficient, multiplied by 2^64\n /// @param c price of shares in terms of Dai, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- starts as c at initialization\n /// @return fyTokenIn the amount of fyToken a user could sell for given amount of Shares\n function fyTokenInForSharesOut(\n uint128 sharesReserves,\n uint128 fyTokenReserves,\n uint128 sharesOut,\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128) {\n /* https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n\n y = fyToken reserves\n z = shares reserves\n x = Δz (sharesOut)\n\n ( sum )^( invA ) - y\n ( Za ) + ( Ya ) - ( Zxa )^( invA ) - y\n Δy = ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz - μx)^(1-t) )^(1 / (1 - t)) - y\n\n */\n\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n\n uint128 a = _computeA(timeTillMaturity, k, g);\n uint256 sum;\n {\n // normalizedSharesReserves = μ * sharesReserves\n uint256 normalizedSharesReserves;\n require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, \"YieldMath: Rate overflow (nsr)\");\n\n // za = c/μ * (normalizedSharesReserves ** a)\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 za;\n require(\n (za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,\n \"YieldMath: Rate overflow (za)\"\n );\n\n // ya = fyTokenReserves ** a\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 ya = fyTokenReserves.pow(a, ONE);\n\n // normalizedSharesOut = μ * sharesOut\n uint256 normalizedSharesOut;\n require((normalizedSharesOut = mu.mulu(sharesOut)) <= MAX, \"YieldMath: Rate overflow (nso)\");\n\n // zx = normalizedSharesReserves + sharesOut * μ\n require(normalizedSharesReserves >= normalizedSharesOut, \"YieldMath: Too many shares in\");\n uint256 zx = normalizedSharesReserves - normalizedSharesOut;\n\n // zxa = c/μ * zx ** a\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE));\n\n // sum = za + ya - zxa\n // z < MAX, y < MAX, a < 1. It can only underflow, not overflow.\n require((sum = za + ya - zxa) <= MAX, \"YieldMath: > fyToken reserves\");\n }\n\n // result = fyTokenReserves - (sum ** (1/a))\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 result;\n require(\n (result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,\n \"YieldMath: Rounding error\"\n );\n\n return uint128(result);\n }\n }\n\n /* ----------------------------------------------------------------------------------------------------------------\n ┌───────────────────────────────┐ .-:::::::::::-.\n ┌──────────────┐ │ │ .:::::::::::::::::.\n │$ $│ \\│ │/ : _______ __ __ :\n │ ┌────────────┴─┐ \\│ │/ :: | || | | |::\n │ │$ $│ │ sharesInForFYTokenOut │ ::: | ___|| |_| |:::\n │$│ ┌────────────┴─┐ ────────▶ │ │ ────────▶ ::: | |___ | |:::\n └─┤ │$ $│ │ │ ::: | ___||_ _|:::\n │$│ SHARES │ /│ │\\ ::: | | | | :::\n └─┤ ???? │ /│ │\\ :: |___| |___| ::\n │$ $│ │ \\(^o^)/ │ : `fyTokenOut` :\n └──────────────┘ │ YieldMath │ `:::::::::::::::::'\n └───────────────────────────────┘ `-:::::::::::-'\n */\n /// @param sharesReserves yield bearing vault shares reserve amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param fyTokenOut fyToken amount to be traded\n /// @param timeTillMaturity time till maturity in seconds e.g. 90 days in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds\n /// @param g fee coefficient, multiplied by 2^64 -- sb under 1.0 for selling shares to pool\n /// @param c price of shares in terms of their base, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- starts as c at initialization\n /// @return result the amount of shares a user would have to pay for given amount of fyToken\n function sharesInForFYTokenOut(\n uint128 sharesReserves,\n uint128 fyTokenReserves,\n uint128 fyTokenOut,\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128) {\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n return\n _sharesInForFYTokenOut(\n sharesReserves,\n fyTokenReserves,\n fyTokenOut,\n _computeA(timeTillMaturity, k, g),\n c,\n mu\n );\n }\n }\n\n /// @dev Splitting sharesInForFYTokenOut in two functions to avoid stack depth limits\n function _sharesInForFYTokenOut(\n uint128 sharesReserves,\n uint128 fyTokenReserves,\n uint128 fyTokenOut,\n uint128 a,\n int128 c,\n int128 mu\n ) private pure returns (uint128) {\n /* https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n\n y = fyToken reserves\n z = shares reserves\n x = Δy (fyTokenOut)\n\n 1/μ * ( subtotal )^( invA ) - z\n 1/μ * (( Za ) + ( Ya ) - ( Yxa )) / (c/μ) )^( invA ) - z\n Δz = 1/μ * (( c/μ * μz^(1-t) + y^(1-t) - (y - x)^(1-t)) / (c/μ) )^(1 / (1 - t)) - z\n\n */\n unchecked {\n // normalizedSharesReserves = μ * sharesReserves\n require(mu.mulu(sharesReserves) <= MAX, \"YieldMath: Rate overflow (nsr)\");\n\n // za = c/μ * (normalizedSharesReserves ** a)\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 za = c.div(mu).mulu(uint128(mu.mulu(sharesReserves)).pow(a, ONE));\n require(za <= MAX, \"YieldMath: Rate overflow (za)\");\n\n // ya = fyTokenReserves ** a\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 ya = fyTokenReserves.pow(a, ONE);\n\n // yxa = (fyTokenReserves - x) ** aß\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 yxa = (fyTokenReserves - fyTokenOut).pow(a, ONE);\n require(fyTokenOut <= fyTokenReserves, \"YieldMath: Underflow (yxa)\");\n\n uint256 zaYaYxa;\n require((zaYaYxa = (za + ya - yxa)) <= MAX, \"YieldMath: Rate overflow (zyy)\");\n\n int128 subtotal = int128(ONE).div(mu).mul(\n (uint128(zaYaYxa.divu(uint128(c.div(mu)))).pow(uint128(ONE), uint128(a))).i128()\n );\n\n return uint128(subtotal) - sharesReserves;\n }\n }\n\n /// Calculates the max amount of fyToken a user could sell.\n /// @param sharesReserves yield bearing vault shares reserve amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param timeTillMaturity time till maturity in seconds e.g. 90 days in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds\n /// @param g fee coefficient, multiplied by 2^64 -- sb over 1.0 for buying shares from the pool\n /// @param c price of shares in terms of their base, multiplied by 2^64\n /// @return fyTokenIn the max amount of fyToken a user could sell\n function maxFYTokenIn(\n uint128 sharesReserves,\n uint128 fyTokenReserves,\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128 fyTokenIn) {\n /* https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n\n Y = fyToken reserves\n Z = shares reserves\n y = maxFYTokenIn\n\n ( sum )^( invA ) - Y\n ( Za ) + ( Ya ) )^( invA ) - Y\n Δy = ( c/μ * (μz)^(1-t) + Y^(1-t) )^(1 / (1 - t)) - Y\n\n */\n\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n\n uint128 a = _computeA(timeTillMaturity, k, g);\n uint256 sum;\n {\n // normalizedSharesReserves = μ * sharesReserves\n uint256 normalizedSharesReserves;\n require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, \"YieldMath: Rate overflow (nsr)\");\n\n // za = c/μ * (normalizedSharesReserves ** a)\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 za;\n require(\n (za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,\n \"YieldMath: Rate overflow (za)\"\n );\n\n // ya = fyTokenReserves ** a\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 ya = fyTokenReserves.pow(a, ONE);\n\n // sum = za + ya\n // z < MAX, y < MAX, a < 1. It can only underflow, not overflow.\n require((sum = za + ya) <= MAX, \"YieldMath: > fyToken reserves\");\n }\n\n // result = (sum ** (1/a)) - fyTokenReserves\n // The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to\n // fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) * (2^63)^(1 - y/z)\n uint256 result;\n require(\n (result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,\n \"YieldMath: Rounding error\"\n );\n\n fyTokenIn = uint128(result);\n }\n }\n\n /// Calculates the max amount of fyToken a user could get.\n /// https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n /// @param sharesReserves yield bearing vault shares reserve amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param timeTillMaturity time till maturity in seconds e.g. 90 days in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds\n /// @param g fee coefficient, multiplied by 2^64 -- sb under 1.0 for selling shares to pool\n /// @param c price of shares in terms of their base, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- c at initialization\n /// @return fyTokenOut the max amount of fyToken a user could get\n function maxFYTokenOut(\n uint128 sharesReserves,\n uint128 fyTokenReserves,\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128 fyTokenOut) {\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n\n int128 a = int128(_computeA(timeTillMaturity, k, g));\n\n /*\n y = maxFyTokenOut\n Y = fyTokenReserves (virtual)\n Z = sharesReserves\n\n Y - ( ( numerator ) / ( denominator ) )^invA\n Y - ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA\n y = Y - ( ( c/μ * (μZ)^a + Y^a ) / ( c/μ + 1 ) )^(1/a)\n */\n\n // za = c/μ * ((μ * (sharesReserves / 1e18)) ** a)\n int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));\n\n // ya = (fyTokenReserves / 1e18) ** a\n int128 ya = fyTokenReserves.divu(WAD).pow(a);\n\n // numerator = za + ya\n int128 numerator = za.add(ya);\n\n // denominator = c/u + 1\n int128 denominator = c.div(mu).add(int128(ONE));\n\n // rightTerm = (numerator / denominator) ** (1/a)\n int128 rightTerm = numerator.div(denominator).pow(int128(ONE).div(a));\n\n // maxFYTokenOut_ = fyTokenReserves - (rightTerm * 1e18)\n require((fyTokenOut = fyTokenReserves - uint128(rightTerm.mulu(WAD))) <= MAX, \"YieldMath: Underflow error\");\n }\n }\n\n /// Calculates the max amount of base a user could sell.\n /// https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n /// @param sharesReserves yield bearing vault shares reserve amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param timeTillMaturity time till maturity in seconds e.g. 90 days in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds\n /// @param g fee coefficient, multiplied by 2^64 -- sb under 1.0 for selling shares to pool\n /// @param c price of shares in terms of their base, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- c at initialization\n /// @return sharesIn Calculates the max amount of base a user could sell.\n function maxSharesIn(\n uint128 sharesReserves, // z\n uint128 fyTokenReserves, // x\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128 sharesIn) {\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n\n int128 a = int128(_computeA(timeTillMaturity, k, g));\n\n /*\n y = maxSharesIn_\n Y = fyTokenReserves (virtual)\n Z = sharesReserves\n\n 1/μ ( ( numerator ) / ( denominator ) )^invA - Z\n 1/μ ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA - Z\n y = 1/μ ( ( c/μ * (μZ)^a + Y^a ) / ( c/u + 1 ) )^(1/a) - Z\n */\n\n // za = c/μ * ((μ * (sharesReserves / 1e18)) ** a)\n int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));\n\n // ya = (fyTokenReserves / 1e18) ** a\n int128 ya = fyTokenReserves.divu(WAD).pow(a);\n\n // numerator = za + ya\n int128 numerator = za.add(ya);\n\n // denominator = c/u + 1\n int128 denominator = c.div(mu).add(int128(ONE));\n\n // leftTerm = 1/μ * (numerator / denominator) ** (1/a)\n int128 leftTerm = int128(ONE).div(mu).mul(numerator.div(denominator).pow(int128(ONE).div(a)));\n\n // maxSharesIn_ = (leftTerm * 1e18) - sharesReserves\n require((sharesIn = uint128(leftTerm.mulu(WAD)) - sharesReserves) <= MAX, \"YieldMath: Underflow error\");\n }\n }\n\n /*\n This function is not needed as it's return value is driven directly by the shares liquidity of the pool\n\n https://hackmd.io/lRZ4mgdrRgOpxZQXqKYlFw?view#MaxSharesOut\n\n function maxSharesOut(\n uint128 sharesReserves, // z\n uint128 fyTokenReserves, // x\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128 maxSharesOut_) {} */\n\n /// Calculates the total supply invariant.\n /// https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/\n /// @param sharesReserves yield bearing vault shares reserve amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param totalSupply total supply\n /// @param timeTillMaturity time till maturity in seconds e.g. 90 days in seconds\n /// @param k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds\n /// @param g fee coefficient, multiplied by 2^64 -- use under 1.0 (g2)\n /// @param c price of shares in terms of their base, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- c at initialization\n /// @return result Calculates the total supply invariant.\n function invariant(\n uint128 sharesReserves, // z\n uint128 fyTokenReserves, // x\n uint256 totalSupply, // s\n uint128 timeTillMaturity,\n int128 k,\n int128 g,\n int128 c,\n int128 mu\n ) public pure returns (uint128 result) {\n if (totalSupply == 0) return 0;\n int128 a = int128(_computeA(timeTillMaturity, k, g));\n\n result = _invariant(sharesReserves, fyTokenReserves, totalSupply, a, c, mu);\n }\n\n /// @param sharesReserves yield bearing vault shares reserve amount\n /// @param fyTokenReserves fyToken reserves amount\n /// @param totalSupply total supply\n /// @param a 1 - g * t computed\n /// @param c price of shares in terms of their base, multiplied by 2^64\n /// @param mu (μ) Normalization factor -- c at initialization\n /// @return result Calculates the total supply invariant.\n function _invariant(\n uint128 sharesReserves, // z\n uint128 fyTokenReserves, // x\n uint256 totalSupply, // s\n int128 a,\n int128 c,\n int128 mu\n ) internal pure returns (uint128 result) {\n unchecked {\n require(c > 0 && mu > 0, \"YieldMath: c and mu must be positive\");\n\n /*\n y = invariant\n Y = fyTokenReserves (virtual)\n Z = sharesReserves\n s = total supply\n\n c/μ ( ( numerator ) / ( denominator ) )^invA / s \n c/μ ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA / s \n y = c/μ ( ( c/μ * (μZ)^a + Y^a ) / ( c/u + 1 ) )^(1/a) / s\n */\n\n // za = c/μ * ((μ * (sharesReserves / 1e18)) ** a)\n int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));\n\n // ya = (fyTokenReserves / 1e18) ** a\n int128 ya = fyTokenReserves.divu(WAD).pow(a);\n\n // numerator = za + ya\n int128 numerator = za.add(ya);\n\n // denominator = c/u + 1\n int128 denominator = c.div(mu).add(int128(ONE));\n\n // topTerm = c/μ * (numerator / denominator) ** (1/a)\n int128 topTerm = c.div(mu).mul((numerator.div(denominator)).pow(int128(ONE).div(a)));\n\n result = uint128((topTerm.mulu(WAD) * WAD) / totalSupply);\n }\n }\n\n /* UTILITY FUNCTIONS\n ******************************************************************************************************************/\n\n function _computeA(\n uint128 timeTillMaturity,\n int128 k,\n int128 g\n ) private pure returns (uint128) {\n // t = k * timeTillMaturity\n int128 t = k.mul(timeTillMaturity.fromUInt());\n require(t >= 0, \"YieldMath: t must be positive\"); // Meaning neither T or k can be negative\n\n // a = (1 - gt)\n int128 a = int128(ONE).sub(g.mul(t));\n require(a > 0, \"YieldMath: Too far from maturity\");\n require(a <= int128(ONE), \"YieldMath: g must be positive\");\n\n return uint128(a);\n }\n}\n"
},
"@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n\nlibrary CastU256U128 {\n /// @dev Safely cast an uint256 to an uint128\n function u128(uint256 x) internal pure returns (uint128 y) {\n require (x <= type(uint128).max, \"Cast overflow\");\n y = uint128(x);\n }\n}"
},
"@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n\nlibrary CastU128I128 {\n /// @dev Safely cast an uint128 to an int128\n function i128(uint128 x) internal pure returns (int128 y) {\n require (x <= uint128(type(int128).max), \"Cast overflow\");\n y = int128(x);\n }\n}"
},
"@yield-protocol/utils-v2/contracts/cast/CastU256I256.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n\nlibrary CastU256I256 {\n /// @dev Safely cast an uint256 to an int256\n function i256(uint256 x) internal pure returns (int256 y) {\n require (x <= uint256(type(int256).max), \"Cast overflow\");\n y = int256(x);\n }\n}"
},
"@yield-protocol/utils-v2/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms.\n *\n * Roles are referred to by their `bytes4` identifier. These are expected to be the \n * signatures for all the functions in the contract. Special roles should be exposed\n * in the external API and be unique:\n *\n * ```\n * bytes4 public constant ROOT = 0x00000000;\n * ```\n *\n * Roles represent restricted access to a function call. For that purpose, use {auth}:\n *\n * ```\n * function foo() public auth {\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `ROOT`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {setRoleAdmin}.\n *\n * WARNING: The `ROOT` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\ncontract AccessControl {\n struct RoleData {\n mapping (address => bool) members;\n bytes4 adminRole;\n }\n\n mapping (bytes4 => RoleData) private _roles;\n\n bytes4 public constant ROOT = 0x00000000;\n bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833()\n bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function\n bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368()\n\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role\n *\n * `ROOT` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call.\n */\n event RoleGranted(bytes4 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes4 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members. \n * Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore.\n */\n constructor () {\n _grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender\n _setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree\n }\n\n /**\n * @dev Each function in the contract has its own role, identified by their msg.sig signature.\n * ROOT can give and remove access to each function, lock any further access being granted to\n * a specific action, or even create other roles to delegate admin control over a function.\n */\n modifier auth() {\n require (_hasRole(msg.sig, msg.sender), \"Access denied\");\n _;\n }\n\n /**\n * @dev Allow only if the caller has been granted the admin role of `role`.\n */\n modifier admin(bytes4 role) {\n require (_hasRole(_getRoleAdmin(role), msg.sender), \"Only admin\");\n _;\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes4 role, address account) external view returns (bool) {\n return _hasRole(role, account);\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes4 role) external view returns (bytes4) {\n return _getRoleAdmin(role);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n\n * If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) {\n _setRoleAdmin(role, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes4 role, address account) external virtual admin(role) {\n _grantRole(role, account);\n }\n\n \n /**\n * @dev Grants all of `role` in `roles` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - For each `role` in `roles`, the caller must have ``role``'s admin role.\n */\n function grantRoles(bytes4[] memory roles, address account) external virtual {\n for (uint256 i = 0; i < roles.length; i++) {\n require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), \"Only admin\");\n _grantRole(roles[i], account);\n }\n }\n\n /**\n * @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``.\n\n * Emits a {RoleAdminChanged} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function lockRole(bytes4 role) external virtual admin(role) {\n _setRoleAdmin(role, LOCK);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes4 role, address account) external virtual admin(role) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes all of `role` in `roles` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - For each `role` in `roles`, the caller must have ``role``'s admin role.\n */\n function revokeRoles(bytes4[] memory roles, address account) external virtual {\n for (uint256 i = 0; i < roles.length; i++) {\n require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), \"Only admin\");\n _revokeRole(roles[i], account);\n }\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes4 role, address account) external virtual {\n require(account == msg.sender, \"Renounce only for self\");\n\n _revokeRole(role, account);\n }\n\n function _hasRole(bytes4 role, address account) internal view returns (bool) {\n return _roles[role].members[account];\n }\n\n function _getRoleAdmin(bytes4 role) internal view returns (bytes4) {\n return _roles[role].adminRole;\n }\n\n function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual {\n if (_getRoleAdmin(role) != adminRole) {\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, adminRole);\n }\n }\n\n function _grantRole(bytes4 role, address account) internal {\n if (!_hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, msg.sender);\n }\n }\n\n function _revokeRole(bytes4 role, address account) internal {\n if (_hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, msg.sender);\n }\n }\n}"
},
"@yield-protocol/utils-v2/contracts/math/WDiv.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n\nlibrary WDiv { // Fixed point arithmetic in 18 decimal units\n // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol\n /// @dev Divide an amount by a fixed point factor with 18 decimals\n function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = (x * 1e18) / y;\n }\n}"
},
"@yield-protocol/utils-v2/contracts/cast/CastU128U104.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n\nlibrary CastU128U104 {\n /// @dev Safely cast an uint128 to an uint104\n function u104(uint128 x) internal pure returns (uint104 y) {\n require (x <= type(uint104).max, \"Cast overflow\");\n y = uint104(x);\n }\n}"
},
"@yield-protocol/utils-v2/contracts/math/RDiv.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n\nlibrary RDiv { // Fixed point arithmetic for ray (27 decimal units)\n /// @dev Divide an amount by a fixed point factor with 27 decimals\n function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = (x * 1e27) / y;\n }\n}"
},
"@yield-protocol/utils-v2/contracts/token/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Inspired on token.sol from DappHub. Natspec adpated from OpenZeppelin.\n\npragma solidity ^0.8.0;\nimport \"./IERC20Metadata.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n * \n * Calls to {transferFrom} do not check for allowance if the caller is the owner\n * of the funds. This allows to reduce the number of approvals that are necessary.\n *\n * Finally, {transferFrom} does not decrease the allowance if it is set to\n * type(uint256).max. This reduces the gas costs without any likely impact.\n */\ncontract ERC20 is IERC20Metadata {\n uint256 internal _totalSupply;\n mapping (address => uint256) internal _balanceOf;\n mapping (address => mapping (address => uint256)) internal _allowance;\n string public override name = \"???\";\n string public override symbol = \"???\";\n uint8 public override decimals = 18;\n\n /**\n * @dev Sets the values for {name}, {symbol} and {decimals}.\n */\n constructor(string memory name_, string memory symbol_, uint8 decimals_) {\n name = name_;\n symbol = symbol_;\n decimals = decimals_;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() external view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address guy) external view virtual override returns (uint256) {\n return _balanceOf[guy];\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) external view virtual override returns (uint256) {\n return _allowance[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n */\n function approve(address spender, uint wad) external virtual override returns (bool) {\n return _setAllowance(msg.sender, spender, wad);\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - the caller must have a balance of at least `wad`.\n */\n function transfer(address dst, uint wad) external virtual override returns (bool) {\n return _transfer(msg.sender, dst, wad);\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * Requirements:\n *\n * - `src` must have a balance of at least `wad`.\n * - the caller is not `src`, it must have allowance for ``src``'s tokens of at least\n * `wad`.\n */\n /// if_succeeds {:msg \"TransferFrom - decrease allowance\"} msg.sender != src ==> old(_allowance[src][msg.sender]) >= wad;\n function transferFrom(address src, address dst, uint wad) external virtual override returns (bool) {\n _decreaseAllowance(src, wad);\n\n return _transfer(src, dst, wad);\n }\n\n /**\n * @dev Moves tokens `wad` from `src` to `dst`.\n * \n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `src` must have a balance of at least `amount`.\n */\n /// if_succeeds {:msg \"Transfer - src decrease\"} old(_balanceOf[src]) >= _balanceOf[src];\n /// if_succeeds {:msg \"Transfer - dst increase\"} _balanceOf[dst] >= old(_balanceOf[dst]);\n /// if_succeeds {:msg \"Transfer - supply\"} old(_balanceOf[src]) + old(_balanceOf[dst]) == _balanceOf[src] + _balanceOf[dst];\n function _transfer(address src, address dst, uint wad) internal virtual returns (bool) {\n require(_balanceOf[src] >= wad, \"ERC20: Insufficient balance\");\n unchecked { _balanceOf[src] = _balanceOf[src] - wad; }\n _balanceOf[dst] = _balanceOf[dst] + wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n /**\n * @dev Sets the allowance granted to `spender` by `owner`.\n *\n * Emits an {Approval} event indicating the updated allowance.\n */\n function _setAllowance(address owner, address spender, uint wad) internal virtual returns (bool) {\n _allowance[owner][spender] = wad;\n emit Approval(owner, spender, wad);\n\n return true;\n }\n\n /**\n * @dev Decreases the allowance granted to the caller by `src`, unless src == msg.sender or _allowance[src][msg.sender] == MAX\n *\n * Emits an {Approval} event indicating the updated allowance, if the allowance is updated.\n *\n * Requirements:\n *\n * - `spender` must have allowance for the caller of at least\n * `wad`, unless src == msg.sender\n */\n /// if_succeeds {:msg \"Decrease allowance - underflow\"} old(_allowance[src][msg.sender]) <= _allowance[src][msg.sender];\n function _decreaseAllowance(address src, uint wad) internal virtual returns (bool) {\n if (src != msg.sender) {\n uint256 allowed = _allowance[src][msg.sender];\n if (allowed != type(uint).max) {\n require(allowed >= wad, \"ERC20: Insufficient approval\");\n unchecked { _setAllowance(src, msg.sender, allowed - wad); }\n }\n }\n\n return true;\n }\n\n /** @dev Creates `wad` tokens and assigns them to `dst`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n */\n /// if_succeeds {:msg \"Mint - balance overflow\"} old(_balanceOf[dst]) >= _balanceOf[dst];\n /// if_succeeds {:msg \"Mint - supply overflow\"} old(_totalSupply) >= _totalSupply;\n function _mint(address dst, uint wad) internal virtual returns (bool) {\n _balanceOf[dst] = _balanceOf[dst] + wad;\n _totalSupply = _totalSupply + wad;\n emit Transfer(address(0), dst, wad);\n\n return true;\n }\n\n /**\n * @dev Destroys `wad` tokens from `src`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `src` must have at least `wad` tokens.\n */\n /// if_succeeds {:msg \"Burn - balance underflow\"} old(_balanceOf[src]) <= _balanceOf[src];\n /// if_succeeds {:msg \"Burn - supply underflow\"} old(_totalSupply) <= _totalSupply;\n function _burn(address src, uint wad) internal virtual returns (bool) {\n unchecked {\n require(_balanceOf[src] >= wad, \"ERC20: Insufficient balance\");\n _balanceOf[src] = _balanceOf[src] - wad;\n _totalSupply = _totalSupply - wad;\n emit Transfer(src, address(0), wad);\n }\n\n return true;\n }\n}"
},
"@yield-protocol/utils-v2/contracts/token/ERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol\npragma solidity ^0.8.0;\n\nimport \"./ERC20.sol\";\nimport \"./IERC2612.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to use their tokens\n * without sending any transactions by setting {IERC20-allowance} with a\n * signature using the {permit} method, and then spend them via\n * {IERC20-transferFrom}.\n *\n * The {permit} signature mechanism conforms to the {IERC2612} interface.\n */\nabstract contract ERC20Permit is ERC20, IERC2612 {\n mapping (address => uint256) public override nonces;\n\n bytes32 public immutable PERMIT_TYPEHASH = keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n bytes32 private immutable _DOMAIN_SEPARATOR;\n uint256 public immutable deploymentChainId;\n\n constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_, decimals_) {\n deploymentChainId = block.chainid;\n _DOMAIN_SEPARATOR = _calculateDomainSeparator(block.chainid);\n }\n\n /// @dev Calculate the DOMAIN_SEPARATOR.\n function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {\n return keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(bytes(version())),\n chainId,\n address(this)\n )\n );\n }\n\n /// @dev Return the DOMAIN_SEPARATOR.\n function DOMAIN_SEPARATOR() external view returns (bytes32) {\n return block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid);\n }\n\n /// @dev Setting the version as a function so that it can be overriden\n function version() public pure virtual returns(string memory) { return \"1\"; }\n\n /**\n * @dev See {IERC2612-permit}.\n *\n * In cases where the free option is not a concern, deadline can simply be\n * set to uint(-1), so it should be seen as an optional parameter\n */\n function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external virtual override {\n require(deadline >= block.timestamp, \"ERC20Permit: expired deadline\");\n\n bytes32 hashStruct = keccak256(\n abi.encode(\n PERMIT_TYPEHASH,\n owner,\n spender,\n amount,\n nonces[owner]++,\n deadline\n )\n );\n\n bytes32 hash = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid),\n hashStruct\n )\n );\n\n address signer = ecrecover(hash, v, r, s);\n require(\n signer != address(0) && signer == owner,\n \"ERC20Permit: invalid signature\"\n );\n\n _setAllowance(owner, spender, amount);\n }\n}\n"
},
"@yield-protocol/yieldspace-tv/src/Pool/PoolErrors.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.15;\n\n/* POOL ERRORS\n******************************************************************************************************************/\n\n/// The pool has matured and maybe you should too.\nerror AfterMaturity();\n\n/// The approval of the sharesToken failed miserably.\nerror ApproveFailed();\n\n/// The update would cause the FYToken cached to be less than the total supply. This should never happen but may\n/// occur due to unexpected rounding errors. We cannot allow this to happen as it could have many unexpected and\n/// side effects which may pierce the fabric of the space-time continuum.\nerror FYTokenCachedBadState();\n\n/// The pool has already been initialized. What are you thinking?\n/// @dev To save gas, total supply == 0 is checked instead of a state variable.\nerror Initialized();\n\n/// Trade results in negative interest rates because fyToken balance < (newSharesBalance * mu). Don't neg me.\nerror NegativeInterestRatesNotAllowed(uint128 newFYTokenBalance, uint128 newSharesBalanceTimesMu);\n\n/// Represents the fee in bps, and it cannot be larger than 10,000.\n/// @dev https://en.wikipedia.org/wiki/10,000 per wikipedia:\n/// 10,000 (ten thousand) is the natural number following 9,999 and preceding 10,001.\n/// @param proposedFee The fee that was proposed.\nerror InvalidFee(uint16 proposedFee);\n\n/// The year is 2106 and an invalid maturity date was passed into the constructor.\n/// Maturity date must be less than type(uint32).max\nerror MaturityOverflow();\n\n/// Mu cannot be zero. And you're not a hero.\nerror MuCannotBeZero();\n\n/// Not enough base was found in the pool contract to complete the requested action. You just wasted gas.\n/// @param baseAvailable The amount of unaccounted for base tokens.\n/// @param baseNeeded The amount of base tokens required for the mint.\nerror NotEnoughBaseIn(uint256 baseAvailable, uint256 baseNeeded);\n\n/// Not enough fYTokens were found in the pool contract to complete the requested action :( smh.\n/// @param fYTokensAvailable The amount of unaccounted for fYTokens.\n/// @param fYTokensNeeded The amount of fYToken tokens required for the mint.\nerror NotEnoughFYTokenIn(uint256 fYTokensAvailable, uint256 fYTokensNeeded);\n\n/// The pool has not been initialized yet. INTRUDER ALERT!\n/// @dev To save gas, total supply == 0 is checked instead of a state variable\nerror NotInitialized();\n\n/// The reserves have changed compared with the last cache which causes the burn to fall outside the bounds of min/max\n/// slippage ratios selected. This is likely the result of a peanut butter sandwich attack.\n/// @param newRatio The ratio that would have resulted from the mint.\n/// @param minRatio The minimum ratio allowed as specified by the caller.\n/// @param maxRatio The maximum ratio allowed as specified by the caller\nerror SlippageDuringBurn(uint256 newRatio, uint256 minRatio, uint256 maxRatio);\n\n/// The reserves have changed compared with the last cache which causes the mint to fall outside the bounds of min/max\n/// slippage ratios selected. This is likely the result of a bologna sandwich attack.\n/// @param newRatio The ratio that would have resulted from the mint.\n/// @param minRatio The minimum ratio allowed as specified by the caller.\n/// @param maxRatio The maximum ratio allowed as specified by the caller\nerror SlippageDuringMint(uint256 newRatio, uint256 minRatio, uint256 maxRatio);\n\n/// Minimum amount of fyToken (per the min arg) would not be met for the trade. Try again.\n/// @param fyTokenOut fyTokens that would be obtained through the trade.\n/// @param min The minimum amount of fyTokens as specified by the caller.\nerror SlippageDuringSellBase(uint128 fyTokenOut, uint128 min);\n\n\n/// Minimum amount of base (per the min arg) would not be met for the trade. Maybe you'll get lucky next time.\n/// @param baseOut bases that would be obtained through the trade.\n/// @param min The minimum amount of bases as specified by the caller.\nerror SlippageDuringSellFYToken(uint128 baseOut, uint128 min);\n"
},
"@yield-protocol/utils-v2/contracts/token/MinimalTransferHelper.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Taken from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol\n\npragma solidity >=0.6.0;\n\nimport \"./IERC20.sol\";\nimport \"../utils/RevertMsgExtractor.sol\";\n\n\n// helper methods for transferring ERC20 tokens that do not consistently return true/false\nlibrary MinimalTransferHelper {\n /// @notice Transfers tokens from msg.sender to a recipient\n /// @dev Errors with the underlying revert message if transfer fails\n /// @param token The contract address of the token which will be transferred\n /// @param to The recipient of the transfer\n /// @param value The value of the transfer\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));\n if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert(RevertMsgExtractor.getRevertMsg(data));\n }\n}"
},
"@yield-protocol/yieldspace-tv/src/Pool/PoolEvents.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.15;\n\n/* POOL EVENTS\n ******************************************************************************************************************/\n\nabstract contract PoolEvents {\n /// Fees have been updated.\n event FeesSet(uint16 g1Fee);\n\n /// Pool is matured and all LP tokens burned. gg.\n event gg();\n\n /// gm. Pool is initialized.\n event gm();\n\n /// A liquidity event has occured (burn / mint).\n event Liquidity(\n uint32 maturity,\n address indexed from,\n address indexed to,\n address indexed fyTokenTo,\n int256 base,\n int256 fyTokens,\n int256 poolTokens\n );\n\n /// The _update fn has run and cached balances updated.\n event Sync(uint112 baseCached, uint112 fyTokenCached, uint256 cumulativeBalancesRatio);\n\n /// One of the four trading functions has been called:\n /// - buyBase\n /// - sellBase\n /// - buyFYToken\n /// - sellFYToken\n event Trade(uint32 maturity, address indexed from, address indexed to, int256 base, int256 fyTokens);\n}\n"
},
"@yield-protocol/yieldspace-tv/src/interfaces/IERC4626.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.15;\nimport \"@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol\";\nimport \"@yield-protocol/utils-v2/contracts/token/IERC20.sol\";\n\ninterface IERC4626 is IERC20, IERC20Metadata {\n function asset() external returns (IERC20);\n function convertToAssets(uint256 shares) external view returns (uint256);\n function convertToShares(uint256 assets) external view returns (uint256);\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n function mint(address receiver, uint256 shares) external returns (uint256 assets);\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n"
},
"@yield-protocol/yieldspace-tv/src/interfaces/IPool.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >= 0.8.0;\nimport \"@yield-protocol/utils-v2/contracts/token/IERC20.sol\";\nimport \"@yield-protocol/utils-v2/contracts/token/IERC2612.sol\";\nimport {IMaturingToken} from \"./IMaturingToken.sol\";\nimport {IERC20Metadata} from \"@yield-protocol/utils-v2/contracts/token/ERC20.sol\";\n\ninterface IPool is IERC20, IERC2612 {\n function baseToken() external view returns(IERC20Metadata);\n function base() external view returns(IERC20);\n function burn(address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256);\n function burnForBase(address to, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256);\n function buyBase(address to, uint128 baseOut, uint128 max) external returns(uint128);\n function buyBasePreview(uint128 baseOut) external view returns(uint128);\n function buyFYToken(address to, uint128 fyTokenOut, uint128 max) external returns(uint128);\n function buyFYTokenPreview(uint128 fyTokenOut) external view returns(uint128);\n function currentCumulativeRatio() external view returns (uint256 currentCumulativeRatio_, uint256 blockTimestampCurrent);\n function cumulativeRatioLast() external view returns (uint256);\n function fyToken() external view returns(IMaturingToken);\n function g1() external view returns(int128);\n function g2() external view returns(int128);\n function getC() external view returns (int128);\n function getCurrentSharePrice() external view returns (uint256);\n function getCache() external view returns (uint104 baseCached, uint104 fyTokenCached, uint32 blockTimestampLast, uint16 g1Fee_);\n function getBaseBalance() external view returns(uint128);\n function getFYTokenBalance() external view returns(uint128);\n function getSharesBalance() external view returns(uint128);\n function init(address to) external returns (uint256, uint256, uint256);\n function maturity() external view returns(uint32);\n function mint(address to, address remainder, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256);\n function mu() external view returns (int128);\n function mintWithBase(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256);\n function retrieveBase(address to) external returns(uint128 retrieved);\n function retrieveFYToken(address to) external returns(uint128 retrieved);\n function retrieveShares(address to) external returns(uint128 retrieved);\n function scaleFactor() external view returns(uint96);\n function sellBase(address to, uint128 min) external returns(uint128);\n function sellBasePreview(uint128 baseIn) external view returns(uint128);\n function sellFYToken(address to, uint128 min) external returns(uint128);\n function sellFYTokenPreview(uint128 fyTokenIn) external view returns(uint128);\n function setFees(uint16 g1Fee_) external;\n function sharesToken() external view returns(IERC20Metadata);\n function ts() external view returns(int128);\n function wrap(address receiver) external returns (uint256 shares);\n function wrapPreview(uint256 assets) external view returns (uint256 shares);\n function unwrap(address receiver) external returns (uint256 assets);\n function unwrapPreview(uint256 shares) external view returns (uint256 assets);\n /// Returns the max amount of FYTokens that can be sold to the pool\n function maxFYTokenIn() external view returns (uint128) ;\n /// Returns the max amount of FYTokens that can be bought from the pool\n function maxFYTokenOut() external view returns (uint128) ;\n /// Returns the max amount of Base that can be sold to the pool\n function maxBaseIn() external view returns (uint128) ;\n /// Returns the max amount of Base that can be bought from the pool\n function maxBaseOut() external view returns (uint128);\n /// Returns the result of the total supply invariant function\n function invariant() external view returns (uint128);\n}"
},
"@yield-protocol/yieldspace-tv/src/interfaces/IMaturingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.15;\nimport \"@yield-protocol/utils-v2/contracts/token/IERC20.sol\";\n\ninterface IMaturingToken is IERC20 {\n function maturity() external view returns (uint256);\n}"
},
"@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}"
},
"@yield-protocol/utils-v2/contracts/token/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(address sender, address recipient, uint256 amount) 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}"
},
"@yield-protocol/utils-v2/contracts/token/IERC2612.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC2612 standard as defined in the EIP.\n *\n * Adds the {permit} method, which can be used to change one's\n * {IERC20-allowance} without having to send a transaction, by signing a\n * message. This allows users to spend tokens without having to hold Ether.\n *\n * See https://eips.ethereum.org/EIPS/eip-2612.\n */\ninterface IERC2612 {\n /**\n * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,\n * given `owner`'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n /**\n * @dev Returns the current ERC2612 nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n}\n"
},
"@yield-protocol/utils-v2/contracts/utils/RevertMsgExtractor.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Taken from https://github.com/sushiswap/BoringSolidity/blob/441e51c0544cf2451e6116fe00515e71d7c42e2c/contracts/BoringBatchable.sol\n\npragma solidity >=0.6.0;\n\n\nlibrary RevertMsgExtractor {\n /// @dev Helper function to extract a useful revert message from a failed call.\n /// If the returned data is malformed or not correctly abi encoded then this call can fail itself.\n function getRevertMsg(bytes memory returnData)\n internal pure\n returns (string memory)\n {\n // If the _res length is less than 68, then the transaction failed silently (without a revert message)\n if (returnData.length < 68) return \"Transaction reverted silently\";\n\n assembly {\n // Slice the sighash.\n returnData := add(returnData, 0x04)\n }\n return abi.decode(returnData, (string)); // All that remains is the revert string\n }\n}"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 100
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {
"@yield-protocol/yieldspace-tv/src/YieldMath.sol": {
"YieldMath": "0x4031057e802da9a7de7ed1da6401be1aff531f12"
}
}
}
}