{ "language": "Solidity", "sources": { "contracts/strategies/HStrategy.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/utils/Multicall.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/proxy/Clones.sol\";\nimport \"../interfaces/external/univ3/INonfungiblePositionManager.sol\";\nimport \"../interfaces/external/univ3/IUniswapV3Pool.sol\";\nimport \"../interfaces/external/univ3/IUniswapV3Factory.sol\";\nimport \"../interfaces/external/univ3/ISwapRouter.sol\";\nimport \"../interfaces/vaults/IERC20Vault.sol\";\nimport \"../interfaces/vaults/IUniV3Vault.sol\";\nimport \"../libraries/ExceptionsLibrary.sol\";\nimport \"../libraries/CommonLibrary.sol\";\nimport \"../libraries/external/FullMath.sol\";\nimport \"../libraries/external/TickMath.sol\";\nimport \"../utils/DefaultAccessControlLateInit.sol\";\nimport \"../utils/HStrategyHelper.sol\";\nimport \"../utils/ContractMeta.sol\";\nimport \"../utils/UniV3Helper.sol\";\n\ncontract HStrategy is ContractMeta, Multicall, DefaultAccessControlLateInit {\n using SafeERC20 for IERC20;\n\n // IMMUTABLES\n uint32 public constant DENOMINATOR = 10**9;\n bytes4 public constant APPROVE_SELECTOR = 0x095ea7b3;\n bytes4 public constant EXACT_INPUT_SINGLE_SELECTOR = ISwapRouter.exactInputSingle.selector;\n ISwapRouter public immutable router;\n\n IERC20Vault public erc20Vault;\n IIntegrationVault public moneyVault;\n IUniV3Vault public uniV3Vault;\n address[] public tokens;\n\n INonfungiblePositionManager private immutable _positionManager;\n IUniswapV3Pool public pool;\n uint24 public swapFees;\n UniV3Helper private immutable _uniV3Helper;\n HStrategyHelper private immutable _hStrategyHelper;\n Interval private shortInterval;\n bool private needPositionRebalance;\n bool private newPositionMinted;\n\n // MUTABLE PARAMS\n\n /// @notice general params of the strategy - responsible for emulating interval and rebalance conditions\n /// @param halfOfShortInterval half of width of the uniV3 position measured in the strategy in ticks\n /// @param tickNeighborhood width of the neighbourhood of the current position border, in which rebalance can be called.\n /// Example: if the upperTick=10, tickNeighbourhood=5, rebalance can be called for all ticks greater than 10 - 5 = 5\n /// @param domainLowerTick the lower tick of the domain uniV3 position\n /// @param domainUpperTick the upper tick of the domain uniV3 position\n struct StrategyParams {\n int24 halfOfShortInterval;\n int24 tickNeighborhood;\n int24 domainLowerTick;\n int24 domainUpperTick;\n }\n\n /// @notice params of the actual minted position\n /// @param minToken0ForOpening the amount of token0 are tried to be depositted on the new position\n /// @param minToken1ForOpening the amount of token1 are tried to be depositted on the new position\n struct MintingParams {\n uint256 minToken0ForOpening;\n uint256 minToken1ForOpening;\n }\n\n /// @notice params of the interaction with oracle\n /// @param averagePriceTimeSpan delta in seconds, passed to oracle to get the price averagePriceTimeSpan seconds ago\n /// @param maxTickDeviation the upper bound for an absolute deviation between the spot price and the price for given number seconds ago\n struct OracleParams {\n uint32 averagePriceTimeSpan;\n uint24 maxTickDeviation;\n }\n\n /// @param erc20CapitalRatioD the ratio of tokens kept in money vault instead of erc20. The ratio is maintained for each token\n /// @param minCapitalDeviationD the needed deviation from target amount of capital in some vault to call rebalance or swap tokens\n /// @param minRebalanceDeviationD the needed deviation from expected amounts to call swap of tokens\n struct RatioParams {\n uint256 erc20CapitalRatioD;\n uint256 minCapitalDeviationD;\n uint256 minRebalanceDeviationD;\n }\n\n StrategyParams public strategyParams;\n MintingParams public mintingParams;\n OracleParams public oracleParams;\n RatioParams public ratioParams;\n\n // INTERNAL STRUCTURES\n\n /// @notice parameters of the current position\n /// @param lowerTick lower tick of interval\n /// @param upperTick upper tick of interval\n struct Interval {\n int24 lowerTick;\n int24 upperTick;\n }\n\n /// @notice rebalance parameters restricting the tokens transfer\n struct RebalanceTokenAmounts {\n uint256[] pulledToUniV3Vault;\n uint256[] pulledFromUniV3Vault;\n int256[] swappedAmounts;\n uint256[] burnedAmounts;\n uint256 deadline;\n }\n\n /// @notice structure for keeping information about capital in different vaults\n /// @param erc20TokensAmountInToken0 the capital of erc20 vault calculated in token0\n /// @param moneyTokensAmountInToken0 the capital of money vault calculated in token0\n /// @param uniV3TokensAmountInToken0 the capital of uniV3 vault calculated in token0\n /// @param totalTokensInToken0 the total capital calculated in token0\n struct TokenAmountsInToken0 {\n uint256 erc20TokensAmountInToken0;\n uint256 moneyTokensAmountInToken0;\n uint256 uniV3TokensAmountInToken0;\n uint256 totalTokensInToken0;\n }\n\n /// @notice structure for calculation of the current and expected amounts of tokens on all vaults\n /// @param erc20Token0 the current amount of token0 on erc20 vault\n /// @param erc20Token1 the current amount of token1 on erc20 vault\n /// @param moneyToken0 the current amount of token0 on money vault\n /// @param moneyToken1 the current amount of token1 on money vault\n /// @param uniV3Token0 the current amount of token0 on uniV3 vault\n /// @param uniV3Token1 the current amount of token1 on uniV3 vault\n struct TokenAmounts {\n uint256 erc20Token0;\n uint256 erc20Token1;\n uint256 moneyToken0;\n uint256 moneyToken1;\n uint256 uniV3Token0;\n uint256 uniV3Token1;\n }\n\n /// @notice structure for the calculation of expected ratios between capitals in different assets\n /// @param token0RatioD the ratio of the capital in token0 / totalCapital\n /// @param token1RatioD the ratio of the capital in token1 / totalCapital\n /// @param uniV3RatioD the ratio of the capital in uniV3 / totalCapital\n struct ExpectedRatios {\n uint32 token0RatioD;\n uint32 token1RatioD;\n uint32 uniV3RatioD;\n }\n\n /// @notice structure for keeping information about the current position, pool state and oracle price\n /// @param nft the nft of the position in positionManager\n /// @param liquidity the total liquidity of the position\n /// @param lowerTick the lower tick of the position\n /// @param upperTick the upper tick of the position\n /// @param domainLowerTick the lower tick of the domain position\n /// @param domainUpperTick the upper tick of the domain position\n /// @param lowerPriceSqrtX96 the square root of the price at lower tick of the position\n /// @param upperPriceSqrtX96 the square root of the price at upper tick of the position\n /// @param domainLowerPriceSqrtX96 the square root of the price at lower tick of the domain position\n /// @param domainUpperPriceSqrtX96 the square root of the price at upper tick of the domain position\n /// @param intervalPriceSqrtX96 the square root of the spot price limited by the boundaries of the domain interval\n /// @param spotPriceX96 the spot price\n struct DomainPositionParams {\n uint256 nft;\n uint128 liquidity;\n int24 lowerTick;\n int24 upperTick;\n int24 domainLowerTick;\n int24 domainUpperTick;\n uint160 lowerPriceSqrtX96;\n uint160 upperPriceSqrtX96;\n uint160 domainLowerPriceSqrtX96;\n uint160 domainUpperPriceSqrtX96;\n uint160 intervalPriceSqrtX96;\n uint256 spotPriceX96;\n }\n\n // ------------------- EXTERNAL, MUTATING -------------------\n\n /// @notice constructs a strategy\n /// @param positionManager_ the position manager for uniV3\n /// @param router_ the uniV3 router for swapping tokens\n /// @param uniV3Helper_ the address of the helper contract for uniV3\n /// @param hStrategyHelper_ the address of the strategy helper contract\n constructor(\n INonfungiblePositionManager positionManager_,\n ISwapRouter router_,\n address uniV3Helper_,\n address hStrategyHelper_\n ) {\n require(address(positionManager_) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n require(address(router_) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n require(uniV3Helper_ != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n require(hStrategyHelper_ != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n _positionManager = positionManager_;\n router = router_;\n _uniV3Helper = UniV3Helper(uniV3Helper_);\n _hStrategyHelper = HStrategyHelper(hStrategyHelper_);\n DefaultAccessControlLateInit.init(address(this));\n }\n\n /// @notice initializes the strategy\n /// @param tokens_ the addresses of the tokens managed by the strategy\n /// @param erc20Vault_ the address of the erc20 vault\n /// @param moneyVault_ the address of the moneyVault. It is expected to be yEarn or AAVE\n /// @param uniV3Vault_ the address of uniV3Vault. It is expected to not hold the position\n /// @param fee_ the fee of the uniV3 pool on which the vault operates\n /// @param admin_ the addres of the admin of the strategy\n function initialize(\n address[] memory tokens_,\n IERC20Vault erc20Vault_,\n IIntegrationVault moneyVault_,\n IUniV3Vault uniV3Vault_,\n uint24 fee_,\n address admin_\n ) external {\n DefaultAccessControlLateInit.init(admin_); // call once is checked here\n address[] memory erc20Tokens = erc20Vault_.vaultTokens();\n address[] memory moneyTokens = moneyVault_.vaultTokens();\n address[] memory uniV3Tokens = uniV3Vault_.vaultTokens();\n require(tokens_.length == 2, ExceptionsLibrary.INVALID_LENGTH);\n require(erc20Tokens.length == 2, ExceptionsLibrary.INVALID_LENGTH);\n require(moneyTokens.length == 2, ExceptionsLibrary.INVALID_LENGTH);\n require(uniV3Tokens.length == 2, ExceptionsLibrary.INVALID_LENGTH);\n for (uint256 i = 0; i < 2; i++) {\n require(erc20Tokens[i] == tokens_[i], ExceptionsLibrary.INVARIANT);\n require(moneyTokens[i] == tokens_[i], ExceptionsLibrary.INVARIANT);\n require(uniV3Tokens[i] == tokens_[i], ExceptionsLibrary.INVARIANT);\n }\n erc20Vault = erc20Vault_;\n moneyVault = moneyVault_;\n uniV3Vault = uniV3Vault_;\n tokens = tokens_;\n IUniswapV3Factory factory = IUniswapV3Factory(_positionManager.factory());\n pool = IUniswapV3Pool(factory.getPool(tokens_[0], tokens_[1], fee_));\n require(address(pool) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n }\n\n /// @notice creates the clone of the strategy\n /// @param tokens_ the addresses of the tokens managed by the strategy\n /// @param erc20Vault_ the address of the erc20 vault\n /// @param moneyVault_ the address of the moneyVault. It is expected to be yEarn or AAVE\n /// @param uniV3Vault_ the address of uniV3Vault. It is expected to not hold the position\n /// @param fee_ the fee of the uniV3 pool on which the vault operates\n /// @param admin_ the addres of the admin of the strategy\n /// @return strategy the address of new strategy\n function createStrategy(\n address[] memory tokens_,\n IERC20Vault erc20Vault_,\n IIntegrationVault moneyVault_,\n IUniV3Vault uniV3Vault_,\n uint24 fee_,\n address admin_\n ) external returns (HStrategy strategy) {\n strategy = HStrategy(Clones.clone(address(this)));\n strategy.initialize(tokens_, erc20Vault_, moneyVault_, uniV3Vault_, fee_, admin_);\n }\n\n /// @notice updates parameters of the strategy. Can be called only by admin\n /// @param newStrategyParams the new parameters\n function updateStrategyParams(StrategyParams calldata newStrategyParams) external {\n _requireAdmin();\n int24 tickSpacing = pool.tickSpacing();\n require(\n newStrategyParams.halfOfShortInterval > 0 &&\n (newStrategyParams.halfOfShortInterval % tickSpacing == 0) &&\n newStrategyParams.tickNeighborhood <= newStrategyParams.halfOfShortInterval &&\n newStrategyParams.tickNeighborhood >= TickMath.MIN_TICK,\n ExceptionsLibrary.INVARIANT\n );\n\n int24 globalIntervalWidth = newStrategyParams.domainUpperTick - newStrategyParams.domainLowerTick;\n require(\n (newStrategyParams.domainLowerTick % tickSpacing == 0) &&\n (newStrategyParams.domainUpperTick % tickSpacing == 0) &&\n globalIntervalWidth > newStrategyParams.halfOfShortInterval &&\n (globalIntervalWidth % newStrategyParams.halfOfShortInterval == 0),\n ExceptionsLibrary.INVARIANT\n );\n StrategyParams memory strategyParams_ = strategyParams;\n if (\n newStrategyParams.halfOfShortInterval != strategyParams_.halfOfShortInterval ||\n newStrategyParams.domainLowerTick != strategyParams_.domainLowerTick ||\n newStrategyParams.domainUpperTick != strategyParams_.domainUpperTick\n ) {\n needPositionRebalance = true;\n }\n strategyParams = newStrategyParams;\n emit UpdateStrategyParams(tx.origin, msg.sender, newStrategyParams);\n }\n\n /// @notice updates parameters for minting position. Can be called only by admin\n /// @param newMintingParams the new parameters\n function updateMintingParams(MintingParams calldata newMintingParams) external {\n _requireAdmin();\n require(\n newMintingParams.minToken0ForOpening > 0 &&\n newMintingParams.minToken1ForOpening > 0 &&\n (newMintingParams.minToken0ForOpening <= 1000000000) &&\n (newMintingParams.minToken1ForOpening <= 1000000000),\n ExceptionsLibrary.INVARIANT\n );\n mintingParams = newMintingParams;\n emit UpdateMintingParams(tx.origin, msg.sender, newMintingParams);\n }\n\n /// @notice updates oracle parameters. Can be called only by admin\n /// @param newOracleParams the new parameters\n function updateOracleParams(OracleParams calldata newOracleParams) external {\n _requireAdmin();\n require(\n newOracleParams.averagePriceTimeSpan > 0 && newOracleParams.maxTickDeviation <= uint24(TickMath.MAX_TICK),\n ExceptionsLibrary.INVARIANT\n );\n oracleParams = newOracleParams;\n emit UpdateOracleParams(tx.origin, msg.sender, newOracleParams);\n }\n\n /// @notice updates parameters of the capital ratios and deviation. Can be called only by admin\n /// @param newRatioParams the new parameters\n function updateRatioParams(RatioParams calldata newRatioParams) external {\n _requireAdmin();\n require(\n newRatioParams.erc20CapitalRatioD <= DENOMINATOR &&\n newRatioParams.minCapitalDeviationD <= newRatioParams.erc20CapitalRatioD &&\n newRatioParams.minRebalanceDeviationD > 0 &&\n newRatioParams.minRebalanceDeviationD <= DENOMINATOR,\n ExceptionsLibrary.INVARIANT\n );\n ratioParams = newRatioParams;\n emit UpdateRatioParams(tx.origin, msg.sender, newRatioParams);\n }\n\n /// @notice updates swap fees for uniswapV3Pool swaps\n /// @param newSwapFees the new parameters\n function updateSwapFees(uint24 newSwapFees) external {\n _requireAdmin();\n address poolForSwaps = IUniswapV3Factory(_positionManager.factory()).getPool(tokens[0], tokens[1], newSwapFees);\n require(poolForSwaps != address(0), ExceptionsLibrary.INVARIANT);\n swapFees = newSwapFees;\n emit UpdateSwapFees(tx.origin, msg.sender, newSwapFees);\n }\n\n /// @notice manual pulling tokens from vault. Can be called only by admin\n /// @param fromVault the address of the vault to pull tokens from\n /// @param toVault the address of the vault to pull tokens to\n /// @param tokenAmounts the amount of tokens to be pulled\n /// @param vaultOptions additional options for `pull` method\n function manualPull(\n IIntegrationVault fromVault,\n IIntegrationVault toVault,\n uint256[] memory tokenAmounts,\n bytes memory vaultOptions\n ) external {\n _requireAdmin();\n fromVault.pull(address(toVault), tokens, tokenAmounts, vaultOptions);\n }\n\n /// @notice rebalance method. Need to be called if the new position is needed\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param moneyVaultOptions additional parameters for pulling for `pull` method for money vault\n /// @return actualPulledAmounts actual transferred amounts\n /// @return burnedAmounts actual burned amounts from uniV3 position\n function rebalance(RebalanceTokenAmounts memory restrictions, bytes memory moneyVaultOptions)\n external\n returns (RebalanceTokenAmounts memory actualPulledAmounts, uint256[] memory burnedAmounts)\n {\n _requireAtLeastOperator();\n IUniswapV3Pool pool_ = pool;\n (, int24 tick, , , , , ) = pool_.slot0();\n _hStrategyHelper.checkSpotTickDeviationFromAverage(tick, address(pool_), oracleParams, _uniV3Helper);\n burnedAmounts = _partialRebalanceOfUniV3Position(restrictions, tick);\n actualPulledAmounts = _capitalRebalance(restrictions, moneyVaultOptions, tick);\n }\n\n /// @notice rebalance, that if needed burns old univ3 position and mints new\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param tick current price tick\n /// @return burnedAmounts actual transferred amounts of tokens from position while burn\n function _partialRebalanceOfUniV3Position(RebalanceTokenAmounts memory restrictions, int24 tick)\n internal\n returns (uint256[] memory burnedAmounts)\n {\n IIntegrationVault erc20Vault_ = erc20Vault;\n IUniV3Vault uniV3Vault_ = uniV3Vault;\n uint256 uniV3Nft = uniV3Vault_.uniV3Nft();\n StrategyParams memory strategyParams_ = strategyParams;\n IUniswapV3Pool pool_ = pool;\n address[] memory tokens_ = tokens;\n burnedAmounts = new uint256[](2);\n burnedAmounts[0] = type(uint256).max;\n burnedAmounts[1] = type(uint256).max;\n newPositionMinted = false;\n {\n Interval memory shortInterval_ = shortInterval;\n int24 tickNeighborhood = strategyParams_.tickNeighborhood;\n\n if (\n shortInterval_.lowerTick + tickNeighborhood <= tick &&\n shortInterval_.upperTick - tickNeighborhood >= tick &&\n !needPositionRebalance\n ) {\n return burnedAmounts;\n }\n needPositionRebalance = false;\n\n (int24 newLowerTick, int24 newUpperTick) = _hStrategyHelper.calculateNewPositionTicks(\n tick,\n strategyParams_\n );\n\n if (newLowerTick == shortInterval_.lowerTick && shortInterval_.upperTick == newUpperTick) {\n return burnedAmounts;\n }\n\n shortInterval = Interval({lowerTick: newLowerTick, upperTick: newUpperTick});\n }\n\n if (uniV3Nft != 0) {\n // cannot burn only if it is first call of the rebalance function\n // and we dont have any position\n burnedAmounts = _drainPosition(restrictions, erc20Vault_, uniV3Vault_, uniV3Nft, tokens_);\n }\n\n _mintPosition(pool_, restrictions.deadline, _positionManager, uniV3Vault_, uniV3Nft, tokens_);\n }\n\n /// @notice rebalance amount of tokens between vaults. Need to be called when no new position is needed\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param moneyVaultOptions additional parameters for pulling for `pull` method for money vault\n /// @param tick spot tick for calculations\n /// @return actualPulledAmounts actual transferred amounts\n function _capitalRebalance(\n RebalanceTokenAmounts memory restrictions,\n bytes memory moneyVaultOptions,\n int24 tick\n ) internal returns (RebalanceTokenAmounts memory actualPulledAmounts) {\n HStrategyHelper hStrategyHelper_ = _hStrategyHelper;\n IUniV3Vault uniV3Vault_ = uniV3Vault;\n DomainPositionParams memory domainPositionParams;\n {\n uint256 uniV3Nft = uniV3Vault_.uniV3Nft();\n require(uniV3Nft != 0, ExceptionsLibrary.INVARIANT);\n domainPositionParams = hStrategyHelper_.calculateAndCheckDomainPositionParams(\n tick,\n strategyParams,\n uniV3Nft,\n _positionManager\n );\n }\n IIntegrationVault moneyVault_ = moneyVault;\n IIntegrationVault erc20Vault_ = erc20Vault;\n TokenAmounts memory currentTokenAmounts = hStrategyHelper_.calculateCurrentTokenAmounts(\n erc20Vault_,\n moneyVault_,\n domainPositionParams\n );\n TokenAmounts memory expectedTokenAmounts = hStrategyHelper_.calculateExpectedTokenAmounts(\n currentTokenAmounts,\n domainPositionParams,\n hStrategyHelper_,\n _uniV3Helper,\n ratioParams\n );\n\n if (!hStrategyHelper_.tokenRebalanceNeeded(currentTokenAmounts, expectedTokenAmounts, ratioParams)) {\n return actualPulledAmounts;\n }\n\n address[] memory tokens_ = tokens;\n actualPulledAmounts.pulledFromUniV3Vault = _pullExtraTokens(\n hStrategyHelper_,\n expectedTokenAmounts,\n restrictions,\n moneyVaultOptions,\n domainPositionParams,\n erc20Vault_,\n moneyVault_,\n uniV3Vault_,\n tokens_\n );\n\n if (hStrategyHelper_.swapNeeded(currentTokenAmounts, expectedTokenAmounts, ratioParams, domainPositionParams)) {\n actualPulledAmounts.swappedAmounts = _swapTokens(\n currentTokenAmounts,\n expectedTokenAmounts,\n restrictions,\n erc20Vault_,\n tokens_\n );\n }\n\n TokenAmounts memory missingTokenAmounts;\n {\n (, , , , , , , uint128 liquidity, , , , ) = _positionManager.positions(uniV3Vault_.uniV3Nft());\n missingTokenAmounts = hStrategyHelper_.calculateMissingTokenAmounts(\n moneyVault_,\n expectedTokenAmounts,\n domainPositionParams,\n liquidity\n );\n }\n actualPulledAmounts.pulledToUniV3Vault = _pullMissingTokens(\n missingTokenAmounts,\n restrictions,\n moneyVaultOptions,\n erc20Vault_,\n moneyVault_,\n uniV3Vault_,\n tokens_\n );\n }\n\n // ------------------- INTERNAL, MUTABLE -------------------\n\n /// @notice determining the amount of tokens to be swapped and swapping it\n /// @param currentTokenAmounts the current amount of tokens\n /// @param expectedTokenAmounts the amount of tokens we expect to have after rebalance\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param erc20Vault_ ERC20 vault of the strategy\n /// @param tokens_ the addresses of the tokens managed by the strategy\n /// @return swappedAmounts acutal amount of swapped tokens\n function _swapTokens(\n TokenAmounts memory currentTokenAmounts,\n TokenAmounts memory expectedTokenAmounts,\n RebalanceTokenAmounts memory restrictions,\n IIntegrationVault erc20Vault_,\n address[] memory tokens_\n ) internal returns (int256[] memory swappedAmounts) {\n (uint256 expectedToken0Amount, uint256 expectedToken1Amount) = _accumulateTokens(expectedTokenAmounts);\n (uint256 currentToken0Amount, uint256 currentToken1Amount) = _accumulateTokens(currentTokenAmounts);\n\n if (currentToken0Amount >= expectedToken0Amount && currentToken1Amount <= expectedToken1Amount) {\n swappedAmounts = _swapTokensOnERC20Vault(\n currentToken0Amount - expectedToken0Amount,\n 0,\n restrictions,\n erc20Vault_,\n tokens_\n );\n } else if (currentToken0Amount <= expectedToken0Amount && currentToken1Amount >= expectedToken1Amount) {\n swappedAmounts = _swapTokensOnERC20Vault(\n currentToken1Amount - expectedToken1Amount,\n 1,\n restrictions,\n erc20Vault_,\n tokens_\n );\n } else {\n revert(ExceptionsLibrary.INVALID_STATE);\n }\n }\n\n /// @notice pulling extra tokens from money and uniV3 vaults on erc20\n /// @param hStrategyHelper_ the helper of the strategy\n /// @param expectedTokenAmounts the amount of tokens we expect to have after rebalance\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param moneyVaultOptions additional parameters for pulling for `pull` method for money vault\n /// @param domainPositionParams the current state of the pool and position\n /// @param erc20Vault_ ERC20 vault of the strategy\n /// @param moneyVault_ Money vault of the strategy\n /// @param uniV3Vault_ UniswapV3 vault of the strategy\n /// @param tokens_ the addresses of the tokens managed by the strategy\n /// @return pulledFromUniV3Vault the actual amount of tokens pulled from UniV3Vault\n function _pullExtraTokens(\n HStrategyHelper hStrategyHelper_,\n TokenAmounts memory expectedTokenAmounts,\n RebalanceTokenAmounts memory restrictions,\n bytes memory moneyVaultOptions,\n DomainPositionParams memory domainPositionParams,\n IIntegrationVault erc20Vault_,\n IIntegrationVault moneyVault_,\n IUniV3Vault uniV3Vault_,\n address[] memory tokens_\n ) internal returns (uint256[] memory pulledFromUniV3Vault) {\n pulledFromUniV3Vault = new uint256[](2);\n if (!newPositionMinted) {\n uint256[] memory extraTokenAmountsForPull = hStrategyHelper_.calculateExtraTokenAmountsForUniV3Vault(\n expectedTokenAmounts,\n domainPositionParams\n );\n\n if (extraTokenAmountsForPull[0] > 0 || extraTokenAmountsForPull[1] > 0) {\n pulledFromUniV3Vault = uniV3Vault_.pull(address(erc20Vault_), tokens_, extraTokenAmountsForPull, \"\");\n _compareAmounts(restrictions.pulledFromUniV3Vault, pulledFromUniV3Vault);\n }\n }\n\n {\n uint256[] memory extraTokenAmountsForPull = hStrategyHelper_.calculateExtraTokenAmountsForMoneyVault(\n moneyVault_,\n expectedTokenAmounts\n );\n\n if (extraTokenAmountsForPull[0] > 0 || extraTokenAmountsForPull[1] > 0) {\n moneyVault_.pull(address(erc20Vault_), tokens_, extraTokenAmountsForPull, moneyVaultOptions);\n }\n }\n }\n\n /// @notice pulling missing tokens from erc20 vault on money and uniV3 vaults\n /// @param missingTokenAmounts the amount of missing tokens\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param moneyVaultOptions additional parameters for pulling for `pull` method for money vault\n /// @param erc20Vault_ ERC20 vault of the strategy\n /// @param moneyVault_ Money vault of the strategy\n /// @param uniV3Vault_ UniswapV3 vault of the strategy\n /// @param tokens_ the addresses of the tokens managed by the strategy\n /// @return pulledToUniV3Vault the actual amount of tokens pulled into UniV3Vault\n function _pullMissingTokens(\n TokenAmounts memory missingTokenAmounts,\n RebalanceTokenAmounts memory restrictions,\n bytes memory moneyVaultOptions,\n IIntegrationVault erc20Vault_,\n IIntegrationVault moneyVault_,\n IUniV3Vault uniV3Vault_,\n address[] memory tokens_\n ) internal returns (uint256[] memory pulledToUniV3Vault) {\n pulledToUniV3Vault = new uint256[](2);\n uint256[] memory extraTokenAmountsForPull = new uint256[](2);\n {\n if (missingTokenAmounts.uniV3Token0 > 0 || missingTokenAmounts.uniV3Token1 > 0) {\n extraTokenAmountsForPull[0] = missingTokenAmounts.uniV3Token0;\n extraTokenAmountsForPull[1] = missingTokenAmounts.uniV3Token1;\n pulledToUniV3Vault = erc20Vault_.pull(address(uniV3Vault_), tokens_, extraTokenAmountsForPull, \"\");\n _compareAmounts(restrictions.pulledToUniV3Vault, pulledToUniV3Vault);\n }\n }\n {\n if (missingTokenAmounts.moneyToken0 > 0 || missingTokenAmounts.moneyToken1 > 0) {\n extraTokenAmountsForPull[0] = missingTokenAmounts.moneyToken0;\n extraTokenAmountsForPull[1] = missingTokenAmounts.moneyToken1;\n erc20Vault_.pull(address(moneyVault_), tokens_, extraTokenAmountsForPull, moneyVaultOptions);\n }\n }\n }\n\n /// @notice minting new position inside the domain interval\n /// @param pool_ address of uniV3 pool\n /// @param deadline maximal duration of swap offer on uniV3\n /// @param positionManager_ uniV3 position manager\n /// @param uniV3Vault_ UniswapV3 vault of the strategy\n /// @param oldNft the nft of the burning position\n /// @param tokens_ addresses of tokens of strategy\n /// @param tokens_ the addresses of the tokens managed by the strategy\n function _mintPosition(\n IUniswapV3Pool pool_,\n uint256 deadline,\n INonfungiblePositionManager positionManager_,\n IUniV3Vault uniV3Vault_,\n uint256 oldNft,\n address[] memory tokens_\n ) internal {\n uint256 minToken0ForOpening;\n uint256 minToken1ForOpening;\n {\n MintingParams memory mintingParams_ = mintingParams;\n minToken0ForOpening = mintingParams_.minToken0ForOpening;\n minToken1ForOpening = mintingParams_.minToken1ForOpening;\n }\n IERC20(tokens_[0]).safeApprove(address(positionManager_), minToken0ForOpening);\n IERC20(tokens_[1]).safeApprove(address(positionManager_), minToken1ForOpening);\n Interval memory shortInterval_ = shortInterval;\n (uint256 newNft, , , ) = positionManager_.mint(\n INonfungiblePositionManager.MintParams({\n token0: tokens_[0],\n token1: tokens_[1],\n fee: pool_.fee(),\n tickLower: shortInterval_.lowerTick,\n tickUpper: shortInterval_.upperTick,\n amount0Desired: minToken0ForOpening,\n amount1Desired: minToken1ForOpening,\n amount0Min: 0,\n amount1Min: 0,\n recipient: address(this),\n deadline: deadline\n })\n );\n IERC20(tokens_[0]).safeApprove(address(positionManager_), 0);\n IERC20(tokens_[1]).safeApprove(address(positionManager_), 0);\n\n positionManager_.safeTransferFrom(address(this), address(uniV3Vault_), newNft);\n if (oldNft != 0) {\n positionManager_.burn(oldNft);\n }\n newPositionMinted = true;\n emit MintUniV3Position(newNft, shortInterval_.lowerTick, shortInterval_.upperTick);\n }\n\n /// @notice draining all assets from uniV3\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param erc20Vault_ ERC20 vault of the strategy\n /// @param uniV3Vault_ UniswapV3 vault of the strategy\n /// @param uniV3Nft the nft of the position from position manager\n /// @param tokens_ the addresses of the tokens managed by the strategy\n /// @return drainedTokens actual amount of tokens got from draining position\n function _drainPosition(\n RebalanceTokenAmounts memory restrictions,\n IIntegrationVault erc20Vault_,\n IUniV3Vault uniV3Vault_,\n uint256 uniV3Nft,\n address[] memory tokens_\n ) internal returns (uint256[] memory drainedTokens) {\n drainedTokens = uniV3Vault_.liquidityToTokenAmounts(type(uint128).max);\n drainedTokens = uniV3Vault_.pull(address(erc20Vault_), tokens_, drainedTokens, \"\");\n _compareAmounts(restrictions.burnedAmounts, drainedTokens);\n emit BurnUniV3Position(uniV3Nft);\n }\n\n /// @notice swapping tokens\n /// @param amountIn amount of tokens to be swapped\n /// @param tokenInIndex the index of token to be swapped (0 or 1)\n /// @param restrictions the restrictions of the amount of tokens to be transferred\n /// @param erc20Vault_ ERC20 vault of the strategy\n /// @param tokens_ the addresses of the tokens managed by the strategy\n /// @return amountsOut actual amount of tokens got from swap\n function _swapTokensOnERC20Vault(\n uint256 amountIn,\n uint256 tokenInIndex,\n RebalanceTokenAmounts memory restrictions,\n IIntegrationVault erc20Vault_,\n address[] memory tokens_\n ) internal returns (int256[] memory amountsOut) {\n {\n (uint256[] memory tvl, ) = erc20Vault_.tvl();\n if (tvl[tokenInIndex] < amountIn) {\n amountIn = tvl[tokenInIndex];\n }\n }\n\n bytes memory routerResult;\n if (amountIn > 0) {\n ISwapRouter.ExactInputSingleParams memory swapParams = ISwapRouter.ExactInputSingleParams({\n tokenIn: tokens_[tokenInIndex],\n tokenOut: tokens_[tokenInIndex ^ 1],\n fee: swapFees,\n recipient: address(erc20Vault_),\n deadline: restrictions.deadline,\n amountIn: amountIn,\n amountOutMinimum: 0,\n sqrtPriceLimitX96: 0\n });\n bytes memory data = abi.encode(swapParams);\n erc20Vault_.externalCall(tokens_[tokenInIndex], APPROVE_SELECTOR, abi.encode(address(router), amountIn)); // approve\n routerResult = erc20Vault_.externalCall(address(router), EXACT_INPUT_SINGLE_SELECTOR, data); // swap\n erc20Vault_.externalCall(tokens_[tokenInIndex], APPROVE_SELECTOR, abi.encode(address(router), 0)); // reset allowance\n uint256 amountOut = abi.decode(routerResult, (uint256));\n\n require(\n restrictions.swappedAmounts[tokenInIndex ^ 1] >= 0 && restrictions.swappedAmounts[tokenInIndex] <= 0,\n ExceptionsLibrary.INVARIANT\n );\n require(\n restrictions.swappedAmounts[tokenInIndex ^ 1] <= int256(amountOut),\n ExceptionsLibrary.LIMIT_UNDERFLOW\n );\n require(restrictions.swappedAmounts[tokenInIndex] >= -int256(amountIn), ExceptionsLibrary.LIMIT_OVERFLOW);\n\n amountsOut = new int256[](2);\n amountsOut[tokenInIndex ^ 1] = int256(amountOut);\n amountsOut[tokenInIndex] = -int256(amountIn);\n\n emit SwapTokensOnERC20Vault(tx.origin, swapParams);\n } else {\n require(restrictions.swappedAmounts[tokenInIndex ^ 1] == 0, ExceptionsLibrary.LIMIT_OVERFLOW);\n require(restrictions.swappedAmounts[tokenInIndex] == 0, ExceptionsLibrary.LIMIT_UNDERFLOW);\n return new int256[](2);\n }\n }\n\n // ------------------- INTERNAL, VIEW -------------------\n\n /// @notice method comparing needed amount of tokens and actual. Reverts in for any elent holds needed[i] > actual[i]\n /// @param needed the needed amount of tokens from some action\n /// @param actual actual amount of tokens from the action\n function _compareAmounts(uint256[] memory needed, uint256[] memory actual) internal pure {\n for (uint256 i = 0; i < 2; i++) {\n require(needed[i] <= actual[i], ExceptionsLibrary.LIMIT_UNDERFLOW);\n }\n }\n\n /// @notice method calculates sums for both tokens along all vaults\n /// @param tokenAmouts given token amounts\n /// @return token0 amount of token 0 over all vaults for given tokenAmouts\n /// @return token1 amount of token 1 over all vaults for given tokenAmouts\n function _accumulateTokens(TokenAmounts memory tokenAmouts) internal pure returns (uint256 token0, uint256 token1) {\n token0 = tokenAmouts.erc20Token0 + tokenAmouts.moneyToken0 + tokenAmouts.uniV3Token0;\n token1 = tokenAmouts.erc20Token1 + tokenAmouts.moneyToken1 + tokenAmouts.uniV3Token1;\n }\n\n function _contractName() internal pure override returns (bytes32) {\n return bytes32(\"HStrategy\");\n }\n\n function _contractVersion() internal pure override returns (bytes32) {\n return bytes32(\"1.0.0\");\n }\n\n /// @notice Emitted when new position in UniV3Pool has been minted.\n /// @param uniV3Nft nft of new minted position\n /// @param lowerTick lowerTick of that position\n /// @param upperTick upperTick of that position\n event MintUniV3Position(uint256 uniV3Nft, int24 lowerTick, int24 upperTick);\n\n /// @notice Emitted when position in UniV3Pool has been burnt.\n /// @param uniV3Nft nft of new minted position\n event BurnUniV3Position(uint256 uniV3Nft);\n\n /// @notice Emitted when swap is initiated.\n /// @param origin Origin of the transaction (tx.origin)\n /// @param swapParams Swap domainPositionParams\n event SwapTokensOnERC20Vault(address indexed origin, ISwapRouter.ExactInputSingleParams swapParams);\n\n /// @notice Emitted when Strategy strategyParams are set.\n /// @param origin Origin of the transaction (tx.origin)\n /// @param sender Sender of the call (msg.sender)\n /// @param strategyParams Updated strategyParams\n event UpdateStrategyParams(address indexed origin, address indexed sender, StrategyParams strategyParams);\n\n /// @notice Emitted when Strategy mintingParams are set.\n /// @param origin Origin of the transaction (tx.origin)\n /// @param sender Sender of the call (msg.sender)\n /// @param mintingParams Updated mintingParams\n event UpdateMintingParams(address indexed origin, address indexed sender, MintingParams mintingParams);\n\n /// @notice Emitted when Strategy oracleParams are set.\n /// @param origin Origin of the transaction (tx.origin)\n /// @param sender Sender of the call (msg.sender)\n /// @param oracleParams Updated oracleParams\n event UpdateOracleParams(address indexed origin, address indexed sender, OracleParams oracleParams);\n\n /// @notice Emitted when Strategy ratioParams are set.\n /// @param origin Origin of the transaction (tx.origin)\n /// @param sender Sender of the call (msg.sender)\n /// @param ratioParams Updated ratioParams\n event UpdateRatioParams(address indexed origin, address indexed sender, RatioParams ratioParams);\n\n /// @notice Emitted when new swap fees for UniV3Pool swaps are set.\n /// @param newSwapFees new swap fee\n /// @param origin Origin of the transaction (tx.origin)\n /// @param sender Sender of the call (msg.sender)\n event UpdateSwapFees(address indexed origin, address indexed sender, uint24 newSwapFees);\n}\n" }, "@openzeppelin/contracts/utils/Multicall.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/Multicall.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Address.sol\";\n\n/**\n * @dev Provides a function to batch together multiple calls in a single external call.\n *\n * _Available since v4.1._\n */\nabstract contract Multicall {\n /**\n * @dev Receives and executes a batch of function calls on this contract.\n */\n function multicall(bytes[] calldata data) external returns (bytes[] memory results) {\n results = new bytes[](data.length);\n for (uint256 i = 0; i < data.length; i++) {\n results[i] = Address.functionDelegateCall(address(this), data[i]);\n }\n return results;\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "@openzeppelin/contracts/proxy/Clones.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (proxy/Clones.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for\n * deploying minimal proxy contracts, also known as \"clones\".\n *\n * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies\n * > a minimal bytecode implementation that delegates all calls to a known, fixed address.\n *\n * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`\n * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the\n * deterministic method.\n *\n * _Available since v3.4._\n */\nlibrary Clones {\n /**\n * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n *\n * This function uses the create opcode, which should never revert.\n */\n function clone(address implementation) internal returns (address instance) {\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(ptr, 0x14), shl(0x60, implementation))\n mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n instance := create(0, ptr, 0x37)\n }\n require(instance != address(0), \"ERC1167: create failed\");\n }\n\n /**\n * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n *\n * This function uses the create2 opcode and a `salt` to deterministically deploy\n * the clone. Using the same `implementation` and `salt` multiple time will revert, since\n * the clones cannot be deployed twice at the same address.\n */\n function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(ptr, 0x14), shl(0x60, implementation))\n mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n instance := create2(0, ptr, 0x37, salt)\n }\n require(instance != address(0), \"ERC1167: create2 failed\");\n }\n\n /**\n * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n */\n function predictDeterministicAddress(\n address implementation,\n bytes32 salt,\n address deployer\n ) internal pure returns (address predicted) {\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(ptr, 0x14), shl(0x60, implementation))\n mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)\n mstore(add(ptr, 0x38), shl(0x60, deployer))\n mstore(add(ptr, 0x4c), salt)\n mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))\n predicted := keccak256(add(ptr, 0x37), 0x55)\n }\n }\n\n /**\n * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n */\n function predictDeterministicAddress(address implementation, bytes32 salt)\n internal\n view\n returns (address predicted)\n {\n return predictDeterministicAddress(implementation, salt, address(this));\n }\n}\n" }, "contracts/interfaces/external/univ3/INonfungiblePositionManager.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity 0.8.9;\r\npragma abicoder v2;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\r\nimport \"./IPeripheryImmutableState.sol\";\r\n\r\n/// @title Non-fungible token for positions\r\n/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred\r\n/// and authorized.\r\ninterface INonfungiblePositionManager is IPeripheryImmutableState, IERC721 {\r\n /// @notice Emitted when liquidity is increased for a position NFT\r\n /// @dev Also emitted when a token is minted\r\n /// @param tokenId The ID of the token for which liquidity was increased\r\n /// @param liquidity The amount by which liquidity for the NFT position was increased\r\n /// @param amount0 The amount of token0 that was paid for the increase in liquidity\r\n /// @param amount1 The amount of token1 that was paid for the increase in liquidity\r\n event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);\r\n /// @notice Emitted when liquidity is decreased for a position NFT\r\n /// @param tokenId The ID of the token for which liquidity was decreased\r\n /// @param liquidity The amount by which liquidity for the NFT position was decreased\r\n /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity\r\n /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity\r\n event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);\r\n /// @notice Emitted when tokens are collected for a position NFT\r\n /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior\r\n /// @param tokenId The ID of the token for which underlying tokens were collected\r\n /// @param recipient The address of the account that received the collected tokens\r\n /// @param amount0 The amount of token0 owed to the position that was collected\r\n /// @param amount1 The amount of token1 owed to the position that was collected\r\n event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);\r\n\r\n /// @notice Returns the position information associated with a given token ID.\r\n /// @dev Throws if the token ID is not valid.\r\n /// @param tokenId The ID of the token that represents the position\r\n /// @return nonce The nonce for permits\r\n /// @return operator The address that is approved for spending\r\n /// @return token0 The address of the token0 for a specific pool\r\n /// @return token1 The address of the token1 for a specific pool\r\n /// @return fee The fee associated with the pool\r\n /// @return tickLower The lower end of the tick range for the position\r\n /// @return tickUpper The higher end of the tick range for the position\r\n /// @return liquidity The liquidity of the position\r\n /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position\r\n /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position\r\n /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation\r\n /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation\r\n function positions(uint256 tokenId)\r\n external\r\n view\r\n returns (\r\n uint96 nonce,\r\n address operator,\r\n address token0,\r\n address token1,\r\n uint24 fee,\r\n int24 tickLower,\r\n int24 tickUpper,\r\n uint128 liquidity,\r\n uint256 feeGrowthInside0LastX128,\r\n uint256 feeGrowthInside1LastX128,\r\n uint128 tokensOwed0,\r\n uint128 tokensOwed1\r\n );\r\n\r\n struct MintParams {\r\n address token0;\r\n address token1;\r\n uint24 fee;\r\n int24 tickLower;\r\n int24 tickUpper;\r\n uint256 amount0Desired;\r\n uint256 amount1Desired;\r\n uint256 amount0Min;\r\n uint256 amount1Min;\r\n address recipient;\r\n uint256 deadline;\r\n }\r\n\r\n /// @notice Creates a new position wrapped in a NFT\r\n /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized\r\n /// a method does not exist, i.e. the pool is assumed to be initialized.\r\n /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata\r\n /// @return tokenId The ID of the token that represents the minted position\r\n /// @return liquidity The amount of liquidity for this position\r\n /// @return amount0 The amount of token0\r\n /// @return amount1 The amount of token1\r\n function mint(MintParams calldata params)\r\n external\r\n payable\r\n returns (\r\n uint256 tokenId,\r\n uint128 liquidity,\r\n uint256 amount0,\r\n uint256 amount1\r\n );\r\n\r\n struct IncreaseLiquidityParams {\r\n uint256 tokenId;\r\n uint256 amount0Desired;\r\n uint256 amount1Desired;\r\n uint256 amount0Min;\r\n uint256 amount1Min;\r\n uint256 deadline;\r\n }\r\n\r\n /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`\r\n /// @param params tokenId The ID of the token for which liquidity is being increased,\r\n /// amount0Desired The desired amount of token0 to be spent,\r\n /// amount1Desired The desired amount of token1 to be spent,\r\n /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,\r\n /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,\r\n /// deadline The time by which the transaction must be included to effect the change\r\n /// @return liquidity The new liquidity amount as a result of the increase\r\n /// @return amount0 The amount of token0 to acheive resulting liquidity\r\n /// @return amount1 The amount of token1 to acheive resulting liquidity\r\n function increaseLiquidity(IncreaseLiquidityParams calldata params)\r\n external\r\n payable\r\n returns (\r\n uint128 liquidity,\r\n uint256 amount0,\r\n uint256 amount1\r\n );\r\n\r\n struct DecreaseLiquidityParams {\r\n uint256 tokenId;\r\n uint128 liquidity;\r\n uint256 amount0Min;\r\n uint256 amount1Min;\r\n uint256 deadline;\r\n }\r\n\r\n /// @notice Decreases the amount of liquidity in a position and accounts it to the position\r\n /// @param params tokenId The ID of the token for which liquidity is being decreased,\r\n /// amount The amount by which liquidity will be decreased,\r\n /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,\r\n /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,\r\n /// deadline The time by which the transaction must be included to effect the change\r\n /// @return amount0 The amount of token0 accounted to the position's tokens owed\r\n /// @return amount1 The amount of token1 accounted to the position's tokens owed\r\n function decreaseLiquidity(DecreaseLiquidityParams calldata params)\r\n external\r\n payable\r\n returns (uint256 amount0, uint256 amount1);\r\n\r\n struct CollectParams {\r\n uint256 tokenId;\r\n address recipient;\r\n uint128 amount0Max;\r\n uint128 amount1Max;\r\n }\r\n\r\n /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient\r\n /// @param params tokenId The ID of the NFT for which tokens are being collected,\r\n /// recipient The account that should receive the tokens,\r\n /// amount0Max The maximum amount of token0 to collect,\r\n /// amount1Max The maximum amount of token1 to collect\r\n /// @return amount0 The amount of fees collected in token0\r\n /// @return amount1 The amount of fees collected in token1\r\n function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);\r\n\r\n /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens\r\n /// must be collected first.\r\n /// @param tokenId The ID of the token that is being burned\r\n function burn(uint256 tokenId) external payable;\r\n}\r\n" }, "contracts/interfaces/external/univ3/IUniswapV3Pool.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.5.0;\r\n\r\nimport \"./pool/IUniswapV3PoolActions.sol\";\r\nimport \"./pool/IUniswapV3PoolImmutables.sol\";\r\nimport \"./pool/IUniswapV3PoolState.sol\";\r\nimport \"./pool/IUniswapV3PoolDerivedState.sol\";\r\n\r\n/// @title The interface for a Uniswap V3 Pool\r\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\r\n/// to the ERC20 specification\r\n/// @dev The pool interface is broken up into many smaller pieces\r\ninterface IUniswapV3Pool is\r\n IUniswapV3PoolImmutables,\r\n IUniswapV3PoolState,\r\n IUniswapV3PoolDerivedState,\r\n IUniswapV3PoolActions\r\n{\r\n\r\n}\r\n" }, "contracts/interfaces/external/univ3/IUniswapV3Factory.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity =0.8.9;\r\n\r\n/// @title The interface for the Uniswap V3 Factory\r\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\r\ninterface IUniswapV3Factory {\r\n /// @notice Emitted when the owner of the factory is changed\r\n /// @param oldOwner The owner before the owner was changed\r\n /// @param newOwner The owner after the owner was changed\r\n event OwnerChanged(address indexed oldOwner, address indexed newOwner);\r\n\r\n /// @notice Emitted when a pool is created\r\n /// @param token0 The first token of the pool by address sort order\r\n /// @param token1 The second token of the pool by address sort order\r\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\r\n /// @param tickSpacing The minimum number of ticks between initialized ticks\r\n /// @param pool The address of the created pool\r\n event PoolCreated(\r\n address indexed token0,\r\n address indexed token1,\r\n uint24 indexed fee,\r\n int24 tickSpacing,\r\n address pool\r\n );\r\n\r\n /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\r\n /// @param fee The enabled fee, denominated in hundredths of a bip\r\n /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\r\n event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\r\n\r\n /// @notice Returns the current owner of the factory\r\n /// @dev Can be changed by the current owner via setOwner\r\n /// @return The address of the factory owner\r\n function owner() external view returns (address);\r\n\r\n /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\r\n /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\r\n /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\r\n /// @return The tick spacing\r\n function feeAmountTickSpacing(uint24 fee) external view returns (int24);\r\n\r\n /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\r\n /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\r\n /// @param tokenA The contract address of either token0 or token1\r\n /// @param tokenB The contract address of the other token\r\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\r\n /// @return pool The pool address\r\n function getPool(\r\n address tokenA,\r\n address tokenB,\r\n uint24 fee\r\n ) external view returns (address pool);\r\n\r\n /// @notice Creates a pool for the given two tokens and fee\r\n /// @param tokenA One of the two tokens in the desired pool\r\n /// @param tokenB The other of the two tokens in the desired pool\r\n /// @param fee The desired fee for the pool\r\n /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\r\n /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\r\n /// are invalid.\r\n /// @return pool The address of the newly created pool\r\n function createPool(\r\n address tokenA,\r\n address tokenB,\r\n uint24 fee\r\n ) external returns (address pool);\r\n\r\n /// @notice Updates the owner of the factory\r\n /// @dev Must be called by the current owner\r\n /// @param _owner The new owner of the factory\r\n function setOwner(address _owner) external;\r\n\r\n /// @notice Enables a fee amount with the given tickSpacing\r\n /// @dev Fee amounts may never be removed once enabled\r\n /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\r\n /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\r\n function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\r\n}\r\n" }, "contracts/interfaces/external/univ3/ISwapRouter.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.7.5;\r\npragma abicoder v2;\r\n\r\n/// @title Router token swapping functionality\r\n/// @notice Functions for swapping tokens via Uniswap V3\r\ninterface ISwapRouter {\r\n struct ExactInputSingleParams {\r\n address tokenIn;\r\n address tokenOut;\r\n uint24 fee;\r\n address recipient;\r\n uint256 deadline;\r\n uint256 amountIn;\r\n uint256 amountOutMinimum;\r\n uint160 sqrtPriceLimitX96;\r\n }\r\n\r\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\r\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\r\n /// @return amountOut The amount of the received token\r\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\r\n\r\n struct ExactInputParams {\r\n bytes path;\r\n address recipient;\r\n uint256 deadline;\r\n uint256 amountIn;\r\n uint256 amountOutMinimum;\r\n }\r\n\r\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\r\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\r\n /// @return amountOut The amount of the received token\r\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\r\n\r\n struct ExactOutputSingleParams {\r\n address tokenIn;\r\n address tokenOut;\r\n uint24 fee;\r\n address recipient;\r\n uint256 deadline;\r\n uint256 amountOut;\r\n uint256 amountInMaximum;\r\n uint160 sqrtPriceLimitX96;\r\n }\r\n\r\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\r\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\r\n /// @return amountIn The amount of the input token\r\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\r\n\r\n struct ExactOutputParams {\r\n bytes path;\r\n address recipient;\r\n uint256 deadline;\r\n uint256 amountOut;\r\n uint256 amountInMaximum;\r\n }\r\n\r\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\r\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\r\n /// @return amountIn The amount of the input token\r\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\r\n}\r\n" }, "contracts/interfaces/vaults/IERC20Vault.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"../external/aave/ILendingPool.sol\";\r\nimport \"./IIntegrationVault.sol\";\r\n\r\ninterface IERC20Vault is IIntegrationVault {\r\n /// @notice Initialized a new contract.\r\n /// @dev Can only be initialized by vault governance\r\n /// @param nft_ NFT of the vault in the VaultRegistry\r\n /// @param vaultTokens_ ERC20 tokens that will be managed by this Vault\r\n function initialize(uint256 nft_, address[] memory vaultTokens_) external;\r\n}\r\n" }, "contracts/interfaces/vaults/IUniV3Vault.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\r\nimport \"./IIntegrationVault.sol\";\r\nimport \"../external/univ3/INonfungiblePositionManager.sol\";\r\nimport \"../external/univ3/IUniswapV3Pool.sol\";\r\n\r\ninterface IUniV3Vault is IERC721Receiver, IIntegrationVault {\r\n struct Options {\r\n uint256 amount0Min;\r\n uint256 amount1Min;\r\n uint256 deadline;\r\n }\r\n\r\n /// @notice Reference to INonfungiblePositionManager of UniswapV3 protocol.\r\n function positionManager() external view returns (INonfungiblePositionManager);\r\n\r\n /// @notice Reference to UniswapV3 pool.\r\n function pool() external view returns (IUniswapV3Pool);\r\n\r\n /// @notice NFT of UniV3 position manager\r\n function uniV3Nft() external view returns (uint256);\r\n\r\n /// @notice Returns tokenAmounts corresponding to liquidity, based on the current Uniswap position\r\n /// @param liquidity Liquidity that will be converted to token amounts\r\n /// @return tokenAmounts Token amounts for the specified liquidity\r\n function liquidityToTokenAmounts(uint128 liquidity) external view returns (uint256[] memory tokenAmounts);\r\n\r\n /// @notice Returns liquidity corresponding to token amounts, based on the current Uniswap position\r\n /// @param tokenAmounts Token amounts that will be converted to liquidity\r\n /// @return liquidity Liquidity for the specified token amounts\r\n function tokenAmountsToLiquidity(uint256[] memory tokenAmounts) external view returns (uint128 liquidity);\r\n\r\n /// @notice Initialized a new contract.\r\n /// @dev Can only be initialized by vault governance\r\n /// @param nft_ NFT of the vault in the VaultRegistry\r\n /// @param vaultTokens_ ERC20 tokens that will be managed by this Vault\r\n /// @param fee_ Fee of the UniV3 pool\r\n /// @param uniV3Helper_ address of helper for UniV3 arithmetic with ticks\r\n function initialize(\r\n uint256 nft_,\r\n address[] memory vaultTokens_,\r\n uint24 fee_,\r\n address uniV3Helper_\r\n ) external;\r\n\r\n /// @notice Collect UniV3 fees to zero vault.\r\n function collectEarnings() external returns (uint256[] memory collectedEarnings);\r\n}\r\n" }, "contracts/libraries/ExceptionsLibrary.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\n/// @notice Exceptions stores project`s smart-contracts exceptions\r\nlibrary ExceptionsLibrary {\r\n string constant ADDRESS_ZERO = \"AZ\";\r\n string constant VALUE_ZERO = \"VZ\";\r\n string constant EMPTY_LIST = \"EMPL\";\r\n string constant NOT_FOUND = \"NF\";\r\n string constant INIT = \"INIT\";\r\n string constant DUPLICATE = \"DUP\";\r\n string constant NULL = \"NULL\";\r\n string constant TIMESTAMP = \"TS\";\r\n string constant FORBIDDEN = \"FRB\";\r\n string constant ALLOWLIST = \"ALL\";\r\n string constant LIMIT_OVERFLOW = \"LIMO\";\r\n string constant LIMIT_UNDERFLOW = \"LIMU\";\r\n string constant INVALID_VALUE = \"INV\";\r\n string constant INVARIANT = \"INVA\";\r\n string constant INVALID_TARGET = \"INVTR\";\r\n string constant INVALID_TOKEN = \"INVTO\";\r\n string constant INVALID_INTERFACE = \"INVI\";\r\n string constant INVALID_SELECTOR = \"INVS\";\r\n string constant INVALID_STATE = \"INVST\";\r\n string constant INVALID_LENGTH = \"INVL\";\r\n string constant LOCK = \"LCKD\";\r\n string constant DISABLED = \"DIS\";\r\n}\r\n" }, "contracts/libraries/CommonLibrary.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"./external/FullMath.sol\";\r\nimport \"./ExceptionsLibrary.sol\";\r\n\r\n/// @notice CommonLibrary shared utilities\r\nlibrary CommonLibrary {\r\n uint256 constant DENOMINATOR = 10**9;\r\n uint256 constant D18 = 10**18;\r\n uint256 constant YEAR = 365 * 24 * 3600;\r\n uint256 constant Q128 = 2**128;\r\n uint256 constant Q96 = 2**96;\r\n uint256 constant Q48 = 2**48;\r\n uint256 constant Q160 = 2**160;\r\n uint256 constant UNI_FEE_DENOMINATOR = 10**6;\r\n\r\n /// @notice Sort uint256 using bubble sort. The sorting is done in-place.\r\n /// @param arr Array of uint256\r\n function sortUint(uint256[] memory arr) internal pure {\r\n uint256 l = arr.length;\r\n for (uint256 i = 0; i < l; ++i) {\r\n for (uint256 j = i + 1; j < l; ++j) {\r\n if (arr[i] > arr[j]) {\r\n uint256 temp = arr[i];\r\n arr[i] = arr[j];\r\n arr[j] = temp;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /// @notice Checks if array of addresses is sorted and all adresses are unique\r\n /// @param tokens A set of addresses to check\r\n /// @return `true` if all addresses are sorted and unique, `false` otherwise\r\n function isSortedAndUnique(address[] memory tokens) internal pure returns (bool) {\r\n if (tokens.length < 2) {\r\n return true;\r\n }\r\n for (uint256 i = 0; i < tokens.length - 1; ++i) {\r\n if (tokens[i] >= tokens[i + 1]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /// @notice Projects tokenAmounts onto subset or superset of tokens\r\n /// @dev\r\n /// Requires both sets of tokens to be sorted. When tokens are not sorted, it's undefined behavior.\r\n /// If there is a token in tokensToProject that is not part of tokens and corresponding tokenAmountsToProject > 0, reverts.\r\n /// Zero token amount is eqiuvalent to missing token\r\n function projectTokenAmounts(\r\n address[] memory tokens,\r\n address[] memory tokensToProject,\r\n uint256[] memory tokenAmountsToProject\r\n ) internal pure returns (uint256[] memory) {\r\n uint256[] memory res = new uint256[](tokens.length);\r\n uint256 t = 0;\r\n uint256 tp = 0;\r\n while ((t < tokens.length) && (tp < tokensToProject.length)) {\r\n if (tokens[t] < tokensToProject[tp]) {\r\n res[t] = 0;\r\n t++;\r\n } else if (tokens[t] > tokensToProject[tp]) {\r\n if (tokenAmountsToProject[tp] == 0) {\r\n tp++;\r\n } else {\r\n revert(\"TPS\");\r\n }\r\n } else {\r\n res[t] = tokenAmountsToProject[tp];\r\n t++;\r\n tp++;\r\n }\r\n }\r\n while (t < tokens.length) {\r\n res[t] = 0;\r\n t++;\r\n }\r\n return res;\r\n }\r\n\r\n /// @notice Calculated sqrt of uint in X96 format\r\n /// @param xX96 input number in X96 format\r\n /// @return sqrt of xX96 in X96 format\r\n function sqrtX96(uint256 xX96) internal pure returns (uint256) {\r\n uint256 sqX96 = sqrt(xX96);\r\n return sqX96 << 48;\r\n }\r\n\r\n /// @notice Calculated sqrt of uint\r\n /// @param x input number\r\n /// @return sqrt of x\r\n function sqrt(uint256 x) internal pure returns (uint256) {\r\n if (x == 0) return 0;\r\n uint256 xx = x;\r\n uint256 r = 1;\r\n if (xx >= 0x100000000000000000000000000000000) {\r\n xx >>= 128;\r\n r <<= 64;\r\n }\r\n if (xx >= 0x10000000000000000) {\r\n xx >>= 64;\r\n r <<= 32;\r\n }\r\n if (xx >= 0x100000000) {\r\n xx >>= 32;\r\n r <<= 16;\r\n }\r\n if (xx >= 0x10000) {\r\n xx >>= 16;\r\n r <<= 8;\r\n }\r\n if (xx >= 0x100) {\r\n xx >>= 8;\r\n r <<= 4;\r\n }\r\n if (xx >= 0x10) {\r\n xx >>= 4;\r\n r <<= 2;\r\n }\r\n if (xx >= 0x8) {\r\n r <<= 1;\r\n }\r\n r = (r + x / r) >> 1;\r\n r = (r + x / r) >> 1;\r\n r = (r + x / r) >> 1;\r\n r = (r + x / r) >> 1;\r\n r = (r + x / r) >> 1;\r\n r = (r + x / r) >> 1;\r\n r = (r + x / r) >> 1;\r\n uint256 r1 = x / r;\r\n return (r < r1 ? r : r1);\r\n }\r\n\r\n /// @notice Recovers signer address from signed message hash\r\n /// @param _ethSignedMessageHash signed message\r\n /// @param _signature contatenated ECDSA r, s, v (65 bytes)\r\n /// @return Recovered address if the signature is valid, address(0) otherwise\r\n function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) {\r\n (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);\r\n\r\n return ecrecover(_ethSignedMessageHash, v, r, s);\r\n }\r\n\r\n /// @notice Get ECDSA r, s, v from signature\r\n /// @param sig signature (65 bytes)\r\n /// @return r ECDSA r\r\n /// @return s ECDSA s\r\n /// @return v ECDSA v\r\n function splitSignature(bytes memory sig)\r\n internal\r\n pure\r\n returns (\r\n bytes32 r,\r\n bytes32 s,\r\n uint8 v\r\n )\r\n {\r\n require(sig.length == 65, ExceptionsLibrary.INVALID_LENGTH);\r\n\r\n assembly {\r\n r := mload(add(sig, 32))\r\n s := mload(add(sig, 64))\r\n v := byte(0, mload(add(sig, 96)))\r\n }\r\n }\r\n}\r\n" }, "contracts/libraries/external/FullMath.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity =0.8.9;\r\n\r\n/// @title Contains 512-bit math functions\r\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\r\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\r\nlibrary FullMath {\r\n /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\r\n /// @param a The multiplicand\r\n /// @param b The multiplier\r\n /// @param denominator The divisor\r\n /// @return result The 256-bit result\r\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\r\n function mulDiv(\r\n uint256 a,\r\n uint256 b,\r\n uint256 denominator\r\n ) internal pure returns (uint256 result) {\r\n // diff: original lib works under 0.7.6 with overflows enabled\r\n unchecked {\r\n // 512-bit multiply [prod1 prod0] = a * b\r\n // Compute the product mod 2**256 and mod 2**256 - 1\r\n // then use the Chinese Remainder Theorem to reconstruct\r\n // the 512 bit result. The result is stored in two 256\r\n // variables such that product = prod1 * 2**256 + prod0\r\n uint256 prod0; // Least significant 256 bits of the product\r\n uint256 prod1; // Most significant 256 bits of the product\r\n assembly {\r\n let mm := mulmod(a, b, not(0))\r\n prod0 := mul(a, b)\r\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\r\n }\r\n\r\n // Handle non-overflow cases, 256 by 256 division\r\n if (prod1 == 0) {\r\n require(denominator > 0);\r\n assembly {\r\n result := div(prod0, denominator)\r\n }\r\n return result;\r\n }\r\n\r\n // Make sure the result is less than 2**256.\r\n // Also prevents denominator == 0\r\n require(denominator > prod1);\r\n\r\n ///////////////////////////////////////////////\r\n // 512 by 256 division.\r\n ///////////////////////////////////////////////\r\n\r\n // Make division exact by subtracting the remainder from [prod1 prod0]\r\n // Compute remainder using mulmod\r\n uint256 remainder;\r\n assembly {\r\n remainder := mulmod(a, b, denominator)\r\n }\r\n // Subtract 256 bit number from 512 bit number\r\n assembly {\r\n prod1 := sub(prod1, gt(remainder, prod0))\r\n prod0 := sub(prod0, remainder)\r\n }\r\n\r\n // Factor powers of two out of denominator\r\n // Compute largest power of two divisor of denominator.\r\n // Always >= 1.\r\n // diff: original uint256 twos = -denominator & denominator;\r\n uint256 twos = uint256(-int256(denominator)) & denominator;\r\n // Divide denominator by power of two\r\n assembly {\r\n denominator := div(denominator, twos)\r\n }\r\n\r\n // Divide [prod1 prod0] by the factors of two\r\n assembly {\r\n prod0 := div(prod0, twos)\r\n }\r\n // Shift in bits from prod1 into prod0. For this we need\r\n // to flip `twos` such that it is 2**256 / twos.\r\n // If twos is zero, then it becomes one\r\n assembly {\r\n twos := add(div(sub(0, twos), twos), 1)\r\n }\r\n prod0 |= prod1 * twos;\r\n\r\n // Invert denominator mod 2**256\r\n // Now that denominator is an odd number, it has an inverse\r\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\r\n // Compute the inverse by starting with a seed that is correct\r\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\r\n uint256 inv = (3 * denominator) ^ 2;\r\n // Now use Newton-Raphson iteration to improve the precision.\r\n // Thanks to Hensel's lifting lemma, this also works in modular\r\n // arithmetic, doubling the correct bits in each step.\r\n inv *= 2 - denominator * inv; // inverse mod 2**8\r\n inv *= 2 - denominator * inv; // inverse mod 2**16\r\n inv *= 2 - denominator * inv; // inverse mod 2**32\r\n inv *= 2 - denominator * inv; // inverse mod 2**64\r\n inv *= 2 - denominator * inv; // inverse mod 2**128\r\n inv *= 2 - denominator * inv; // inverse mod 2**256\r\n\r\n // Because the division is now exact we can divide by multiplying\r\n // with the modular inverse of denominator. This will give us the\r\n // correct result modulo 2**256. Since the precoditions guarantee\r\n // that the outcome is less than 2**256, this is the final result.\r\n // We don't need to compute the high bits of the result and prod1\r\n // is no longer required.\r\n result = prod0 * inv;\r\n return result;\r\n }\r\n }\r\n\r\n /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\r\n /// @param a The multiplicand\r\n /// @param b The multiplier\r\n /// @param denominator The divisor\r\n /// @return result The 256-bit result\r\n function mulDivRoundingUp(\r\n uint256 a,\r\n uint256 b,\r\n uint256 denominator\r\n ) internal pure returns (uint256 result) {\r\n // diff: original lib works under 0.7.6 with overflows enabled\r\n unchecked {\r\n result = mulDiv(a, b, denominator);\r\n if (mulmod(a, b, denominator) > 0) {\r\n require(result < type(uint256).max);\r\n result++;\r\n }\r\n }\r\n }\r\n}\r\n" }, "contracts/libraries/external/TickMath.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity =0.8.9;\r\n\r\n/// @title Math library for computing sqrt prices from ticks and vice versa\r\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\r\n/// prices between 2**-128 and 2**128\r\nlibrary TickMath {\r\n /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\r\n int24 internal constant MIN_TICK = -887272;\r\n /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\r\n int24 internal constant MAX_TICK = -MIN_TICK;\r\n\r\n /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\r\n uint160 internal constant MIN_SQRT_RATIO = 4295128739;\r\n /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\r\n uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\r\n\r\n /// @notice Calculates sqrt(1.0001^tick) * 2^96\r\n /// @dev Throws if |tick| > max tick\r\n /// @param tick The input tick for the above formula\r\n /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\r\n /// at the given tick\r\n function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\r\n uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\r\n // diff: original require(absTick <= uint256(MAX_TICK), \"T\");\r\n require(absTick <= uint256(int256(MAX_TICK)), \"T\");\r\n\r\n uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\r\n if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\r\n if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\r\n if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\r\n if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\r\n if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\r\n if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\r\n if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\r\n if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\r\n if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\r\n if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\r\n if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\r\n if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\r\n if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\r\n if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\r\n if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\r\n if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\r\n if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\r\n if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\r\n if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\r\n\r\n if (tick > 0) ratio = type(uint256).max / ratio;\r\n\r\n // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\r\n // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\r\n // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\r\n sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\r\n }\r\n\r\n /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\r\n /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\r\n /// ever return.\r\n /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\r\n /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\r\n function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\r\n // second inequality must be < because the price can never reach the price at the max tick\r\n require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, \"R\");\r\n uint256 ratio = uint256(sqrtPriceX96) << 32;\r\n\r\n uint256 r = ratio;\r\n uint256 msb = 0;\r\n\r\n assembly {\r\n let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\r\n msb := or(msb, f)\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\r\n msb := or(msb, f)\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n let f := shl(5, gt(r, 0xFFFFFFFF))\r\n msb := or(msb, f)\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n let f := shl(4, gt(r, 0xFFFF))\r\n msb := or(msb, f)\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n let f := shl(3, gt(r, 0xFF))\r\n msb := or(msb, f)\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n let f := shl(2, gt(r, 0xF))\r\n msb := or(msb, f)\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n let f := shl(1, gt(r, 0x3))\r\n msb := or(msb, f)\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n let f := gt(r, 0x1)\r\n msb := or(msb, f)\r\n }\r\n\r\n if (msb >= 128) r = ratio >> (msb - 127);\r\n else r = ratio << (127 - msb);\r\n\r\n int256 log_2 = (int256(msb) - 128) << 64;\r\n\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(63, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(62, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(61, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(60, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(59, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(58, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(57, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(56, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(55, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(54, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(53, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(52, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(51, f))\r\n r := shr(f, r)\r\n }\r\n assembly {\r\n r := shr(127, mul(r, r))\r\n let f := shr(128, r)\r\n log_2 := or(log_2, shl(50, f))\r\n }\r\n\r\n int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\r\n\r\n int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\r\n int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\r\n\r\n tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\r\n }\r\n}\r\n" }, "contracts/utils/DefaultAccessControlLateInit.sol": { "content": "// SPDX-License-Identifier: BSL-1.1\r\npragma solidity 0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/access/AccessControlEnumerable.sol\";\r\nimport \"../interfaces/utils/IDefaultAccessControl.sol\";\r\nimport \"../libraries/ExceptionsLibrary.sol\";\r\n\r\n/// @notice This is a default access control with 3 roles:\r\n///\r\n/// - ADMIN: allowed to do anything\r\n/// - ADMIN_DELEGATE: allowed to do anything except assigning ADMIN and ADMIN_DELEGATE roles\r\n/// - OPERATOR: low-privileged role, generally keeper or some other bot\r\ncontract DefaultAccessControlLateInit is IDefaultAccessControl, AccessControlEnumerable {\r\n bool public initialized;\r\n\r\n bytes32 public constant OPERATOR = keccak256(\"operator\");\r\n bytes32 public constant ADMIN_ROLE = keccak256(\"admin\");\r\n bytes32 public constant ADMIN_DELEGATE_ROLE = keccak256(\"admin_delegate\");\r\n\r\n // ------------------------- EXTERNAL, VIEW ------------------------------\r\n\r\n /// @inheritdoc IDefaultAccessControl\r\n function isAdmin(address sender) public view returns (bool) {\r\n return hasRole(ADMIN_ROLE, sender) || hasRole(ADMIN_DELEGATE_ROLE, sender);\r\n }\r\n\r\n /// @inheritdoc IDefaultAccessControl\r\n function isOperator(address sender) public view returns (bool) {\r\n return hasRole(OPERATOR, sender);\r\n }\r\n\r\n // ------------------------- EXTERNAL, MUTATING ------------------------------\r\n\r\n /// @notice Initializes a new contract with roles and single ADMIN.\r\n /// @param admin Admin of the contract\r\n function init(address admin) public {\r\n require(admin != address(0), ExceptionsLibrary.ADDRESS_ZERO);\r\n require(!initialized, ExceptionsLibrary.INIT);\r\n\r\n _setupRole(OPERATOR, admin);\r\n _setupRole(ADMIN_ROLE, admin);\r\n\r\n _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);\r\n _setRoleAdmin(ADMIN_DELEGATE_ROLE, ADMIN_ROLE);\r\n _setRoleAdmin(OPERATOR, ADMIN_DELEGATE_ROLE);\r\n\r\n initialized = true;\r\n }\r\n\r\n // ------------------------- INTERNAL, VIEW ------------------------------\r\n\r\n function _requireAdmin() internal view {\r\n require(isAdmin(msg.sender), ExceptionsLibrary.FORBIDDEN);\r\n }\r\n\r\n function _requireAtLeastOperator() internal view {\r\n require(isAdmin(msg.sender) || isOperator(msg.sender), ExceptionsLibrary.FORBIDDEN);\r\n }\r\n}\r\n" }, "contracts/utils/HStrategyHelper.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity 0.8.9;\r\n\r\nimport \"../interfaces/external/univ3/INonfungiblePositionManager.sol\";\r\nimport \"../interfaces/vaults/IIntegrationVault.sol\";\r\nimport \"../interfaces/vaults/IUniV3Vault.sol\";\r\nimport \"../interfaces/vaults/IAaveVault.sol\";\r\nimport \"../libraries/CommonLibrary.sol\";\r\nimport \"../libraries/external/TickMath.sol\";\r\nimport \"../libraries/external/LiquidityAmounts.sol\";\r\nimport \"../strategies/HStrategy.sol\";\r\nimport \"./UniV3Helper.sol\";\r\n\r\ncontract HStrategyHelper {\r\n uint32 constant DENOMINATOR = 10**9;\r\n\r\n /// @notice calculates the ratios of the capital on all vaults using price from the oracle\r\n /// @param domainPositionParams the current state of the position, pool and oracle prediction\r\n /// @return ratios ratios of the capital\r\n function calculateExpectedRatios(HStrategy.DomainPositionParams memory domainPositionParams)\r\n external\r\n pure\r\n returns (HStrategy.ExpectedRatios memory ratios)\r\n {\r\n uint256 denominatorX96 = CommonLibrary.Q96 *\r\n 2 -\r\n FullMath.mulDiv(\r\n domainPositionParams.domainLowerPriceSqrtX96,\r\n CommonLibrary.Q96,\r\n domainPositionParams.intervalPriceSqrtX96\r\n ) -\r\n FullMath.mulDiv(\r\n domainPositionParams.intervalPriceSqrtX96,\r\n CommonLibrary.Q96,\r\n domainPositionParams.domainUpperPriceSqrtX96\r\n );\r\n\r\n uint256 nominator0X96 = FullMath.mulDiv(\r\n domainPositionParams.intervalPriceSqrtX96,\r\n CommonLibrary.Q96,\r\n domainPositionParams.upperPriceSqrtX96\r\n ) -\r\n FullMath.mulDiv(\r\n domainPositionParams.intervalPriceSqrtX96,\r\n CommonLibrary.Q96,\r\n domainPositionParams.domainUpperPriceSqrtX96\r\n );\r\n\r\n uint256 nominator1X96 = FullMath.mulDiv(\r\n domainPositionParams.lowerPriceSqrtX96,\r\n CommonLibrary.Q96,\r\n domainPositionParams.intervalPriceSqrtX96\r\n ) -\r\n FullMath.mulDiv(\r\n domainPositionParams.domainLowerPriceSqrtX96,\r\n CommonLibrary.Q96,\r\n domainPositionParams.intervalPriceSqrtX96\r\n );\r\n\r\n ratios.token0RatioD = uint32(FullMath.mulDiv(nominator0X96, DENOMINATOR, denominatorX96));\r\n ratios.token1RatioD = uint32(FullMath.mulDiv(nominator1X96, DENOMINATOR, denominatorX96));\r\n\r\n ratios.uniV3RatioD = DENOMINATOR - ratios.token0RatioD - ratios.token1RatioD;\r\n }\r\n\r\n /// @notice calculates amount of missing tokens for uniV3 and money vaults\r\n /// @param moneyVault the strategy money vault\r\n /// @param expectedTokenAmounts the amount of tokens we expect after rebalance\r\n /// @param domainPositionParams current position and pool state combined with predictions from the oracle\r\n /// @param liquidity current liquidity in position\r\n /// @return missingTokenAmounts amounts of missing tokens\r\n function calculateMissingTokenAmounts(\r\n IIntegrationVault moneyVault,\r\n HStrategy.TokenAmounts memory expectedTokenAmounts,\r\n HStrategy.DomainPositionParams memory domainPositionParams,\r\n uint128 liquidity\r\n ) external view returns (HStrategy.TokenAmounts memory missingTokenAmounts) {\r\n // for uniV3Vault\r\n {\r\n uint256 token0Amount = 0;\r\n uint256 token1Amount = 0;\r\n (token0Amount, token1Amount) = LiquidityAmounts.getAmountsForLiquidity(\r\n domainPositionParams.intervalPriceSqrtX96,\r\n domainPositionParams.lowerPriceSqrtX96,\r\n domainPositionParams.upperPriceSqrtX96,\r\n liquidity\r\n );\r\n\r\n if (token0Amount < expectedTokenAmounts.uniV3Token0) {\r\n missingTokenAmounts.uniV3Token0 = expectedTokenAmounts.uniV3Token0 - token0Amount;\r\n }\r\n if (token1Amount < expectedTokenAmounts.uniV3Token1) {\r\n missingTokenAmounts.uniV3Token1 = expectedTokenAmounts.uniV3Token1 - token1Amount;\r\n }\r\n }\r\n\r\n // for moneyVault\r\n {\r\n (, uint256[] memory maxTvl) = moneyVault.tvl();\r\n uint256 token0Amount = maxTvl[0];\r\n uint256 token1Amount = maxTvl[1];\r\n\r\n if (token0Amount < expectedTokenAmounts.moneyToken0) {\r\n missingTokenAmounts.moneyToken0 = expectedTokenAmounts.moneyToken0 - token0Amount;\r\n }\r\n\r\n if (token1Amount < expectedTokenAmounts.moneyToken1) {\r\n missingTokenAmounts.moneyToken1 = expectedTokenAmounts.moneyToken1 - token1Amount;\r\n }\r\n }\r\n }\r\n\r\n /// @notice calculates extra tokens on uniV3 vault\r\n /// @param expectedTokenAmounts the amount of tokens we expect after rebalance\r\n /// @param domainPositionParams current position and pool state combined with predictions from the oracle\r\n /// @return tokenAmounts extra token amounts on UniV3Vault\r\n function calculateExtraTokenAmountsForUniV3Vault(\r\n HStrategy.TokenAmounts memory expectedTokenAmounts,\r\n HStrategy.DomainPositionParams memory domainPositionParams\r\n ) external pure returns (uint256[] memory tokenAmounts) {\r\n tokenAmounts = new uint256[](2);\r\n (tokenAmounts[0], tokenAmounts[1]) = LiquidityAmounts.getAmountsForLiquidity(\r\n domainPositionParams.intervalPriceSqrtX96,\r\n domainPositionParams.lowerPriceSqrtX96,\r\n domainPositionParams.upperPriceSqrtX96,\r\n domainPositionParams.liquidity\r\n );\r\n\r\n if (tokenAmounts[0] > expectedTokenAmounts.uniV3Token0) {\r\n tokenAmounts[0] -= expectedTokenAmounts.uniV3Token0;\r\n } else {\r\n tokenAmounts[0] = 0;\r\n }\r\n\r\n if (tokenAmounts[1] > expectedTokenAmounts.uniV3Token1) {\r\n tokenAmounts[1] -= expectedTokenAmounts.uniV3Token1;\r\n } else {\r\n tokenAmounts[1] = 0;\r\n }\r\n }\r\n\r\n /// @notice calculates extra tokens on money vault\r\n /// @param moneyVault the strategy money vault\r\n /// @param expectedTokenAmounts the amount of tokens we expect after rebalance\r\n /// @return tokenAmounts extra token amounts on MoneyVault\r\n function calculateExtraTokenAmountsForMoneyVault(\r\n IIntegrationVault moneyVault,\r\n HStrategy.TokenAmounts memory expectedTokenAmounts\r\n ) external view returns (uint256[] memory tokenAmounts) {\r\n (tokenAmounts, ) = moneyVault.tvl();\r\n\r\n if (tokenAmounts[0] > expectedTokenAmounts.moneyToken0) {\r\n tokenAmounts[0] -= expectedTokenAmounts.moneyToken0;\r\n } else {\r\n tokenAmounts[0] = 0;\r\n }\r\n\r\n if (tokenAmounts[1] > expectedTokenAmounts.moneyToken1) {\r\n tokenAmounts[1] -= expectedTokenAmounts.moneyToken1;\r\n } else {\r\n tokenAmounts[1] = 0;\r\n }\r\n }\r\n\r\n /// @notice calculates expected amounts of tokens after rebalance\r\n /// @param expectedRatios ratios of the capital on different assets\r\n /// @param expectedTokenAmountsInToken0 expected capitals (in token0) on the strategy vaults\r\n /// @param domainPositionParams current position and pool state combined with predictions from the oracle\r\n /// @param uniV3Helper helper for uniswap V3 calculations\r\n /// @return amounts amounts of tokens expected after rebalance on the strategy vaults\r\n function calculateExpectedTokenAmountsByExpectedRatios(\r\n HStrategy.ExpectedRatios memory expectedRatios,\r\n HStrategy.TokenAmountsInToken0 memory expectedTokenAmountsInToken0,\r\n HStrategy.DomainPositionParams memory domainPositionParams,\r\n UniV3Helper uniV3Helper\r\n ) external pure returns (HStrategy.TokenAmounts memory amounts) {\r\n amounts.erc20Token0 = FullMath.mulDiv(\r\n expectedRatios.token0RatioD,\r\n expectedTokenAmountsInToken0.erc20TokensAmountInToken0,\r\n expectedRatios.token0RatioD + expectedRatios.token1RatioD\r\n );\r\n amounts.erc20Token1 = FullMath.mulDiv(\r\n expectedTokenAmountsInToken0.erc20TokensAmountInToken0 - amounts.erc20Token0,\r\n domainPositionParams.spotPriceX96,\r\n CommonLibrary.Q96\r\n );\r\n\r\n amounts.moneyToken0 = FullMath.mulDiv(\r\n expectedRatios.token0RatioD,\r\n expectedTokenAmountsInToken0.moneyTokensAmountInToken0,\r\n expectedRatios.token0RatioD + expectedRatios.token1RatioD\r\n );\r\n amounts.moneyToken1 = FullMath.mulDiv(\r\n expectedTokenAmountsInToken0.moneyTokensAmountInToken0 - amounts.moneyToken0,\r\n domainPositionParams.spotPriceX96,\r\n CommonLibrary.Q96\r\n );\r\n\r\n (amounts.uniV3Token0, amounts.uniV3Token1) = uniV3Helper.getPositionTokenAmountsByCapitalOfToken0(\r\n domainPositionParams.lowerPriceSqrtX96,\r\n domainPositionParams.upperPriceSqrtX96,\r\n domainPositionParams.intervalPriceSqrtX96,\r\n domainPositionParams.spotPriceX96,\r\n expectedTokenAmountsInToken0.uniV3TokensAmountInToken0\r\n );\r\n }\r\n\r\n /// @notice calculates current amounts of tokens\r\n /// @param erc20Vault the erc20 vault of the strategy\r\n /// @param moneyVault the money vault of the strategy\r\n /// @param params current position and pool state combined with predictions from the oracle\r\n /// @return amounts amounts of tokens\r\n function calculateCurrentTokenAmounts(\r\n IIntegrationVault erc20Vault,\r\n IIntegrationVault moneyVault,\r\n HStrategy.DomainPositionParams memory params\r\n ) external returns (HStrategy.TokenAmounts memory amounts) {\r\n (amounts.uniV3Token0, amounts.uniV3Token1) = LiquidityAmounts.getAmountsForLiquidity(\r\n params.intervalPriceSqrtX96,\r\n params.lowerPriceSqrtX96,\r\n params.upperPriceSqrtX96,\r\n params.liquidity\r\n );\r\n\r\n {\r\n if (moneyVault.supportsInterface(type(IAaveVault).interfaceId)) {\r\n IAaveVault(address(moneyVault)).updateTvls();\r\n }\r\n (uint256[] memory minMoneyTvl, ) = moneyVault.tvl();\r\n amounts.moneyToken0 = minMoneyTvl[0];\r\n amounts.moneyToken1 = minMoneyTvl[1];\r\n }\r\n {\r\n (uint256[] memory erc20Tvl, ) = erc20Vault.tvl();\r\n amounts.erc20Token0 = erc20Tvl[0];\r\n amounts.erc20Token1 = erc20Tvl[1];\r\n }\r\n }\r\n\r\n /// @notice calculates current capital of the strategy in token0\r\n /// @param params current position and pool state combined with predictions from the oracle\r\n /// @param currentTokenAmounts amounts of the tokens on the erc20 and money vaults\r\n /// @return capital total capital measured in token0\r\n function calculateCurrentCapitalInToken0(\r\n HStrategy.DomainPositionParams memory params,\r\n HStrategy.TokenAmounts memory currentTokenAmounts\r\n ) external pure returns (uint256 capital) {\r\n capital =\r\n currentTokenAmounts.erc20Token0 +\r\n FullMath.mulDiv(currentTokenAmounts.erc20Token1, CommonLibrary.Q96, params.spotPriceX96) +\r\n currentTokenAmounts.uniV3Token0 +\r\n FullMath.mulDiv(currentTokenAmounts.uniV3Token1, CommonLibrary.Q96, params.spotPriceX96) +\r\n currentTokenAmounts.moneyToken0 +\r\n FullMath.mulDiv(currentTokenAmounts.moneyToken1, CommonLibrary.Q96, params.spotPriceX96);\r\n }\r\n\r\n /// @notice calculates expected capitals on the vaults after rebalance\r\n /// @param totalCapitalInToken0 total capital in token0\r\n /// @param expectedRatios ratios of the capitals on the vaults expected after rebalance\r\n /// @param ratioParams_ ratio of the tokens between erc20 and money vault combined with needed deviations for rebalance to be called\r\n /// @return amounts capitals expected after rebalance measured in token0\r\n function calculateExpectedTokenAmountsInToken0(\r\n uint256 totalCapitalInToken0,\r\n HStrategy.ExpectedRatios memory expectedRatios,\r\n HStrategy.RatioParams memory ratioParams_\r\n ) external pure returns (HStrategy.TokenAmountsInToken0 memory amounts) {\r\n amounts.erc20TokensAmountInToken0 = FullMath.mulDiv(\r\n totalCapitalInToken0,\r\n ratioParams_.erc20CapitalRatioD,\r\n DENOMINATOR\r\n );\r\n amounts.uniV3TokensAmountInToken0 = FullMath.mulDiv(\r\n totalCapitalInToken0 - amounts.erc20TokensAmountInToken0,\r\n expectedRatios.uniV3RatioD,\r\n DENOMINATOR\r\n );\r\n amounts.moneyTokensAmountInToken0 =\r\n totalCapitalInToken0 -\r\n amounts.erc20TokensAmountInToken0 -\r\n amounts.uniV3TokensAmountInToken0;\r\n amounts.totalTokensInToken0 = totalCapitalInToken0;\r\n }\r\n\r\n /// @notice return true if the token swap is needed. It is needed if we cannot mint a new position without it\r\n /// @param currentTokenAmounts the amounts of tokens on the vaults\r\n /// @param expectedTokenAmounts the amounts of tokens expected after rebalancing\r\n /// @param ratioParams ratio of the tokens between erc20 and money vault combined with needed deviations for rebalance to be called\r\n /// @param domainPositionParams the current state of the position, pool and oracle prediction\r\n /// @return needed true if the token swap is needed\r\n function swapNeeded(\r\n HStrategy.TokenAmounts memory currentTokenAmounts,\r\n HStrategy.TokenAmounts memory expectedTokenAmounts,\r\n HStrategy.RatioParams memory ratioParams,\r\n HStrategy.DomainPositionParams memory domainPositionParams\r\n ) external pure returns (bool needed) {\r\n uint256 expectedTotalToken0Amount = expectedTokenAmounts.erc20Token0 +\r\n expectedTokenAmounts.moneyToken0 +\r\n expectedTokenAmounts.uniV3Token0;\r\n uint256 expectedTotalToken1Amount = expectedTokenAmounts.erc20Token1 +\r\n expectedTokenAmounts.moneyToken1 +\r\n expectedTokenAmounts.uniV3Token1;\r\n\r\n uint256 currentTotalToken0Amount = currentTokenAmounts.erc20Token0 +\r\n currentTokenAmounts.moneyToken0 +\r\n currentTokenAmounts.uniV3Token0;\r\n int256 token0Delta = int256(currentTotalToken0Amount) - int256(expectedTotalToken0Amount);\r\n if (token0Delta < 0) {\r\n token0Delta = -token0Delta;\r\n }\r\n int256 minDeviation = int256(\r\n FullMath.mulDiv(\r\n expectedTotalToken0Amount +\r\n FullMath.mulDiv(expectedTotalToken1Amount, CommonLibrary.Q96, domainPositionParams.spotPriceX96),\r\n ratioParams.minRebalanceDeviationD,\r\n DENOMINATOR\r\n )\r\n );\r\n return token0Delta >= minDeviation;\r\n }\r\n\r\n /// @notice returns true if the rebalance between assets on different vaults is needed\r\n /// @param currentTokenAmounts the current amounts of tokens on the vaults\r\n /// @param expectedTokenAmounts the amounts of tokens expected after rebalance\r\n /// @param ratioParams ratio of the tokens between erc20 and money vault combined with needed deviations for rebalance to be called\r\n /// @return needed true if the rebalance is needed\r\n function tokenRebalanceNeeded(\r\n HStrategy.TokenAmounts memory currentTokenAmounts,\r\n HStrategy.TokenAmounts memory expectedTokenAmounts,\r\n HStrategy.RatioParams memory ratioParams\r\n ) external pure returns (bool needed) {\r\n uint256 totalToken0Amount = expectedTokenAmounts.erc20Token0 +\r\n expectedTokenAmounts.moneyToken0 +\r\n expectedTokenAmounts.uniV3Token0;\r\n uint256 totalToken1Amount = expectedTokenAmounts.erc20Token1 +\r\n expectedTokenAmounts.moneyToken1 +\r\n expectedTokenAmounts.uniV3Token1;\r\n\r\n uint256 minToken0Deviation = FullMath.mulDiv(ratioParams.minCapitalDeviationD, totalToken0Amount, DENOMINATOR);\r\n uint256 minToken1Deviation = FullMath.mulDiv(ratioParams.minCapitalDeviationD, totalToken1Amount, DENOMINATOR);\r\n\r\n {\r\n if (\r\n currentTokenAmounts.erc20Token0 + minToken0Deviation < expectedTokenAmounts.erc20Token0 ||\r\n currentTokenAmounts.erc20Token0 > expectedTokenAmounts.erc20Token0 + minToken0Deviation ||\r\n currentTokenAmounts.erc20Token1 + minToken1Deviation < expectedTokenAmounts.erc20Token1 ||\r\n currentTokenAmounts.erc20Token1 > expectedTokenAmounts.erc20Token1 + minToken1Deviation\r\n ) {\r\n return true;\r\n }\r\n }\r\n\r\n {\r\n if (\r\n currentTokenAmounts.moneyToken0 + minToken0Deviation < expectedTokenAmounts.moneyToken0 ||\r\n currentTokenAmounts.moneyToken0 > expectedTokenAmounts.moneyToken0 + minToken0Deviation ||\r\n currentTokenAmounts.moneyToken1 + minToken1Deviation < expectedTokenAmounts.moneyToken1 ||\r\n currentTokenAmounts.moneyToken1 > expectedTokenAmounts.moneyToken1 + minToken1Deviation\r\n ) {\r\n return true;\r\n }\r\n }\r\n\r\n {\r\n if (\r\n currentTokenAmounts.uniV3Token0 + minToken0Deviation < expectedTokenAmounts.uniV3Token0 ||\r\n currentTokenAmounts.uniV3Token0 > expectedTokenAmounts.uniV3Token0 + minToken0Deviation ||\r\n currentTokenAmounts.uniV3Token1 + minToken1Deviation < expectedTokenAmounts.uniV3Token1 ||\r\n currentTokenAmounts.uniV3Token1 > expectedTokenAmounts.uniV3Token1 + minToken1Deviation\r\n ) {\r\n return true;\r\n }\r\n }\r\n }\r\n\r\n /// @param tick current price tick\r\n /// @param strategyParams_ the current parameters of the strategy\r\n /// @param uniV3Nft the nft of the position from position manager\r\n /// @param positionManager_ the position manager for uniV3\r\n function calculateAndCheckDomainPositionParams(\r\n int24 tick,\r\n HStrategy.StrategyParams memory strategyParams_,\r\n uint256 uniV3Nft,\r\n INonfungiblePositionManager positionManager_\r\n ) external view returns (HStrategy.DomainPositionParams memory params) {\r\n (, , , , , int24 lowerTick, int24 upperTick, uint128 liquidity, , , , ) = positionManager_.positions(uniV3Nft);\r\n\r\n params = HStrategy.DomainPositionParams({\r\n nft: uniV3Nft,\r\n liquidity: liquidity,\r\n lowerTick: lowerTick,\r\n upperTick: upperTick,\r\n domainLowerTick: strategyParams_.domainLowerTick,\r\n domainUpperTick: strategyParams_.domainUpperTick,\r\n lowerPriceSqrtX96: TickMath.getSqrtRatioAtTick(lowerTick),\r\n upperPriceSqrtX96: TickMath.getSqrtRatioAtTick(upperTick),\r\n domainLowerPriceSqrtX96: TickMath.getSqrtRatioAtTick(strategyParams_.domainLowerTick),\r\n domainUpperPriceSqrtX96: TickMath.getSqrtRatioAtTick(strategyParams_.domainUpperTick),\r\n intervalPriceSqrtX96: TickMath.getSqrtRatioAtTick(tick),\r\n spotPriceX96: 0\r\n });\r\n params.spotPriceX96 = FullMath.mulDiv(\r\n params.intervalPriceSqrtX96,\r\n params.intervalPriceSqrtX96,\r\n CommonLibrary.Q96\r\n );\r\n if (params.intervalPriceSqrtX96 < params.lowerPriceSqrtX96) {\r\n params.intervalPriceSqrtX96 = params.lowerPriceSqrtX96;\r\n } else if (params.intervalPriceSqrtX96 > params.upperPriceSqrtX96) {\r\n params.intervalPriceSqrtX96 = params.upperPriceSqrtX96;\r\n }\r\n }\r\n\r\n /// @param tick current price tick\r\n /// @param pool_ address of uniV3 pool\r\n /// @param oracleParams_ oracle parameters\r\n /// @param uniV3Helper helper for uniswap V3 calculations\r\n function checkSpotTickDeviationFromAverage(\r\n int24 tick,\r\n address pool_,\r\n HStrategy.OracleParams memory oracleParams_,\r\n UniV3Helper uniV3Helper\r\n ) external view {\r\n (bool withFail, int24 deviation) = uniV3Helper.getTickDeviationForTimeSpan(\r\n tick,\r\n pool_,\r\n oracleParams_.averagePriceTimeSpan\r\n );\r\n require(!withFail, ExceptionsLibrary.INVALID_STATE);\r\n if (deviation < 0) {\r\n deviation = -deviation;\r\n }\r\n require(uint24(deviation) <= oracleParams_.maxTickDeviation, ExceptionsLibrary.LIMIT_OVERFLOW);\r\n }\r\n\r\n /// @param spotTick current price tick\r\n /// @param strategyParams_ parameters of strategy\r\n /// @return lowerTick lower tick of new position\r\n /// @return upperTick upper tick of new position\r\n function calculateNewPositionTicks(int24 spotTick, HStrategy.StrategyParams memory strategyParams_)\r\n external\r\n pure\r\n returns (int24 lowerTick, int24 upperTick)\r\n {\r\n if (spotTick < strategyParams_.domainLowerTick) {\r\n spotTick = strategyParams_.domainLowerTick;\r\n } else if (spotTick > strategyParams_.domainUpperTick) {\r\n spotTick = strategyParams_.domainUpperTick;\r\n }\r\n\r\n int24 deltaToLowerTick = spotTick - strategyParams_.domainLowerTick;\r\n deltaToLowerTick -= (deltaToLowerTick % strategyParams_.halfOfShortInterval);\r\n int24 lowerEstimationCentralTick = strategyParams_.domainLowerTick + deltaToLowerTick;\r\n int24 upperEstimationCentralTick = lowerEstimationCentralTick + strategyParams_.halfOfShortInterval;\r\n int24 centralTick = 0;\r\n if (spotTick - lowerEstimationCentralTick <= upperEstimationCentralTick - spotTick) {\r\n centralTick = lowerEstimationCentralTick;\r\n } else {\r\n centralTick = upperEstimationCentralTick;\r\n }\r\n\r\n lowerTick = centralTick - strategyParams_.halfOfShortInterval;\r\n upperTick = centralTick + strategyParams_.halfOfShortInterval;\r\n\r\n if (lowerTick < strategyParams_.domainLowerTick) {\r\n lowerTick = strategyParams_.domainLowerTick;\r\n upperTick = lowerTick + (strategyParams_.halfOfShortInterval << 1);\r\n } else if (upperTick > strategyParams_.domainUpperTick) {\r\n upperTick = strategyParams_.domainUpperTick;\r\n lowerTick = upperTick - (strategyParams_.halfOfShortInterval << 1);\r\n }\r\n }\r\n\r\n /// @param currentTokenAmounts current token amounts on vaults in both tokens\r\n /// @param domainPositionParams the current state of the position, pool and oracle prediction\r\n /// @param hStrategyHelper_ address of HStrategyHelper\r\n /// @param uniV3Helper helper for uniswap V3 calculations\r\n /// @param ratioParams ratio parameters\r\n /// @return expectedTokenAmounts expected amounts of tokens after rebalance on vaults\r\n function calculateExpectedTokenAmounts(\r\n HStrategy.TokenAmounts memory currentTokenAmounts,\r\n HStrategy.DomainPositionParams memory domainPositionParams,\r\n HStrategyHelper hStrategyHelper_,\r\n UniV3Helper uniV3Helper,\r\n HStrategy.RatioParams memory ratioParams\r\n ) external pure returns (HStrategy.TokenAmounts memory expectedTokenAmounts) {\r\n HStrategy.ExpectedRatios memory expectedRatios = hStrategyHelper_.calculateExpectedRatios(domainPositionParams);\r\n uint256 currentCapitalInToken0 = hStrategyHelper_.calculateCurrentCapitalInToken0(\r\n domainPositionParams,\r\n currentTokenAmounts\r\n );\r\n HStrategy.TokenAmountsInToken0 memory expectedTokenAmountsInToken0 = hStrategyHelper_\r\n .calculateExpectedTokenAmountsInToken0(currentCapitalInToken0, expectedRatios, ratioParams);\r\n return\r\n hStrategyHelper_.calculateExpectedTokenAmountsByExpectedRatios(\r\n expectedRatios,\r\n expectedTokenAmountsInToken0,\r\n domainPositionParams,\r\n uniV3Helper\r\n );\r\n }\r\n}\r\n" }, "contracts/utils/ContractMeta.sol": { "content": "// SPDX-License-Identifier: BSL-1.1\r\npragma solidity 0.8.9;\r\n\r\nimport \"../interfaces/utils/IContractMeta.sol\";\r\n\r\nabstract contract ContractMeta is IContractMeta {\r\n // ------------------- EXTERNAL, VIEW -------------------\r\n\r\n function contractName() external pure returns (string memory) {\r\n return _bytes32ToString(_contractName());\r\n }\r\n\r\n function contractNameBytes() external pure returns (bytes32) {\r\n return _contractName();\r\n }\r\n\r\n function contractVersion() external pure returns (string memory) {\r\n return _bytes32ToString(_contractVersion());\r\n }\r\n\r\n function contractVersionBytes() external pure returns (bytes32) {\r\n return _contractVersion();\r\n }\r\n\r\n // ------------------- INTERNAL, VIEW -------------------\r\n\r\n function _contractName() internal pure virtual returns (bytes32);\r\n\r\n function _contractVersion() internal pure virtual returns (bytes32);\r\n\r\n function _bytes32ToString(bytes32 b) internal pure returns (string memory s) {\r\n s = new string(32);\r\n uint256 len = 32;\r\n for (uint256 i = 0; i < 32; ++i) {\r\n if (uint8(b[i]) == 0) {\r\n len = i;\r\n break;\r\n }\r\n }\r\n assembly {\r\n mstore(s, len)\r\n mstore(add(s, 0x20), b)\r\n }\r\n }\r\n}\r\n" }, "contracts/utils/UniV3Helper.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.8.9;\n\nimport \"../interfaces/external/univ3/IUniswapV3Pool.sol\";\nimport \"../interfaces/external/univ3/INonfungiblePositionManager.sol\";\nimport \"../libraries/CommonLibrary.sol\";\nimport \"../libraries/external/TickMath.sol\";\nimport \"../libraries/external/LiquidityAmounts.sol\";\nimport \"../libraries/external/OracleLibrary.sol\";\n\ncontract UniV3Helper {\n function liquidityToTokenAmounts(\n uint128 liquidity,\n IUniswapV3Pool pool,\n uint256 uniV3Nft,\n INonfungiblePositionManager positionManager\n ) external view returns (uint256[] memory tokenAmounts) {\n tokenAmounts = new uint256[](2);\n (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = positionManager.positions(uniV3Nft);\n\n (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();\n uint160 sqrtPriceAX96 = TickMath.getSqrtRatioAtTick(tickLower);\n uint160 sqrtPriceBX96 = TickMath.getSqrtRatioAtTick(tickUpper);\n (tokenAmounts[0], tokenAmounts[1]) = LiquidityAmounts.getAmountsForLiquidity(\n sqrtPriceX96,\n sqrtPriceAX96,\n sqrtPriceBX96,\n liquidity\n );\n }\n\n function tokenAmountsToLiquidity(\n uint256[] memory tokenAmounts,\n IUniswapV3Pool pool,\n uint256 uniV3Nft,\n INonfungiblePositionManager positionManager\n ) external view returns (uint128 liquidity) {\n (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = positionManager.positions(uniV3Nft);\n (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();\n uint160 sqrtPriceAX96 = TickMath.getSqrtRatioAtTick(tickLower);\n uint160 sqrtPriceBX96 = TickMath.getSqrtRatioAtTick(tickUpper);\n\n liquidity = LiquidityAmounts.getLiquidityForAmounts(\n sqrtPriceX96,\n sqrtPriceAX96,\n sqrtPriceBX96,\n tokenAmounts[0],\n tokenAmounts[1]\n );\n }\n\n function _getFeeGrowthInside(\n IUniswapV3Pool pool,\n int24 tickLower,\n int24 tickUpper,\n int24 tickCurrent,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128\n ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {\n unchecked {\n (, , uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128, , , , ) = pool.ticks(\n tickLower\n );\n (, , uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128, , , , ) = pool.ticks(\n tickUpper\n );\n\n // calculate fee growth below\n uint256 feeGrowthBelow0X128;\n uint256 feeGrowthBelow1X128;\n if (tickCurrent >= tickLower) {\n feeGrowthBelow0X128 = lowerFeeGrowthOutside0X128;\n feeGrowthBelow1X128 = lowerFeeGrowthOutside1X128;\n } else {\n feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128;\n feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128;\n }\n\n // calculate fee growth above\n uint256 feeGrowthAbove0X128;\n uint256 feeGrowthAbove1X128;\n if (tickCurrent < tickUpper) {\n feeGrowthAbove0X128 = upperFeeGrowthOutside0X128;\n feeGrowthAbove1X128 = upperFeeGrowthOutside1X128;\n } else {\n feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upperFeeGrowthOutside0X128;\n feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upperFeeGrowthOutside1X128;\n }\n\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;\n }\n }\n\n function calculatePositionInfo(\n INonfungiblePositionManager positionManager,\n IUniswapV3Pool pool,\n uint256 uniV3Nft\n )\n external\n view\n returns (\n int24 tickLower,\n int24 tickUpper,\n uint128 liquidity,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n )\n {\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n (\n ,\n ,\n ,\n ,\n ,\n tickLower,\n tickUpper,\n liquidity,\n feeGrowthInside0LastX128,\n feeGrowthInside1LastX128,\n tokensOwed0,\n tokensOwed1\n ) = positionManager.positions(uniV3Nft);\n\n if (liquidity == 0) {\n return (tickLower, tickUpper, liquidity, tokensOwed0, tokensOwed1);\n }\n\n uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128();\n uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128();\n (, int24 tick, , , , , ) = pool.slot0();\n\n (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = _getFeeGrowthInside(\n pool,\n tickLower,\n tickUpper,\n tick,\n feeGrowthGlobal0X128,\n feeGrowthGlobal1X128\n );\n\n uint256 feeGrowthInside0DeltaX128;\n uint256 feeGrowthInside1DeltaX128;\n unchecked {\n feeGrowthInside0DeltaX128 = feeGrowthInside0X128 - feeGrowthInside0LastX128;\n feeGrowthInside1DeltaX128 = feeGrowthInside1X128 - feeGrowthInside1LastX128;\n }\n\n tokensOwed0 += uint128(FullMath.mulDiv(feeGrowthInside0DeltaX128, liquidity, CommonLibrary.Q128));\n\n tokensOwed1 += uint128(FullMath.mulDiv(feeGrowthInside1DeltaX128, liquidity, CommonLibrary.Q128));\n }\n\n function getTickDeviationForTimeSpan(\n int24 tick,\n address pool_,\n uint32 secondsAgo\n ) external view returns (bool withFail, int24 deviation) {\n int24 averageTick;\n (averageTick, , withFail) = OracleLibrary.consult(pool_, secondsAgo);\n deviation = tick - averageTick;\n }\n\n /// @dev calculates the distribution of tokens that can be added to the position after swap for given capital in token 0\n function getPositionTokenAmountsByCapitalOfToken0(\n uint256 lowerPriceSqrtX96,\n uint256 upperPriceSqrtX96,\n uint256 spotPriceForSqrtFormulasX96,\n uint256 spotPriceX96,\n uint256 capital\n ) external pure returns (uint256 token0Amount, uint256 token1Amount) {\n // sqrt(upperPrice) * (sqrt(price) - sqrt(lowerPrice))\n uint256 lowerPriceTermX96 = FullMath.mulDiv(\n upperPriceSqrtX96,\n spotPriceForSqrtFormulasX96 - lowerPriceSqrtX96,\n CommonLibrary.Q96\n );\n // sqrt(price) * (sqrt(upperPrice) - sqrt(price))\n uint256 upperPriceTermX96 = FullMath.mulDiv(\n spotPriceForSqrtFormulasX96,\n upperPriceSqrtX96 - spotPriceForSqrtFormulasX96,\n CommonLibrary.Q96\n );\n\n token1Amount = FullMath.mulDiv(\n FullMath.mulDiv(capital, spotPriceX96, CommonLibrary.Q96),\n lowerPriceTermX96,\n lowerPriceTermX96 + upperPriceTermX96\n );\n\n token0Amount = capital - FullMath.mulDiv(token1Amount, CommonLibrary.Q96, spotPriceX96);\n }\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" }, "@openzeppelin/contracts/token/ERC721/IERC721.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n}\n" }, "contracts/interfaces/external/univ3/IPeripheryImmutableState.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity =0.8.9;\r\n\r\n/// @title Immutable state\r\n/// @notice Functions that return immutable state of the router\r\ninterface IPeripheryImmutableState {\r\n /// @return Returns the address of the Uniswap V3 factory\r\n function factory() external view returns (address);\r\n\r\n /// @return Returns the address of WETH9\r\n function WETH9() external view returns (address);\r\n}\r\n" }, "@openzeppelin/contracts/utils/introspection/IERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" }, "contracts/interfaces/external/univ3/pool/IUniswapV3PoolActions.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.5.0;\r\n\r\n/// @title Permissionless pool actions\r\n/// @notice Contains pool methods that can be called by anyone\r\ninterface IUniswapV3PoolActions {\r\n /// @notice Sets the initial price for the pool\r\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\r\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\r\n function initialize(uint160 sqrtPriceX96) external;\r\n\r\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\r\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\r\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\r\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\r\n /// @param recipient The address for which the liquidity will be created\r\n /// @param tickLower The lower tick of the position in which to add liquidity\r\n /// @param tickUpper The upper tick of the position in which to add liquidity\r\n /// @param amount The amount of liquidity to mint\r\n /// @param data Any data that should be passed through to the callback\r\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\r\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\r\n function mint(\r\n address recipient,\r\n int24 tickLower,\r\n int24 tickUpper,\r\n uint128 amount,\r\n bytes calldata data\r\n ) external returns (uint256 amount0, uint256 amount1);\r\n\r\n /// @notice Collects tokens owed to a position\r\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\r\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\r\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\r\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\r\n /// @param recipient The address which should receive the fees collected\r\n /// @param tickLower The lower tick of the position for which to collect fees\r\n /// @param tickUpper The upper tick of the position for which to collect fees\r\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\r\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\r\n /// @return amount0 The amount of fees collected in token0\r\n /// @return amount1 The amount of fees collected in token1\r\n function collect(\r\n address recipient,\r\n int24 tickLower,\r\n int24 tickUpper,\r\n uint128 amount0Requested,\r\n uint128 amount1Requested\r\n ) external returns (uint128 amount0, uint128 amount1);\r\n\r\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\r\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\r\n /// @dev Fees must be collected separately via a call to #collect\r\n /// @param tickLower The lower tick of the position for which to burn liquidity\r\n /// @param tickUpper The upper tick of the position for which to burn liquidity\r\n /// @param amount How much liquidity to burn\r\n /// @return amount0 The amount of token0 sent to the recipient\r\n /// @return amount1 The amount of token1 sent to the recipient\r\n function burn(\r\n int24 tickLower,\r\n int24 tickUpper,\r\n uint128 amount\r\n ) external returns (uint256 amount0, uint256 amount1);\r\n\r\n /// @notice Swap token0 for token1, or token1 for token0\r\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\r\n /// @param recipient The address to receive the output of the swap\r\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\r\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\r\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\r\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\r\n /// @param data Any data to be passed through to the callback\r\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\r\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\r\n function swap(\r\n address recipient,\r\n bool zeroForOne,\r\n int256 amountSpecified,\r\n uint160 sqrtPriceLimitX96,\r\n bytes calldata data\r\n ) external returns (int256 amount0, int256 amount1);\r\n\r\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\r\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\r\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\r\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\r\n /// @param recipient The address which will receive the token0 and token1 amounts\r\n /// @param amount0 The amount of token0 to send\r\n /// @param amount1 The amount of token1 to send\r\n /// @param data Any data to be passed through to the callback\r\n function flash(\r\n address recipient,\r\n uint256 amount0,\r\n uint256 amount1,\r\n bytes calldata data\r\n ) external;\r\n\r\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\r\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\r\n /// the input observationCardinalityNext.\r\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\r\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\r\n}\r\n" }, "contracts/interfaces/external/univ3/pool/IUniswapV3PoolImmutables.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.5.0;\r\n\r\n/// @title Pool state that never changes\r\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\r\ninterface IUniswapV3PoolImmutables {\r\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\r\n /// @return The contract address\r\n function factory() external view returns (address);\r\n\r\n /// @notice The first of the two tokens of the pool, sorted by address\r\n /// @return The token contract address\r\n function token0() external view returns (address);\r\n\r\n /// @notice The second of the two tokens of the pool, sorted by address\r\n /// @return The token contract address\r\n function token1() external view returns (address);\r\n\r\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\r\n /// @return The fee\r\n function fee() external view returns (uint24);\r\n\r\n /// @notice The pool tick spacing\r\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\r\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\r\n /// This value is an int24 to avoid casting even though it is always positive.\r\n /// @return The tick spacing\r\n function tickSpacing() external view returns (int24);\r\n\r\n /// @notice The maximum amount of position liquidity that can use any tick in the range\r\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\r\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\r\n /// @return The max amount of liquidity per tick\r\n function maxLiquidityPerTick() external view returns (uint128);\r\n}\r\n" }, "contracts/interfaces/external/univ3/pool/IUniswapV3PoolState.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity =0.8.9;\r\n\r\n/// @title Pool state that can change\r\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\r\n/// per transaction\r\ninterface IUniswapV3PoolState {\r\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\r\n /// when accessed externally.\r\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\r\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\r\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\r\n /// boundary.\r\n /// observationIndex The index of the last oracle observation that was written,\r\n /// observationCardinality The current maximum number of observations stored in the pool,\r\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\r\n /// feeProtocol The protocol fee for both tokens of the pool.\r\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\r\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\r\n /// unlocked Whether the pool is currently locked to reentrancy\r\n function slot0()\r\n external\r\n view\r\n returns (\r\n uint160 sqrtPriceX96,\r\n int24 tick,\r\n uint16 observationIndex,\r\n uint16 observationCardinality,\r\n uint16 observationCardinalityNext,\r\n uint8 feeProtocol,\r\n bool unlocked\r\n );\r\n\r\n /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\r\n /// @dev This value can overflow the uint256\r\n function feeGrowthGlobal0X128() external view returns (uint256);\r\n\r\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\r\n /// @dev This value can overflow the uint256\r\n function feeGrowthGlobal1X128() external view returns (uint256);\r\n\r\n /// @notice The amounts of token0 and token1 that are owed to the protocol\r\n /// @dev Protocol fees will never exceed uint128 max in either token\r\n function protocolPerformanceFees() external view returns (uint128 token0, uint128 token1);\r\n\r\n /// @notice The currently in range liquidity available to the pool\r\n /// @dev This value has no relationship to the total liquidity across all ticks\r\n function liquidity() external view returns (uint128);\r\n\r\n /// @notice Look up information about a specific tick in the pool\r\n /// @param tick The tick to look up\r\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\r\n /// tick upper,\r\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\r\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\r\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\r\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\r\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\r\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\r\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\r\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\r\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\r\n /// a specific position.\r\n function ticks(int24 tick)\r\n external\r\n view\r\n returns (\r\n uint128 liquidityGross,\r\n int128 liquidityNet,\r\n uint256 feeGrowthOutside0X128,\r\n uint256 feeGrowthOutside1X128,\r\n int56 tickCumulativeOutside,\r\n uint160 secondsPerLiquidityOutsideX128,\r\n uint32 secondsOutside,\r\n bool initialized\r\n );\r\n\r\n /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\r\n function tickBitmap(int16 wordPosition) external view returns (uint256);\r\n\r\n /// @notice Returns the information about a position by the position's key\r\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\r\n /// @return _liquidity The amount of liquidity in the position,\r\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\r\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\r\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\r\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\r\n function positions(bytes32 key)\r\n external\r\n view\r\n returns (\r\n uint128 _liquidity,\r\n uint256 feeGrowthInside0LastX128,\r\n uint256 feeGrowthInside1LastX128,\r\n uint128 tokensOwed0,\r\n uint128 tokensOwed1\r\n );\r\n\r\n /// @notice Returns data about a specific observation index\r\n /// @param index The element of the observations array to fetch\r\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\r\n /// ago, rather than at a specific index in the array.\r\n /// @return blockTimestamp The timestamp of the observation,\r\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\r\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\r\n /// Returns initialized whether the observation has been initialized and the values are safe to use\r\n function observations(uint256 index)\r\n external\r\n view\r\n returns (\r\n uint32 blockTimestamp,\r\n int56 tickCumulative,\r\n uint160 secondsPerLiquidityCumulativeX128,\r\n bool initialized\r\n );\r\n}\r\n" }, "contracts/interfaces/external/univ3/pool/IUniswapV3PoolDerivedState.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.5.0;\r\n\r\n/// @title Pool state that is not stored\r\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\r\n/// blockchain. The functions here may have variable gas costs.\r\ninterface IUniswapV3PoolDerivedState {\r\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\r\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\r\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\r\n /// you must call it with secondsAgos = [3600, 0].\r\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\r\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\r\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\r\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\r\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\r\n /// timestamp\r\n function observe(uint32[] calldata secondsAgos)\r\n external\r\n view\r\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\r\n}\r\n" }, "contracts/interfaces/external/aave/ILendingPool.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\r\npragma solidity 0.8.9;\r\npragma experimental ABIEncoderV2;\r\n\r\nimport {ILendingPoolAddressesProvider} from \"./ILendingPoolAddressesProvider.sol\";\r\nimport {DataTypes} from \"./DataTypes.sol\";\r\n\r\ninterface ILendingPool {\r\n /**\r\n * @dev Emitted on deposit()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address initiating the deposit\r\n * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens\r\n * @param amount The amount deposited\r\n * @param referral The referral code used\r\n **/\r\n event Deposit(\r\n address indexed reserve,\r\n address user,\r\n address indexed onBehalfOf,\r\n uint256 amount,\r\n uint16 indexed referral\r\n );\r\n\r\n /**\r\n * @dev Emitted on withdraw()\r\n * @param reserve The address of the underlyng asset being withdrawn\r\n * @param user The address initiating the withdrawal, owner of aTokens\r\n * @param to Address that will receive the underlying\r\n * @param amount The amount to be withdrawn\r\n **/\r\n event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\r\n\r\n /**\r\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\r\n * @param reserve The address of the underlying asset being borrowed\r\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\r\n * initiator of the transaction on flashLoan()\r\n * @param onBehalfOf The address that will be getting the debt\r\n * @param amount The amount borrowed out\r\n * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable\r\n * @param borrowRate The numeric rate at which the user has borrowed\r\n * @param referral The referral code used\r\n **/\r\n event Borrow(\r\n address indexed reserve,\r\n address user,\r\n address indexed onBehalfOf,\r\n uint256 amount,\r\n uint256 borrowRateMode,\r\n uint256 borrowRate,\r\n uint16 indexed referral\r\n );\r\n\r\n /**\r\n * @dev Emitted on repay()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The beneficiary of the repayment, getting his debt reduced\r\n * @param repayer The address of the user initiating the repay(), providing the funds\r\n * @param amount The amount repaid\r\n **/\r\n event Repay(address indexed reserve, address indexed user, address indexed repayer, uint256 amount);\r\n\r\n /**\r\n * @dev Emitted on swapBorrowRateMode()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user swapping his rate mode\r\n * @param rateMode The rate mode that the user wants to swap to\r\n **/\r\n event Swap(address indexed reserve, address indexed user, uint256 rateMode);\r\n\r\n /**\r\n * @dev Emitted on setUserUseReserveAsCollateral()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user enabling the usage as collateral\r\n **/\r\n event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\r\n\r\n /**\r\n * @dev Emitted on setUserUseReserveAsCollateral()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user enabling the usage as collateral\r\n **/\r\n event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\r\n\r\n /**\r\n * @dev Emitted on rebalanceStableBorrowRate()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user for which the rebalance has been executed\r\n **/\r\n event RebalanceStableBorrowRate(address indexed reserve, address indexed user);\r\n\r\n /**\r\n * @dev Emitted on flashLoan()\r\n * @param target The address of the flash loan receiver contract\r\n * @param initiator The address initiating the flash loan\r\n * @param asset The address of the asset being flash borrowed\r\n * @param amount The amount flash borrowed\r\n * @param premium The fee flash borrowed\r\n * @param referralCode The referral code used\r\n **/\r\n event FlashLoan(\r\n address indexed target,\r\n address indexed initiator,\r\n address indexed asset,\r\n uint256 amount,\r\n uint256 premium,\r\n uint16 referralCode\r\n );\r\n\r\n /**\r\n * @dev Emitted when the pause is triggered.\r\n */\r\n event Paused();\r\n\r\n /**\r\n * @dev Emitted when the pause is lifted.\r\n */\r\n event Unpaused();\r\n\r\n /**\r\n * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via\r\n * LendingPoolCollateral manager using a DELEGATECALL\r\n * This allows to have the events in the generated ABI for LendingPool.\r\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\r\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\r\n * @param user The address of the borrower getting liquidated\r\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\r\n * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator\r\n * @param liquidator The address of the liquidator\r\n * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants\r\n * to receive the underlying collateral asset directly\r\n **/\r\n event LiquidationCall(\r\n address indexed collateralAsset,\r\n address indexed debtAsset,\r\n address indexed user,\r\n uint256 debtToCover,\r\n uint256 liquidatedCollateralAmount,\r\n address liquidator,\r\n bool receiveAToken\r\n );\r\n\r\n /**\r\n * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared\r\n * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,\r\n * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it\r\n * gets added to the LendingPool ABI\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param liquidityRate The new liquidity rate\r\n * @param stableBorrowRate The new stable borrow rate\r\n * @param variableBorrowRate The new variable borrow rate\r\n * @param liquidityIndex The new liquidity index\r\n * @param variableBorrowIndex The new variable borrow index\r\n **/\r\n event ReserveDataUpdated(\r\n address indexed reserve,\r\n uint256 liquidityRate,\r\n uint256 stableBorrowRate,\r\n uint256 variableBorrowRate,\r\n uint256 liquidityIndex,\r\n uint256 variableBorrowIndex\r\n );\r\n\r\n /**\r\n * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\r\n * - E.g. User deposits 100 USDC and gets in return 100 aUSDC\r\n * @param asset The address of the underlying asset to deposit\r\n * @param amount The amount to be deposited\r\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\r\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\r\n * is a different wallet\r\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\r\n * 0 if the action is executed directly by the user, without any middle-man\r\n **/\r\n function deposit(\r\n address asset,\r\n uint256 amount,\r\n address onBehalfOf,\r\n uint16 referralCode\r\n ) external;\r\n\r\n /**\r\n * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\r\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\r\n * @param asset The address of the underlying asset to withdraw\r\n * @param amount The underlying amount to be withdrawn\r\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\r\n * @param to Address that will receive the underlying, same as msg.sender if the user\r\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\r\n * different wallet\r\n * @return The final amount withdrawn\r\n **/\r\n function withdraw(\r\n address asset,\r\n uint256 amount,\r\n address to\r\n ) external returns (uint256);\r\n\r\n /**\r\n * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\r\n * already deposited enough collateral, or he was given enough allowance by a credit delegator on the\r\n * corresponding debt token (StableDebtToken or VariableDebtToken)\r\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\r\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\r\n * @param asset The address of the underlying asset to borrow\r\n * @param amount The amount to be borrowed\r\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\r\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\r\n * 0 if the action is executed directly by the user, without any middle-man\r\n * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself\r\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\r\n * if he has been given credit delegation allowance\r\n **/\r\n function borrow(\r\n address asset,\r\n uint256 amount,\r\n uint256 interestRateMode,\r\n uint16 referralCode,\r\n address onBehalfOf\r\n ) external;\r\n\r\n /**\r\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\r\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\r\n * @param asset The address of the borrowed underlying asset previously borrowed\r\n * @param amount The amount to repay\r\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\r\n * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\r\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\r\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\r\n * other borrower whose debt should be removed\r\n * @return The final amount repaid\r\n **/\r\n function repay(\r\n address asset,\r\n uint256 amount,\r\n uint256 rateMode,\r\n address onBehalfOf\r\n ) external returns (uint256);\r\n\r\n /**\r\n * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa\r\n * @param asset The address of the underlying asset borrowed\r\n * @param rateMode The rate mode that the user wants to swap to\r\n **/\r\n function swapBorrowRateMode(address asset, uint256 rateMode) external;\r\n\r\n /**\r\n * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\r\n * - Users can be rebalanced if the following conditions are satisfied:\r\n * 1. Usage ratio is above 95%\r\n * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been\r\n * borrowed at a stable rate and depositors are not earning enough\r\n * @param asset The address of the underlying asset borrowed\r\n * @param user The address of the user to be rebalanced\r\n **/\r\n function rebalanceStableBorrowRate(address asset, address user) external;\r\n\r\n /**\r\n * @dev Allows depositors to enable/disable a specific deposited asset as collateral\r\n * @param asset The address of the underlying asset deposited\r\n * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise\r\n **/\r\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\r\n\r\n /**\r\n * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\r\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\r\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\r\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\r\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\r\n * @param user The address of the borrower getting liquidated\r\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\r\n * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants\r\n * to receive the underlying collateral asset directly\r\n **/\r\n function liquidationCall(\r\n address collateralAsset,\r\n address debtAsset,\r\n address user,\r\n uint256 debtToCover,\r\n bool receiveAToken\r\n ) external;\r\n\r\n /**\r\n * @dev Allows smartcontracts to access the liquidity of the pool within one transaction,\r\n * as long as the amount taken plus a fee is returned.\r\n * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.\r\n * For further details please visit https://developers.aave.com\r\n * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface\r\n * @param assets The addresses of the assets being flash-borrowed\r\n * @param amounts The amounts amounts being flash-borrowed\r\n * @param modes Types of the debt to open if the flash loan is not returned:\r\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\r\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\r\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\r\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\r\n * @param params Variadic packed params to pass to the receiver as extra information\r\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\r\n * 0 if the action is executed directly by the user, without any middle-man\r\n **/\r\n function flashLoan(\r\n address receiverAddress,\r\n address[] calldata assets,\r\n uint256[] calldata amounts,\r\n uint256[] calldata modes,\r\n address onBehalfOf,\r\n bytes calldata params,\r\n uint16 referralCode\r\n ) external;\r\n\r\n /**\r\n * @dev Returns the user account data across all the reserves\r\n * @param user The address of the user\r\n * @return totalCollateralETH the total collateral in ETH of the user\r\n * @return totalDebtETH the total debt in ETH of the user\r\n * @return availableBorrowsETH the borrowing power left of the user\r\n * @return currentLiquidationThreshold the liquidation threshold of the user\r\n * @return ltv the loan to value of the user\r\n * @return healthFactor the current health factor of the user\r\n **/\r\n function getUserAccountData(address user)\r\n external\r\n view\r\n returns (\r\n uint256 totalCollateralETH,\r\n uint256 totalDebtETH,\r\n uint256 availableBorrowsETH,\r\n uint256 currentLiquidationThreshold,\r\n uint256 ltv,\r\n uint256 healthFactor\r\n );\r\n\r\n function initReserve(\r\n address reserve,\r\n address aTokenAddress,\r\n address stableDebtAddress,\r\n address variableDebtAddress,\r\n address interestRateStrategyAddress\r\n ) external;\r\n\r\n function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external;\r\n\r\n function setConfiguration(address reserve, uint256 configuration) external;\r\n\r\n /**\r\n * @dev Returns the configuration of the reserve\r\n * @param asset The address of the underlying asset of the reserve\r\n * @return The configuration of the reserve\r\n **/\r\n function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);\r\n\r\n /**\r\n * @dev Returns the configuration of the user across all the reserves\r\n * @param user The user address\r\n * @return The configuration of the user\r\n **/\r\n function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);\r\n\r\n /**\r\n * @dev Returns the normalized income normalized income of the reserve\r\n * @param asset The address of the underlying asset of the reserve\r\n * @return The reserve's normalized income\r\n */\r\n function getReserveNormalizedIncome(address asset) external view returns (uint256);\r\n\r\n /**\r\n * @dev Returns the normalized variable debt per unit of asset\r\n * @param asset The address of the underlying asset of the reserve\r\n * @return The reserve normalized variable debt\r\n */\r\n function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);\r\n\r\n /**\r\n * @dev Returns the state and configuration of the reserve\r\n * @param asset The address of the underlying asset of the reserve\r\n * @return The state of the reserve\r\n **/\r\n function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);\r\n\r\n function finalizeTransfer(\r\n address asset,\r\n address from,\r\n address to,\r\n uint256 amount,\r\n uint256 balanceFromAfter,\r\n uint256 balanceToBefore\r\n ) external;\r\n\r\n function getReservesList() external view returns (address[] memory);\r\n\r\n function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);\r\n\r\n function setPause(bool val) external;\r\n\r\n function paused() external view returns (bool);\r\n}\r\n" }, "contracts/interfaces/vaults/IIntegrationVault.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"../external/erc/IERC1271.sol\";\r\nimport \"./IVault.sol\";\r\n\r\ninterface IIntegrationVault is IVault, IERC1271 {\r\n /// @notice Pushes tokens on the vault balance to the underlying protocol. For example, for Yearn this operation will take USDC from\r\n /// the contract balance and convert it to yUSDC.\r\n /// @dev Tokens **must** be a subset of Vault Tokens. However, the convention is that if tokenAmount == 0 it is the same as token is missing.\r\n ///\r\n /// Also notice that this operation doesn't guarantee that tokenAmounts will be invested in full.\r\n /// @param tokens Tokens to push\r\n /// @param tokenAmounts Amounts of tokens to push\r\n /// @param options Additional options that could be needed for some vaults. E.g. for Uniswap this could be `deadline` param. For the exact bytes structure see concrete vault descriptions\r\n /// @return actualTokenAmounts The amounts actually invested. It could be less than tokenAmounts (but not higher)\r\n function push(\r\n address[] memory tokens,\r\n uint256[] memory tokenAmounts,\r\n bytes memory options\r\n ) external returns (uint256[] memory actualTokenAmounts);\r\n\r\n /// @notice The same as `push` method above but transfers tokens to vault balance prior to calling push.\r\n /// After the `push` it returns all the leftover tokens back (`push` method doesn't guarantee that tokenAmounts will be invested in full).\r\n /// @param tokens Tokens to push\r\n /// @param tokenAmounts Amounts of tokens to push\r\n /// @param options Additional options that could be needed for some vaults. E.g. for Uniswap this could be `deadline` param. For the exact bytes structure see concrete vault descriptions\r\n /// @return actualTokenAmounts The amounts actually invested. It could be less than tokenAmounts (but not higher)\r\n function transferAndPush(\r\n address from,\r\n address[] memory tokens,\r\n uint256[] memory tokenAmounts,\r\n bytes memory options\r\n ) external returns (uint256[] memory actualTokenAmounts);\r\n\r\n /// @notice Pulls tokens from the underlying protocol to the `to` address.\r\n /// @dev Can only be called but Vault Owner or Strategy. Vault owner is the owner of NFT for this vault in VaultManager.\r\n /// Strategy is approved address for the vault NFT.\r\n /// When called by vault owner this method just pulls the tokens from the protocol to the `to` address\r\n /// When called by strategy on vault other than zero vault it pulls the tokens to zero vault (required `to` == zero vault)\r\n /// When called by strategy on zero vault it pulls the tokens to zero vault, pushes tokens on the `to` vault, and reclaims everything that's left.\r\n /// Thus any vault other than zero vault cannot have any tokens on it\r\n ///\r\n /// Tokens **must** be a subset of Vault Tokens. However, the convention is that if tokenAmount == 0 it is the same as token is missing.\r\n ///\r\n /// Pull is fulfilled on the best effort basis, i.e. if the tokenAmounts overflows available funds it withdraws all the funds.\r\n /// @param to Address to receive the tokens\r\n /// @param tokens Tokens to pull\r\n /// @param tokenAmounts Amounts of tokens to pull\r\n /// @param options Additional options that could be needed for some vaults. E.g. for Uniswap this could be `deadline` param. For the exact bytes structure see concrete vault descriptions\r\n /// @return actualTokenAmounts The amounts actually withdrawn. It could be less than tokenAmounts (but not higher)\r\n function pull(\r\n address to,\r\n address[] memory tokens,\r\n uint256[] memory tokenAmounts,\r\n bytes memory options\r\n ) external returns (uint256[] memory actualTokenAmounts);\r\n\r\n /// @notice Claim ERC20 tokens from vault balance to zero vault.\r\n /// @dev Cannot be called from zero vault.\r\n /// @param tokens Tokens to claim\r\n /// @return actualTokenAmounts Amounts reclaimed\r\n function reclaimTokens(address[] memory tokens) external returns (uint256[] memory actualTokenAmounts);\r\n\r\n /// @notice Execute one of whitelisted calls.\r\n /// @dev Can only be called by Vault Owner or Strategy. Vault owner is the owner of NFT for this vault in VaultManager.\r\n /// Strategy is approved address for the vault NFT.\r\n ///\r\n /// Since this method allows sending arbitrary transactions, the destinations of the calls\r\n /// are whitelisted by Protocol Governance.\r\n /// @param to Address of the reward pool\r\n /// @param selector Selector of the call\r\n /// @param data Abi encoded parameters to `to::selector`\r\n /// @return result Result of execution of the call\r\n function externalCall(\r\n address to,\r\n bytes4 selector,\r\n bytes memory data\r\n ) external payable returns (bytes memory result);\r\n}\r\n" }, "contracts/interfaces/external/aave/ILendingPoolAddressesProvider.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\r\npragma solidity 0.8.9;\r\n\r\n/**\r\n * @title LendingPoolAddressesProvider contract\r\n * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles\r\n * - Acting also as factory of proxies and admin of those, so with right to change its implementations\r\n * - Owned by the Aave Governance\r\n * @author Aave\r\n **/\r\ninterface ILendingPoolAddressesProvider {\r\n event MarketIdSet(string newMarketId);\r\n event LendingPoolUpdated(address indexed newAddress);\r\n event ConfigurationAdminUpdated(address indexed newAddress);\r\n event EmergencyAdminUpdated(address indexed newAddress);\r\n event LendingPoolConfiguratorUpdated(address indexed newAddress);\r\n event LendingPoolCollateralManagerUpdated(address indexed newAddress);\r\n event PriceOracleUpdated(address indexed newAddress);\r\n event LendingRateOracleUpdated(address indexed newAddress);\r\n event ProxyCreated(bytes32 id, address indexed newAddress);\r\n event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);\r\n\r\n function getMarketId() external view returns (string memory);\r\n\r\n function setMarketId(string calldata marketId) external;\r\n\r\n function setAddress(bytes32 id, address newAddress) external;\r\n\r\n function setAddressAsProxy(bytes32 id, address impl) external;\r\n\r\n function getAddress(bytes32 id) external view returns (address);\r\n\r\n function getLendingPool() external view returns (address);\r\n\r\n function setLendingPoolImpl(address pool) external;\r\n\r\n function getLendingPoolConfigurator() external view returns (address);\r\n\r\n function setLendingPoolConfiguratorImpl(address configurator) external;\r\n\r\n function getLendingPoolCollateralManager() external view returns (address);\r\n\r\n function setLendingPoolCollateralManager(address manager) external;\r\n\r\n function getPoolAdmin() external view returns (address);\r\n\r\n function setPoolAdmin(address admin) external;\r\n\r\n function getEmergencyAdmin() external view returns (address);\r\n\r\n function setEmergencyAdmin(address admin) external;\r\n\r\n function getPriceOracle() external view returns (address);\r\n\r\n function setPriceOracle(address priceOracle) external;\r\n\r\n function getLendingRateOracle() external view returns (address);\r\n\r\n function setLendingRateOracle(address lendingRateOracle) external;\r\n}\r\n" }, "contracts/interfaces/external/aave/DataTypes.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\r\npragma solidity 0.8.9;\r\n\r\nlibrary DataTypes {\r\n // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.\r\n struct ReserveData {\r\n //stores the reserve configuration\r\n ReserveConfigurationMap configuration;\r\n //the liquidity index. Expressed in ray\r\n uint128 liquidityIndex;\r\n //variable borrow index. Expressed in ray\r\n uint128 variableBorrowIndex;\r\n //the current supply rate. Expressed in ray\r\n uint128 currentLiquidityRate;\r\n //the current variable borrow rate. Expressed in ray\r\n uint128 currentVariableBorrowRate;\r\n //the current stable borrow rate. Expressed in ray\r\n uint128 currentStableBorrowRate;\r\n uint40 lastUpdateTimestamp;\r\n //tokens addresses\r\n address aTokenAddress;\r\n address stableDebtTokenAddress;\r\n address variableDebtTokenAddress;\r\n //address of the interest rate strategy\r\n address interestRateStrategyAddress;\r\n //the id of the reserve. Represents the position in the list of the active reserves\r\n uint8 id;\r\n }\r\n\r\n struct ReserveConfigurationMap {\r\n //bit 0-15: LTV\r\n //bit 16-31: Liq. threshold\r\n //bit 32-47: Liq. bonus\r\n //bit 48-55: Decimals\r\n //bit 56: Reserve is active\r\n //bit 57: reserve is frozen\r\n //bit 58: borrowing is enabled\r\n //bit 59: stable rate borrowing enabled\r\n //bit 60-63: reserved\r\n //bit 64-79: reserve factor\r\n uint256 data;\r\n }\r\n\r\n struct UserConfigurationMap {\r\n uint256 data;\r\n }\r\n\r\n enum InterestRateMode {\r\n NONE,\r\n STABLE,\r\n VARIABLE\r\n }\r\n}\r\n" }, "contracts/interfaces/external/erc/IERC1271.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\ninterface IERC1271 {\r\n /// @notice Verifies offchain signature.\r\n /// @dev Should return whether the signature provided is valid for the provided hash\r\n ///\r\n /// MUST return the bytes4 magic value 0x1626ba7e when function passes.\r\n ///\r\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)\r\n ///\r\n /// MUST allow external calls\r\n /// @param _hash Hash of the data to be signed\r\n /// @param _signature Signature byte array associated with _hash\r\n /// @return magicValue 0x1626ba7e if valid, 0xffffffff otherwise\r\n function isValidSignature(bytes32 _hash, bytes memory _signature) external view returns (bytes4 magicValue);\r\n}\r\n" }, "contracts/interfaces/vaults/IVault.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"./IVaultGovernance.sol\";\r\n\r\ninterface IVault is IERC165 {\r\n /// @notice Checks if the vault is initialized\r\n\r\n function initialized() external view returns (bool);\r\n\r\n /// @notice VaultRegistry NFT for this vault\r\n function nft() external view returns (uint256);\r\n\r\n /// @notice Address of the Vault Governance for this contract.\r\n function vaultGovernance() external view returns (IVaultGovernance);\r\n\r\n /// @notice ERC20 tokens under Vault management.\r\n function vaultTokens() external view returns (address[] memory);\r\n\r\n /// @notice Checks if a token is vault token\r\n /// @param token Address of the token to check\r\n /// @return `true` if this token is managed by Vault\r\n function isVaultToken(address token) external view returns (bool);\r\n\r\n /// @notice Total value locked for this contract.\r\n /// @dev Generally it is the underlying token value of this contract in some\r\n /// other DeFi protocol. For example, for USDC Yearn Vault this would be total USDC balance that could be withdrawn for Yearn to this contract.\r\n /// The tvl itself is estimated in some range. Sometimes the range is exact, sometimes it's not\r\n /// @return minTokenAmounts Lower bound for total available balances estimation (nth tokenAmount corresponds to nth token in vaultTokens)\r\n /// @return maxTokenAmounts Upper bound for total available balances estimation (nth tokenAmount corresponds to nth token in vaultTokens)\r\n function tvl() external view returns (uint256[] memory minTokenAmounts, uint256[] memory maxTokenAmounts);\r\n\r\n /// @notice Existential amounts for each token\r\n function pullExistentials() external view returns (uint256[] memory);\r\n}\r\n" }, "contracts/interfaces/vaults/IVaultGovernance.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"../IProtocolGovernance.sol\";\r\nimport \"../IVaultRegistry.sol\";\r\nimport \"./IVault.sol\";\r\n\r\ninterface IVaultGovernance {\r\n /// @notice Internal references of the contract.\r\n /// @param protocolGovernance Reference to Protocol Governance\r\n /// @param registry Reference to Vault Registry\r\n struct InternalParams {\r\n IProtocolGovernance protocolGovernance;\r\n IVaultRegistry registry;\r\n IVault singleton;\r\n }\r\n\r\n // ------------------- EXTERNAL, VIEW -------------------\r\n\r\n /// @notice Timestamp in unix time seconds after which staged Delayed Strategy Params could be committed.\r\n /// @param nft Nft of the vault\r\n function delayedStrategyParamsTimestamp(uint256 nft) external view returns (uint256);\r\n\r\n /// @notice Timestamp in unix time seconds after which staged Delayed Protocol Params could be committed.\r\n function delayedProtocolParamsTimestamp() external view returns (uint256);\r\n\r\n /// @notice Timestamp in unix time seconds after which staged Delayed Protocol Params Per Vault could be committed.\r\n /// @param nft Nft of the vault\r\n function delayedProtocolPerVaultParamsTimestamp(uint256 nft) external view returns (uint256);\r\n\r\n /// @notice Timestamp in unix time seconds after which staged Internal Params could be committed.\r\n function internalParamsTimestamp() external view returns (uint256);\r\n\r\n /// @notice Internal Params of the contract.\r\n function internalParams() external view returns (InternalParams memory);\r\n\r\n /// @notice Staged new Internal Params.\r\n /// @dev The Internal Params could be committed after internalParamsTimestamp\r\n function stagedInternalParams() external view returns (InternalParams memory);\r\n\r\n // ------------------- EXTERNAL, MUTATING -------------------\r\n\r\n /// @notice Stage new Internal Params.\r\n /// @param newParams New Internal Params\r\n function stageInternalParams(InternalParams memory newParams) external;\r\n\r\n /// @notice Commit staged Internal Params.\r\n function commitInternalParams() external;\r\n}\r\n" }, "contracts/interfaces/IProtocolGovernance.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"./utils/IDefaultAccessControl.sol\";\r\nimport \"./IUnitPricesGovernance.sol\";\r\n\r\ninterface IProtocolGovernance is IDefaultAccessControl, IUnitPricesGovernance {\r\n /// @notice CommonLibrary protocol params.\r\n /// @param maxTokensPerVault Max different token addresses that could be managed by the vault\r\n /// @param governanceDelay The delay (in secs) that must pass before setting new pending params to commiting them\r\n /// @param protocolTreasury The address that collects protocolFees, if protocolFee is not zero\r\n /// @param forceAllowMask If a permission bit is set in this mask it forces all addresses to have this permission as true\r\n /// @param withdrawLimit Withdraw limit (in unit prices, i.e. usd)\r\n struct Params {\r\n uint256 maxTokensPerVault;\r\n uint256 governanceDelay;\r\n address protocolTreasury;\r\n uint256 forceAllowMask;\r\n uint256 withdrawLimit;\r\n }\r\n\r\n // ------------------- EXTERNAL, VIEW -------------------\r\n\r\n /// @notice Timestamp after which staged granted permissions for the given address can be committed.\r\n /// @param target The given address\r\n /// @return Zero if there are no staged permission grants, timestamp otherwise\r\n function stagedPermissionGrantsTimestamps(address target) external view returns (uint256);\r\n\r\n /// @notice Staged granted permission bitmask for the given address.\r\n /// @param target The given address\r\n /// @return Bitmask\r\n function stagedPermissionGrantsMasks(address target) external view returns (uint256);\r\n\r\n /// @notice Permission bitmask for the given address.\r\n /// @param target The given address\r\n /// @return Bitmask\r\n function permissionMasks(address target) external view returns (uint256);\r\n\r\n /// @notice Timestamp after which staged pending protocol parameters can be committed\r\n /// @return Zero if there are no staged parameters, timestamp otherwise.\r\n function stagedParamsTimestamp() external view returns (uint256);\r\n\r\n /// @notice Staged pending protocol parameters.\r\n function stagedParams() external view returns (Params memory);\r\n\r\n /// @notice Current protocol parameters.\r\n function params() external view returns (Params memory);\r\n\r\n /// @notice Addresses for which non-zero permissions are set.\r\n function permissionAddresses() external view returns (address[] memory);\r\n\r\n /// @notice Permission addresses staged for commit.\r\n function stagedPermissionGrantsAddresses() external view returns (address[] memory);\r\n\r\n /// @notice Return all addresses where rawPermissionMask bit for permissionId is set to 1.\r\n /// @param permissionId Id of the permission to check.\r\n /// @return A list of dirty addresses.\r\n function addressesByPermission(uint8 permissionId) external view returns (address[] memory);\r\n\r\n /// @notice Checks if address has permission or given permission is force allowed for any address.\r\n /// @param addr Address to check\r\n /// @param permissionId Permission to check\r\n function hasPermission(address addr, uint8 permissionId) external view returns (bool);\r\n\r\n /// @notice Checks if address has all permissions.\r\n /// @param target Address to check\r\n /// @param permissionIds A list of permissions to check\r\n function hasAllPermissions(address target, uint8[] calldata permissionIds) external view returns (bool);\r\n\r\n /// @notice Max different ERC20 token addresses that could be managed by the protocol.\r\n function maxTokensPerVault() external view returns (uint256);\r\n\r\n /// @notice The delay for committing any governance params.\r\n function governanceDelay() external view returns (uint256);\r\n\r\n /// @notice The address of the protocol treasury.\r\n function protocolTreasury() external view returns (address);\r\n\r\n /// @notice Permissions mask which defines if ordinary permission should be reverted.\r\n /// This bitmask is xored with ordinary mask.\r\n function forceAllowMask() external view returns (uint256);\r\n\r\n /// @notice Withdraw limit per token per block.\r\n /// @param token Address of the token\r\n /// @return Withdraw limit per token per block\r\n function withdrawLimit(address token) external view returns (uint256);\r\n\r\n /// @notice Addresses that has staged validators.\r\n function stagedValidatorsAddresses() external view returns (address[] memory);\r\n\r\n /// @notice Timestamp after which staged granted permissions for the given address can be committed.\r\n /// @param target The given address\r\n /// @return Zero if there are no staged permission grants, timestamp otherwise\r\n function stagedValidatorsTimestamps(address target) external view returns (uint256);\r\n\r\n /// @notice Staged validator for the given address.\r\n /// @param target The given address\r\n /// @return Validator\r\n function stagedValidators(address target) external view returns (address);\r\n\r\n /// @notice Addresses that has validators.\r\n function validatorsAddresses() external view returns (address[] memory);\r\n\r\n /// @notice Address that has validators.\r\n /// @param i The number of address\r\n /// @return Validator address\r\n function validatorsAddress(uint256 i) external view returns (address);\r\n\r\n /// @notice Validator for the given address.\r\n /// @param target The given address\r\n /// @return Validator\r\n function validators(address target) external view returns (address);\r\n\r\n // ------------------- EXTERNAL, MUTATING, GOVERNANCE, IMMEDIATE -------------------\r\n\r\n /// @notice Rollback all staged validators.\r\n function rollbackStagedValidators() external;\r\n\r\n /// @notice Revoke validator instantly from the given address.\r\n /// @param target The given address\r\n function revokeValidator(address target) external;\r\n\r\n /// @notice Stages a new validator for the given address\r\n /// @param target The given address\r\n /// @param validator The validator for the given address\r\n function stageValidator(address target, address validator) external;\r\n\r\n /// @notice Commits validator for the given address.\r\n /// @dev Reverts if governance delay has not passed yet.\r\n /// @param target The given address.\r\n function commitValidator(address target) external;\r\n\r\n /// @notice Commites all staged validators for which governance delay passed\r\n /// @return Addresses for which validators were committed\r\n function commitAllValidatorsSurpassedDelay() external returns (address[] memory);\r\n\r\n /// @notice Rollback all staged granted permission grant.\r\n function rollbackStagedPermissionGrants() external;\r\n\r\n /// @notice Commits permission grants for the given address.\r\n /// @dev Reverts if governance delay has not passed yet.\r\n /// @param target The given address.\r\n function commitPermissionGrants(address target) external;\r\n\r\n /// @notice Commites all staged permission grants for which governance delay passed.\r\n /// @return An array of addresses for which permission grants were committed.\r\n function commitAllPermissionGrantsSurpassedDelay() external returns (address[] memory);\r\n\r\n /// @notice Revoke permission instantly from the given address.\r\n /// @param target The given address.\r\n /// @param permissionIds A list of permission ids to revoke.\r\n function revokePermissions(address target, uint8[] memory permissionIds) external;\r\n\r\n /// @notice Commits staged protocol params.\r\n /// Reverts if governance delay has not passed yet.\r\n function commitParams() external;\r\n\r\n // ------------------- EXTERNAL, MUTATING, GOVERNANCE, DELAY -------------------\r\n\r\n /// @notice Sets new pending params that could have been committed after governance delay expires.\r\n /// @param newParams New protocol parameters to set.\r\n function stageParams(Params memory newParams) external;\r\n\r\n /// @notice Stage granted permissions that could have been committed after governance delay expires.\r\n /// Resets commit delay and permissions if there are already staged permissions for this address.\r\n /// @param target Target address\r\n /// @param permissionIds A list of permission ids to grant\r\n function stagePermissionGrants(address target, uint8[] memory permissionIds) external;\r\n}\r\n" }, "contracts/interfaces/IVaultRegistry.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity =0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\r\nimport \"./IProtocolGovernance.sol\";\r\n\r\ninterface IVaultRegistry is IERC721 {\r\n /// @notice Get Vault for the giver NFT ID.\r\n /// @param nftId NFT ID\r\n /// @return vault Address of the Vault contract\r\n function vaultForNft(uint256 nftId) external view returns (address vault);\r\n\r\n /// @notice Get NFT ID for given Vault contract address.\r\n /// @param vault Address of the Vault contract\r\n /// @return nftId NFT ID\r\n function nftForVault(address vault) external view returns (uint256 nftId);\r\n\r\n /// @notice Checks if the nft is locked for all transfers\r\n /// @param nft NFT to check for lock\r\n /// @return `true` if locked, false otherwise\r\n function isLocked(uint256 nft) external view returns (bool);\r\n\r\n /// @notice Register new Vault and mint NFT.\r\n /// @param vault address of the vault\r\n /// @param owner owner of the NFT\r\n /// @return nft Nft minted for the given Vault\r\n function registerVault(address vault, address owner) external returns (uint256 nft);\r\n\r\n /// @notice Number of Vaults registered.\r\n function vaultsCount() external view returns (uint256);\r\n\r\n /// @notice All Vaults registered.\r\n function vaults() external view returns (address[] memory);\r\n\r\n /// @notice Address of the ProtocolGovernance.\r\n function protocolGovernance() external view returns (IProtocolGovernance);\r\n\r\n /// @notice Address of the staged ProtocolGovernance.\r\n function stagedProtocolGovernance() external view returns (IProtocolGovernance);\r\n\r\n /// @notice Minimal timestamp when staged ProtocolGovernance can be applied.\r\n function stagedProtocolGovernanceTimestamp() external view returns (uint256);\r\n\r\n /// @notice Stage new ProtocolGovernance.\r\n /// @param newProtocolGovernance new ProtocolGovernance\r\n function stageProtocolGovernance(IProtocolGovernance newProtocolGovernance) external;\r\n\r\n /// @notice Commit new ProtocolGovernance.\r\n function commitStagedProtocolGovernance() external;\r\n\r\n /// @notice Lock NFT for transfers\r\n /// @dev Use this method when vault structure is set up and should become immutable. Can be called by owner.\r\n /// @param nft - NFT to lock\r\n function lockNft(uint256 nft) external;\r\n}\r\n" }, "contracts/interfaces/utils/IDefaultAccessControl.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/access/IAccessControlEnumerable.sol\";\r\n\r\ninterface IDefaultAccessControl is IAccessControlEnumerable {\r\n /// @notice Checks that the address is contract admin.\r\n /// @param who Address to check\r\n /// @return `true` if who is admin, `false` otherwise\r\n function isAdmin(address who) external view returns (bool);\r\n\r\n /// @notice Checks that the address is contract admin.\r\n /// @param who Address to check\r\n /// @return `true` if who is operator, `false` otherwise\r\n function isOperator(address who) external view returns (bool);\r\n}\r\n" }, "contracts/interfaces/IUnitPricesGovernance.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\r\nimport \"./utils/IDefaultAccessControl.sol\";\r\n\r\ninterface IUnitPricesGovernance is IDefaultAccessControl, IERC165 {\r\n // ------------------- EXTERNAL, VIEW -------------------\r\n\r\n /// @notice Estimated amount of token worth 1 USD staged for commit.\r\n /// @param token Address of the token\r\n /// @return The amount of token\r\n function stagedUnitPrices(address token) external view returns (uint256);\r\n\r\n /// @notice Timestamp after which staged unit prices for the given token can be committed.\r\n /// @param token Address of the token\r\n /// @return Timestamp\r\n function stagedUnitPricesTimestamps(address token) external view returns (uint256);\r\n\r\n /// @notice Estimated amount of token worth 1 USD.\r\n /// @param token Address of the token\r\n /// @return The amount of token\r\n function unitPrices(address token) external view returns (uint256);\r\n\r\n // ------------------- EXTERNAL, MUTATING -------------------\r\n\r\n /// @notice Stage estimated amount of token worth 1 USD staged for commit.\r\n /// @param token Address of the token\r\n /// @param value The amount of token\r\n function stageUnitPrice(address token, uint256 value) external;\r\n\r\n /// @notice Reset staged value\r\n /// @param token Address of the token\r\n function rollbackUnitPrice(address token) external;\r\n\r\n /// @notice Commit staged unit price\r\n /// @param token Address of the token\r\n function commitUnitPrice(address token) external;\r\n}\r\n" }, "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\n}\n" }, "@openzeppelin/contracts/access/IAccessControl.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` 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(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 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(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\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 {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\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(bytes32 role, address account) external;\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(bytes32 role, address account) external;\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(bytes32 role, address account) external;\n}\n" }, "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" }, "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" }, "@openzeppelin/contracts/access/AccessControl.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\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 `DEFAULT_ADMIN_ROLE`, 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 `DEFAULT_ADMIN_ROLE` 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 */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role, _msgSender());\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(uint160(account), 20),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\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(bytes32 role) public view override returns (bytes32) {\n return _roles[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(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\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(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\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 revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" }, "@openzeppelin/contracts/utils/structs/EnumerableSet.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping(bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (lastIndex != toDeleteIndex) {\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n return _values(set._inner);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n assembly {\n result := store\n }\n\n return result;\n }\n}\n" }, "@openzeppelin/contracts/utils/Context.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n" }, "@openzeppelin/contracts/utils/Strings.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n}\n" }, "@openzeppelin/contracts/utils/introspection/ERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" }, "contracts/interfaces/vaults/IAaveVault.sol": { "content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.9;\r\n\r\nimport \"../external/aave/ILendingPool.sol\";\r\nimport \"./IIntegrationVault.sol\";\r\n\r\ninterface IAaveVault is IIntegrationVault {\r\n /// @notice Reference to Aave protocol lending pool.\r\n function lendingPool() external view returns (ILendingPool);\r\n\r\n /// @notice Update all tvls to current aToken balances.\r\n function updateTvls() external;\r\n\r\n /// @notice Initialized a new contract.\r\n /// @dev Can only be initialized by vault governance\r\n /// @param nft_ NFT of the vault in the VaultRegistry\r\n /// @param vaultTokens_ ERC20 tokens that will be managed by this Vault\r\n function initialize(uint256 nft_, address[] memory vaultTokens_) external;\r\n}\r\n" }, "contracts/libraries/external/LiquidityAmounts.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity =0.8.9;\r\n\r\nimport \"./FullMath.sol\";\r\nimport \"./FixedPoint96.sol\";\r\n\r\n/// @title Liquidity amount functions\r\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\r\nlibrary LiquidityAmounts {\r\n /// @notice Downcasts uint256 to uint128\r\n /// @param x The uint258 to be downcasted\r\n /// @return y The passed value, downcasted to uint128\r\n function toUint128(uint256 x) private pure returns (uint128 y) {\r\n require((y = uint128(x)) == x);\r\n }\r\n\r\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\r\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\r\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\r\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\r\n /// @param amount0 The amount0 being sent in\r\n /// @return liquidity The amount of returned liquidity\r\n function getLiquidityForAmount0(\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint256 amount0\r\n ) internal pure returns (uint128 liquidity) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\r\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\r\n }\r\n\r\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\r\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\r\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\r\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\r\n /// @param amount1 The amount1 being sent in\r\n /// @return liquidity The amount of returned liquidity\r\n function getLiquidityForAmount1(\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint256 amount1\r\n ) internal pure returns (uint128 liquidity) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\r\n }\r\n\r\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\r\n /// pool prices and the prices at the tick boundaries\r\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\r\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\r\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\r\n /// @param amount0 The amount of token0 being sent in\r\n /// @param amount1 The amount of token1 being sent in\r\n /// @return liquidity The maximum amount of liquidity received\r\n function getLiquidityForAmounts(\r\n uint160 sqrtRatioX96,\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint256 amount0,\r\n uint256 amount1\r\n ) internal pure returns (uint128 liquidity) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n\r\n if (sqrtRatioX96 <= sqrtRatioAX96) {\r\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\r\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\r\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\r\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\r\n\r\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\r\n } else {\r\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\r\n }\r\n }\r\n\r\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\r\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\r\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\r\n /// @param liquidity The liquidity being valued\r\n /// @return amount0 The amount of token0\r\n function getAmount0ForLiquidity(\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint128 liquidity\r\n ) internal pure returns (uint256 amount0) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n\r\n return\r\n FullMath.mulDiv(\r\n uint256(liquidity) << FixedPoint96.RESOLUTION,\r\n sqrtRatioBX96 - sqrtRatioAX96,\r\n sqrtRatioBX96\r\n ) / sqrtRatioAX96;\r\n }\r\n\r\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\r\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\r\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\r\n /// @param liquidity The liquidity being valued\r\n /// @return amount1 The amount of token1\r\n function getAmount1ForLiquidity(\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint128 liquidity\r\n ) internal pure returns (uint256 amount1) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n\r\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\r\n }\r\n\r\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\r\n /// pool prices and the prices at the tick boundaries\r\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\r\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\r\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\r\n /// @param liquidity The liquidity being valued\r\n /// @return amount0 The amount of token0\r\n /// @return amount1 The amount of token1\r\n function getAmountsForLiquidity(\r\n uint160 sqrtRatioX96,\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint128 liquidity\r\n ) internal pure returns (uint256 amount0, uint256 amount1) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n\r\n if (sqrtRatioX96 <= sqrtRatioAX96) {\r\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\r\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\r\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\r\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\r\n } else {\r\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\r\n }\r\n }\r\n}\r\n" }, "contracts/libraries/external/FixedPoint96.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity =0.8.9;\r\n\r\n/// @title FixedPoint96\r\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\r\n/// @dev Used in SqrtPriceMath.sol\r\nlibrary FixedPoint96 {\r\n uint8 internal constant RESOLUTION = 96;\r\n uint256 internal constant Q96 = 0x1000000000000000000000000;\r\n}\r\n" }, "contracts/interfaces/utils/IContractMeta.sol": { "content": "// SPDX-License-Identifier: BSL-1.1\r\npragma solidity 0.8.9;\r\n\r\ninterface IContractMeta {\r\n function contractName() external view returns (string memory);\r\n function contractNameBytes() external view returns (bytes32);\r\n\r\n function contractVersion() external view returns (string memory);\r\n function contractVersionBytes() external view returns (bytes32);\r\n}\r\n" }, "contracts/libraries/external/OracleLibrary.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity 0.8.9;\r\n\r\nimport \"./FullMath.sol\";\r\nimport \"./TickMath.sol\";\r\nimport \"../../interfaces/external/univ3/IUniswapV3Pool.sol\";\r\n\r\n/// @title Oracle library\r\n/// @notice Provides functions to integrate with V3 pool oracle\r\nlibrary OracleLibrary {\r\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\r\n /// @param pool Address of the pool that we want to observe\r\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\r\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\r\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\r\n /// @return withFail Flag that true if function observe of IUniswapV3Pool reverts with some error\r\n function consult(address pool, uint32 secondsAgo)\r\n internal\r\n view\r\n returns (\r\n int24 arithmeticMeanTick,\r\n uint128 harmonicMeanLiquidity,\r\n bool withFail\r\n )\r\n {\r\n require(secondsAgo != 0, \"BP\");\r\n\r\n uint32[] memory secondsAgos = new uint32[](2);\r\n secondsAgos[0] = secondsAgo;\r\n secondsAgos[1] = 0;\r\n\r\n try IUniswapV3Pool(pool).observe(secondsAgos) returns (\r\n int56[] memory tickCumulatives,\r\n uint160[] memory secondsPerLiquidityCumulativeX128s\r\n ) {\r\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\r\n uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] -\r\n secondsPerLiquidityCumulativeX128s[0];\r\n\r\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\r\n // Always round to negative infinity\r\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0))\r\n arithmeticMeanTick--;\r\n\r\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\r\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\r\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\r\n } catch {\r\n return (0, 0, true);\r\n }\r\n }\r\n}\r\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "evmVersion": "istanbul", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} } }