{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/HubbleViewer.sol",
    "Parent Contracts": [
        "contracts/Interfaces.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract HubbleViewer is IHubbleViewer {\n    using SafeCast for uint256;\n    using SafeCast for int256;\n\n    int256 constant PRECISION_INT = 1e6;\n    uint256 constant PRECISION_UINT = 1e6;\n\n    uint constant VUSD_IDX = 0;\n\n    IClearingHouse public immutable clearingHouse;\n    IMarginAccount public immutable marginAccount;\n    address public immutable registry;\n\n    struct Position {\n        int256 size;\n        uint256 openNotional;\n        int256 unrealizedPnl;\n        uint256 avgOpen;\n    }\n\n    /// @dev UI Helper\n    struct MarketInfo {\n        address amm;\n        address underlying;\n    }\n\n    constructor(\n        IClearingHouse _clearingHouse,\n        IMarginAccount _marginAccount,\n        address _registry\n    ) {\n        clearingHouse = _clearingHouse;\n        marginAccount = _marginAccount;\n        registry = _registry;\n    }\n\n    function getMarginFractionAndMakerStatus(address[] calldata traders)\n        external\n        view\n        returns(int256[] memory fractions, bool[] memory isMaker)\n    {\n        uint len = traders.length;\n        fractions = new int256[](len);\n        isMaker = new bool[](len);\n        for (uint i = 0; i < len; i++) {\n            fractions[i] = clearingHouse.getMarginFraction(traders[i]);\n            isMaker[i] = clearingHouse.isMaker(traders[i]);\n        }\n    }\n\n    function getNotionalPositionAndMargin(address[] calldata traders)\n        external\n        view\n        returns(uint256[] memory notionalPositions, int256[] memory margins)\n    {\n        notionalPositions = new uint256[](traders.length);\n        margins = new int256[](traders.length);\n        for (uint i = 0; i < traders.length; i++) {\n            (notionalPositions[i], margins[i]) = clearingHouse.getNotionalPositionAndMargin(traders[i], true /* includeFundingPayments */);\n        }\n    }\n\n    function marginAccountLiquidatationStatus(address[] calldata traders)\n        external\n        view\n        returns(IMarginAccount.LiquidationStatus[] memory isLiquidatable, uint[] memory repayAmount, uint[] memory incentivePerDollar)\n    {\n        isLiquidatable = new IMarginAccount.LiquidationStatus[](traders.length);\n        repayAmount = new uint[](traders.length);\n        incentivePerDollar = new uint[](traders.length);\n        for (uint i = 0; i < traders.length; i++) {\n            (isLiquidatable[i], repayAmount[i], incentivePerDollar[i]) = marginAccount.isLiquidatable(traders[i], true);\n        }\n    }\n\n    /**\n    * @notice Get information about all user positions\n    * @param trader Trader for which information is to be obtained\n    * @return positions in order of amms\n    *   positions[i].size - BaseAssetQuantity amount longed (+ve) or shorted (-ve)\n    *   positions[i].openNotional - $ value of position\n    *   positions[i].unrealizedPnl - in dollars. +ve is profit, -ve if loss\n    *   positions[i].avgOpen - Average $ value at which position was started\n    */\n    function userPositions(address trader) external view returns(Position[] memory positions) {\n        uint l = clearingHouse.getAmmsLength();\n        positions = new Position[](l);\n        for (uint i = 0; i < l; i++) {\n            IAMM amm = clearingHouse.amms(i);\n            (positions[i].size, positions[i].openNotional, ) = amm.positions(trader);\n            if (positions[i].size == 0) {\n                positions[i].unrealizedPnl = 0;\n                positions[i].avgOpen = 0;\n            } else {\n                (,positions[i].unrealizedPnl) = amm.getTakerNotionalPositionAndUnrealizedPnl(trader);\n                positions[i].avgOpen = positions[i].openNotional * 1e18 / _abs(positions[i].size).toUint256();\n            }\n        }\n    }\n\n    /**\n    * @notice Get information about maker's all impermanent positions\n    * @param maker Maker for which information is to be obtained\n    * @return positions in order of amms\n    *   positions[i].size - BaseAssetQuantity amount longed (+ve) or shorted (-ve)\n    *   positions[i].openNotional - $ value of position\n    *   positions[i].unrealizedPnl - in dollars. +ve is profit, -ve if loss\n    *   positions[i].avgOpen - Average $ value at which position was started\n    */\n    function makerPositions(address maker) external view returns(Position[] memory positions) {\n        uint l = clearingHouse.getAmmsLength();\n        positions = new Position[](l);\n        for (uint i = 0; i < l; i++) {\n            (\n                positions[i].size,\n                positions[i].openNotional,\n                positions[i].unrealizedPnl\n            ) = getMakerPositionAndUnrealizedPnl(maker, i);\n            if (positions[i].size == 0) {\n                positions[i].avgOpen = 0;\n            } else {\n                positions[i].avgOpen = positions[i].openNotional * 1e18 / _abs(positions[i].size).toUint256();\n            }\n        }\n    }\n\n    function markets() external view returns(MarketInfo[] memory _markets) {\n        uint l = clearingHouse.getAmmsLength();\n        _markets = new MarketInfo[](l);\n        for (uint i = 0; i < l; i++) {\n            IAMM amm = clearingHouse.amms(i);\n            _markets[i] = MarketInfo(address(amm), amm.underlyingAsset());\n        }\n    }\n\n    /**\n    * Get final margin fraction and liquidation price if user longs/shorts baseAssetQuantity\n    * @param idx AMM Index\n    * @param baseAssetQuantity Positive if long, negative if short, scaled 18 decimals\n    * @return expectedMarginFraction Resultant Margin fraction when the trade is executed\n    * @return quoteAssetQuantity USD rate for the trade\n    * @return liquidationPrice Mark Price at which trader will be liquidated\n    */\n    function getTakerExpectedMFAndLiquidationPrice(address trader, uint idx, int256 baseAssetQuantity)\n        external\n        view\n        returns (int256 expectedMarginFraction, uint256 quoteAssetQuantity, uint256 liquidationPrice)\n    {\n        IAMM amm = clearingHouse.amms(idx);\n        // get quoteAsset required to swap baseAssetQuantity\n        quoteAssetQuantity = getQuote(baseAssetQuantity, idx);\n\n        // get total notionalPosition and margin (including unrealizedPnL and funding)\n        (uint256 notionalPosition, int256 margin) = clearingHouse.getNotionalPositionAndMargin(trader, true /* includeFundingPayments */);\n\n        // get market specific position info\n        (int256 takerPosSize,,) = amm.positions(trader);\n        uint takerNowNotional = amm.getCloseQuote(takerPosSize);\n        uint takerUpdatedNotional = amm.getCloseQuote(takerPosSize + baseAssetQuantity);\n        // Calculate new total notionalPosition\n        notionalPosition = notionalPosition + takerUpdatedNotional - takerNowNotional;\n\n        margin -= _calculateTradeFee(quoteAssetQuantity).toInt256();\n        expectedMarginFraction = _getMarginFraction(margin, notionalPosition);\n        liquidationPrice = _getLiquidationPrice(trader, amm, notionalPosition, margin, baseAssetQuantity, quoteAssetQuantity);\n    }\n\n    /**\n    * Get final margin fraction and liquidation price if user add/remove liquidity\n    * @param idx AMM Index\n    * @param vUSD vUSD amount to be added in the pool (in 6 decimals)\n    * @param isRemove true is liquidity is being removed, false if added\n    * @return expectedMarginFraction Resultant Margin fraction after the tx\n    * @return liquidationPrice Mark Price at which maker will be liquidated\n    */\n    function getMakerExpectedMFAndLiquidationPrice(address trader, uint idx, uint vUSD, bool isRemove)\n        external\n        view\n        returns (int256 expectedMarginFraction, uint256 liquidationPrice)\n    {\n        // get total notionalPosition and margin (including unrealizedPnL and funding)\n        (uint256 notionalPosition, int256 margin) = clearingHouse.getNotionalPositionAndMargin(trader, true /* includeFundingPayments */);\n\n        IAMM amm = clearingHouse.amms(idx);\n\n        // get taker info\n        (int256 takerPosSize,,) = amm.positions(trader);\n        uint takerNotional = amm.getCloseQuote(takerPosSize);\n        // get maker info\n        (uint makerDebt,,,,,,) = amm.makers(trader);\n        // calculate total value of deposited liquidity after the tx\n        if (isRemove) {\n            makerDebt = 2 * (makerDebt - vUSD);\n        } else {\n            makerDebt = 2 * (makerDebt + vUSD);\n        }\n\n        {\n            // calculate effective notionalPosition\n            (int256 makerPosSize,,) = getMakerPositionAndUnrealizedPnl(trader, idx);\n            uint totalPosNotional = amm.getCloseQuote(makerPosSize + takerPosSize);\n            notionalPosition += _max(makerDebt + takerNotional, totalPosNotional);\n        }\n\n        {\n            (uint nowNotional,,,) = amm.getNotionalPositionAndUnrealizedPnl(trader);\n            notionalPosition -= nowNotional;\n        }\n\n        expectedMarginFraction = _getMarginFraction(margin, notionalPosition);\n        liquidationPrice = _getLiquidationPrice(trader, amm, notionalPosition, margin, 0, 0);\n    }\n\n    function getLiquidationPrice(address trader, uint idx) external view returns (uint liquidationPrice) {\n        // get total notionalPosition and margin (including unrealizedPnL and funding)\n        (uint256 notionalPosition, int256 margin) = clearingHouse.getNotionalPositionAndMargin(trader, true /* includeFundingPayments */);\n        IAMM amm = clearingHouse.amms(idx);\n        liquidationPrice = _getLiquidationPrice(trader, amm, notionalPosition, margin, 0, 0);\n    }\n\n    /**\n    * @notice get maker impermanent position and unrealizedPnl for a particular amm\n    * @param _maker maker address\n    * @param idx amm index\n    * @return position Maker's current impermanent position\n    * @return openNotional Position open notional for the current impermanent position inclusive of fee earned\n    * @return unrealizedPnl PnL if maker removes liquidity and closes their impermanent position in the same amm\n    */\n    function getMakerPositionAndUnrealizedPnl(address _maker, uint idx)\n        override\n        public\n        view\n        returns (int256 position, uint openNotional, int256 unrealizedPnl)\n    {\n        IAMM amm = clearingHouse.amms(idx);\n        IVAMM vamm = amm.vamm();\n\n        (uint vUSD, uint vAsset, uint dToken,,,,) = amm.makers(_maker);\n        (position, openNotional, unrealizedPnl) = vamm.get_maker_position(dToken, vUSD, vAsset, dToken);\n    }\n\n    /**\n    * @notice calculate amount of quote asset required for trade\n    * @param baseAssetQuantity base asset to long/short\n    * @param idx amm index\n    */\n    function getQuote(int256 baseAssetQuantity, uint idx) public view returns(uint256 quoteAssetQuantity) {\n        IAMM amm = clearingHouse.amms(idx);\n        IVAMM vamm = amm.vamm();\n\n        if (baseAssetQuantity >= 0) {\n            return vamm.get_dx(0, 1, baseAssetQuantity.toUint256()) + 1;\n        }\n        // rounding-down while shorting is not a problem\n        // because lower the min_dy, more permissible it is\n        return vamm.get_dy(1, 0, (-baseAssetQuantity).toUint256());\n    }\n\n    /**\n    * @notice calculate amount of base asset required for trade\n    * @param quoteAssetQuantity amount of quote asset to long/short\n    * @param idx amm index\n    * @param isLong long - true, short - false\n    */\n    function getBase(uint256 quoteAssetQuantity, uint idx, bool isLong) external view returns(int256 /* baseAssetQuantity */) {\n        IAMM amm = clearingHouse.amms(idx);\n        IVAMM vamm = amm.vamm();\n\n        uint256 baseAssetQuantity;\n        if (isLong) {\n            baseAssetQuantity = vamm.get_dy(0, 1, quoteAssetQuantity);\n            return baseAssetQuantity.toInt256();\n        }\n        baseAssetQuantity = vamm.get_dx(1, 0, quoteAssetQuantity);\n        return -(baseAssetQuantity.toInt256());\n    }\n\n    /**\n    * @notice Get total liquidity deposited by maker and its current value\n    * @param _maker maker for which information to be obtained\n    * @return\n    *   vAsset - current base asset amount of maker in the pool\n    *   vUSD - current quote asset amount of maker in the pool\n    *   totalDeposited - total value of initial liquidity deposited in the pool by maker\n    *   dToken - maker dToken balance\n    *   vAssetBalance - base token liquidity in the pool\n    *   vUSDBalance - quote token liquidity in the pool\n    */\n    function getMakerLiquidity(address _maker, uint idx) external view returns (uint vAsset, uint vUSD, uint totalDeposited, uint dToken, uint vAssetBalance, uint vUSDBalance) {\n        IAMM amm = clearingHouse.amms(idx);\n        IVAMM vamm = amm.vamm();\n        (vUSD,, dToken,,,,) = amm.makers(_maker);\n\n        totalDeposited = 2 * vUSD;\n        uint totalDTokenSupply = vamm.totalSupply();\n        vUSDBalance = vamm.balances(0);\n        vAssetBalance = vamm.balances(1);\n\n        if (totalDTokenSupply > 0) {\n            vUSD = vUSDBalance * dToken / totalDTokenSupply;\n            vAsset = vAssetBalance * dToken / totalDTokenSupply;\n        }\n    }\n\n    /**\n    * @notice calculate base and quote asset amount form dToken\n     */\n    function calcWithdrawAmounts(uint dToken, uint idx) external view returns (uint quoteAsset, uint baseAsset) {\n        IAMM amm = clearingHouse.amms(idx);\n        IVAMM vamm = amm.vamm();\n\n        uint totalDTokenSupply = vamm.totalSupply();\n        if (totalDTokenSupply > 0) {\n            quoteAsset = vamm.balances(0) * dToken / totalDTokenSupply;\n            baseAsset = vamm.balances(1) * dToken / totalDTokenSupply;\n        }\n    }\n\n    /**\n    * @notice Get amount of token to add/remove given the amount of other token\n    * @param inputAmount quote/base asset amount to add or remove, base - 18 decimal, quote - 6 decimal\n    * @param isBase true if inputAmount is base asset\n    * @param deposit true -> addLiquidity, false -> removeLiquidity\n    * @return fillAmount base/quote asset amount to be added/removed\n    *         dToken - equivalent dToken amount\n    */\n    function getMakerQuote(uint idx, uint inputAmount, bool isBase, bool deposit) external view returns (uint fillAmount, uint dToken) {\n        IAMM amm = clearingHouse.amms(idx);\n        IVAMM vamm = amm.vamm();\n\n        if (isBase) {\n            // calculate quoteAsset amount, fillAmount = quoteAsset, inputAmount = baseAsset\n            uint baseAssetBal = vamm.balances(1);\n            if (baseAssetBal == 0) {\n                fillAmount = inputAmount * vamm.price_scale() / 1e30;\n            } else {\n                fillAmount = inputAmount * vamm.balances(0) / baseAssetBal;\n            }\n            dToken = vamm.calc_token_amount([fillAmount, inputAmount], deposit);\n        } else {\n            uint bal0 = vamm.balances(0);\n            // calculate quote asset amount, fillAmount = baseAsset, inputAmount = quoteAsset\n            if (bal0 == 0) {\n                fillAmount = inputAmount * 1e30 / vamm.price_scale();\n            } else {\n                fillAmount = inputAmount * vamm.balances(1) / bal0;\n            }\n            dToken = vamm.calc_token_amount([inputAmount, fillAmount], deposit);\n        }\n    }\n\n    /**\n    * @notice get user margin for all collaterals\n    */\n    function userInfo(address trader) external view returns(int256[] memory) {\n        uint length = marginAccount.supportedAssetsLen();\n        int256[] memory _margin = new int256[](length);\n        // -ve funding means user received funds\n        _margin[VUSD_IDX] = marginAccount.margin(VUSD_IDX, trader) - clearingHouse.getTotalFunding(trader);\n        for (uint i = 1; i < length; i++) {\n            _margin[i] = marginAccount.margin(i, trader);\n        }\n        return _margin;\n    }\n\n    /**\n    * @notice get user account information\n    */\n    function getAccountInfo(address trader) external view returns (\n        int totalCollateral,\n        int256 freeMargin,\n        int256 marginFraction,\n        uint notionalPosition,\n        int256 unrealizedPnl\n    ) {\n        int256 margin;\n        (margin, totalCollateral) = marginAccount.weightedAndSpotCollateral(trader);\n        marginFraction = clearingHouse.getMarginFraction(trader);\n        (notionalPosition, unrealizedPnl) = clearingHouse.getTotalNotionalPositionAndUnrealizedPnl(trader);\n        int256 minAllowableMargin = clearingHouse.minAllowableMargin();\n        freeMargin = margin + unrealizedPnl - clearingHouse.getTotalFunding(trader) - notionalPosition.toInt256() * minAllowableMargin / PRECISION_INT;\n    }\n\n    // Internal\n\n    /**\n    * @dev At liquidation,\n    * (margin + pnl) / notionalPosition = maintenanceMargin (MM)\n    * => pnl = MM * notionalPosition - margin\n    *\n    * for long, pnl = liquidationPrice * size - openNotional\n    * => liquidationPrice = (pnl + openNotional) / size\n    *\n    * for short, pnl = openNotional - liquidationPrice * size\n    * => liquidationPrice = (openNotional - pnl) / size\n    */\n    function _getLiquidationPrice(\n            address trader,\n            IAMM amm,\n            uint256 notionalPosition,\n            int256 margin,\n            int256 baseAssetQuantity,\n            uint quoteAssetQuantity\n        )\n        internal\n        view\n        returns(uint256 liquidationPrice)\n    {\n        if (notionalPosition == 0) {\n            return 0;\n        }\n\n        (, int256 unrealizedPnl, int256 totalPosSize, uint256 openNotional) = amm.getNotionalPositionAndUnrealizedPnl(trader);\n\n        if (baseAssetQuantity != 0) {\n            // Calculate effective position and openNotional\n            if (baseAssetQuantity * totalPosSize >= 0) { // increasingPosition i.e. same direction trade\n                openNotional += quoteAssetQuantity;\n            } else { // open reverse position\n                uint totalPosNotional = amm.getCloseQuote(totalPosSize + baseAssetQuantity);\n                if (_abs(totalPosSize) >= _abs(baseAssetQuantity)) { // position side remains same after the trade\n                    (openNotional,) = amm.getOpenNotionalWhileReducingPosition(\n                        totalPosSize,\n                        totalPosNotional,\n                        unrealizedPnl,\n                        baseAssetQuantity\n                    );\n                } else { // position side changes after the trade\n                    openNotional = totalPosNotional;\n                }\n            }\n            totalPosSize += baseAssetQuantity;\n        }\n\n        int256 pnlForLiquidation = clearingHouse.maintenanceMargin() * notionalPosition.toInt256() / PRECISION_INT - margin;\n        int256 _liquidationPrice;\n        if (totalPosSize > 0) {\n            _liquidationPrice = (openNotional.toInt256() + pnlForLiquidation) * 1e18 / totalPosSize;\n        } else if (totalPosSize < 0) {\n            _liquidationPrice = (openNotional.toInt256() - pnlForLiquidation) * 1e18 / (-totalPosSize);\n        }\n\n        if (_liquidationPrice < 0) { // is this possible?\n            _liquidationPrice = 0;\n        }\n        return _liquidationPrice.toUint256();\n    }\n\n    function _calculateTradeFee(uint quoteAsset) internal view returns (uint) {\n        return quoteAsset * clearingHouse.tradeFee() / PRECISION_UINT;\n    }\n\n    // Pure\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_INT / notionalPosition.toInt256();\n    }\n\n    function _abs(int x) private pure returns (int) {\n        return x >= 0 ? x : -x;\n    }\n\n    function _max(uint x, uint y) private pure returns (uint) {\n        return x >= y ? x : y;\n    }\n}"
}