{
    "Function": "slitherConstructorConstantVariables",
    "File": "src/contracts/core/Slasher.sol",
    "Parent Contracts": [
        "src/contracts/permissions/Pausable.sol",
        "src/contracts/interfaces/IPausable.sol",
        "src/contracts/interfaces/ISlasher.sol",
        "lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol",
        "lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol",
        "lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract Slasher is Initializable, OwnableUpgradeable, ISlasher, Pausable {\n    using StructuredLinkedList for StructuredLinkedList.List;\n\n    uint256 private constant HEAD = 0;\n\n    uint8 internal constant PAUSED_OPT_INTO_SLASHING = 0;\n    uint8 internal constant PAUSED_FIRST_STAKE_UPDATE = 1;\n    uint8 internal constant PAUSED_NEW_FREEZING = 2;\n\n    /// @notice The central StrategyManager contract of EigenLayer\n    IStrategyManager public immutable strategyManager;\n    /// @notice The DelegationManager contract of EigenLayer\n    IDelegationManager public immutable delegation;\n    // operator => whitelisted contract with slashing permissions => (the time before which the contract is allowed to slash the user, block it was last updated)\n    mapping(address => mapping(address => MiddlewareDetails)) internal _whitelistedContractDetails;\n    // staker => if their funds are 'frozen' and potentially subject to slashing or not\n    mapping(address => bool) internal frozenStatus;\n\n    uint32 internal constant MAX_CAN_SLASH_UNTIL = type(uint32).max;\n\n    /**\n     * operator => a linked list of the addresses of the whitelisted middleware with permission to slash the operator, i.e. which  \n     * the operator is serving. Sorted by the block at which they were last updated (content of updates below) in ascending order.\n     * This means the 'HEAD' (i.e. start) of the linked list will have the stalest 'updateBlock' value.\n     */\n    mapping(address => StructuredLinkedList.List) internal _operatorToWhitelistedContractsByUpdate;\n\n    /**\n     * operator => \n     *  [\n     *      (\n     *          the least recent update block of all of the middlewares it's serving/served, \n     *          latest time that the stake bonded at that update needed to serve until\n     *      )\n     *  ]\n     */\n    mapping(address => MiddlewareTimes[]) internal _operatorToMiddlewareTimes;\n\n    /// @notice Emitted when a middleware times is added to `operator`'s array.\n    event MiddlewareTimesAdded(address operator, uint256 index, uint32 stalestUpdateBlock, uint32 latestServeUntilBlock);\n\n    /// @notice Emitted when `operator` begins to allow `contractAddress` to slash them.\n    event OptedIntoSlashing(address indexed operator, address indexed contractAddress);\n\n    /// @notice Emitted when `contractAddress` signals that it will no longer be able to slash `operator` after the `contractCanSlashOperatorUntilBlock`.\n    event SlashingAbilityRevoked(address indexed operator, address indexed contractAddress, uint32 contractCanSlashOperatorUntilBlock);\n\n    /**\n     * @notice Emitted when `slashingContract` 'freezes' the `slashedOperator`.\n     * @dev The `slashingContract` must have permission to slash the `slashedOperator`, i.e. `canSlash(slasherOperator, slashingContract)` must return 'true'.\n     */\n    event OperatorFrozen(address indexed slashedOperator, address indexed slashingContract);\n\n    /// @notice Emitted when `previouslySlashedAddress` is 'unfrozen', allowing them to again move deposited funds within EigenLayer.\n    event FrozenStatusReset(address indexed previouslySlashedAddress);\n\n    constructor(IStrategyManager _strategyManager, IDelegationManager _delegation) {\n        strategyManager = _strategyManager;\n        delegation = _delegation;\n        _disableInitializers();\n    }\n\n    /// @notice Ensures that the operator has opted into slashing by the caller, and that the caller has never revoked its slashing ability.\n    modifier onlyRegisteredForService(address operator) {\n        require(_whitelistedContractDetails[operator][msg.sender].contractCanSlashOperatorUntilBlock == MAX_CAN_SLASH_UNTIL,\n            \"Slasher.onlyRegisteredForService: Operator has not opted into slashing by caller\");\n        _;\n    }\n\n    // EXTERNAL FUNCTIONS\n    function initialize(\n        address initialOwner,\n        IPauserRegistry _pauserRegistry,\n        uint256 initialPausedStatus\n    ) external initializer {\n        _initializePauser(_pauserRegistry, initialPausedStatus);\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @notice Gives the `contractAddress` permission to slash the funds of the caller.\n     * @dev Typically, this function must be called prior to registering for a middleware.\n     */\n    function optIntoSlashing(address contractAddress) external onlyWhenNotPaused(PAUSED_OPT_INTO_SLASHING) {\n        require(delegation.isOperator(msg.sender), \"Slasher.optIntoSlashing: msg.sender is not a registered operator\");\n        _optIntoSlashing(msg.sender, contractAddress);\n    }\n\n    /**\n     * @notice Used for 'slashing' a certain operator.\n     * @param toBeFrozen The operator to be frozen.\n     * @dev Technically the operator is 'frozen' (hence the name of this function), and then subject to slashing pending a decision by a human-in-the-loop.\n     * @dev The operator must have previously given the caller (which should be a contract) the ability to slash them, through a call to `optIntoSlashing`.\n     */\n    function freezeOperator(address toBeFrozen) external onlyWhenNotPaused(PAUSED_NEW_FREEZING) {\n        require(\n            canSlash(toBeFrozen, msg.sender),\n            \"Slasher.freezeOperator: msg.sender does not have permission to slash this operator\"\n        );\n        _freezeOperator(toBeFrozen, msg.sender);\n    }\n\n    /**\n     * @notice Removes the 'frozen' status from each of the `frozenAddresses`\n     * @dev Callable only by the contract owner (i.e. governance).\n     */\n    function resetFrozenStatus(address[] calldata frozenAddresses) external onlyOwner {\n        for (uint256 i = 0; i < frozenAddresses.length;) {\n            _resetFrozenStatus(frozenAddresses[i]);\n            unchecked {\n                ++i;\n            }\n        }\n    }\n\n    /**\n     * @notice this function is a called by middlewares during an operator's registration to make sure the operator's stake at registration \n     *         is slashable until serveUntilBlock\n     * @param operator the operator whose stake update is being recorded\n     * @param serveUntilBlock the block until which the operator's stake at the current block is slashable\n     * @dev adds the middleware's slashing contract to the operator's linked list\n     */\n    function recordFirstStakeUpdate(address operator, uint32 serveUntilBlock) \n        external \n        onlyWhenNotPaused(PAUSED_FIRST_STAKE_UPDATE)\n        onlyRegisteredForService(operator)\n    {\n        // update the 'stalest' stakes update time + latest 'serveUntil' time of the `operator`\n        _recordUpdateAndAddToMiddlewareTimes(operator, uint32(block.number), serveUntilBlock);\n\n        // Push the middleware to the end of the update list. This will fail if the caller *is* already in the list.\n        require(_operatorToWhitelistedContractsByUpdate[operator].pushBack(_addressToUint(msg.sender)), \n            \"Slasher.recordFirstStakeUpdate: Appending middleware unsuccessful\");\n    }\n\n    /**\n     * @notice this function is a called by middlewares during a stake update for an operator (perhaps to free pending withdrawals)\n     *         to make sure the operator's stake at updateBlock is slashable until serveUntilBlock\n     * @param operator the operator whose stake update is being recorded\n     * @param updateBlock the block for which the stake update is being recorded\n     * @param serveUntilBlock the block until which the operator's stake at updateBlock is slashable\n     * @param insertAfter the element of the operators linked list that the currently updating middleware should be inserted after\n     * @dev insertAfter should be calculated offchain before making the transaction that calls this. this is subject to race conditions, \n     *      but it is anticipated to be rare and not detrimental.\n     */\n    function recordStakeUpdate(address operator, uint32 updateBlock, uint32 serveUntilBlock, uint256 insertAfter) \n        external \n        onlyRegisteredForService(operator) \n    {\n        // sanity check on input\n        require(updateBlock <= block.number, \"Slasher.recordStakeUpdate: cannot provide update for future block\");\n        // update the 'stalest' stakes update time + latest 'serveUntilBlock' of the `operator`\n        _recordUpdateAndAddToMiddlewareTimes(operator, updateBlock, serveUntilBlock);\n\n        /**\n         * Move the middleware to its correct update position, determined by `updateBlock` and indicated via `insertAfter`.\n         * If the the middleware is the only one in the list, then no need to mutate the list\n         */\n        if (_operatorToWhitelistedContractsByUpdate[operator].sizeOf() != 1) {\n            // Remove the caller (middleware) from the list. This will fail if the caller is *not* already in the list.\n            require(_operatorToWhitelistedContractsByUpdate[operator].remove(_addressToUint(msg.sender)) != 0, \n                \"Slasher.recordStakeUpdate: Removing middleware unsuccessful\");\n            // Run routine for updating the `operator`'s linked list of middlewares\n            _updateMiddlewareList(operator, updateBlock, insertAfter);\n        // if there is precisely one middleware in the list, then ensure that the caller is indeed the singular list entrant\n        } else {\n            require(_operatorToWhitelistedContractsByUpdate[operator].getHead() == _addressToUint(msg.sender),\n                \"Slasher.recordStakeUpdate: Caller is not the list entrant\");\n        }\n    }\n\n    /**\n     * @notice this function is a called by middlewares during an operator's deregistration to make sure the operator's stake at deregistration \n     *         is slashable until serveUntilBlock\n     * @param operator the operator whose stake update is being recorded\n     * @param serveUntilBlock the block until which the operator's stake at the current block is slashable\n     * @dev removes the middleware's slashing contract to the operator's linked list and revokes the middleware's (i.e. caller's) ability to\n     * slash `operator` once `serveUntilBlock` is reached\n     */\n    function recordLastStakeUpdateAndRevokeSlashingAbility(address operator, uint32 serveUntilBlock) external onlyRegisteredForService(operator) {\n        // update the 'stalest' stakes update time + latest 'serveUntilBlock' of the `operator`\n        _recordUpdateAndAddToMiddlewareTimes(operator, uint32(block.number), serveUntilBlock);\n        // remove the middleware from the list\n        require(_operatorToWhitelistedContractsByUpdate[operator].remove(_addressToUint(msg.sender)) != 0,\n             \"Slasher.recordLastStakeUpdateAndRevokeSlashingAbility: Removing middleware unsuccessful\");\n        // revoke the middleware's ability to slash `operator` after `serverUntil`\n        _revokeSlashingAbility(operator, msg.sender, serveUntilBlock);\n    }\n\n    // VIEW FUNCTIONS\n\n    /// @notice Returns the block until which `serviceContract` is allowed to slash the `operator`.\n    function contractCanSlashOperatorUntilBlock(address operator, address serviceContract) external view returns (uint32) {\n        return _whitelistedContractDetails[operator][serviceContract].contractCanSlashOperatorUntilBlock;\n    }\n\n    /// @notice Returns the block at which the `serviceContract` last updated its view of the `operator`'s stake\n    function latestUpdateBlock(address operator, address serviceContract) external view returns (uint32) {\n        return _whitelistedContractDetails[operator][serviceContract].latestUpdateBlock;\n    }\n\n    /*\n    * @notice Returns `_whitelistedContractDetails[operator][serviceContract]`.\n    * @dev A getter function like this appears to be necessary for returning a struct from storage in struct form, rather than as a tuple.\n    */\n    function whitelistedContractDetails(address operator, address serviceContract) external view returns (MiddlewareDetails memory) {\n        return _whitelistedContractDetails[operator][serviceContract];\n    }\n\n\n    /**\n     * @notice Used to determine whether `staker` is actively 'frozen'. If a staker is frozen, then they are potentially subject to\n     * slashing of their funds, and cannot cannot deposit or withdraw from the strategyManager until the slashing process is completed\n     * and the staker's status is reset (to 'unfrozen').\n     * @return Returns 'true' if `staker` themselves has their status set to frozen, OR if the staker is delegated\n     * to an operator who has their status set to frozen. Otherwise returns 'false'.\n     */\n    function isFrozen(address staker) external view returns (bool) {\n        if (frozenStatus[staker]) {\n            return true;\n        } else if (delegation.isDelegated(staker)) {\n            address operatorAddress = delegation.delegatedTo(staker);\n            return (frozenStatus[operatorAddress]);\n        } else {\n            return false;\n        }\n    }\n\n    /// @notice Returns true if `slashingContract` is currently allowed to slash `toBeSlashed`.\n    function canSlash(address toBeSlashed, address slashingContract) public view returns (bool) {\n        if (block.number < _whitelistedContractDetails[toBeSlashed][slashingContract].contractCanSlashOperatorUntilBlock) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @notice Returns 'true' if `operator` can currently complete a withdrawal started at the `withdrawalStartBlock`, with `middlewareTimesIndex` used\n     * to specify the index of a `MiddlewareTimes` struct in the operator's list (i.e. an index in `_operatorToMiddlewareTimes[operator]`). The specified\n     * struct is consulted as proof of the `operator`'s ability (or lack thereof) to complete the withdrawal.\n     * This function will return 'false' if the operator cannot currently complete a withdrawal started at the `withdrawalStartBlock`, *or* in the event\n     * that an incorrect `middlewareTimesIndex` is supplied, even if one or more correct inputs exist.\n     * @param operator Either the operator who queued the withdrawal themselves, or if the withdrawing party is a staker who delegated to an operator,\n     * this address is the operator *who the staker was delegated to* at the time of the `withdrawalStartBlock`.\n     * @param withdrawalStartBlock The block number at which the withdrawal was initiated.\n     * @param middlewareTimesIndex Indicates an index in `_operatorToMiddlewareTimes[operator]` to consult as proof of the `operator`'s ability to withdraw\n     * @dev The correct `middlewareTimesIndex` input should be computable off-chain.\n     */\n    function canWithdraw(address operator, uint32 withdrawalStartBlock, uint256 middlewareTimesIndex) external view returns (bool) {\n        // if the operator has never registered for a middleware, just return 'true'\n        if (_operatorToMiddlewareTimes[operator].length == 0) {\n            return true;\n        }\n\n        // pull the MiddlewareTimes struct at the `middlewareTimesIndex`th position in `_operatorToMiddlewareTimes[operator]`\n        MiddlewareTimes memory update = _operatorToMiddlewareTimes[operator][middlewareTimesIndex];\n\n        /**\n         * Case-handling for if the operator is not registered for any middlewares (i.e. they previously registered but are no longer registered for any),\n         * AND the withdrawal was initiated after the 'stalestUpdateBlock' of the MiddlewareTimes struct specified by the provided `middlewareTimesIndex`.\n         * NOTE: we check the 2nd of these 2 conditions first for gas efficiency, to help avoid an extra SLOAD in all other cases.\n         */\n        if (withdrawalStartBlock >= update.stalestUpdateBlock && _operatorToWhitelistedContractsByUpdate[operator].size == 0) {\n            /**\n             * In this case, we just check against the 'latestServeUntilBlock' of the last MiddlewareTimes struct. This is because the operator not being registered\n             * for any middlewares (i.e. `_operatorToWhitelistedContractsByUpdate.size == 0`) means no new MiddlewareTimes structs will be being pushed, *and* the operator \n             * will not be undertaking any new obligations (so just checking against the last entry is OK, unlike when the operator is actively registered for >=1 middleware).\n             */\n            update = _operatorToMiddlewareTimes[operator][_operatorToMiddlewareTimes[operator].length - 1];\n            return (uint32(block.number) > update.latestServeUntilBlock);\n        }\n        \n        /**\n         * Make sure the stalest update block at the time of the update is strictly after `withdrawalStartBlock` and ensure that the current time\n         * is after the `latestServeUntilBlock` of the update. This assures us that this that all middlewares were updated after the withdrawal began, and\n         * that the stake is no longer slashable.\n         */\n        return(\n            withdrawalStartBlock < update.stalestUpdateBlock \n            &&\n            uint32(block.number) > update.latestServeUntilBlock\n        );\n    }\n\n    /// @notice Getter function for fetching `_operatorToMiddlewareTimes[operator][arrayIndex]`.\n    function operatorToMiddlewareTimes(address operator, uint256 arrayIndex) external view returns (MiddlewareTimes memory) {\n        return _operatorToMiddlewareTimes[operator][arrayIndex];\n    }\n\n    /// @notice Getter function for fetching `_operatorToMiddlewareTimes[operator].length`.\n    function middlewareTimesLength(address operator) external view returns (uint256) {\n        return _operatorToMiddlewareTimes[operator].length;\n    }\n\n    /// @notice Getter function for fetching `_operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`.\n    function getMiddlewareTimesIndexBlock(address operator, uint32 index) external view returns (uint32) {\n        return _operatorToMiddlewareTimes[operator][index].stalestUpdateBlock;\n    }\n\n    /// @notice Getter function for fetching `_operatorToMiddlewareTimes[operator][index].latestServeUntilBlock`.\n    function getMiddlewareTimesIndexServeUntilBlock(address operator, uint32 index) external view returns (uint32) {\n        return _operatorToMiddlewareTimes[operator][index].latestServeUntilBlock;\n    }\n\n    /// @notice Getter function for fetching `_operatorToWhitelistedContractsByUpdate[operator].size`.\n    function operatorWhitelistedContractsLinkedListSize(address operator) external view returns (uint256) {\n        return _operatorToWhitelistedContractsByUpdate[operator].size;\n    }\n\n    /// @notice Getter function for fetching a single node in the operator's linked list (`_operatorToWhitelistedContractsByUpdate[operator]`).\n    function operatorWhitelistedContractsLinkedListEntry(address operator, address node) external view returns (bool, uint256, uint256) {\n        return StructuredLinkedList.getNode(_operatorToWhitelistedContractsByUpdate[operator], _addressToUint(node));\n    }\n\n    /**\n     * @notice A search routine for finding the correct input value of `insertAfter` to `recordStakeUpdate` / `_updateMiddlewareList`.\n     * @dev Used within this contract only as a fallback in the case when an incorrect value of `insertAfter` is supplied as an input to `_updateMiddlewareList`.\n     * @dev The return value should *either* be 'HEAD' (i.e. zero) in the event that the node being inserted in the linked list has an `updateBlock`\n     * that is less than the HEAD of the list, *or* the return value should specify the last `node` in the linked list for which\n     * `_whitelistedContractDetails[operator][node].latestUpdateBlock <= updateBlock`,\n     * i.e. the node such that the *next* node either doesn't exist,\n     * OR\n     * `_whitelistedContractDetails[operator][nextNode].latestUpdateBlock > updateBlock`.\n     */\n    function getCorrectValueForInsertAfter(address operator, uint32 updateBlock) public view returns (uint256) {\n        uint256 node = _operatorToWhitelistedContractsByUpdate[operator].getHead();\n        /**\n         * Special case:\n         * If the node being inserted in the linked list has an `updateBlock` that is less than the HEAD of the list, then we set `insertAfter = HEAD`.\n         * In _updateMiddlewareList(), the new node will be pushed to the front (HEAD) of the list.\n         */\n        if (_whitelistedContractDetails[operator][_uintToAddress(node)].latestUpdateBlock > updateBlock) {\n            return HEAD;\n        }\n        /**\n         * `node` being zero (i.e. equal to 'HEAD') indicates an empty/non-existent node, i.e. reaching the end of the linked list.\n         * Since the linked list is ordered in ascending order of update blocks, we simply start from the head of the list and step through until\n         * we find a the *last* `node` for which `_whitelistedContractDetails[operator][node].latestUpdateBlock <= updateBlock`, or\n         * otherwise reach the end of the list.\n         */\n        (, uint256 nextNode) = _operatorToWhitelistedContractsByUpdate[operator].getNextNode(node);\n        while ((nextNode != HEAD) && (_whitelistedContractDetails[operator][_uintToAddress(node)].latestUpdateBlock <= updateBlock)) {\n            node = nextNode;\n            (, nextNode) = _operatorToWhitelistedContractsByUpdate[operator].getNextNode(node);\n        }\n        return node;\n    }\n\n    /// @notice gets the node previous to the given node in the operators middleware update linked list\n    /// @dev used in offchain libs for updating stakes\n    function getPreviousWhitelistedContractByUpdate(address operator, uint256 node) external view returns (bool, uint256) {\n        return _operatorToWhitelistedContractsByUpdate[operator].getPreviousNode(node);\n    }\n\n    // INTERNAL FUNCTIONS\n\n    function _optIntoSlashing(address operator, address contractAddress) internal {\n        //allow the contract to slash anytime before a time VERY far in the future\n        _whitelistedContractDetails[operator][contractAddress].contractCanSlashOperatorUntilBlock = MAX_CAN_SLASH_UNTIL;\n        emit OptedIntoSlashing(operator, contractAddress);\n    }\n\n    function _revokeSlashingAbility(address operator, address contractAddress, uint32 serveUntilBlock) internal {\n        require(serveUntilBlock != MAX_CAN_SLASH_UNTIL, \"Slasher._revokeSlashingAbility: serveUntilBlock time must be limited\");\n        // contractAddress can now only slash operator before `serveUntilBlock`\n        _whitelistedContractDetails[operator][contractAddress].contractCanSlashOperatorUntilBlock = serveUntilBlock;\n        emit SlashingAbilityRevoked(operator, contractAddress, serveUntilBlock);\n    }\n\n    function _freezeOperator(address toBeFrozen, address slashingContract) internal {\n        if (!frozenStatus[toBeFrozen]) {\n            frozenStatus[toBeFrozen] = true;\n            emit OperatorFrozen(toBeFrozen, slashingContract);\n        }\n    }\n\n    function _resetFrozenStatus(address previouslySlashedAddress) internal {\n        if (frozenStatus[previouslySlashedAddress]) {\n            frozenStatus[previouslySlashedAddress] = false;\n            emit FrozenStatusReset(previouslySlashedAddress);\n        }\n    }\n\n    /**\n     * @notice records the most recent updateBlock for the currently updating middleware and appends an entry to the operator's list of \n     *         MiddlewareTimes if relavent information has updated\n     * @param operator the entity whose stake update is being recorded\n     * @param updateBlock the block number for which the currently updating middleware is updating the serveUntilBlock for\n     * @param serveUntilBlock the block until which the operator's stake at updateBlock is slashable\n     * @dev this function is only called during externally called stake updates by middleware contracts that can slash operator\n     */\n    function _recordUpdateAndAddToMiddlewareTimes(address operator, uint32 updateBlock, uint32 serveUntilBlock) internal {\n        // reject any stale update, i.e. one from before that of the most recent recorded update for the currently updating middleware\n        require(_whitelistedContractDetails[operator][msg.sender].latestUpdateBlock <= updateBlock, \n                \"Slasher._recordUpdateAndAddToMiddlewareTimes: can't push a previous update\");\n        _whitelistedContractDetails[operator][msg.sender].latestUpdateBlock = updateBlock;\n        // get the latest recorded MiddlewareTimes, if the operator's list of MiddlwareTimes is non empty\n        MiddlewareTimes memory curr;\n        uint256 _operatorToMiddlewareTimesLength = _operatorToMiddlewareTimes[operator].length;\n        if (_operatorToMiddlewareTimesLength != 0) {\n            curr = _operatorToMiddlewareTimes[operator][_operatorToMiddlewareTimesLength - 1];\n        }\n        MiddlewareTimes memory next = curr;\n        bool pushToMiddlewareTimes;\n        // if the serve until is later than the latest recorded one, update it\n        if (serveUntilBlock > curr.latestServeUntilBlock) {\n            next.latestServeUntilBlock = serveUntilBlock;\n            // mark that we need push next to middleware times array because it contains new information\n            pushToMiddlewareTimes = true;\n        } \n        \n        // If this is the very first middleware added to the operator's list of middleware, then we add an entry to _operatorToMiddlewareTimes\n        if (_operatorToWhitelistedContractsByUpdate[operator].size == 0) {\n            next.stalestUpdateBlock = updateBlock;\n            pushToMiddlewareTimes = true;\n        }\n        // If the middleware is the first in the list, we will update the `stalestUpdateBlock` field in MiddlewareTimes\n        else if (_operatorToWhitelistedContractsByUpdate[operator].getHead() == _addressToUint(msg.sender)) {\n            // if the updated middleware was the earliest update, set it to the 2nd earliest update's update time\n            (bool hasNext, uint256 nextNode) = _operatorToWhitelistedContractsByUpdate[operator].getNextNode(_addressToUint(msg.sender));\n\n            if (hasNext) {\n                // get the next middleware's latest update block\n                uint32 nextMiddlewaresLeastRecentUpdateBlock = _whitelistedContractDetails[operator][_uintToAddress(nextNode)].latestUpdateBlock;\n                if (nextMiddlewaresLeastRecentUpdateBlock < updateBlock) {\n                    // if there is a next node, then set the stalestUpdateBlock to its recorded value\n                    next.stalestUpdateBlock = nextMiddlewaresLeastRecentUpdateBlock;\n                } else {\n                    //otherwise updateBlock is the least recent update as well\n                    next.stalestUpdateBlock = updateBlock;\n                }\n            } else {\n                // otherwise this is the only middleware so right now is the stalestUpdateBlock\n                next.stalestUpdateBlock = updateBlock;\n            }\n            // mark that we need to push `next` to middleware times array because it contains new information\n            pushToMiddlewareTimes = true;\n        }\n        \n        // if `next` has new information, then push it\n        if (pushToMiddlewareTimes) {\n            _operatorToMiddlewareTimes[operator].push(next);\n            emit MiddlewareTimesAdded(operator, _operatorToMiddlewareTimes[operator].length - 1, next.stalestUpdateBlock, next.latestServeUntilBlock);\n        }\n    }\n\n    /// @notice A routine for updating the `operator`'s linked list of middlewares, inside `recordStakeUpdate`.\n    function _updateMiddlewareList(address operator, uint32 updateBlock, uint256 insertAfter) internal {\n        /**\n         * boolean used to track if the `insertAfter input to this function is incorrect. If it is, then `runFallbackRoutine` will\n         * be flipped to 'true', and we will use `getCorrectValueForInsertAfter` to find the correct input. This routine helps solve\n         * a race condition where the proper value of `insertAfter` changes while a transaction is pending.\n         */\n       \n        bool runFallbackRoutine = false;\n        // If this condition is met, then the `updateBlock` input should be after `insertAfter`'s latest updateBlock\n        if (insertAfter != HEAD) {\n            // Check that `insertAfter` exists. If not, we will use the fallback routine to find the correct value for `insertAfter`.\n            if (!_operatorToWhitelistedContractsByUpdate[operator].nodeExists(insertAfter)) {\n                runFallbackRoutine = true;\n            }\n\n            /**\n             * Make sure `insertAfter` specifies a node for which the most recent updateBlock was *at or before* updateBlock.\n             * Again, if not,  we will use the fallback routine to find the correct value for `insertAfter`.\n             */\n            if ((!runFallbackRoutine) && (_whitelistedContractDetails[operator][_uintToAddress(insertAfter)].latestUpdateBlock > updateBlock)) {\n                runFallbackRoutine = true;\n            }\n\n            // if we have not marked `runFallbackRoutine` as 'true' yet, then that means the `insertAfter` input was correct so far\n            if (!runFallbackRoutine) {\n                // Get `insertAfter`'s successor. `hasNext` will be false if `insertAfter` is the last node in the list\n                (bool hasNext, uint256 nextNode) = _operatorToWhitelistedContractsByUpdate[operator].getNextNode(insertAfter);\n                if (hasNext) {\n                    /**\n                     * Make sure the element after `insertAfter`'s most recent updateBlock was *strictly after* `updateBlock`.\n                     * Again, if not,  we will use the fallback routine to find the correct value for `insertAfter`.\n                     */\n                    if (_whitelistedContractDetails[operator][_uintToAddress(nextNode)].latestUpdateBlock <= updateBlock) {\n                        runFallbackRoutine = true;\n                    }\n                }\n            }\n\n            // if we have not marked `runFallbackRoutine` as 'true' yet, then that means the `insertAfter` input was correct on all counts\n            if (!runFallbackRoutine) {\n                /** \n                 * Insert the caller (middleware) after `insertAfter`.\n                 * This will fail if `msg.sender` is already in the list, which they shouldn't be because they were removed from the list above.\n                 */\n                require(_operatorToWhitelistedContractsByUpdate[operator].insertAfter(insertAfter, _addressToUint(msg.sender)),\n                    \"Slasher.recordStakeUpdate: Inserting middleware unsuccessful\");\n            // in this case (runFallbackRoutine == true), we run a search routine to find the correct input value of `insertAfter` and then rerun this function\n            } else {\n                insertAfter = getCorrectValueForInsertAfter(operator, updateBlock);\n                _updateMiddlewareList(operator, updateBlock, insertAfter);\n            }\n        // In this case (insertAfter == HEAD), the `updateBlock` input should be before every other middleware's latest updateBlock.\n        } else {\n            /**\n             * Check that `updateBlock` is before any other middleware's latest updateBlock.\n             * If not, use the fallback routine to find the correct value for `insertAfter`.\n             */\n            if (_whitelistedContractDetails[operator][\n                _uintToAddress(_operatorToWhitelistedContractsByUpdate[operator].getHead()) ].latestUpdateBlock <= updateBlock)\n            {\n                runFallbackRoutine = true;\n            }\n            // if we have not marked `runFallbackRoutine` as 'true' yet, then that means the `insertAfter` input was correct on all counts\n            if (!runFallbackRoutine) {\n                /**\n                 * Insert the middleware at the start (i.e. HEAD) of the list.\n                 * This will fail if `msg.sender` is already in the list, which they shouldn't be because they were removed from the list above.\n                 */\n                require(_operatorToWhitelistedContractsByUpdate[operator].pushFront(_addressToUint(msg.sender)), \n                    \"Slasher.recordStakeUpdate: Preppending middleware unsuccessful\");\n            // in this case (runFallbackRoutine == true), we run a search routine to find the correct input value of `insertAfter` and then rerun this function\n            } else {\n                insertAfter = getCorrectValueForInsertAfter(operator, updateBlock);\n                _updateMiddlewareList(operator, updateBlock, insertAfter);\n            }\n        }\n    }\n\n    function _addressToUint(address addr) internal pure returns(uint256) {\n        return uint256(uint160(addr));\n    }\n\n    function _uintToAddress(uint256 x) internal pure returns(address) {\n        return address(uint160(x));\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[46] private __gap;\n}"
}