{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/managers/SherlockProtocolManager.sol",
    "Parent Contracts": [
        "contracts/managers/Manager.sol",
        "node_modules/@openzeppelin/contracts/security/Pausable.sol",
        "node_modules/@openzeppelin/contracts/access/Ownable.sol",
        "node_modules/@openzeppelin/contracts/utils/Context.sol",
        "contracts/interfaces/managers/ISherlockProtocolManager.sol",
        "contracts/interfaces/managers/IManager.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract SherlockProtocolManager is ISherlockProtocolManager, Manager {\n  using SafeERC20 for IERC20;\n\n  // Represents the token that protocols pay with (currently USDC)\n  IERC20 public immutable token;\n\n  // This is the ceiling value that can be set for the threshold (based on USDC balance) at which a protocol can get removed\n  uint256 public constant MIN_BALANCE_SANITY_CEILING = 30_000 * 10**6; // 30k usdc\n\n  // A removed protocol is still able to make a claim for this amount of time after its removal\n  uint256 public constant PROTOCOL_CLAIM_DEADLINE = 7 days;\n\n  // This is the amount that cannot be withdrawn (measured in seconds of payment) if a protocol wants to remove active balance\n  uint256 public constant MIN_SECONDS_LEFT = 7 days;\n\n  // Convenient for percentage calculations\n  uint256 internal constant HUNDRED_PERCENT = 10**18;\n\n  // The minimum active \"seconds of coverage left\" a protocol must have before arbitragers can remove the protocol from coverage\n  // This value is calculated from a protocol's active balance divided by the premium per second the protocol is paying\n  uint256 public constant MIN_SECONDS_OF_COVERAGE = 12 hours;\n\n  // This is an address that is controlled by a covered protocol (maybe its a multisig used by that protocol, etc.)\n  mapping(bytes32 => address) internal protocolAgent_;\n\n  // The percentage of premiums that is NOT sent to stakers (set aside for security experts, reinsurance partners, etc.)\n  mapping(bytes32 => uint256) internal nonStakersPercentage;\n\n  // The premium per second paid by each protocol is stored in this mapping\n  mapping(bytes32 => uint256) internal premiums_;\n\n  // Each protocol should keep an active balance (in USDC) which is drawn against to pay stakers, nonstakers, etc.\n  // This \"active balance\" is really just an accounting concept, doesn't mean tokens have been transferred or not\n  mapping(bytes32 => uint256) internal activeBalances;\n\n  // The timestamp at which Sherlock last ran this internal accounting (on the active balance) for each protocol\n  mapping(bytes32 => uint256) internal lastAccountedEachProtocol;\n\n  // The amount that can be claimed by nonstakers for each protocol\n  // We need this value so we can track how much payment is coming from each protocol\n  mapping(bytes32 => uint256) internal nonStakersClaimableByProtocol;\n\n  // The last time where the global accounting was run (to calc allPremiumsPerSecToStakers below)\n  uint256 internal lastAccountedGlobal;\n\n  // This is the total amount of premiums paid (per second) by all the covered protocols (added up)\n  uint256 internal allPremiumsPerSecToStakers;\n\n  // This is the amount that was claimable by stakers the last time the accounting was run\n  // The claimable amount presumably changes every second so this value is marked \"last\" because it is usually out-of-date\n  uint256 internal lastClaimablePremiumsForStakers;\n\n  // The minimum active balance (measured in USDC) a protocol must keep before arbitragers can remove the protocol from coverage\n  // This is one of two criteria a protocol must meet in order to avoid removal (the other is MIN_SECONDS_OF_COVERAGE)\n  uint256 public override minActiveBalance;\n\n  // Removed protocols can still make a claim up until this timestamp (will be 10 days or something)\n  mapping(bytes32 => uint256) internal removedProtocolClaimDeadline;\n\n  // Mapping to store the protocolAgents for removed protocols (useful for claims made by a removed protocol)\n  mapping(bytes32 => address) internal removedProtocolAgent;\n\n  // Current amount of coverage (i.e. 20M USDC) for a protocol\n  mapping(bytes32 => uint256) internal currentCoverage;\n\n  // Previous amount of coverage for a protocol\n  // Previous is also tracked in case a protocol lowers their coverage amount but still needs to make a claim on the old, higher amount\n  mapping(bytes32 => uint256) internal previousCoverage;\n\n  // Setting the token to USDC\n  constructor(IERC20 _token) {\n    if (address(_token) == address(0)) revert ZeroArgument();\n    token = _token;\n  }\n\n  // Modifier used to ensure a protocol exists (has been instantiated and not removed)\n  modifier protocolExists(bytes32 _protocol) {\n    _verifyProtocolExists(_protocol);\n    _;\n  }\n\n  /// @notice View current protocolAgent of `_protocol`\n  /// @param _protocol Protocol identifier\n  /// @return Address able to submit claims\n  function protocolAgent(bytes32 _protocol) external view override returns (address) {\n    address agent = protocolAgent_[_protocol];\n    if (agent != address(0)) return agent;\n\n    // If a protocol has been removed but is still within the claim deadline, the protocolAgent is returned\n    // Note: Old protocol agent will never be address(0)\n    if (block.timestamp <= removedProtocolClaimDeadline[_protocol]) {\n      return removedProtocolAgent[_protocol];\n    }\n\n    // If a protocol was never instantiated or was removed and the claim deadline has passed, this error is returned\n    revert ProtocolNotExists(_protocol);\n  }\n\n  // Checks if the protocol exists, then returns the current premium per second being charged\n  /// @notice View current premium of protocol\n  /// @param _protocol Protocol identifier\n  /// @return Amount of premium `_protocol` pays per second\n  function premium(bytes32 _protocol)\n    external\n    view\n    override\n    protocolExists(_protocol)\n    returns (uint256)\n  {\n    return premiums_[_protocol];\n  }\n\n  // Checks to see if a protocol has a protocolAgent assigned to it (we use this to check if a protocol exists)\n  // If a protocol has been removed, it will throw an error here no matter what (even if still within claim window)\n  function _verifyProtocolExists(bytes32 _protocol) internal view returns (address _protocolAgent) {\n    _protocolAgent = protocolAgent_[_protocol];\n    if (_protocolAgent == address(0)) revert ProtocolNotExists(_protocol);\n  }\n\n  //\n  // View methods\n  //\n\n  // Calcs the debt accrued by the protocol since it last had an accounting update\n  // This is the amount that needs to be removed from a protocol's active balance\n  function _calcIncrementalProtocolDebt(bytes32 _protocol) internal view returns (uint256) {\n    return (block.timestamp - lastAccountedEachProtocol[_protocol]) * premiums_[_protocol];\n  }\n\n  /// @notice View the amount nonstakers can claim from this protocol\n  /// @param _protocol Protocol identifier\n  /// @return Amount of tokens claimable by nonstakers\n  /// @dev this reads from a storage variable + (now-lastsettled) * premiums\n  // Note: This function works even for removed protocols because of nonStakersClaimableByProtocol[_protocol]\n  // When a protocol gets removed, nonStakersClaimableByProtocol[_protocol] is updated and then doesn't change since the protocol has been removed\n  function nonStakersClaimable(bytes32 _protocol) external view override returns (uint256) {\n    // Calcs the debt of a protocol since the last accounting update\n    uint256 debt = _calcIncrementalProtocolDebt(_protocol);\n    // Gets the active balance of the protocol\n    uint256 balance = activeBalances[_protocol];\n    // The debt should never be higher than the balance (only happens if the arbitrages fail)\n    if (debt > balance) debt = balance;\n\n    // Adds the incremental claimable amount owed to nonstakers to the total claimable amount\n    return\n      nonStakersClaimableByProtocol[_protocol] +\n      (nonStakersPercentage[_protocol] * debt) /\n      HUNDRED_PERCENT;\n  }\n\n  /// @notice View current amount of all premiums that are owed to stakers\n  /// @return Premiums claimable\n  /// @dev Will increase every block\n  /// @dev base + (now - last_settled) * ps\n  function claimablePremiums() public view override returns (uint256) {\n    // Takes last balance and adds (number of seconds since last accounting update * total premiums per second)\n    return\n      lastClaimablePremiumsForStakers +\n      (block.timestamp - lastAccountedGlobal) *\n      allPremiumsPerSecToStakers;\n  }\n\n  /// @notice View seconds of coverage left for `_protocol` before it runs out of active balance\n  /// @param _protocol Protocol identifier\n  /// @return Seconds of coverage left\n  function secondsOfCoverageLeft(bytes32 _protocol)\n    external\n    view\n    override\n    protocolExists(_protocol)\n    returns (uint256)\n  {\n    return _secondsOfCoverageLeft(_protocol);\n  }\n\n  // Helper function to return seconds of coverage left for a protocol\n  // Gets the current active balance of the protocol and divides by the premium per second for the protocol\n  function _secondsOfCoverageLeft(bytes32 _protocol) internal view returns (uint256) {\n    uint256 premium = premiums_[_protocol];\n    if (premium == 0) return 0;\n    return _activeBalance(_protocol) / premium;\n  }\n\n  /// @notice View current active balance of covered protocol\n  /// @param _protocol Protocol identifier\n  /// @return Active balance\n  /// @dev Accrued debt is subtracted from the stored active balance\n  function activeBalance(bytes32 _protocol)\n    external\n    view\n    override\n    protocolExists(_protocol)\n    returns (uint256)\n  {\n    return _activeBalance(_protocol);\n  }\n\n  // Helper function to calc the active balance of a protocol at current time\n  function _activeBalance(bytes32 _protocol) internal view returns (uint256) {\n    uint256 debt = _calcIncrementalProtocolDebt(_protocol);\n    uint256 balance = activeBalances[_protocol];\n    // The debt should never be higher than the balance (only happens if the arbitrages fail)\n    if (debt > balance) return 0;\n    return balance - debt;\n  }\n\n  //\n  // State methods\n  //\n\n  /// @notice Helps set the premium per second for an individual protocol\n  /// @param _protocol Protocol identifier\n  /// @param _premium New premium per second\n  /// @return oldPremiumPerSecond and nonStakerPercentage are returned for gas savings in the calling function\n  function _setSingleProtocolPremium(bytes32 _protocol, uint256 _premium)\n    internal\n    returns (uint256 oldPremiumPerSecond, uint256 nonStakerPercentage)\n  {\n    // _settleProtocolDebt() subtracts debt from the protocol's active balance and updates the % due to nonstakers\n    // Also updates the last accounted timestamp for this protocol\n    // nonStakerPercentage is carried over from _settleProtocolDebt() for gas savings\n    // nonStakerPercentage represents the percentage that goes to nonstakers for this protocol\n    nonStakerPercentage = _settleProtocolDebt(_protocol);\n    // Stores the old premium before it gets updated\n    oldPremiumPerSecond = premiums_[_protocol];\n\n    if (oldPremiumPerSecond != _premium) {\n      // Sets the protocol's premium per second to the new value\n      premiums_[_protocol] = _premium;\n      emit ProtocolPremiumChanged(_protocol, oldPremiumPerSecond, _premium);\n    }\n    // We check if the NEW premium causes the _secondsOfCoverageLeft for the protocol to be less than the threshold for arbing\n    // We don't need to check the min balance requirement for arbs because that value doesn't change like secondsOfCoverageLeft changes\n    // Effectively we just need to make sure we don't accidentally run a protocol's active balance down below the point\n    // Where arbs would no longer be incentivized to remove the protocol\n    // Because if a protocol is not removed by arbs before running out of active balance, this can cause problems\n    if (_premium != 0 && _secondsOfCoverageLeft(_protocol) < MIN_SECONDS_OF_COVERAGE) {\n      revert InsufficientBalance(_protocol);\n    }\n  }\n\n  /// @notice Sets a single protocol's premium per second and also updates the global total of premiums per second\n  /// @param _protocol Protocol identifier\n  /// @param _premium New premium per second\n  function _setSingleAndGlobalProtocolPremium(bytes32 _protocol, uint256 _premium) internal {\n    // Sets the individual protocol's premium and returns oldPremiumPerSecond and nonStakerPercentage for gas savings\n    (uint256 oldPremiumPerSecond, uint256 nonStakerPercentage) = _setSingleProtocolPremium(\n      _protocol,\n      _premium\n    );\n    // Settling the total amount of premiums owed to stakers before a new premium per second gets set\n    _settleTotalDebt();\n    // This calculates the new global premium per second that gets paid to stakers\n    // We input the same nonStakerPercentage twice because we simply aren't updating that value in this function\n    allPremiumsPerSecToStakers = _calcGlobalPremiumPerSecForStakers(\n      oldPremiumPerSecond,\n      _premium,\n      nonStakerPercentage,\n      nonStakerPercentage,\n      allPremiumsPerSecToStakers\n    );\n  }\n\n  // Internal function to set a new protocolAgent for a specific protocol\n  // _oldAgent is only included as part of emitting an event\n  function _setProtocolAgent(\n    bytes32 _protocol,\n    address _oldAgent,\n    address _protocolAgent\n  ) internal {\n    protocolAgent_[_protocol] = _protocolAgent;\n    emit ProtocolAgentTransfer(_protocol, _oldAgent, _protocolAgent);\n  }\n\n  // Subtracts the accrued debt from a protocol's active balance\n  // Credits the amount that can be claimed by nonstakers for this protocol\n  // Takes the protocol ID as a param and returns the nonStakerPercentage for gas savings\n  // Most of this function is dealing with an edge case related to a protocol not being removed by arbs\n  function _settleProtocolDebt(bytes32 _protocol) internal returns (uint256 _nonStakerPercentage) {\n    // This calcs the accrued debt of the protocol since it was last updated\n    uint256 debt = _calcIncrementalProtocolDebt(_protocol);\n    // This pulls the percentage that is sent to nonstakers\n    _nonStakerPercentage = nonStakersPercentage[_protocol];\n    // In case the protocol has accrued debt, this code block will ensure the debt is settled properly\n    if (debt != 0) {\n      // Pulls the stored active balance of the protocol\n      uint256 balance = activeBalances[_protocol];\n      // This is the start of handling an edge case where arbitragers don't remove this protocol before debt becomes greater than active balance\n      // Economically speaking, this point should never be reached as arbs will get rewarded for removing the protocol before this point\n      // The arb would use forceRemoveByActiveBalance and forceRemoveBySecondsOfCoverage\n      // However, if arbs don't come in, the premium for this protocol should be set to 0 asap otherwise accounting for stakers/nonstakers gets messed up\n      if (debt > balance) {\n        // This error amount represents the magnitude of the mistake\n        uint256 error = debt - balance;\n        // Gets the latest value of claimable premiums for stakers\n        _settleTotalDebt();\n        // @note to production, set premium first to zero before solving accounting issue.\n        // otherwise the accounting error keeps increasing\n        uint256 lastClaimablePremiumsForStakers_ = lastClaimablePremiumsForStakers;\n\n        // Figures out the amount due to stakers by subtracting the nonstaker percentage from 100%\n        uint256 claimablePremiumError = ((HUNDRED_PERCENT - _nonStakerPercentage) * error) /\n          HUNDRED_PERCENT;\n\n        // This insufficient tokens var is simply how we know (emitted as an event) how many tokens the protocol is short\n        uint256 insufficientTokens;\n\n        // The idea here is that lastClaimablePremiumsForStakers has gotten too big accidentally\n        // We need to decrease the balance of lastClaimablePremiumsForStakers by the amount that was added in error\n        // This first line can be true if claimPremiumsForStakers() has been called and\n        // lastClaimablePremiumsForStakers would be 0 but a faulty protocol could cause claimablePremiumError to be >0 still\n        if (claimablePremiumError > lastClaimablePremiumsForStakers_) {\n          insufficientTokens = claimablePremiumError - lastClaimablePremiumsForStakers_;\n          lastClaimablePremiumsForStakers = 0;\n        } else {\n          // If the error is not bigger than the claimable premiums, then we just decrease claimable premiums\n          // By the amount that was added in error (error) and insufficientTokens = 0\n          lastClaimablePremiumsForStakers =\n            lastClaimablePremiumsForStakers_ -\n            claimablePremiumError;\n        }\n\n        // If two events are thrown, the values need to be summed up for the actual state.\n        // This means an error of this type will continue until it is handled\n        emit AccountingError(_protocol, claimablePremiumError, insufficientTokens);\n        // We set the debt equal to the balance, and in the next line we effectively set the protocol's active balance to 0 in this case\n        debt = balance;\n      }\n      // Subtracts the accrued debt (since last update) from the protocol's active balance and updates active balance\n      activeBalances[_protocol] = balance - debt;\n      // Adds the requisite amount of the debt to the balance claimable by nonstakers for this protocol\n      nonStakersClaimableByProtocol[_protocol] += (_nonStakerPercentage * debt) / HUNDRED_PERCENT;\n    }\n    // Updates the last accounted timestamp for this protocol\n    lastAccountedEachProtocol[_protocol] = block.timestamp;\n  }\n\n  // Multiplies the total premium per second * number of seconds since the last global accounting update\n  // And adds it to the total claimable amount for stakers\n  function _settleTotalDebt() internal {\n    lastClaimablePremiumsForStakers +=\n      (block.timestamp - lastAccountedGlobal) *\n      allPremiumsPerSecToStakers;\n    lastAccountedGlobal = block.timestamp;\n  }\n\n  // Calculates the global premium per second for stakers\n  // Takes a specific protocol's old and new values for premium per second and nonstaker percentage and the old global premium per second to stakers\n  // Subtracts out the old values of a protocol's premium per second and nonstaker percentage and adds the new ones\n  function _calcGlobalPremiumPerSecForStakers(\n    uint256 _premiumOld,\n    uint256 _premiumNew,\n    uint256 _nonStakerPercentageOld,\n    uint256 _nonStakerPercentageNew,\n    uint256 _inMemAllPremiumsPerSecToStakers\n  ) internal pure returns (uint256) {\n    return\n      _inMemAllPremiumsPerSecToStakers +\n      ((HUNDRED_PERCENT - _nonStakerPercentageNew) * _premiumNew) /\n      HUNDRED_PERCENT -\n      ((HUNDRED_PERCENT - _nonStakerPercentageOld) * _premiumOld) /\n      HUNDRED_PERCENT;\n  }\n\n  // Helper function to remove and clean up a protocol from Sherlock\n  // Params are the protocol ID and the protocol agent to which funds should be sent and from which post-removal claims can be made\n  function _forceRemoveProtocol(bytes32 _protocol, address _agent) internal {\n    // Sets the individual protocol's premium to zero and updates the global premium variable for a zero premium at this protocol\n    _setSingleAndGlobalProtocolPremium(_protocol, 0);\n\n    // Grabs the protocol's active balance\n    uint256 balance = activeBalances[_protocol];\n\n    // If there's still some active balance, delete the entry and send the remaining balance to the protocol agent\n    if (balance != 0) {\n      delete activeBalances[_protocol];\n      token.safeTransfer(_agent, balance);\n\n      emit ProtocolBalanceWithdrawn(_protocol, balance);\n    }\n\n    // Sets the protocol agent to zero address (as part of clean up)\n    _setProtocolAgent(_protocol, _agent, address(0));\n\n    // Cleans up other mappings for this protocol\n    delete nonStakersPercentage[_protocol];\n    delete lastAccountedEachProtocol[_protocol];\n    // `premiums_` mapping is not deleted here as it's already 0 because of the `_setSingleAndGlobalProtocolPremium` call above\n\n    // Sets a deadline in the future until which this protocol agent can still make claims for this removed protocol\n    removedProtocolClaimDeadline[_protocol] = block.timestamp + PROTOCOL_CLAIM_DEADLINE;\n\n    // This mapping allows Sherlock to verify the protocol agent making a claim after the protocol has been removed\n    // Remember, only the protocol agent can make claims on behalf of the protocol, so this must be checked\n    removedProtocolAgent[_protocol] = _agent;\n\n    emit ProtocolUpdated(_protocol, bytes32(0), uint256(0), uint256(0));\n    emit ProtocolRemoved(_protocol);\n  }\n\n  /// @notice Sets the minimum active balance before an arb can remove a protocol\n  /// @param _minActiveBalance Minimum balance needed (in USDC)\n  /// @dev Only gov\n  function setMinActiveBalance(uint256 _minActiveBalance) external override onlyOwner {\n    // New value cannot be the same as current value\n    if (minActiveBalance == _minActiveBalance) revert InvalidArgument();\n    // Can't set a value that is too high to be reasonable\n    if (_minActiveBalance >= MIN_BALANCE_SANITY_CEILING) revert InvalidConditions();\n\n    emit MinBalance(minActiveBalance, _minActiveBalance);\n    minActiveBalance = _minActiveBalance;\n  }\n\n  // This function allows the nonstakers role to claim tokens owed to them by a specific protocol\n  /// @notice Choose an `_amount` of tokens that nonstakers (`_receiver` address) will receive from `_protocol`\n  /// @param _protocol Protocol identifier\n  /// @param _amount Amount of tokens\n  /// @param _receiver Address to receive tokens\n  /// @dev Only callable by nonstakers role\n  function nonStakersClaim(\n    bytes32 _protocol,\n    uint256 _amount,\n    address _receiver\n  ) external override whenNotPaused {\n    if (_protocol == bytes32(0)) revert ZeroArgument();\n    if (_amount == uint256(0)) revert ZeroArgument();\n    if (_receiver == address(0)) revert ZeroArgument();\n    // Only the nonstakers role (multisig or contract) can pull the funds\n    if (msg.sender != sherlockCore.nonStakersAddress()) revert Unauthorized();\n\n    // Call can't be executed on protocol that is removed\n    if (protocolAgent_[_protocol] != address(0)) {\n      // Updates the amount that nonstakers can claim from this protocol\n      _settleProtocolDebt(_protocol);\n    }\n\n    // Sets balance to the amount that is claimable by nonstakers for this specific protocol\n    uint256 balance = nonStakersClaimableByProtocol[_protocol];\n    // If the amount requested is more than what's owed to nonstakers, revert\n    if (_amount > balance) revert InsufficientBalance(_protocol);\n\n    // Sets the claimable amount to whatever is left over after this amount is pulled\n    nonStakersClaimableByProtocol[_protocol] = balance - _amount;\n    // Transfers the amount requested to the `_receiver` address\n    token.safeTransfer(_receiver, _amount);\n  }\n\n  // Transfers funds owed to stakers from this contract to the Sherlock core contract (where we handle paying out stakers)\n  /// @notice Transfer current claimable premiums (for stakers) to core Sherlock address\n  /// @dev Callable by everyone\n  /// @dev Funds will be transferred to Sherlock core contract\n  function claimPremiumsForStakers() external override whenNotPaused {\n    // Gets address of core Sherlock contract\n    address sherlock = address(sherlockCore);\n    // Revert if core Sherlock contract not initialized yet\n    if (sherlock == address(0)) revert InvalidConditions();\n\n    // claimablePremiums is different from _settleTotalDebt() because it does not change state\n    // Retrieves current amount of all premiums that are owed to stakers\n    uint256 amount = claimablePremiums();\n\n    // Transfers all the premiums owed to stakers to the Sherlock core contract\n    if (amount != 0) {\n      // Global value of premiums owed to stakers is set to zero since we are transferring the entire amount out\n      lastClaimablePremiumsForStakers = 0;\n      lastAccountedGlobal = block.timestamp;\n      token.safeTransfer(sherlock, amount);\n    }\n  }\n\n  // Function is used in the SherlockClaimManager contract to decide if a proposed claim falls under either the current or previous coverage amounts\n  /// @param _protocol Protocol identifier\n  /// @return current and previous are the current and previous coverage amounts for this protocol\n  // Note For this process to work, a protocol's coverage amount should not be set more than once in the span of claim delay period (7 days or something)\n  function coverageAmounts(bytes32 _protocol)\n    external\n    view\n    override\n    returns (uint256 current, uint256 previous)\n  {\n    // Checks to see if the protocol has an active protocolAgent (protocol not removed)\n    // OR checks to see if the removed protocol is still within the claim window\n    // If so, gives the current and previous coverage, otherwise throws an error\n    if (\n      protocolAgent_[_protocol] != address(0) ||\n      block.timestamp <= removedProtocolClaimDeadline[_protocol]\n    ) {\n      return (currentCoverage[_protocol], previousCoverage[_protocol]);\n    }\n\n    revert ProtocolNotExists(_protocol);\n  }\n\n  /// @notice Add a new protocol to Sherlock\n  /// @param _protocol Protocol identifier\n  /// @param _protocolAgent Address able to submit a claim on behalf of the protocol\n  /// @param _coverage Hash referencing the active coverage agreement\n  /// @param _nonStakers Percentage of premium payments to nonstakers, scaled by 10**18\n  /// @param _coverageAmount Max amount claimable by this protocol\n  /// @dev Adding a protocol allows the `_protocolAgent` to submit a claim\n  /// @dev Coverage is not started yet as the protocol doesn't pay a premium at this point\n  /// @dev `_nonStakers` is scaled by 10**18\n  /// @dev Only callable by governance\n  function protocolAdd(\n    bytes32 _protocol,\n    address _protocolAgent,\n    bytes32 _coverage,\n    uint256 _nonStakers,\n    uint256 _coverageAmount\n  ) external override onlyOwner {\n    if (_protocol == bytes32(0)) revert ZeroArgument();\n    if (_protocolAgent == address(0)) revert ZeroArgument();\n    // Checks to make sure the protocol doesn't exist already\n    if (protocolAgent_[_protocol] != address(0)) revert InvalidConditions();\n\n    // Updates the protocol agent and passes in the old agent which is 0 address in this case\n    _setProtocolAgent(_protocol, address(0), _protocolAgent);\n\n    // Delete mappings that are potentially non default values\n    // From previous time protocol was added/removed\n    delete removedProtocolClaimDeadline[_protocol];\n    delete removedProtocolAgent[_protocol];\n    delete currentCoverage[_protocol];\n    delete previousCoverage[_protocol];\n\n    emit ProtocolAdded(_protocol);\n\n    // Most of the logic for actually adding a protocol in this function\n    protocolUpdate(_protocol, _coverage, _nonStakers, _coverageAmount);\n  }\n\n  /// @notice Update info regarding a protocol\n  /// @param _protocol Protocol identifier\n  /// @param _coverage Hash referencing the active coverage agreement\n  /// @param _nonStakers Percentage of premium payments to nonstakers, scaled by 10**18\n  /// @param _coverageAmount Max amount claimable by this protocol\n  /// @dev Only callable by governance\n  /// @dev `_nonStakers` can be 0\n  function protocolUpdate(\n    bytes32 _protocol,\n    bytes32 _coverage,\n    uint256 _nonStakers,\n    uint256 _coverageAmount\n  ) public override onlyOwner {\n    if (_coverage == bytes32(0)) revert ZeroArgument();\n    if (_nonStakers > HUNDRED_PERCENT) revert InvalidArgument();\n    if (_coverageAmount == uint256(0)) revert ZeroArgument();\n\n    // Checks to make sure the protocol has been assigned a protocol agent\n    _verifyProtocolExists(_protocol);\n\n    // Subtracts the accrued debt from a protocol's active balance (if any)\n    // Updates the amount that can be claimed by nonstakers\n    _settleProtocolDebt(_protocol);\n\n    // Updates the global claimable amount for stakers\n    _settleTotalDebt();\n\n    // Gets the premium per second for this protocol\n    uint256 premium = premiums_[_protocol];\n\n    // Updates allPremiumsPerSecToStakers (premium is not able to be updated in this function, but percentage to nonstakers can be)\n    allPremiumsPerSecToStakers = _calcGlobalPremiumPerSecForStakers(\n      premium,\n      premium,\n      nonStakersPercentage[_protocol],\n      _nonStakers,\n      allPremiumsPerSecToStakers\n    );\n\n    // Updates the stored value of percentage of premiums that go to nonstakers\n    nonStakersPercentage[_protocol] = _nonStakers;\n\n    // Updates previous coverage and current coverage amounts\n    previousCoverage[_protocol] = currentCoverage[_protocol];\n    currentCoverage[_protocol] = _coverageAmount;\n\n    emit ProtocolUpdated(_protocol, _coverage, _nonStakers, _coverageAmount);\n  }\n\n  /// @notice Remove a protocol from coverage\n  /// @param _protocol Protocol identifier\n  /// @dev Before removing a protocol the premium must be 0\n  /// @dev Removing a protocol basically stops the `_protocolAgent` from being active (can still submit claims until claim deadline though)\n  /// @dev Pays off debt + sends remaining balance to protocol agent\n  /// @dev This call should be subject to a timelock\n  /// @dev Only callable by governance\n  function protocolRemove(bytes32 _protocol) external override onlyOwner {\n    // checks to make sure the protocol actually has a protocol agent\n    address agent = _verifyProtocolExists(_protocol);\n\n    // Removes a protocol from Sherlock and cleans up its data\n    // Params are the protocol ID and the protocol agent to which remaining active balance should be sent and from which post-removal claims can be made\n    _forceRemoveProtocol(_protocol, agent);\n  }\n\n  /// @notice Remove a protocol with insufficient active balance\n  /// @param _protocol Protocol identifier\n  // msg.sender receives whatever is left of the insufficient active balance, this should incentivize arbs to call this function\n  function forceRemoveByActiveBalance(bytes32 _protocol) external override whenNotPaused {\n    address agent = _verifyProtocolExists(_protocol);\n\n    // Gets the latest value of the active balance at this protocol\n    _settleProtocolDebt(_protocol);\n    // Sets latest value of active balance to remainingBalance variable\n    uint256 remainingBalance = activeBalances[_protocol];\n\n    // This means the protocol still has adequate active balance and thus cannot be removed\n    if (remainingBalance >= minActiveBalance) revert InvalidConditions();\n\n    // Sets the protocol's active balance to 0\n    delete activeBalances[_protocol];\n    // Removes the protocol from coverage\n    _forceRemoveProtocol(_protocol, agent);\n\n    if (remainingBalance != 0) {\n      // sends the remaining balance to msg.sender\n      token.safeTransfer(msg.sender, remainingBalance);\n    }\n    emit ProtocolRemovedByArb(_protocol, msg.sender, remainingBalance);\n  }\n\n  /// @notice Calculate if arb is possible and what the reward would be\n  /// @param _protocol Protocol identifier\n  /// @return arbAmount Amount reward for arbing\n  /// @return able Indicator if arb call is even possible\n  /// @dev Doesn't subtract the current protocol debt from the active balance\n  function _calcForceRemoveBySecondsOfCoverage(bytes32 _protocol)\n    internal\n    view\n    returns (uint256 arbAmount, bool able)\n  {\n    uint256 secondsLeft = _secondsOfCoverageLeft(_protocol);\n\n    // If arb is not possible return false\n    if (secondsLeft >= MIN_SECONDS_OF_COVERAGE) return (0, false);\n\n    // This percentage scales over time\n    // Reaches 100% on 0 seconds of coverage left\n    uint256 percentageScaled = HUNDRED_PERCENT -\n      (secondsLeft * HUNDRED_PERCENT) /\n      MIN_SECONDS_OF_COVERAGE;\n\n    able = true;\n    arbAmount = (activeBalances[_protocol] * percentageScaled) / HUNDRED_PERCENT;\n  }\n\n  /// @notice Removes a protocol with insufficent seconds of coverage left\n  /// @param _protocol Protocol identifier\n  // Seconds of coverage is defined by the active balance of the protocol divided by the protocol's premium per second\n  function forceRemoveBySecondsOfCoverage(bytes32 _protocol) external override whenNotPaused {\n    // NOTE: We use _secondsOfCoverageLeft() below and include this check instead of secondsOfCoverageLeft() for gas savings\n    address agent = _verifyProtocolExists(_protocol);\n\n    // NOTE: We don't give the arb the full remaining balance like we do in forceRemoveByActiveBalance()\n    // This is because we know the exact balance the arb will get in forceRemoveByActiveBalance()\n    // But when removing based on seconds of coverage left, the remainingBalance could still be quite large\n    // So it's better to scale the arb reward over time. It's a little complex because the remainingBalance\n    // Decreases over time also but reward will be highest at the midpoint of percentageScaled (50%)\n    _settleProtocolDebt(_protocol);\n    (uint256 arbAmount, bool able) = _calcForceRemoveBySecondsOfCoverage(_protocol);\n    if (able == false) revert InvalidConditions();\n\n    if (arbAmount != 0) {\n      // subtracts the amount that will be paid to the arb from the active balance\n      activeBalances[_protocol] -= arbAmount;\n    }\n\n    // Removes the protocol from coverage\n    // This function also pays the active balance to the protocol agent, so it's good we do this after subtracting arb amount above\n    _forceRemoveProtocol(_protocol, agent);\n\n    // Done after removing protocol to mitigate reentrency pattern\n    // (In case token allows callback)\n    if (arbAmount != 0) {\n      token.safeTransfer(msg.sender, arbAmount);\n    }\n    emit ProtocolRemovedByArb(_protocol, msg.sender, arbAmount);\n  }\n\n  /// @notice Set premium of `_protocol` to `_premium`\n  /// @param _protocol Protocol identifier\n  /// @param _premium Amount of premium `_protocol` pays per second\n  /// @dev The value 0 would mean inactive coverage\n  /// @dev Only callable by governance\n  function setProtocolPremium(bytes32 _protocol, uint256 _premium) external override onlyOwner {\n    // Checks to see if protocol has a protocol agent\n    _verifyProtocolExists(_protocol);\n\n    // Updates individual protocol's premium and allPremiumsPerSecToStakers\n    _setSingleAndGlobalProtocolPremium(_protocol, _premium);\n  }\n\n  /// @notice Set premium of multiple protocols\n  /// @param _protocol Array of protocol identifiers\n  /// @param _premium Array of premium amounts protocols pay per second\n  /// @dev The value 0 would mean inactive coverage\n  /// @dev Only callable by governance\n  function setProtocolPremiums(bytes32[] calldata _protocol, uint256[] calldata _premium)\n    external\n    override\n    onlyOwner\n  {\n    // Checks to make sure there are an equal amount of entries in each array\n    if (_protocol.length != _premium.length) revert UnequalArrayLength();\n    if (_protocol.length == 0) revert InvalidArgument();\n\n    // Updates the global claimable amount for stakers\n    _settleTotalDebt();\n\n    uint256 allPremiumsPerSecToStakers_ = allPremiumsPerSecToStakers;\n\n    // Loops through the array of protocols and checks to make sure each has a protocol agent assigned\n    for (uint256 i; i < _protocol.length; i++) {\n      _verifyProtocolExists(_protocol[i]);\n\n      // Sets the protocol premium for that specific protocol\n      // Function returns the old premium and nonStakerPercentage for that specific protocol\n      (uint256 oldPremiumPerSecond, uint256 nonStakerPercentage) = _setSingleProtocolPremium(\n        _protocol[i],\n        _premium[i]\n      );\n\n      // Calculates the new global premium which adds up all premiums paid by all protocols\n      allPremiumsPerSecToStakers_ = _calcGlobalPremiumPerSecForStakers(\n        oldPremiumPerSecond,\n        _premium[i],\n        nonStakerPercentage,\n        nonStakerPercentage,\n        allPremiumsPerSecToStakers_\n      );\n    }\n\n    // After the loop has finished, sets allPremiumsPerSecToStakers to the final temp value\n    allPremiumsPerSecToStakers = allPremiumsPerSecToStakers_;\n  }\n\n  // This is how protocols pay for coverage by increasing their active balance\n  /// @notice Deposits `_amount` of token to the active balance of `_protocol`\n  /// @param _protocol Protocol identifier\n  /// @param _amount Amount of tokens to deposit\n  /// @dev Approval should be made before calling\n  function depositToActiveBalance(bytes32 _protocol, uint256 _amount)\n    external\n    override\n    whenNotPaused\n  {\n    if (_amount == uint256(0)) revert ZeroArgument();\n    _verifyProtocolExists(_protocol);\n\n    // Transfers _amount to this contract\n    token.safeTransferFrom(msg.sender, address(this), _amount);\n    // Increases the active balance of the protocol by _amount\n    activeBalances[_protocol] += _amount;\n\n    emit ProtocolBalanceDeposited(_protocol, _amount);\n  }\n\n  // If a protocol has paid too much into the active balance (which is how a protocol pays the premium)\n  // Then the protocol can remove some of the active balance (up until there is 7 days worth of balance left)\n  /// @notice Withdraws `_amount` of token from the active balance of `_protocol`\n  /// @param _protocol Protocol identifier\n  /// @param _amount Amount of tokens to withdraw\n  /// @dev Only protocol agent is able to withdraw\n  /// @dev Balance can be withdrawn up until 7 days worth of active balance\n  function withdrawActiveBalance(bytes32 _protocol, uint256 _amount)\n    external\n    override\n    whenNotPaused\n  {\n    if (_amount == uint256(0)) revert ZeroArgument();\n    // Only the protocol agent can call this function\n    if (msg.sender != _verifyProtocolExists(_protocol)) revert Unauthorized();\n\n    // Updates the active balance of the protocol\n    _settleProtocolDebt(_protocol);\n\n    // Sets currentBalance to the active balance of the protocol\n    uint256 currentBalance = activeBalances[_protocol];\n    // Reverts if trying to withdraw more than the active balance\n    if (_amount > currentBalance) revert InsufficientBalance(_protocol);\n\n    // Removes the _amount to be withdrawn from the active balance\n    activeBalances[_protocol] = currentBalance - _amount;\n    // Reverts if a protocol has less than 7 days worth of active balance left\n    if (_secondsOfCoverageLeft(_protocol) < MIN_SECONDS_LEFT) revert InsufficientBalance(_protocol);\n\n    // Transfers the amount to the msg.sender (protocol agent)\n    token.safeTransfer(msg.sender, _amount);\n    emit ProtocolBalanceWithdrawn(_protocol, _amount);\n  }\n\n  /// @notice Transfer protocol agent role\n  /// @param _protocol Protocol identifier\n  /// @param _protocolAgent Account able to submit a claim on behalf of the protocol\n  /// @dev Only the active protocolAgent is able to transfer the role\n  function transferProtocolAgent(bytes32 _protocol, address _protocolAgent)\n    external\n    override\n    whenNotPaused\n  {\n    if (_protocolAgent == address(0)) revert ZeroArgument();\n    // Can't set the new protocol agent to the caller address\n    if (msg.sender == _protocolAgent) revert InvalidArgument();\n    // Because the caller must be the current protocol agent\n    if (msg.sender != _verifyProtocolExists(_protocol)) revert Unauthorized();\n\n    // Sets the protocol agent to the new address\n    _setProtocolAgent(_protocol, msg.sender, _protocolAgent);\n  }\n\n  /// @notice Function used to check if this is the current active protocol manager\n  /// @return Boolean indicating it's active\n  /// @dev If inactive the owner can pull all ERC20s and ETH\n  /// @dev Will be checked by calling the sherlock contract\n  function isActive() public view returns (bool) {\n    return address(sherlockCore.sherlockProtocolManager()) == address(this);\n  }\n\n  // Only contract owner can call this\n  // Sends all specified tokens in this contract to the receiver's address (as well as ETH)\n  function sweep(address _receiver, IERC20[] memory _extraTokens) external onlyOwner {\n    if (_receiver == address(0)) revert ZeroArgument();\n    // This contract must NOT be the current assigned protocol manager contract\n    if (isActive()) revert InvalidConditions();\n    // Executes the sweep for ERC-20s specified in _extraTokens as well as for ETH\n    _sweep(_receiver, _extraTokens);\n  }\n}"
}