{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/AMM.sol",
    "Parent Contracts": [
        "contracts/legos/Governable.sol",
        "node_modules/@openzeppelin/contracts/proxy/utils/Initializable.sol",
        "contracts/legos/Governable.sol",
        "contracts/Interfaces.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract AMM is IAMM, Governable {\n    using SafeCast for uint256;\n    using SafeCast for int256;\n\n    uint256 public constant spotPriceTwapInterval = 1 hours;\n    uint256 public constant fundingPeriod = 1 hours;\n    int256 constant BASE_PRECISION = 1e18;\n\n    // System-wide config\n\n    IOracle public oracle;\n    address public clearingHouse;\n\n    // AMM config\n\n    IVAMM override public vamm;\n    address override public underlyingAsset;\n    string public name;\n\n    uint256 public fundingBufferPeriod;\n    uint256 public nextFundingTime;\n    int256 public fundingRate;\n    int256 public cumulativePremiumFraction;\n    int256 public cumulativePremiumPerDtoken;\n    int256 public posAccumulator;\n\n    uint256 public longOpenInterestNotional;\n    uint256 public shortOpenInterestNotional;\n\n    enum Side { LONG, SHORT }\n    struct Position {\n        int256 size;\n        uint256 openNotional;\n        int256 lastPremiumFraction;\n    }\n    mapping(address => Position) override public positions;\n\n    struct Maker {\n        uint vUSD;\n        uint vAsset;\n        uint dToken;\n        int pos; // position\n        int posAccumulator; // value of global.posAccumulator until which pos has been updated\n        int lastPremiumFraction;\n        int lastPremiumPerDtoken;\n    }\n    mapping(address => Maker) override public makers;\n\n    struct ReserveSnapshot {\n        uint256 lastPrice;\n        uint256 timestamp;\n        uint256 blockNumber;\n    }\n    ReserveSnapshot[] public reserveSnapshots;\n\n    /**\n    * @dev We do not deliberately have a Pause state. There is only a master-level pause at clearingHouse level\n    */\n    enum AMMState { Inactive, Ignition, Active }\n    AMMState public ammState;\n\n    uint256[50] private __gap;\n\n    // Events\n\n    event PositionChanged(address indexed trader, int256 size, uint256 openNotional, int256 realizedPnl);\n    event FundingRateUpdated(int256 premiumFraction, int256 rate, uint256 underlyingPrice, uint256 timestamp, uint256 blockNumber);\n    event FundingPaid(address indexed trader, int256 takerPosSize, int256 takerFundingPayment, int256 makerFundingPayment, int256 latestCumulativePremiumFraction, int256 latestPremiumPerDtoken);\n    event Swap(int256 baseAsset, uint256 quoteAsset, uint256 lastPrice, uint256 openInterestNotional);\n    event LiquidityAdded(address indexed maker, uint dToken, uint baseAsset, uint quoteAsset, uint timestamp);\n    event LiquidityRemoved(address indexed maker, uint dToken, uint baseAsset, uint quoteAsset, uint timestamp, int256 realizedPnl);\n\n    modifier onlyClearingHouse() {\n        require(msg.sender == clearingHouse, \"Only clearingHouse\");\n        _;\n    }\n\n    modifier onlyVamm() {\n        require(msg.sender == address(vamm), \"Only VAMM\");\n        _;\n    }\n\n    function initialize(\n        address _registry,\n        address _underlyingAsset,\n        string memory _name,\n        address _vamm,\n        address _governance\n    ) external initializer {\n        _setGovernace(_governance);\n\n        vamm = IVAMM(_vamm);\n        underlyingAsset = _underlyingAsset;\n        name = _name;\n        fundingBufferPeriod = 15 minutes;\n\n        syncDeps(_registry);\n    }\n\n    /**\n    * @dev baseAssetQuantity != 0 has been validated in clearingHouse._openPosition()\n    */\n    function openPosition(address trader, int256 baseAssetQuantity, uint quoteAssetLimit)\n        override\n        external\n        onlyClearingHouse\n        returns (int realizedPnl, uint quoteAsset, bool isPositionIncreased)\n    {\n        require(ammState == AMMState.Active, \"AMM.openPosition.not_active\");\n        Position memory position = positions[trader];\n        bool isNewPosition = position.size == 0 ? true : false;\n        Side side = baseAssetQuantity > 0 ? Side.LONG : Side.SHORT;\n        if (isNewPosition || (position.size > 0 ? Side.LONG : Side.SHORT) == side) {\n            // realizedPnl = 0;\n            quoteAsset = _increasePosition(trader, baseAssetQuantity, quoteAssetLimit);\n            isPositionIncreased = true;\n        } else {\n            (realizedPnl, quoteAsset, isPositionIncreased) = _openReversePosition(trader, baseAssetQuantity, quoteAssetLimit);\n        }\n        _emitPositionChanged(trader, realizedPnl);\n    }\n\n    function liquidatePosition(address trader)\n        override\n        external\n        onlyClearingHouse\n        returns (int realizedPnl, uint quoteAsset)\n    {\n        // don't need an ammState check because there should be no active positions\n        Position memory position = positions[trader];\n        bool isLongPosition = position.size > 0 ? true : false;\n        // sending market orders can fk the trader. @todo put some safe guards around price of liquidations\n        if (isLongPosition) {\n            (realizedPnl, quoteAsset) = _reducePosition(trader, -position.size, 0);\n        } else {\n            (realizedPnl, quoteAsset) = _reducePosition(trader, -position.size, type(uint).max);\n        }\n        _emitPositionChanged(trader, realizedPnl);\n    }\n\n    function updatePosition(address trader)\n        override\n        external\n        onlyClearingHouse\n        returns(int256 fundingPayment)\n    {\n        if (ammState != AMMState.Active) return 0;\n        (\n            int256 takerFundingPayment,\n            int256 makerFundingPayment,\n            int256 latestCumulativePremiumFraction,\n            int256 latestPremiumPerDtoken\n        ) = getPendingFundingPayment(trader);\n\n        Position storage position = positions[trader];\n        position.lastPremiumFraction = latestCumulativePremiumFraction;\n\n        Maker storage maker = makers[trader];\n        maker.lastPremiumFraction = latestCumulativePremiumFraction;\n        maker.lastPremiumPerDtoken = latestPremiumPerDtoken;\n\n        emit FundingPaid(trader, position.size, takerFundingPayment, makerFundingPayment, latestCumulativePremiumFraction, latestPremiumPerDtoken);\n\n        // +: trader paid, -: trader received\n        fundingPayment = takerFundingPayment + makerFundingPayment;\n        if (fundingPayment < 0) {\n            fundingPayment -= fundingPayment / 1e3; // receivers charged 0.1% to account for rounding-offs\n        }\n    }\n\n    function addLiquidity(address maker, uint baseAssetQuantity, uint minDToken)\n        override\n        external\n        onlyClearingHouse\n    {\n        require(ammState != AMMState.Inactive, \"AMM.addLiquidity.amm_inactive\");\n        uint quoteAsset;\n        uint baseAssetBal = vamm.balances(1);\n        if (baseAssetBal == 0) {\n            quoteAsset = baseAssetQuantity * vamm.price_scale() / 1e30;\n        } else {\n            quoteAsset = baseAssetQuantity * vamm.balances(0) / baseAssetBal;\n        }\n\n        uint _dToken = vamm.add_liquidity([quoteAsset, baseAssetQuantity], minDToken);\n\n        // updates\n        Maker storage _maker = makers[maker];\n        if (_maker.dToken > 0) { // Maker only accumulates position when they had non-zero liquidity\n            _maker.pos += (posAccumulator - _maker.posAccumulator) * _maker.dToken.toInt256() / 1e18;\n        }\n        _maker.vUSD += quoteAsset;\n        _maker.vAsset += baseAssetQuantity;\n        _maker.dToken += _dToken;\n        _maker.posAccumulator = posAccumulator;\n        emit LiquidityAdded(maker, _dToken, baseAssetQuantity, quoteAsset, _blockTimestamp());\n    }\n\n    function removeLiquidity(address maker, uint amount, uint minQuote, uint minBase)\n        override\n        external\n        onlyClearingHouse\n        returns (int256 /* realizedPnl */, uint /* quoteAsset */)\n    {\n        Maker memory _maker = makers[maker];\n        if (_maker.dToken == 0) {\n            return (0,0);\n        }\n\n        Position memory _taker = positions[maker];\n        // amount <= _maker.dToken will be asserted when updating maker.dToken\n        (\n            int256 makerPosition,\n            uint256 totalOpenNotional,\n            int256 feeAdjustedPnl,\n            uint[2] memory dBalances\n        ) = vamm.remove_liquidity(\n            amount,\n            [minQuote /* minimum QuoteAsset amount */, minBase /* minimum BaseAsset amount */],\n            _maker.vUSD,\n            _maker.vAsset,\n            _maker.dToken,\n            _taker.size,\n            _taker.openNotional\n        );\n\n        {\n            // update maker info\n            Maker storage __maker = makers[maker];\n            uint diff = _maker.dToken - amount;\n\n            if (diff == 0) {\n                __maker.pos = 0;\n                __maker.vAsset = 0;\n                __maker.vUSD = 0;\n                __maker.dToken = 0;\n            } else {\n                // muitiply by diff because a taker position will also be opened while removing liquidity and its funding payment is calculated seperately\n                __maker.pos = _maker.pos + (posAccumulator - _maker.posAccumulator) * diff.toInt256() / 1e18;\n                __maker.vAsset = _maker.vAsset * diff / _maker.dToken;\n                __maker.vUSD = _maker.vUSD * diff / _maker.dToken;\n                __maker.dToken = diff;\n            }\n            __maker.posAccumulator = posAccumulator;\n        }\n\n        int256 realizedPnl = feeAdjustedPnl;\n        {\n            if (makerPosition != 0) {\n                // translate impermanent position to a permanent one\n                Position storage position = positions[maker];\n                if (makerPosition * position.size < 0) { // reducing or reversing position\n                    uint newNotional = getCloseQuote(position.size + makerPosition);\n                    int256 reducePositionPnl = _getPnlWhileReducingPosition(position.size, position.openNotional, makerPosition, newNotional);\n                    realizedPnl += reducePositionPnl;\n                }\n                position.openNotional = totalOpenNotional;\n                position.size += makerPosition;\n\n                // update long and short open interest notional\n                if (makerPosition > 0) {\n                    longOpenInterestNotional += makerPosition.toUint256();\n                } else {\n                    shortOpenInterestNotional += (-makerPosition).toUint256();\n                }\n            }\n        }\n\n        emit LiquidityRemoved(maker, amount, dBalances[1] /** baseAsset */,\n            dBalances[0] /** quoteAsset */, _blockTimestamp(), realizedPnl);\n        return (realizedPnl, dBalances[0]);\n    }\n\n\n    function getOpenNotionalWhileReducingPosition(\n        int256 positionSize,\n        uint256 newNotionalPosition,\n        int256 unrealizedPnl,\n        int256 baseAssetQuantity\n    )\n        override\n        public\n        pure\n        returns(uint256 remainOpenNotional, int realizedPnl)\n    {\n        require(abs(positionSize) >= abs(baseAssetQuantity), \"AMM.ONLY_REDUCE_POS\");\n        bool isLongPosition = positionSize > 0 ? true : false;\n\n        realizedPnl = unrealizedPnl * abs(baseAssetQuantity) / abs(positionSize);\n        int256 unrealizedPnlAfter = unrealizedPnl - realizedPnl;\n\n        /**\n        * We need to determine the openNotional value of the reduced position now.\n        * We know notionalPosition and unrealizedPnlAfter (unrealizedPnl times the ratio of open position)\n        * notionalPosition = notionalPosition - quoteAsset (exchangedQuoteAssetAmount)\n        * calculate openNotional (it's different depends on long or short side)\n        * long: unrealizedPnl = notionalPosition - openNotional => openNotional = notionalPosition - unrealizedPnl\n        * short: unrealizedPnl = openNotional - notionalPosition => openNotional = notionalPosition + unrealizedPnl\n        */\n        if (isLongPosition) {\n            /**\n            * Let baseAssetQuantity = Q, position.size = size, by definition of _reducePosition, abs(size) >= abs(Q)\n            * quoteAsset = notionalPosition * Q / size\n            * unrealizedPnlAfter = unrealizedPnl - realizedPnl = unrealizedPnl - unrealizedPnl * Q / size\n            * remainOpenNotional = notionalPosition - notionalPosition * Q / size - unrealizedPnl + unrealizedPnl * Q / size\n            * => remainOpenNotional = notionalPosition(size-Q)/size - unrealizedPnl(size-Q)/size\n            * => remainOpenNotional = (notionalPosition - unrealizedPnl) * (size-Q)/size\n            * Since notionalPosition includes the PnL component, notionalPosition >= unrealizedPnl and size >= Q\n            * Hence remainOpenNotional >= 0\n            */\n            remainOpenNotional = (newNotionalPosition.toInt256() - unrealizedPnlAfter).toUint256();  // will assert that remainOpenNotional >= 0\n        } else {\n            /**\n            * Let baseAssetQuantity = Q, position.size = size, by definition of _reducePosition, abs(size) >= abs(Q)\n            * quoteAsset = notionalPosition * Q / size\n            * unrealizedPnlAfter = unrealizedPnl - realizedPnl = unrealizedPnl - unrealizedPnl * Q / size\n            * remainOpenNotional = notionalPosition - notionalPosition * Q / size + unrealizedPnl - unrealizedPnl * Q / size\n            * => remainOpenNotional = notionalPosition(size-Q)/size + unrealizedPnl(size-Q)/size\n            * => remainOpenNotional = (notionalPosition + unrealizedPnl) * (size-Q)/size\n            * => In AMM.sol, unrealizedPnl = position.openNotional - notionalPosition\n            * => notionalPosition + unrealizedPnl >= 0\n            * Hence remainOpenNotional >= 0\n            */\n            remainOpenNotional = (newNotionalPosition.toInt256() + unrealizedPnlAfter).toUint256();  // will assert that remainOpenNotional >= 0\n        }\n    }\n\n    /**\n     * @notice update funding rate\n     * @dev only allow to update while reaching `nextFundingTime`\n     */\n    function settleFunding()\n        override\n        external\n        onlyClearingHouse\n    {\n        if (ammState != AMMState.Active) return;\n        require(_blockTimestamp() >= nextFundingTime, \"settle funding too early\");\n\n        // premium = twapMarketPrice - twapIndexPrice\n        // timeFraction = fundingPeriod(1 hour) / 1 day\n        // premiumFraction = premium * timeFraction\n        int256 underlyingPrice = getUnderlyingTwapPrice(spotPriceTwapInterval);\n        int256 premium = getTwapPrice(spotPriceTwapInterval) - underlyingPrice;\n        int256 premiumFraction = (premium * int256(fundingPeriod)) / 1 days;\n\n        // update funding rate = premiumFraction / twapIndexPrice\n        _updateFundingRate(premiumFraction, underlyingPrice);\n\n        int256 premiumPerDtoken = posAccumulator * premiumFraction;\n\n        // makers pay slightly more to account for rounding off\n        premiumPerDtoken = (premiumPerDtoken / BASE_PRECISION) + 1;\n\n        cumulativePremiumFraction += premiumFraction;\n        cumulativePremiumPerDtoken += premiumPerDtoken;\n\n        // Updates for next funding event\n        // in order to prevent multiple funding settlement during very short time after network congestion\n        uint256 minNextValidFundingTime = _blockTimestamp() + fundingBufferPeriod;\n\n        // floor((nextFundingTime + fundingPeriod) / 3600) * 3600\n        uint256 nextFundingTimeOnHourStart = ((nextFundingTime + fundingPeriod) / 1 hours) * 1 hours;\n\n        // max(nextFundingTimeOnHourStart, minNextValidFundingTime)\n        nextFundingTime = nextFundingTimeOnHourStart > minNextValidFundingTime\n            ? nextFundingTimeOnHourStart\n            : minNextValidFundingTime;\n    }\n\n    // View\n\n    function getSnapshotLen() external view returns (uint256) {\n        return reserveSnapshots.length;\n    }\n\n    function getUnderlyingTwapPrice(uint256 _intervalInSeconds) public view returns (int256) {\n        return oracle.getUnderlyingTwapPrice(underlyingAsset, _intervalInSeconds);\n    }\n\n    function getTwapPrice(uint256 _intervalInSeconds) public view returns (int256) {\n        return int256(_calcTwap(_intervalInSeconds));\n    }\n\n    function getNotionalPositionAndUnrealizedPnl(address trader)\n        override\n        external\n        view\n        returns(uint256 notionalPosition, int256 unrealizedPnl, int256 size, uint256 openNotional)\n    {\n        Position memory _taker = positions[trader];\n        Maker memory _maker = makers[trader];\n\n        (notionalPosition, size, unrealizedPnl, openNotional) = vamm.get_notional(\n            _maker.dToken,\n            _maker.vUSD,\n            _maker.vAsset,\n            _taker.size,\n            _taker.openNotional\n        );\n    }\n\n    function getPendingFundingPayment(address trader)\n        override\n        public\n        view\n        returns(\n            int256 takerFundingPayment,\n            int256 makerFundingPayment,\n            int256 latestCumulativePremiumFraction,\n            int256 latestPremiumPerDtoken\n        )\n    {\n        latestCumulativePremiumFraction = cumulativePremiumFraction;\n        Position memory taker = positions[trader];\n\n        takerFundingPayment = (latestCumulativePremiumFraction - taker.lastPremiumFraction)\n            * taker.size\n            / BASE_PRECISION;\n\n        // Maker funding payment\n        latestPremiumPerDtoken = cumulativePremiumPerDtoken;\n\n        Maker memory maker = makers[trader];\n        int256 dToken = maker.dToken.toInt256();\n        if (dToken > 0) {\n            int256 cpf = latestCumulativePremiumFraction - maker.lastPremiumFraction;\n            makerFundingPayment = (\n                maker.pos * cpf +\n                (\n                    latestPremiumPerDtoken\n                    - maker.lastPremiumPerDtoken\n                    - maker.posAccumulator * cpf / BASE_PRECISION\n                ) * dToken\n            ) / BASE_PRECISION;\n        }\n    }\n\n    function getCloseQuote(int256 baseAssetQuantity) override public view returns(uint256 quoteAssetQuantity) {\n        if (baseAssetQuantity > 0) {\n            return vamm.get_dy(1, 0, baseAssetQuantity.toUint256());\n        } else if (baseAssetQuantity < 0) {\n            return vamm.get_dx(0, 1, (-baseAssetQuantity).toUint256());\n        }\n        return 0;\n    }\n\n    function getTakerNotionalPositionAndUnrealizedPnl(address trader) override public view returns(uint takerNotionalPosition, int256 unrealizedPnl) {\n        Position memory position = positions[trader];\n        if (position.size > 0) {\n            takerNotionalPosition = vamm.get_dy(1, 0, position.size.toUint256());\n            unrealizedPnl = takerNotionalPosition.toInt256() - position.openNotional.toInt256();\n        } else if (position.size < 0) {\n            takerNotionalPosition = vamm.get_dx(0, 1, (-position.size).toUint256());\n            unrealizedPnl = position.openNotional.toInt256() - takerNotionalPosition.toInt256();\n        }\n    }\n\n    function lastPrice() external view returns(uint256) {\n        return vamm.last_prices() / 1e12;\n    }\n\n    function openInterestNotional() public view returns (uint256) {\n        return longOpenInterestNotional + shortOpenInterestNotional;\n    }\n\n    // internal\n\n    /**\n    * @dev Go long on an asset\n    * @param baseAssetQuantity Exact base asset quantity to go long\n    * @param max_dx Maximum amount of quote asset to be used while longing baseAssetQuantity. Lower means longing at a lower price (desirable).\n    * @return quoteAssetQuantity quote asset utilised. quoteAssetQuantity / baseAssetQuantity was the average rate.\n      quoteAssetQuantity <= max_dx\n    */\n    function _long(int256 baseAssetQuantity, uint max_dx) internal returns (uint256 quoteAssetQuantity) {\n        require(baseAssetQuantity > 0, \"VAMM._long: baseAssetQuantity is <= 0\");\n\n        uint _lastPrice;\n        (quoteAssetQuantity, _lastPrice) = vamm.exchangeExactOut(\n            0, // sell quote asset\n            1, // purchase base asset\n            baseAssetQuantity.toUint256(), // long exactly. Note that statement asserts that baseAssetQuantity >= 0\n            max_dx\n        ); // 6 decimals precision\n\n        _addReserveSnapshot(_lastPrice);\n        // since maker position will be opposite of the trade\n        posAccumulator -= baseAssetQuantity * 1e18 / vamm.totalSupply().toInt256();\n        emit Swap(baseAssetQuantity, quoteAssetQuantity, _lastPrice, openInterestNotional());\n    }\n\n    /**\n    * @dev Go short on an asset\n    * @param baseAssetQuantity Exact base asset quantity to short\n    * @param min_dy Minimum amount of quote asset to be used while shorting baseAssetQuantity. Higher means shorting at a higher price (desirable).\n    * @return quoteAssetQuantity quote asset utilised. quoteAssetQuantity / baseAssetQuantity was the average short rate.\n      quoteAssetQuantity >= min_dy.\n    */\n    function _short(int256 baseAssetQuantity, uint min_dy) internal returns (uint256 quoteAssetQuantity) {\n        require(baseAssetQuantity < 0, \"VAMM._short: baseAssetQuantity is >= 0\");\n\n        uint _lastPrice;\n        (quoteAssetQuantity, _lastPrice) = vamm.exchange(\n            1, // sell base asset\n            0, // get quote asset\n            (-baseAssetQuantity).toUint256(), // short exactly. Note that statement asserts that baseAssetQuantity <= 0\n            min_dy\n        );\n\n        _addReserveSnapshot(_lastPrice);\n        // since maker position will be opposite of the trade\n        posAccumulator -= baseAssetQuantity * 1e18 / vamm.totalSupply().toInt256();\n        emit Swap(baseAssetQuantity, quoteAssetQuantity, _lastPrice, openInterestNotional());\n    }\n\n    function _emitPositionChanged(address trader, int256 realizedPnl) internal {\n        Position memory position = positions[trader];\n        emit PositionChanged(trader, position.size, position.openNotional, realizedPnl);\n    }\n\n    // @dev check takerPosition != 0 before calling\n    function _getPnlWhileReducingPosition(\n        int256 takerPosition,\n        uint takerOpenNotional,\n        int256 makerPosition,\n        uint newNotional\n    ) internal pure returns (int256 pnlToBeRealized) {\n        /**\n            makerNotional = newNotional * makerPos / totalPos\n            if (side remains same)\n                reducedOpenNotional = takerOpenNotional * makerPos / takerPos\n                pnl = makerNotional - reducedOpenNotional\n            else (reverse position)\n                closedPositionNotional = newNotional * takerPos / totalPos\n                pnl = closePositionNotional - takerOpenNotional\n         */\n\n        uint totalPosition = abs(makerPosition + takerPosition).toUint256();\n        if (abs(takerPosition) > abs(makerPosition)) { // taker position side remains same\n            uint reducedOpenNotional = takerOpenNotional * abs(makerPosition).toUint256() / abs(takerPosition).toUint256();\n            uint makerNotional = newNotional * abs(makerPosition).toUint256() / totalPosition;\n            pnlToBeRealized = _getPnlToBeRealized(takerPosition, makerNotional, reducedOpenNotional);\n        } else { // taker position side changes\n            // @todo handle case when totalPosition = 0\n            uint closedPositionNotional = newNotional * abs(takerPosition).toUint256() / totalPosition;\n            pnlToBeRealized = _getPnlToBeRealized(takerPosition, closedPositionNotional, takerOpenNotional);\n        }\n    }\n\n    function _getPnlToBeRealized(int256 takerPosition, uint notionalPosition, uint openNotional) internal pure returns (int256 pnlToBeRealized) {\n        if (takerPosition > 0) {\n            pnlToBeRealized = notionalPosition.toInt256() - openNotional.toInt256();\n        } else {\n            pnlToBeRealized = openNotional.toInt256() - notionalPosition.toInt256();\n        }\n    }\n\n    function _increasePosition(address trader, int256 baseAssetQuantity, uint quoteAssetLimit)\n        internal\n        returns(uint quoteAsset)\n    {\n        if (baseAssetQuantity > 0) { // Long - purchase baseAssetQuantity\n            longOpenInterestNotional += baseAssetQuantity.toUint256();\n            quoteAsset = _long(baseAssetQuantity, quoteAssetLimit);\n        } else { // Short - sell baseAssetQuantity\n            shortOpenInterestNotional += (-baseAssetQuantity).toUint256();\n            quoteAsset = _short(baseAssetQuantity, quoteAssetLimit);\n        }\n        positions[trader].size += baseAssetQuantity; // -ve baseAssetQuantity will increase short position\n        positions[trader].openNotional += quoteAsset;\n    }\n\n    function _openReversePosition(address trader, int256 baseAssetQuantity, uint quoteAssetLimit)\n        internal\n        returns (int realizedPnl, uint quoteAsset, bool isPositionIncreased)\n    {\n        Position memory position = positions[trader];\n        if (abs(position.size) >= abs(baseAssetQuantity)) {\n            (realizedPnl, quoteAsset) = _reducePosition(trader, baseAssetQuantity, quoteAssetLimit);\n        } else {\n            uint closedRatio = (quoteAssetLimit * abs(position.size).toUint256()) / abs(baseAssetQuantity).toUint256();\n            (realizedPnl, quoteAsset) = _reducePosition(trader, -position.size, closedRatio);\n\n            // this is required because the user might pass a very less value (slippage-prone) while shorting\n            if (quoteAssetLimit >= quoteAsset) {\n                quoteAssetLimit -= quoteAsset;\n            }\n            quoteAsset += _increasePosition(trader, baseAssetQuantity + position.size, quoteAssetLimit);\n            isPositionIncreased = true;\n        }\n    }\n\n    /**\n    * @dev validate that baseAssetQuantity <= position.size should be performed before the call to _reducePosition\n    */\n    function _reducePosition(address trader, int256 baseAssetQuantity, uint quoteAssetLimit)\n        internal\n        returns (int realizedPnl, uint256 quoteAsset)\n    {\n        (, int256 unrealizedPnl) = getTakerNotionalPositionAndUnrealizedPnl(trader);\n\n        Position storage position = positions[trader]; // storage because there are updates at the end\n        bool isLongPosition = position.size > 0 ? true : false;\n\n        if (isLongPosition) {\n            longOpenInterestNotional -= (-baseAssetQuantity).toUint256();\n            quoteAsset = _short(baseAssetQuantity, quoteAssetLimit);\n        } else {\n            shortOpenInterestNotional -= baseAssetQuantity.toUint256();\n            quoteAsset = _long(baseAssetQuantity, quoteAssetLimit);\n        }\n        uint256 notionalPosition = getCloseQuote(position.size + baseAssetQuantity);\n        (position.openNotional, realizedPnl) = getOpenNotionalWhileReducingPosition(position.size, notionalPosition, unrealizedPnl, baseAssetQuantity);\n        position.size += baseAssetQuantity;\n    }\n\n    function _addReserveSnapshot(uint256 price)\n        internal\n    {\n        uint256 currentBlock = block.number;\n        uint256 blockTimestamp = _blockTimestamp();\n\n        if (reserveSnapshots.length == 0) {\n            reserveSnapshots.push(\n                ReserveSnapshot(price, blockTimestamp, currentBlock)\n            );\n            return;\n        }\n\n        ReserveSnapshot storage latestSnapshot = reserveSnapshots[reserveSnapshots.length - 1];\n        // update values in snapshot if in the same block\n        if (currentBlock == latestSnapshot.blockNumber) {\n            latestSnapshot.lastPrice = price;\n        } else {\n            reserveSnapshots.push(\n                ReserveSnapshot(price, blockTimestamp, currentBlock)\n            );\n        }\n    }\n\n    function _blockTimestamp() internal view virtual returns (uint256) {\n        return block.timestamp;\n    }\n\n    function _calcTwap(uint256 _intervalInSeconds)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 snapshotIndex = reserveSnapshots.length - 1;\n        uint256 currentPrice = reserveSnapshots[snapshotIndex].lastPrice;\n        if (_intervalInSeconds == 0) {\n            return currentPrice;\n        }\n\n        uint256 baseTimestamp = _blockTimestamp() - _intervalInSeconds;\n        ReserveSnapshot memory currentSnapshot = reserveSnapshots[snapshotIndex];\n        // return the latest snapshot price directly\n        // if only one snapshot or the timestamp of latest snapshot is earlier than asking for\n        if (reserveSnapshots.length == 1 || currentSnapshot.timestamp <= baseTimestamp) {\n            return currentPrice;\n        }\n\n        uint256 previousTimestamp = currentSnapshot.timestamp;\n        uint256 period = _blockTimestamp() - previousTimestamp;\n        uint256 weightedPrice = currentPrice * period;\n        while (true) {\n            // if snapshot history is too short\n            if (snapshotIndex == 0) {\n                return weightedPrice / period;\n            }\n\n            snapshotIndex = snapshotIndex - 1;\n            currentSnapshot = reserveSnapshots[snapshotIndex];\n            currentPrice = reserveSnapshots[snapshotIndex].lastPrice;\n\n            // check if current round timestamp is earlier than target timestamp\n            if (currentSnapshot.timestamp <= baseTimestamp) {\n                // weighted time period will be (target timestamp - previous timestamp). For example,\n                // now is 1000, _interval is 100, then target timestamp is 900. If timestamp of current round is 970,\n                // and timestamp of NEXT round is 880, then the weighted time period will be (970 - 900) = 70,\n                // instead of (970 - 880)\n                weightedPrice = weightedPrice + (currentPrice * (previousTimestamp - baseTimestamp));\n                break;\n            }\n\n            uint256 timeFraction = previousTimestamp - currentSnapshot.timestamp;\n            weightedPrice = weightedPrice + (currentPrice * timeFraction);\n            period = period + timeFraction;\n            previousTimestamp = currentSnapshot.timestamp;\n        }\n        return weightedPrice / _intervalInSeconds;\n    }\n\n    function _updateFundingRate(\n        int256 _premiumFraction,\n        int256 _underlyingPrice\n    ) internal {\n        fundingRate = _premiumFraction * 1e6 / _underlyingPrice;\n        emit FundingRateUpdated(_premiumFraction, fundingRate, _underlyingPrice.toUint256(), _blockTimestamp(), block.number);\n    }\n\n    // Pure\n\n    function abs(int x) private pure returns (int) {\n        return x >= 0 ? x : -x;\n    }\n\n    // Governance\n\n    function setAmmState(AMMState _state) external onlyGovernance {\n        require(ammState != _state, \"AMM.setAmmState.sameState\");\n        ammState = _state;\n        if (_state == AMMState.Active) {\n            nextFundingTime = ((_blockTimestamp() + fundingPeriod) / 1 hours) * 1 hours;\n        }\n    }\n\n    function syncDeps(address _registry) public onlyGovernance {\n        IRegistry registry = IRegistry(_registry);\n        clearingHouse = registry.clearingHouse();\n        oracle = IOracle(registry.oracle());\n    }\n\n    function setFundingBufferPeriod(uint _fundingBufferPeriod) external onlyGovernance {\n        fundingBufferPeriod = _fundingBufferPeriod;\n    }\n}"
}