{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/ClearingHouse.sol",
    "Parent Contracts": [
        "contracts/legos/HubbleBase.sol",
        "node_modules/@openzeppelin/contracts/metatx/ERC2771Context.sol",
        "node_modules/@openzeppelin/contracts/security/Pausable.sol",
        "node_modules/@openzeppelin/contracts/utils/Context.sol",
        "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 ClearingHouse is IClearingHouse, HubbleBase {\n    using SafeCast for uint256;\n    using SafeCast for int256;\n\n    uint256 constant PRECISION = 1e6;\n\n    int256 override public maintenanceMargin;\n    uint override public tradeFee;\n    uint override public liquidationPenalty;\n    int256 public minAllowableMargin;\n\n    VUSD public vusd;\n    IInsuranceFund public insuranceFund;\n    IMarginAccount public marginAccount;\n    IAMM[] override public amms;\n\n    uint256[50] private __gap;\n\n    event PositionModified(address indexed trader, uint indexed idx, int256 baseAsset, uint quoteAsset, uint256 timestamp);\n    event PositionLiquidated(address indexed trader, uint indexed idx, int256 baseAsset, uint256 quoteAsset, uint256 timestamp);\n    event MarketAdded(uint indexed idx, address indexed amm);\n\n    constructor(address _trustedForwarder) HubbleBase(_trustedForwarder) {}\n\n    function initialize(\n        address _governance,\n        address _insuranceFund,\n        address _marginAccount,\n        address _vusd,\n        int256 _maintenanceMargin,\n        int256 _minAllowableMargin,\n        uint _tradeFee,\n        uint _liquidationPenalty\n    ) external initializer {\n        _setGovernace(_governance);\n\n        insuranceFund = IInsuranceFund(_insuranceFund);\n        marginAccount = IMarginAccount(_marginAccount);\n        vusd = VUSD(_vusd);\n\n        require(_maintenanceMargin > 0, \"_maintenanceMargin < 0\");\n        maintenanceMargin = _maintenanceMargin;\n        minAllowableMargin = _minAllowableMargin;\n        tradeFee = _tradeFee;\n        liquidationPenalty = _liquidationPenalty;\n    }\n\n    /**\n    * @notice Open/Modify/Close Position\n    * @param idx AMM index\n    * @param baseAssetQuantity Quantity of the base asset to Long (baseAssetQuantity > 0) or Short (baseAssetQuantity < 0)\n    * @param quoteAssetLimit Rate at which the trade is executed in the AMM. Used to cap slippage.\n    */\n    function openPosition(uint idx, int256 baseAssetQuantity, uint quoteAssetLimit) override external whenNotPaused {\n        _openPosition(_msgSender(), idx, baseAssetQuantity, quoteAssetLimit);\n    }\n\n    function closePosition(uint idx, uint quoteAssetLimit) override external whenNotPaused {\n        address trader = _msgSender();\n        (int256 size,,) = amms[idx].positions(trader);\n        _openPosition(trader, idx, -size, quoteAssetLimit);\n    }\n\n    function _openPosition(address trader, uint idx, int256 baseAssetQuantity, uint quoteAssetLimit) internal {\n        require(baseAssetQuantity != 0, \"CH: baseAssetQuantity == 0\");\n\n        updatePositions(trader); // adjust funding payments\n\n        (int realizedPnl, uint quoteAsset, bool isPositionIncreased) = amms[idx].openPosition(trader, baseAssetQuantity, quoteAssetLimit);\n        uint _tradeFee = _chargeFeeAndRealizePnL(trader, realizedPnl, quoteAsset, false /* isLiquidation */);\n        marginAccount.transferOutVusd(address(insuranceFund), _tradeFee);\n\n        if (isPositionIncreased) {\n            require(isAboveMinAllowableMargin(trader), \"CH: Below Minimum Allowable Margin\");\n        }\n        emit PositionModified(trader, idx, baseAssetQuantity, quoteAsset, _blockTimestamp());\n    }\n\n    /**\n    * @notice Add liquidity to the amm. The free margin from margin account is utilized for the same\n    *   The liquidity can be provided on leverage.\n    * @param idx Index of the AMM\n    * @param baseAssetQuantity Amount of the asset to add to AMM. Equivalent amount of USD side is automatically added.\n    *   This means that user is actually adding 2 * baseAssetQuantity * markPrice.\n    * @param minDToken Min amount of dTokens to receive. Used to cap slippage.\n    */\n    function addLiquidity(uint idx, uint256 baseAssetQuantity, uint minDToken) override external whenNotPaused {\n        address maker = _msgSender();\n        updatePositions(maker);\n        amms[idx].addLiquidity(maker, baseAssetQuantity, minDToken);\n        require(isAboveMinAllowableMargin(maker), \"CH: Below Minimum Allowable Margin\");\n    }\n\n    /**\n    * @notice Remove liquidity from the amm.\n    * @param idx Index of the AMM\n    * @param dToken Measure of the liquidity to remove.\n    * @param minQuoteValue Min amount of USD to remove.\n    * @param minBaseValue Min amount of base to remove.\n    *   Both the above params enable capping slippage in either direction.\n    */\n    function removeLiquidity(uint idx, uint256 dToken, uint minQuoteValue, uint minBaseValue) override external whenNotPaused {\n        address maker = _msgSender();\n        updatePositions(maker);\n        (int256 realizedPnl,) = amms[idx].removeLiquidity(maker, dToken, minQuoteValue, minBaseValue);\n        marginAccount.realizePnL(maker, realizedPnl);\n    }\n\n    function updatePositions(address trader) override public whenNotPaused {\n        require(address(trader) != address(0), 'CH: 0x0 trader Address');\n        int256 fundingPayment;\n        for (uint i = 0; i < amms.length; i++) {\n            fundingPayment += amms[i].updatePosition(trader);\n        }\n        // -ve fundingPayment means trader should receive funds\n        marginAccount.realizePnL(trader, -fundingPayment);\n    }\n\n    function settleFunding() override external whenNotPaused {\n        for (uint i = 0; i < amms.length; i++) {\n            amms[i].settleFunding();\n        }\n    }\n\n    /* ****************** */\n    /*    Liquidations    */\n    /* ****************** */\n\n    function liquidate(address trader) override external whenNotPaused {\n        updatePositions(trader);\n        if (isMaker(trader)) {\n            _liquidateMaker(trader);\n        } else {\n            _liquidateTaker(trader);\n        }\n    }\n\n    function liquidateMaker(address maker) override public whenNotPaused {\n        updatePositions(maker);\n        _liquidateMaker(maker);\n    }\n\n    function liquidateTaker(address trader) override public whenNotPaused {\n        require(!isMaker(trader), 'CH: Remove Liquidity First');\n        updatePositions(trader);\n        _liquidateTaker(trader);\n    }\n\n    /* ********************* */\n    /* Liquidations Internal */\n    /* ********************* */\n\n    function _liquidateMaker(address maker) internal {\n        require(\n            _calcMarginFraction(maker, false) < maintenanceMargin,\n            \"CH: Above Maintenance Margin\"\n        );\n        int256 realizedPnl;\n        uint quoteAsset;\n        for (uint i = 0; i < amms.length; i++) {\n            (,, uint dToken,,,,) = amms[i].makers(maker);\n            // @todo put checks on slippage\n            (int256 _realizedPnl, uint _quote) = amms[i].removeLiquidity(maker, dToken, 0, 0);\n            realizedPnl += _realizedPnl;\n            quoteAsset += _quote;\n        }\n\n        _disperseLiquidationFee(\n            _chargeFeeAndRealizePnL(\n                maker,\n                realizedPnl,\n                2 * quoteAsset,  // total liquidity value = 2 * quote value\n                true // isLiquidation\n            )\n        );\n    }\n\n    function _liquidateTaker(address trader) internal {\n        require(_calcMarginFraction(trader, false /* check funding payments again */) < maintenanceMargin, \"Above Maintenance Margin\");\n        int realizedPnl;\n        uint quoteAsset;\n        int256 size;\n        IAMM _amm;\n        for (uint i = 0; i < amms.length; i++) { // liquidate all positions\n            _amm = amms[i];\n            (size,,) = _amm.positions(trader);\n            if (size != 0) {\n                (int _realizedPnl, uint _quoteAsset) = _amm.liquidatePosition(trader);\n                realizedPnl += _realizedPnl;\n                quoteAsset += _quoteAsset;\n                emit PositionLiquidated(trader, i, size, _quoteAsset, _blockTimestamp());\n            }\n        }\n\n        _disperseLiquidationFee(\n            _chargeFeeAndRealizePnL(trader, realizedPnl, quoteAsset, true /* isLiquidation */)\n        );\n    }\n\n    function _disperseLiquidationFee(uint liquidationFee) internal {\n        if (liquidationFee > 0) {\n            uint toInsurance = liquidationFee / 2;\n            marginAccount.transferOutVusd(address(insuranceFund), toInsurance);\n            marginAccount.transferOutVusd(_msgSender(), liquidationFee - toInsurance);\n        }\n    }\n\n    function _chargeFeeAndRealizePnL(\n        address trader,\n        int realizedPnl,\n        uint quoteAsset,\n        bool isLiquidation\n    )\n        internal\n        returns (uint fee)\n    {\n        fee = isLiquidation ? _calculateLiquidationPenalty(quoteAsset) : _calculateTradeFee(quoteAsset);\n        int256 marginCharge = realizedPnl - fee.toInt256();\n        if (marginCharge != 0) {\n            marginAccount.realizePnL(trader, marginCharge);\n        }\n    }\n\n    /* ****************** */\n    /*        View        */\n    /* ****************** */\n\n    function isAboveMaintenanceMargin(address trader) override external view returns(bool) {\n        return getMarginFraction(trader) >= maintenanceMargin;\n    }\n\n    function isAboveMinAllowableMargin(address trader) override public view returns(bool) {\n        return getMarginFraction(trader) >= minAllowableMargin;\n    }\n\n    function getMarginFraction(address trader) override public view returns(int256) {\n        return _calcMarginFraction(trader, true /* includeFundingPayments */);\n    }\n\n    function isMaker(address trader) override public view returns(bool) {\n        for (uint i = 0; i < amms.length; i++) {\n            (,, uint dToken,,,,) = amms[i].makers(trader);\n            if (dToken > 0) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    function getTotalFunding(address trader) override public view returns(int256 totalFunding) {\n        int256 takerFundingPayment;\n        int256 makerFundingPayment;\n        for (uint i = 0; i < amms.length; i++) {\n            (takerFundingPayment, makerFundingPayment,,) = amms[i].getPendingFundingPayment(trader);\n            totalFunding += (takerFundingPayment + makerFundingPayment);\n        }\n    }\n\n    function getTotalNotionalPositionAndUnrealizedPnl(address trader)\n        override\n        public\n        view\n        returns(uint256 notionalPosition, int256 unrealizedPnl)\n    {\n        uint256 _notionalPosition;\n        int256 _unrealizedPnl;\n        for (uint i = 0; i < amms.length; i++) {\n            (_notionalPosition, _unrealizedPnl,,) = amms[i].getNotionalPositionAndUnrealizedPnl(trader);\n            notionalPosition += _notionalPosition;\n            unrealizedPnl += _unrealizedPnl;\n        }\n    }\n\n    function getNotionalPositionAndMargin(address trader, bool includeFundingPayments)\n        override\n        public\n        view\n        returns(uint256 notionalPosition, int256 margin)\n    {\n        int256 unrealizedPnl;\n        (notionalPosition, unrealizedPnl) = getTotalNotionalPositionAndUnrealizedPnl(trader);\n        margin = marginAccount.getNormalizedMargin(trader);\n        margin += unrealizedPnl;\n        if (includeFundingPayments) {\n            margin -= getTotalFunding(trader); // -ve fundingPayment means trader should receive funds\n        }\n    }\n\n    function getAmmsLength() override external view returns(uint) {\n        return amms.length;\n    }\n\n    function getAMMs() external view returns (IAMM[] memory) {\n        return amms;\n    }\n\n    /* ****************** */\n    /*   Internal View    */\n    /* ****************** */\n\n    function _calculateTradeFee(uint quoteAsset) internal view returns (uint) {\n        return quoteAsset * tradeFee / PRECISION;\n    }\n\n    function _calculateLiquidationPenalty(uint quoteAsset) internal view returns (uint) {\n        return quoteAsset * liquidationPenalty / PRECISION;\n    }\n\n    function _calcMarginFraction(address trader, bool includeFundingPayments) internal view returns(int256) {\n        (uint256 notionalPosition, int256 margin) = getNotionalPositionAndMargin(trader, includeFundingPayments);\n        return _getMarginFraction(margin, notionalPosition);\n    }\n\n    /* ****************** */\n    /*        Pure        */\n    /* ****************** */\n\n    function _getMarginFraction(int256 accountValue, uint notionalPosition) private pure returns(int256) {\n        if (notionalPosition == 0) {\n            return type(int256).max;\n        }\n        return accountValue * PRECISION.toInt256() / notionalPosition.toInt256();\n    }\n\n    /* ****************** */\n    /*     Governance     */\n    /* ****************** */\n\n    function whitelistAmm(address _amm) external onlyGovernance {\n        emit MarketAdded(amms.length, _amm);\n        amms.push(IAMM(_amm));\n    }\n\n    function setParams(\n        int _maintenanceMargin,\n        int _minAllowableMargin,\n        uint _tradeFee,\n        uint _liquidationPenality\n    ) external onlyGovernance {\n        tradeFee = _tradeFee;\n        liquidationPenalty = _liquidationPenality;\n        maintenanceMargin = _maintenanceMargin;\n        minAllowableMargin = _minAllowableMargin;\n    }\n}"
}