{
    "Function": "slitherConstructorConstantVariables",
    "File": "src/V3Oracle.sol",
    "Parent Contracts": [
        "src/interfaces/IErrors.sol",
        "lib/openzeppelin-contracts/contracts/access/Ownable.sol",
        "lib/openzeppelin-contracts/contracts/utils/Context.sol",
        "src/interfaces/IV3Oracle.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract V3Oracle is IV3Oracle, Ownable, IErrors {\n    uint16 public constant MIN_PRICE_DIFFERENCE = 200; //2%\n\n    uint256 private constant Q96 = 2 ** 96;\n    uint256 private constant Q128 = 2 ** 128;\n\n    event TokenConfigUpdated(address indexed token, TokenConfig config);\n    event OracleModeUpdated(address indexed token, Mode mode);\n    event SetMaxPoolPriceDifference(uint16 maxPoolPriceDifference);\n    event SetEmergencyAdmin(address emergencyAdmin);\n\n    enum Mode {\n        NOT_SET,\n        CHAINLINK_TWAP_VERIFY, // using chainlink for price and TWAP to verify\n        TWAP_CHAINLINK_VERIFY, // using TWAP for price and chainlink to verify\n        CHAINLINK, // using only chainlink directly\n        TWAP // using TWAP directly\n    }\n\n    struct TokenConfig {\n        AggregatorV3Interface feed; // chainlink feed\n        uint32 maxFeedAge;\n        uint8 feedDecimals;\n        uint8 tokenDecimals;\n        IUniswapV3Pool pool; // reference pool\n        bool isToken0;\n        uint32 twapSeconds;\n        Mode mode;\n        uint16 maxDifference; // max price difference x10000\n    }\n\n    // token => config mapping\n    mapping(address => TokenConfig) public feedConfigs;\n\n    address public immutable factory;\n    INonfungiblePositionManager public immutable nonfungiblePositionManager;\n\n    // common token which is used in TWAP pools\n    address public immutable referenceToken;\n    uint8 public immutable referenceTokenDecimals;\n\n    uint16 public maxPoolPriceDifference = MIN_PRICE_DIFFERENCE; // max price difference between oracle derived price and pool price x10000\n\n    // common token which is used in chainlink feeds as \"pair\" (address(0) if USD or another non-token reference)\n    address public immutable chainlinkReferenceToken;\n\n    // address which can call special emergency actions without timelock\n    address public emergencyAdmin;\n\n    // constructor: sets owner of contract\n    constructor(\n        INonfungiblePositionManager _nonfungiblePositionManager,\n        address _referenceToken,\n        address _chainlinkReferenceToken\n    ) {\n        nonfungiblePositionManager = _nonfungiblePositionManager;\n        factory = _nonfungiblePositionManager.factory();\n        referenceToken = _referenceToken;\n        referenceTokenDecimals = IERC20Metadata(_referenceToken).decimals();\n        chainlinkReferenceToken = _chainlinkReferenceToken;\n    }\n\n    /// @notice Gets value and prices of a uniswap v3 lp position in specified token\n    /// @dev uses configured oracles and verfies price on second oracle - if fails - reverts\n    /// @dev all involved tokens must be configured in oracle - otherwise reverts\n    /// @param tokenId tokenId of position\n    /// @param token address of token in which value and prices should be given\n    /// @return value value of complete position at current prices\n    /// @return feeValue value of positions fees only at current prices\n    /// @return price0X96 price of token0\n    /// @return price1X96 price of token1\n    function getValue(uint256 tokenId, address token)\n        external\n        view\n        override\n        returns (uint256 value, uint256 feeValue, uint256 price0X96, uint256 price1X96)\n    {\n        (address token0, address token1, uint24 fee,, uint256 amount0, uint256 amount1, uint256 fees0, uint256 fees1) =\n            getPositionBreakdown(tokenId);\n\n        uint256 cachedChainlinkReferencePriceX96;\n\n        (price0X96, cachedChainlinkReferencePriceX96) =\n            _getReferenceTokenPriceX96(token0, cachedChainlinkReferencePriceX96);\n        (price1X96, cachedChainlinkReferencePriceX96) =\n            _getReferenceTokenPriceX96(token1, cachedChainlinkReferencePriceX96);\n\n        uint256 priceTokenX96;\n        if (token0 == token) {\n            priceTokenX96 = price0X96;\n        } else if (token1 == token) {\n            priceTokenX96 = price1X96;\n        } else {\n            (priceTokenX96,) = _getReferenceTokenPriceX96(token, cachedChainlinkReferencePriceX96);\n        }\n\n        value = (price0X96 * (amount0 + fees0) / Q96 + price1X96 * (amount1 + fees1) / Q96) * Q96 / priceTokenX96;\n        feeValue = (price0X96 * fees0 / Q96 + price1X96 * fees1 / Q96) * Q96 / priceTokenX96;\n        price0X96 = price0X96 * Q96 / priceTokenX96;\n        price1X96 = price1X96 * Q96 / priceTokenX96;\n\n        // checks derived pool price for price manipulation attacks\n        // this prevents manipulations of pool to get distorted proportions of collateral tokens - for borrowing\n        // when a pool is in this state, liquidations will be disabled - but arbitrageurs (or liquidator himself)\n        // will move price back to reasonable range and enable liquidation\n        uint256 derivedPoolPriceX96 = price0X96 * Q96 / price1X96;\n        _checkPoolPrice(token0, token1, fee, derivedPoolPriceX96);\n    }\n\n    function _checkPoolPrice(address token0, address token1, uint24 fee, uint256 derivedPoolPriceX96) internal view {\n        IUniswapV3Pool pool = _getPool(token0, token1, fee);\n        uint256 priceX96 = _getReferencePoolPriceX96(pool, 0);\n        _requireMaxDifference(priceX96, derivedPoolPriceX96, maxPoolPriceDifference);\n    }\n\n    function _requireMaxDifference(uint256 priceX96, uint256 verifyPriceX96, uint256 maxDifferenceX10000)\n        internal\n        pure\n    {\n        uint256 differenceX10000 = priceX96 > verifyPriceX96\n            ? (priceX96 - verifyPriceX96) * 10000 / priceX96\n            : (verifyPriceX96 - priceX96) * 10000 / verifyPriceX96;\n        // if too big difference - revert\n        if (differenceX10000 >= maxDifferenceX10000) {\n            revert PriceDifferenceExceeded();\n        }\n    }\n\n    /// @notice Gets breakdown of a uniswap v3 position (tokens and fee tier, liquidity, current liquidity amounts, uncollected fees)\n    /// @param tokenId tokenId of position\n    /// @return token0 token0 of position\n    /// @return token1 token1 of position\n    /// @return fee fee tier of position\n    /// @return liquidity liquidity of position\n    /// @return amount0 current amount token0\n    /// @return amount1 current amount token1\n    /// @return fees0 current token0 fees of position\n    /// @return fees1 current token1 fees of position\n    function getPositionBreakdown(uint256 tokenId)\n        public\n        view\n        override\n        returns (\n            address token0,\n            address token1,\n            uint24 fee,\n            uint128 liquidity,\n            uint256 amount0,\n            uint256 amount1,\n            uint128 fees0,\n            uint128 fees1\n        )\n    {\n        PositionState memory state = _initializeState(tokenId);\n        (token0, token1, fee) = (state.token0, state.token1, state.fee);\n        (amount0, amount1, fees0, fees1) = _getAmounts(state);\n        liquidity = state.liquidity;\n    }\n\n    /// @notice Sets the max pool difference parameter (onlyOwner)\n    /// @param _maxPoolPriceDifference Set max allowable difference between pool price and derived oracle pool price\n    function setMaxPoolPriceDifference(uint16 _maxPoolPriceDifference) external onlyOwner {\n        if (_maxPoolPriceDifference < MIN_PRICE_DIFFERENCE) {\n            revert InvalidConfig();\n        }\n        maxPoolPriceDifference = _maxPoolPriceDifference;\n        emit SetMaxPoolPriceDifference(_maxPoolPriceDifference);\n    }\n\n    /// @notice Sets or updates the feed configuration for a token (onlyOwner)\n    /// @param token Token to configure\n    /// @param feed Chainlink feed to this token (matching chainlinkReferenceToken)\n    /// @param maxFeedAge Max allowable chainlink feed age\n    /// @param pool TWAP reference pool (matching referenceToken)\n    /// @param twapSeconds TWAP period to use\n    /// @param mode Mode how both oracle should be used\n    /// @param maxDifference Max allowable difference between both oracle prices\n    function setTokenConfig(\n        address token,\n        AggregatorV3Interface feed,\n        uint32 maxFeedAge,\n        IUniswapV3Pool pool,\n        uint32 twapSeconds,\n        Mode mode,\n        uint16 maxDifference\n    ) external onlyOwner {\n        // can not be unset\n        if (mode == Mode.NOT_SET) {\n            revert InvalidConfig();\n        }\n\n        uint8 feedDecimals = feed.decimals();\n        uint8 tokenDecimals = IERC20Metadata(token).decimals();\n\n        TokenConfig memory config;\n\n        if (token != referenceToken) {\n            if (maxDifference < MIN_PRICE_DIFFERENCE) {\n                revert InvalidConfig();\n            }\n\n            address token0 = pool.token0();\n            address token1 = pool.token1();\n            if (!(token0 == token && token1 == referenceToken || token0 == referenceToken && token1 == token)) {\n                revert InvalidPool();\n            }\n            bool isToken0 = token0 == token;\n            config = TokenConfig(\n                feed, maxFeedAge, feedDecimals, tokenDecimals, pool, isToken0, twapSeconds, mode, maxDifference\n            );\n        } else {\n            config = TokenConfig(\n                feed, maxFeedAge, feedDecimals, tokenDecimals, IUniswapV3Pool(address(0)), false, 0, Mode.CHAINLINK, 0\n            );\n        }\n\n        feedConfigs[token] = config;\n\n        emit TokenConfigUpdated(token, config);\n        emit OracleModeUpdated(token, mode);\n    }\n\n    /// @notice Updates the oracle mode for a given token  - this method can be called by owner OR emergencyAdmin\n    /// @param token Token to configure\n    /// @param mode Mode to set\n    function setOracleMode(address token, Mode mode) external {\n        if (msg.sender != emergencyAdmin && msg.sender != owner()) {\n            revert Unauthorized();\n        }\n\n        // can not be unset\n        if (mode == Mode.NOT_SET) {\n            revert InvalidConfig();\n        }\n\n        feedConfigs[token].mode = mode;\n        emit OracleModeUpdated(token, mode);\n    }\n\n    /// @notice Updates emergency admin address (onlyOwner)\n    /// @param admin Emergency admin address\n    function setEmergencyAdmin(address admin) external onlyOwner {\n        emergencyAdmin = admin;\n        emit SetEmergencyAdmin(admin);\n    }\n\n    // Returns the price for a token using the selected oracle mode given as reference token value\n    // The price is calculated using Chainlink, Uniswap v3 TWAP, or both based on the mode\n    function _getReferenceTokenPriceX96(address token, uint256 cachedChainlinkReferencePriceX96)\n        internal\n        view\n        returns (uint256 priceX96, uint256 chainlinkReferencePriceX96)\n    {\n        if (token == referenceToken) {\n            return (Q96, chainlinkReferencePriceX96);\n        }\n\n        TokenConfig memory feedConfig = feedConfigs[token];\n\n        if (feedConfig.mode == Mode.NOT_SET) {\n            revert NotConfigured();\n        }\n\n        uint256 verifyPriceX96;\n\n        bool usesChainlink = (\n            feedConfig.mode == Mode.CHAINLINK_TWAP_VERIFY || feedConfig.mode == Mode.TWAP_CHAINLINK_VERIFY\n                || feedConfig.mode == Mode.CHAINLINK\n        );\n        bool usesTWAP = (\n            feedConfig.mode == Mode.CHAINLINK_TWAP_VERIFY || feedConfig.mode == Mode.TWAP_CHAINLINK_VERIFY\n                || feedConfig.mode == Mode.TWAP\n        );\n\n        if (usesChainlink) {\n            uint256 chainlinkPriceX96 = _getChainlinkPriceX96(token);\n            chainlinkReferencePriceX96 = cachedChainlinkReferencePriceX96 == 0\n                ? _getChainlinkPriceX96(referenceToken)\n                : cachedChainlinkReferencePriceX96;\n\n            chainlinkPriceX96 = (10 ** referenceTokenDecimals) * chainlinkPriceX96 * Q96 / chainlinkReferencePriceX96\n                / (10 ** feedConfig.tokenDecimals);\n\n            if (feedConfig.mode == Mode.TWAP_CHAINLINK_VERIFY) {\n                verifyPriceX96 = chainlinkPriceX96;\n            } else {\n                priceX96 = chainlinkPriceX96;\n            }\n        }\n\n        if (usesTWAP) {\n            uint256 twapPriceX96 = _getTWAPPriceX96(feedConfig);\n            if (feedConfig.mode == Mode.CHAINLINK_TWAP_VERIFY) {\n                verifyPriceX96 = twapPriceX96;\n            } else {\n                priceX96 = twapPriceX96;\n            }\n        }\n\n        if (feedConfig.mode == Mode.CHAINLINK_TWAP_VERIFY || feedConfig.mode == Mode.TWAP_CHAINLINK_VERIFY) {\n            _requireMaxDifference(priceX96, verifyPriceX96, feedConfig.maxDifference);\n        }\n    }\n\n    // calculates chainlink price given feedConfig\n    function _getChainlinkPriceX96(address token) internal view returns (uint256) {\n        if (token == chainlinkReferenceToken) {\n            return Q96;\n        }\n\n        TokenConfig memory feedConfig = feedConfigs[token];\n\n        // if stale data - revert\n        (, int256 answer,, uint256 updatedAt,) = feedConfig.feed.latestRoundData();\n        if (updatedAt + feedConfig.maxFeedAge < block.timestamp || answer < 0) {\n            revert ChainlinkPriceError();\n        }\n\n        return uint256(answer) * Q96 / (10 ** feedConfig.feedDecimals);\n    }\n\n    // calculates TWAP price given feedConfig\n    function _getTWAPPriceX96(TokenConfig memory feedConfig) internal view returns (uint256 poolTWAPPriceX96) {\n        // get reference pool price\n        uint256 priceX96 = _getReferencePoolPriceX96(feedConfig.pool, feedConfig.twapSeconds);\n\n        if (feedConfig.isToken0) {\n            poolTWAPPriceX96 = priceX96;\n        } else {\n            poolTWAPPriceX96 = Q96 * Q96 / priceX96;\n        }\n    }\n\n    // Calculates the reference pool price with scaling factor of 2^96\n    // It uses either the latest slot price or TWAP based on twapSeconds\n    function _getReferencePoolPriceX96(IUniswapV3Pool pool, uint32 twapSeconds) internal view returns (uint256) {\n        uint160 sqrtPriceX96;\n        // if twap seconds set to 0 just use pool price\n        if (twapSeconds == 0) {\n            (sqrtPriceX96,,,,,,) = pool.slot0();\n        } else {\n            uint32[] memory secondsAgos = new uint32[](2);\n            secondsAgos[0] = 0; // from (before)\n            secondsAgos[1] = twapSeconds; // from (before)\n            (int56[] memory tickCumulatives,) = pool.observe(secondsAgos); // pool observe may fail when there is not enough history available (only use pool with enough history!)\n            int24 tick = int24((tickCumulatives[0] - tickCumulatives[1]) / int56(uint56(twapSeconds)));\n            sqrtPriceX96 = TickMath.getSqrtRatioAtTick(tick);\n        }\n\n        return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, Q96);\n    }\n\n    struct PositionState {\n        uint256 tokenId;\n        address token0;\n        address token1;\n        uint24 fee;\n        int24 tickLower;\n        int24 tickUpper;\n        uint128 liquidity;\n        uint256 feeGrowthInside0LastX128;\n        uint256 feeGrowthInside1LastX128;\n        uint128 tokensOwed0;\n        uint128 tokensOwed1;\n        IUniswapV3Pool pool;\n        uint160 sqrtPriceX96;\n        int24 tick;\n        uint160 sqrtPriceX96Lower;\n        uint160 sqrtPriceX96Upper;\n    }\n\n    function _initializeState(uint256 tokenId) internal view returns (PositionState memory state) {\n        (\n            ,\n            ,\n            address token0,\n            address token1,\n            uint24 fee,\n            int24 tickLower,\n            int24 tickUpper,\n            uint128 liquidity,\n            uint256 feeGrowthInside0LastX128,\n            uint256 feeGrowthInside1LastX128,\n            uint128 tokensOwed0,\n            uint128 tokensOwed1\n        ) = nonfungiblePositionManager.positions(tokenId);\n        state.tokenId = tokenId;\n        state.token0 = token0;\n        state.token1 = token1;\n        state.fee = fee;\n        state.tickLower = tickLower;\n        state.tickUpper = tickUpper;\n        state.liquidity = liquidity;\n        state.feeGrowthInside0LastX128 = feeGrowthInside0LastX128;\n        state.feeGrowthInside1LastX128 = feeGrowthInside1LastX128;\n        state.tokensOwed0 = tokensOwed0;\n        state.tokensOwed1 = tokensOwed1;\n        state.pool = _getPool(token0, token1, fee);\n        (state.sqrtPriceX96, state.tick,,,,,) = state.pool.slot0();\n    }\n\n    // calculate position amounts given current price/tick\n    function _getAmounts(PositionState memory state)\n        internal\n        view\n        returns (uint256 amount0, uint256 amount1, uint128 fees0, uint128 fees1)\n    {\n        if (state.liquidity > 0) {\n            state.sqrtPriceX96Lower = TickMath.getSqrtRatioAtTick(state.tickLower);\n            state.sqrtPriceX96Upper = TickMath.getSqrtRatioAtTick(state.tickUpper);\n            (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(\n                state.sqrtPriceX96, state.sqrtPriceX96Lower, state.sqrtPriceX96Upper, state.liquidity\n            );\n        }\n\n        (fees0, fees1) = _getUncollectedFees(state, state.tick);\n        fees0 += state.tokensOwed0;\n        fees1 += state.tokensOwed1;\n    }\n\n    // calculate uncollected fees\n    function _getUncollectedFees(PositionState memory position, int24 tick)\n        internal\n        view\n        returns (uint128 fees0, uint128 fees1)\n    {\n        (uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) = _getFeeGrowthInside(\n            position.pool,\n            position.tickLower,\n            position.tickUpper,\n            tick,\n            position.pool.feeGrowthGlobal0X128(),\n            position.pool.feeGrowthGlobal1X128()\n        );\n\n        // allow overflow - this is as designed by uniswap - see PositionValue library (for solidity < 0.8)\n        uint256 feeGrowth0;\n        uint256 feeGrowth1;\n        unchecked {\n            feeGrowth0 = feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128;\n            feeGrowth1 = feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128;\n        }\n\n        fees0 = uint128(FullMath.mulDiv(feeGrowth0, position.liquidity, Q128));\n        fees1 = uint128(FullMath.mulDiv(feeGrowth1, position.liquidity, Q128));\n    }\n\n    // calculate fee growth for uncollected fees calculation\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        (,, uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128,,,,) = pool.ticks(tickLower);\n        (,, uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128,,,,) = pool.ticks(tickUpper);\n\n        // allow overflow - this is as designed by uniswap - see PositionValue library (for solidity < 0.8)\n        unchecked {\n            if (tickCurrent < tickLower) {\n                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n            } else if (tickCurrent < tickUpper) {\n                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n            } else {\n                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n            }\n        }\n    }\n\n    // helper method to get pool for token\n    function _getPool(address tokenA, address tokenB, uint24 fee) internal view returns (IUniswapV3Pool) {\n        return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));\n    }\n}"
}