{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/src/StabilityPool.sol",
    "Parent Contracts": [
        "contracts/src/Interfaces/IStabilityPoolEvents.sol",
        "contracts/src/Interfaces/IStabilityPool.sol",
        "contracts/src/Interfaces/IBoldRewardsReceiver.sol",
        "contracts/src/Dependencies/LiquityBase.sol",
        "contracts/src/Interfaces/ILiquityBase.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract StabilityPool is LiquityBase, IStabilityPool, IStabilityPoolEvents {\n    using SafeERC20 for IERC20;\n\n    string public constant NAME = \"StabilityPool\";\n\n    IERC20 public immutable collToken;\n    ITroveManager public immutable troveManager;\n    IBoldToken public immutable boldToken;\n\n    uint256 internal collBalance; // deposited coll tracker\n\n    // Tracker for Bold held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.\n    uint256 internal totalBoldDeposits;\n\n    // Total remaining Bold yield gains (from Trove interest mints) held by SP, and not yet paid out to depositors\n    // From the contract's perspective, this is a write-only variable.\n    uint256 internal yieldGainsOwed;\n    // Total remaining Bold yield gains (from Trove interest mints) held by SP, not yet paid out to depositors,\n    // and not accounted for because they were received when the total deposits were too small\n    uint256 internal yieldGainsPending;\n\n    // --- Data structures ---\n\n    struct Deposit {\n        uint256 initialValue;\n    }\n\n    struct Snapshots {\n        uint256 S; // Coll reward sum liqs\n        uint256 P;\n        uint256 B; // Bold reward sum from minted interest\n        uint256 scale;\n    }\n\n    mapping(address => Deposit) public deposits; // depositor address -> Deposit struct\n    mapping(address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct\n    mapping(address => uint256) public stashedColl;\n\n    /*  Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit,\n     * after a series of liquidations have occurred, each of which cancel some Bold debt with the deposit.\n     *\n     * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t\n     * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal.\n     */\n    uint256 public P = P_PRECISION;\n\n    uint256 public constant P_PRECISION = 1e36;\n\n    // A scale change will happen if P decreases by a factor of at least this much\n    uint256 public constant SCALE_FACTOR = 1e9;\n\n    // Highest power `SCALE_FACTOR` can be raised to without overflow\n    uint256 public constant MAX_SCALE_FACTOR_EXPONENT = 8;\n\n    // The number of scale changes after which an untouched deposit stops receiving yield / coll gains\n    uint256 public constant SCALE_SPAN = 2;\n\n    // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1\n    uint256 public currentScale;\n\n    /* Coll Gain sum 'S': During its lifetime, each deposit d_t earns an Coll gain of ( d_t * [S - S_t] )/P_t, where S_t\n     * is the depositor's snapshot of S taken at the time t when the deposit was made.\n     *\n     * The 'S' sums are stored in a mapping (scale => sum).\n     * - The mapping records the sum S at different scales.\n     */\n    mapping(uint256 => uint256) public scaleToS;\n    mapping(uint256 => uint256) public scaleToB;\n\n    // --- Events ---\n\n    event TroveManagerAddressChanged(address _newTroveManagerAddress);\n    event BoldTokenAddressChanged(address _newBoldTokenAddress);\n\n    constructor(IAddressesRegistry _addressesRegistry) LiquityBase(_addressesRegistry) {\n        collToken = _addressesRegistry.collToken();\n        troveManager = _addressesRegistry.troveManager();\n        boldToken = _addressesRegistry.boldToken();\n\n        emit TroveManagerAddressChanged(address(troveManager));\n        emit BoldTokenAddressChanged(address(boldToken));\n    }\n\n    // --- Getters for public variables. Required by IPool interface ---\n\n    function getCollBalance() external view override returns (uint256) {\n        return collBalance;\n    }\n\n    function getTotalBoldDeposits() external view override returns (uint256) {\n        return totalBoldDeposits;\n    }\n\n    function getYieldGainsOwed() external view override returns (uint256) {\n        return yieldGainsOwed;\n    }\n\n    function getYieldGainsPending() external view override returns (uint256) {\n        return yieldGainsPending;\n    }\n\n    // --- External Depositor Functions ---\n\n    /*  provideToSP():\n     * - Calculates depositor's Coll gain\n     * - Calculates the compounded deposit\n     * - Increases deposit, and takes new snapshots of accumulators P and S\n     * - Sends depositor's accumulated Coll gains to depositor\n     */\n    function provideToSP(uint256 _topUp, bool _doClaim) external override {\n        IWhitelist _whitelist = whitelist;\n        if (address(_whitelist) != address(0)) {\n            _requireWhitelisted(_whitelist, msg.sender);\n        }\n\n        _requireNonZeroAmount(_topUp);\n\n        activePool.mintAggInterest();\n\n        uint256 initialDeposit = deposits[msg.sender].initialValue;\n\n        uint256 currentCollGain = getDepositorCollGain(msg.sender);\n        uint256 currentYieldGain = getDepositorYieldGain(msg.sender);\n        uint256 compoundedBoldDeposit = getCompoundedBoldDeposit(msg.sender);\n        (uint256 keptYieldGain, uint256 yieldGainToSend) = _getYieldToKeepOrSend(currentYieldGain, _doClaim);\n        uint256 newDeposit = compoundedBoldDeposit + _topUp + keptYieldGain;\n        (uint256 newStashedColl, uint256 collToSend) = _getNewStashedCollAndCollToSend(\n            msg.sender,\n            currentCollGain,\n            _doClaim\n        );\n\n        emit DepositOperation(\n            msg.sender,\n            Operation.provideToSP,\n            initialDeposit - compoundedBoldDeposit,\n            int256(_topUp),\n            currentYieldGain,\n            yieldGainToSend,\n            currentCollGain,\n            collToSend\n        );\n\n        _updateDepositAndSnapshots(msg.sender, newDeposit, newStashedColl);\n        boldToken.sendToPool(msg.sender, address(this), _topUp);\n        _updateTotalBoldDeposits(_topUp + keptYieldGain, 0);\n        _decreaseYieldGainsOwed(currentYieldGain);\n        _sendBoldtoDepositor(msg.sender, yieldGainToSend);\n        _sendCollGainToDepositor(collToSend);\n\n        // If there were pending yields and with the new deposit we are reaching the threshold, let\u2019s move the yield to owed\n        _updateYieldRewardsSum(0);\n    }\n\n    function _getYieldToKeepOrSend(uint256 _currentYieldGain, bool _doClaim) internal pure returns (uint256, uint256) {\n        uint256 yieldToKeep;\n        uint256 yieldToSend;\n\n        if (_doClaim) {\n            yieldToKeep = 0;\n            yieldToSend = _currentYieldGain;\n        } else {\n            yieldToKeep = _currentYieldGain;\n            yieldToSend = 0;\n        }\n\n        return (yieldToKeep, yieldToSend);\n    }\n\n    /*  withdrawFromSP():\n     * - Calculates depositor's Coll gain\n     * - Calculates the compounded deposit\n     * - Sends the requested BOLD withdrawal to depositor\n     * - (If _amount > userDeposit, the user withdraws all of their compounded deposit)\n     * - Decreases deposit by withdrawn amount and takes new snapshots of accumulators P and S\n     */\n    function withdrawFromSP(uint256 _amount, bool _doClaim) external override {\n        uint256 initialDeposit = deposits[msg.sender].initialValue;\n        _requireUserHasDeposit(initialDeposit);\n\n        activePool.mintAggInterest();\n\n        uint256 currentCollGain = getDepositorCollGain(msg.sender);\n        uint256 currentYieldGain = getDepositorYieldGain(msg.sender);\n        uint256 compoundedBoldDeposit = getCompoundedBoldDeposit(msg.sender);\n        uint256 boldToWithdraw = LiquityMath._min(_amount, compoundedBoldDeposit);\n        (uint256 keptYieldGain, uint256 yieldGainToSend) = _getYieldToKeepOrSend(currentYieldGain, _doClaim);\n        uint256 newDeposit = compoundedBoldDeposit - boldToWithdraw + keptYieldGain;\n        (uint256 newStashedColl, uint256 collToSend) = _getNewStashedCollAndCollToSend(\n            msg.sender,\n            currentCollGain,\n            _doClaim\n        );\n\n        emit DepositOperation(\n            msg.sender,\n            Operation.withdrawFromSP,\n            initialDeposit - compoundedBoldDeposit,\n            -int256(boldToWithdraw),\n            currentYieldGain,\n            yieldGainToSend,\n            currentCollGain,\n            collToSend\n        );\n\n        _updateDepositAndSnapshots(msg.sender, newDeposit, newStashedColl);\n        _decreaseYieldGainsOwed(currentYieldGain);\n        uint256 newTotalBoldDeposits = _updateTotalBoldDeposits(keptYieldGain, boldToWithdraw);\n        _sendBoldtoDepositor(msg.sender, boldToWithdraw + yieldGainToSend);\n        _sendCollGainToDepositor(collToSend);\n\n        require(newTotalBoldDeposits >= MIN_BOLD_IN_SP, \"Withdrawal must leave totalBoldDeposits >= MIN_BOLD_IN_SP\");\n    }\n\n    function _getNewStashedCollAndCollToSend(\n        address _depositor,\n        uint256 _currentCollGain,\n        bool _doClaim\n    ) internal view returns (uint256 newStashedColl, uint256 collToSend) {\n        if (_doClaim) {\n            newStashedColl = 0;\n            collToSend = stashedColl[_depositor] + _currentCollGain;\n        } else {\n            newStashedColl = stashedColl[_depositor] + _currentCollGain;\n            collToSend = 0;\n        }\n    }\n\n    // This function is only needed in the case a user has no deposit but still has remaining stashed Coll gains.\n    function claimAllCollGains() external {\n        _requireUserHasNoDeposit(msg.sender);\n\n        activePool.mintAggInterest();\n\n        uint256 collToSend = stashedColl[msg.sender];\n        _requireNonZeroAmount(collToSend);\n        stashedColl[msg.sender] = 0;\n\n        emit DepositOperation(msg.sender, Operation.claimAllCollGains, 0, 0, 0, 0, 0, collToSend);\n        emit DepositUpdated(msg.sender, 0, 0, 0, 0, 0, 0);\n\n        _sendCollGainToDepositor(collToSend);\n    }\n\n    // --- BOLD reward functions ---\n\n    function triggerBoldRewards(uint256 _boldYield) external {\n        _requireCallerIsActivePool();\n        _updateYieldRewardsSum(_boldYield);\n    }\n\n    function _updateYieldRewardsSum(uint256 _newYield) internal {\n        uint256 accumulatedYieldGains = yieldGainsPending + _newYield;\n        if (accumulatedYieldGains == 0) return;\n\n        // When total deposits is very small, B is not updated. In this case, the BOLD issued is held\n        // until the total deposits reach 1 BOLD (remains in the balance of the SP).\n        if (totalBoldDeposits < MIN_BOLD_IN_SP) {\n            yieldGainsPending = accumulatedYieldGains;\n            return;\n        }\n\n        yieldGainsOwed += accumulatedYieldGains;\n        yieldGainsPending = 0;\n\n        scaleToB[currentScale] += (P * accumulatedYieldGains) / totalBoldDeposits;\n        emit B_Updated(scaleToB[currentScale], currentScale);\n    }\n\n    // --- Liquidation functions ---\n\n    /*\n     * Cancels out the specified debt against the Bold contained in the Stability Pool (as far as possible)\n     * and transfers the Trove's Coll collateral from ActivePool to StabilityPool.\n     * Only called by liquidation functions in the TroveManager.\n     */\n    function offset(uint256 _debtToOffset, uint256 _collToAdd) external override {\n        _requireCallerIsTroveManager();\n\n        scaleToS[currentScale] += (P * _collToAdd) / totalBoldDeposits;\n        emit S_Updated(scaleToS[currentScale], currentScale);\n\n        uint256 numerator = P * (totalBoldDeposits - _debtToOffset);\n        uint256 newP = numerator / totalBoldDeposits;\n\n        // For `P` to turn zero, `totalBoldDeposits` has to be greater than `P * (totalBoldDeposits - _debtToOffset)`.\n        // - As the offset must leave at least 1 BOLD in the SP (MIN_BOLD_IN_SP),\n        //   the minimum value of `totalBoldDeposits - _debtToOffset` is `1e18`\n        // - It can be shown that `P` is always in range (1e27, 1e36].\n        // Thus, to turn `P` zero, `totalBoldDeposits` has to be greater than `(1e27 + 1) * 1e18`,\n        // and the offset has to be (near) maximal.\n        // In other words, there needs to be octillions of BOLD in the SP, which is unlikely to happen in practice.\n        require(newP > 0, \"P must never decrease to 0\");\n\n        // Overflow analyisis of scaling up P:\n        // We know that the resulting P is <= 1e36, and it's the result of dividing numerator by totalBoldDeposits.\n        // Thus, numerator <= 1e36 * totalBoldDeposits, so unless totalBoldDeposits is septillions of BOLD, it won\u2019t overflow.\n        // That holds on every iteration as an upper bound. We multiply numerator by SCALE_FACTOR,\n        // but numerator is by definition smaller than 1e36 * totalBoldDeposits / SCALE_FACTOR.\n        while (newP < P_PRECISION / SCALE_FACTOR) {\n            numerator *= SCALE_FACTOR;\n            newP = numerator / totalBoldDeposits;\n            currentScale += 1;\n            emit ScaleUpdated(currentScale);\n        }\n\n        emit P_Updated(newP);\n        P = newP;\n\n        _moveOffsetCollAndDebt(_collToAdd, _debtToOffset);\n    }\n\n    function _moveOffsetCollAndDebt(uint256 _collToAdd, uint256 _debtToOffset) internal {\n        // Cancel the liquidated Bold debt with the Bold in the stability pool\n        _updateTotalBoldDeposits(0, _debtToOffset);\n\n        // Burn the debt that was successfully offset\n        boldToken.burn(address(this), _debtToOffset);\n\n        // Update internal Coll balance tracker\n        uint256 newCollBalance = collBalance + _collToAdd;\n        collBalance = newCollBalance;\n\n        // Pull Coll from Active Pool\n        activePool.sendColl(address(this), _collToAdd);\n\n        emit StabilityPoolCollBalanceUpdated(newCollBalance);\n    }\n\n    function _updateTotalBoldDeposits(uint256 _depositIncrease, uint256 _depositDecrease) internal returns (uint256) {\n        if (_depositIncrease == 0 && _depositDecrease == 0) return totalBoldDeposits;\n        uint256 newTotalBoldDeposits = totalBoldDeposits + _depositIncrease - _depositDecrease;\n        totalBoldDeposits = newTotalBoldDeposits;\n\n        emit StabilityPoolBoldBalanceUpdated(newTotalBoldDeposits);\n        return newTotalBoldDeposits;\n    }\n\n    function _decreaseYieldGainsOwed(uint256 _amount) internal {\n        if (_amount == 0) return;\n        uint256 newYieldGainsOwed = yieldGainsOwed - _amount;\n        yieldGainsOwed = newYieldGainsOwed;\n    }\n\n    // --- Reward calculator functions for depositor ---\n\n    function getDepositorCollGain(address _depositor) public view override returns (uint256) {\n        uint256 initialDeposit = deposits[_depositor].initialValue;\n        if (initialDeposit == 0) return 0;\n\n        Snapshots storage snapshots = depositSnapshots[_depositor];\n\n        // Coll gains from the same scale in which the deposit was made need no scaling\n        uint256 normalizedGains = scaleToS[snapshots.scale] - snapshots.S;\n\n        // Scale down further coll gains by a power of `SCALE_FACTOR` depending on how many scale changes they span\n        for (uint256 i = 1; i <= SCALE_SPAN; ++i) {\n            normalizedGains += scaleToS[snapshots.scale + i] / SCALE_FACTOR ** i;\n        }\n\n        return LiquityMath._min((initialDeposit * normalizedGains) / snapshots.P, collBalance);\n    }\n\n    function getDepositorYieldGain(address _depositor) public view override returns (uint256) {\n        uint256 initialDeposit = deposits[_depositor].initialValue;\n        if (initialDeposit == 0) return 0;\n\n        Snapshots storage snapshots = depositSnapshots[_depositor];\n\n        // Yield gains from the same scale in which the deposit was made need no scaling\n        uint256 normalizedGains = scaleToB[snapshots.scale] - snapshots.B;\n\n        // Scale down further yield gains by a power of `SCALE_FACTOR` depending on how many scale changes they span\n        for (uint256 i = 1; i <= SCALE_SPAN; ++i) {\n            normalizedGains += scaleToB[snapshots.scale + i] / SCALE_FACTOR ** i;\n        }\n\n        return LiquityMath._min((initialDeposit * normalizedGains) / snapshots.P, yieldGainsOwed);\n    }\n\n    function getDepositorYieldGainWithPending(address _depositor) external view override returns (uint256) {\n        if (totalBoldDeposits < MIN_BOLD_IN_SP) return 0;\n\n        uint256 initialDeposit = deposits[_depositor].initialValue;\n        if (initialDeposit == 0) return 0;\n\n        Snapshots storage snapshots = depositSnapshots[_depositor];\n        uint256 newYieldGainsOwed = yieldGainsOwed;\n\n        // Yield gains from the same scale in which the deposit was made need no scaling\n        uint256 normalizedGains = scaleToB[snapshots.scale] - snapshots.B;\n\n        // Scale down further yield gains by a power of `SCALE_FACTOR` depending on how many scale changes they span\n        for (uint256 i = 1; i <= SCALE_SPAN; ++i) {\n            normalizedGains += scaleToB[snapshots.scale + i] / SCALE_FACTOR ** i;\n        }\n\n        // Pending gains\n        uint256 pendingSPYield = activePool.calcPendingSPYield();\n        newYieldGainsOwed += pendingSPYield;\n\n        if (currentScale <= snapshots.scale + SCALE_SPAN) {\n            normalizedGains +=\n                (P * pendingSPYield) /\n                totalBoldDeposits /\n                SCALE_FACTOR ** (currentScale - snapshots.scale);\n        }\n\n        return LiquityMath._min((initialDeposit * normalizedGains) / snapshots.P, newYieldGainsOwed);\n    }\n\n    // --- Compounded deposit ---\n\n    function getCompoundedBoldDeposit(address _depositor) public view override returns (uint256 compoundedDeposit) {\n        uint256 initialDeposit = deposits[_depositor].initialValue;\n        if (initialDeposit == 0) return 0;\n\n        Snapshots storage snapshots = depositSnapshots[_depositor];\n\n        uint256 scaleDiff = currentScale - snapshots.scale;\n\n        // Compute the compounded deposit. If one or more scale changes in `P` were made during the deposit's lifetime,\n        // account for them.\n        // If more than `MAX_SCALE_FACTOR_EXPONENT` scale changes were made, then the divisor is greater than 2^256 so\n        // any deposit amount would be rounded down to zero.\n        if (scaleDiff <= MAX_SCALE_FACTOR_EXPONENT) {\n            compoundedDeposit = (initialDeposit * P) / snapshots.P / SCALE_FACTOR ** scaleDiff;\n        } else {\n            compoundedDeposit = 0;\n        }\n    }\n\n    // --- Sender functions for Bold deposit and Coll gains ---\n\n    function _sendCollGainToDepositor(uint256 _collAmount) internal {\n        if (_collAmount == 0) return;\n\n        uint256 newCollBalance = collBalance - _collAmount;\n        collBalance = newCollBalance;\n        emit StabilityPoolCollBalanceUpdated(newCollBalance);\n        collToken.safeTransfer(msg.sender, _collAmount);\n    }\n\n    // Send Bold to user and decrease Bold in Pool\n    function _sendBoldtoDepositor(address _depositor, uint256 _boldToSend) internal {\n        if (_boldToSend == 0) return;\n        boldToken.returnFromPool(address(this), _depositor, _boldToSend);\n    }\n\n    // --- Stability Pool Deposit Functionality ---\n\n    function _updateDepositAndSnapshots(address _depositor, uint256 _newDeposit, uint256 _newStashedColl) internal {\n        deposits[_depositor].initialValue = _newDeposit;\n        stashedColl[_depositor] = _newStashedColl;\n\n        if (_newDeposit == 0) {\n            delete depositSnapshots[_depositor];\n            emit DepositUpdated(_depositor, 0, _newStashedColl, 0, 0, 0, 0);\n            return;\n        }\n\n        uint256 currentScaleCached = currentScale;\n        uint256 currentP = P;\n\n        // Get S for the current scale\n        uint256 currentS = scaleToS[currentScaleCached];\n        uint256 currentB = scaleToB[currentScaleCached];\n\n        // Record new snapshots of the latest running product P and sum S for the depositor\n        depositSnapshots[_depositor].P = currentP;\n        depositSnapshots[_depositor].S = currentS;\n        depositSnapshots[_depositor].B = currentB;\n        depositSnapshots[_depositor].scale = currentScaleCached;\n\n        emit DepositUpdated(_depositor, _newDeposit, _newStashedColl, currentP, currentS, currentB, currentScaleCached);\n    }\n\n    // --- 'require' functions ---\n    function _requireCallerIsActivePool() internal view {\n        require(msg.sender == address(activePool), \"StabilityPool: Caller is not ActivePool\");\n    }\n\n    function _requireCallerIsTroveManager() internal view {\n        require(msg.sender == address(troveManager), \"StabilityPool: Caller is not TroveManager\");\n    }\n\n    function _requireUserHasDeposit(uint256 _initialDeposit) internal pure {\n        require(_initialDeposit > 0, \"StabilityPool: User must have a non-zero deposit\");\n    }\n\n    function _requireUserHasNoDeposit(address _address) internal view {\n        uint256 initialDeposit = deposits[_address].initialValue;\n        require(initialDeposit == 0, \"StabilityPool: User must have no deposit\");\n    }\n\n    function _requireNonZeroAmount(uint256 _amount) internal pure {\n        require(_amount > 0, \"StabilityPool: Amount must be non-zero\");\n    }\n}"
}