creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/StakedALT.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\n// Copyright (c) 2024, Alt Research Ltd.\npragma solidity =0.8.23;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {StakedMultiToken} from \"./StakedMultiToken.sol\";\n\ncontract StakedALT is StakedMultiToken {\n    constructor(IERC20 altToken_, uint40 stakingStartTimestamp_) StakedMultiToken(altToken_, stakingStartTimestamp_) {}\n\n    event URIUpdated(string);\n\n    function setURI(string memory newuri) external onlyOwner {\n        _setURI(newuri);\n        emit URIUpdated(newuri);\n    }\n\n    function name() external pure returns (string memory) {\n        return \"Staked ALT\";\n    }\n\n    function symbol() external pure returns (string memory) {\n        return \"STKALT\";\n    }\n\n    function decimals() external pure returns (uint256) {\n        return 1e18;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC20Permit} from \"../extensions/IERC20Permit.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev An operation with an ERC20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data);\n        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\n    }\n}\n"
      },
      "src/StakedMultiToken.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity =0.8.23;\n\nimport {SafeERC20, IERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {\n    ERC1155SupplyUpgradeable,\n    ERC1155Upgradeable\n} from \"@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/ERC1155SupplyUpgradeable.sol\";\n\nimport {IStakedMultiToken} from \"./interfaces/IStakedMultiToken.sol\";\nimport {DistributionData, RewardDistribution} from \"./RewardDistribution.sol\";\nimport {AlertSystem} from \"./AlertSystem.sol\";\nimport {OperatorRegistry} from \"./OperatorRegistry.sol\";\nimport {\n    ArrayLengthMismatch,\n    ZeroVotingStake,\n    FrozenOperator,\n    InsufficientAmount,\n    LessThanMinStakeToVote,\n    ZeroAddress,\n    NotOperator,\n    AlreadyRegistered,\n    InvalidBPS,\n    ZeroExchangeRate,\n    ZeroAmount,\n    InvalidCooldownAmount,\n    InsufficientCooldown,\n    ZeroUnstakeable,\n    InvalidDestination,\n    GreaterThanMaxCooldownSec,\n    StakingNotStartedYet,\n    InvalidStakingStartTime,\n    NotSupported\n} from \"./Errors.sol\";\n\n/// @dev The staked token should be deployed on Ethereum.\n/// This is adapted from https://github.com/bgd-labs/aave-stk-v1-5/blob/8867dd5b1137d4d46acd9716fe98759cb16b1606/src/contracts/StakedTokenV3.sol\n// solhint-disable not-rely-on-time, var-name-mixedcase\n// slither-disable-start timestamp\nabstract contract StakedMultiToken is IStakedMultiToken, ERC1155SupplyUpgradeable, RewardDistribution, AlertSystem {\n    using SafeERC20 for IERC20;\n\n    struct ProtocolConfig {\n        address vault;\n        /// @dev Seconds between starting cooldown and being able to update fee\n        uint40 cooldownSeconds;\n        Fee fee;\n    }\n\n    struct OperatorConfig {\n        /// @dev Seconds between starting cooldown and being able to update fee\n        uint40 cooldownSeconds;\n        mapping(address => Fee) fees;\n    }\n\n    struct Fee {\n        uint40 cooldownEndTimestamp;\n        uint16 bps;\n        uint16 pendingBPS;\n    }\n\n    /// @dev MAX_BPS the maximum number of basis points.\n    /// 10000 basis points are equivalent to 100%.\n    uint256 public constant MAX_BPS = 1e4;\n\n    /// @dev total fee BPS should not exceed MAX_BPS\n    uint16 public constant MAX_PROTOCOL_FEE_BPS = 2e3;\n\n    /// @dev total fee BPS should not exceed MAX_BPS\n    uint16 public constant MAX_OPERATOR_FEE_BPS = 2e3;\n\n    uint40 public constant MAX_COOLDOWN_SEC = 4320000;\n\n    IERC20 public immutable stakedToken;\n    uint40 public immutable stakingStartTimestamp;\n\n    ProtocolConfig public protocolConfig;\n\n    OperatorConfig public operatorConfig;\n\n    /// @dev Seconds between starting cooldown and being able to withdraw\n    uint40 public cooldownSeconds;\n\n    /// hash(operator, distribution id, staker) => rewardsBalance\n    mapping(bytes32 => uint256) private _rewardsBalances;\n\n    uint256 public totalStakedAmount;\n    uint256 public totalCooldownAmount;\n    uint256 public totalFrozenAmount;\n    uint256 public totalFrozenCooldownAmount;\n\n    // operator => total cooldown amount\n    mapping(address => uint256) public totalCooldownAmounts;\n\n    struct CooldownSnapshot {\n        uint40 timestamp;\n        uint216 amount;\n    }\n\n    mapping(address => mapping(address => CooldownSnapshot)) public cooldowns;\n\n    /// @notice Minimum stake required to vote on an alert\n    uint256 public minVotingStake;\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    // slither-disable-next-line unused-state\n    uint256[39] private __gap;\n\n    modifier onlyValidCooldownSec(uint40 cooldownSec_) {\n        if (cooldownSec_ > MAX_COOLDOWN_SEC) {\n            revert GreaterThanMaxCooldownSec();\n        }\n        _;\n    }\n\n    modifier onlyValidOperator(address operator) {\n        if (!isOperator(operator)) {\n            revert NotOperator();\n        }\n        _;\n    }\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor(IERC20 stakedToken_, uint40 stakingStartTimestamp_) {\n        _disableInitializers();\n\n        if (address(stakedToken_) == address(0)) {\n            revert ZeroAddress();\n        }\n\n        if (stakingStartTimestamp_ <= block.timestamp) {\n            revert InvalidStakingStartTime();\n        }\n\n        stakedToken = stakedToken_;\n        stakingStartTimestamp = stakingStartTimestamp_;\n    }\n\n    ///////////////////////\n    // External Functions\n    ///////////////////////\n\n    function initialize(\n        address initialOwner_,\n        string calldata uri_,\n        uint40 cooldownSec_,\n        uint40 cooldownSecForOperatorFeeUpdate_,\n        uint40 cooldownSecForProtocolFeeUpdate_,\n        address protocolFeeVault_,\n        uint16 initialProtocolFeeBPS_,\n        uint256 initialMinVotingStake_,\n        uint16 initialExpiryDuration\n    ) external initializer {\n        if (initialOwner_ == address(0) || protocolFeeVault_ == address(0)) {\n            revert ZeroAddress();\n        }\n        if (initialProtocolFeeBPS_ > MAX_PROTOCOL_FEE_BPS) {\n            revert InvalidBPS();\n        }\n\n        __Pausable_init();\n        // This is a multisig account\n        __Ownable_init(initialOwner_);\n        __ERC1155_init(uri_);\n        __ERC1155Supply_init();\n        __AlertSystem_init(initialExpiryDuration);\n        _setProtocolFeeBPS(initialProtocolFeeBPS_);\n\n        cooldownSeconds = cooldownSec_;\n        operatorConfig.cooldownSeconds = cooldownSecForOperatorFeeUpdate_;\n\n        protocolConfig.cooldownSeconds = cooldownSecForProtocolFeeUpdate_;\n        protocolConfig.vault = protocolFeeVault_;\n\n        minVotingStake = initialMinVotingStake_;\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function registerOperator(address operator, uint16 feeBPS_) external onlyOwner {\n        if (feeBPS_ > MAX_OPERATOR_FEE_BPS) {\n            revert InvalidBPS();\n        }\n\n        if (isOperator(operator)) {\n            revert AlreadyRegistered();\n        }\n\n        // slither-disable-next-line unused-return\n        _addOperator(operator);\n\n        _updateAllDistribution(totalVotingStake());\n        _setOperatorFeeBPS(operator, feeBPS_);\n        emit OperatorRegistered(operator);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function setMinVotingStake(uint256 minVotingStake_) external onlyOwner {\n        minVotingStake = minVotingStake_;\n        emit SetMinVotingStake(minVotingStake_);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function setCooldownSecForOperatorFee(uint40 cooldownSec_) external onlyOwner onlyValidCooldownSec(cooldownSec_) {\n        operatorConfig.cooldownSeconds = cooldownSec_;\n        emit SetCooldownSecForOperatorFee(cooldownSec_);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function setCooldownSecForProtocolFee(uint40 cooldownSec_) external onlyOwner onlyValidCooldownSec(cooldownSec_) {\n        protocolConfig.cooldownSeconds = cooldownSec_;\n        emit SetCooldownSecForProtocolFee(cooldownSec_);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function setCooldownSecForUnstaking(uint40 cooldownSec_) external onlyOwner onlyValidCooldownSec(cooldownSec_) {\n        cooldownSeconds = cooldownSec_;\n        emit SetCooldownSecForUnstaking(cooldownSec_);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function cooldownToUpdateProtocolFee(uint16 feeBPS_) external onlyOwner {\n        if (feeBPS_ > MAX_PROTOCOL_FEE_BPS) {\n            revert InvalidBPS();\n        }\n        uint40 cooldownEndTimestamp = uint40(block.timestamp) + protocolConfig.cooldownSeconds;\n        protocolConfig.fee.cooldownEndTimestamp = cooldownEndTimestamp;\n        protocolConfig.fee.pendingBPS = feeBPS_;\n        emit CooldownToUpdateProtocolFee(feeBPS_, cooldownEndTimestamp);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function setProtocolFeeBPS() external onlyOwner {\n        if (protocolConfig.fee.cooldownEndTimestamp > block.timestamp) {\n            revert InsufficientCooldown();\n        }\n        _setProtocolFeeBPS(protocolConfig.fee.pendingBPS);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function setOperatorFeeBPS() external onlyOperator whenNotPaused {\n        address operator = _msgSender();\n        if (operatorConfig.fees[operator].cooldownEndTimestamp > block.timestamp) {\n            revert InsufficientCooldown();\n        }\n        _setOperatorFeeBPS(operator, operatorConfig.fees[operator].pendingBPS);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function cooldownToUpdateOperatorFee(uint16 feeBPS_) external onlyOperator whenNotPaused {\n        if (feeBPS_ > MAX_OPERATOR_FEE_BPS) {\n            revert InvalidBPS();\n        }\n        address operator = _msgSender();\n        uint40 cooldownEndTimestamp = uint40(block.timestamp) + operatorConfig.cooldownSeconds;\n        operatorConfig.fees[operator].cooldownEndTimestamp = cooldownEndTimestamp;\n        operatorConfig.fees[operator].pendingBPS = feeBPS_;\n\n        emit CooldownToUpdateOperatorFee(operator, feeBPS_, cooldownEndTimestamp);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function stake(address to, address operator, uint256 amount) external {\n        if (amount == 0) {\n            revert ZeroAmount();\n        }\n        if (stakingStartTimestamp > block.timestamp) {\n            revert StakingNotStartedYet();\n        }\n        address from = _msgSender();\n        _updateCurrentUnclaimedRewards(to, operator, votingStake(to, operator));\n        _stake(from, to, operator, amount);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function cooldownToUnstake(address operator, uint256 amountToAdd)\n        external\n        onlyValidOperator(operator)\n        whenNotPaused\n    {\n        address from = _msgSender();\n        uint256 balance = balanceOf(from, operator);\n\n        CooldownSnapshot storage currentCooldown = cooldowns[operator][from];\n\n        uint256 newCooldownAmount = amountToAdd + currentCooldown.amount;\n\n        if (amountToAdd == 0 || newCooldownAmount > balance) {\n            revert InvalidCooldownAmount();\n        }\n\n        _updateCurrentUnclaimedRewards(from, operator, votingStake(from, operator));\n\n        emit CooldownToUnstake(from, operator, newCooldownAmount);\n\n        currentCooldown.amount = uint216(newCooldownAmount);\n        currentCooldown.timestamp = uint40(block.timestamp);\n\n        totalCooldownAmounts[operator] += amountToAdd;\n        totalCooldownAmount += amountToAdd;\n        if (isFrozenOperator(operator)) {\n            totalFrozenCooldownAmount += amountToAdd;\n        }\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    /// @dev This function allows a token holder to transfer their voting stake from one operator to another.\n    /// If the `amount` is 0 or the sender has a zero voting stake with the `fromOperator`, the transaction reverts.\n    /// It first unstakes the voting stake from the `fromOperator` and then stakes the same amount with the `toOperator`.\n    /// The function uses `_msgSender` to identify the caller.\n    function switchOperator(address fromOperator, address toOperator, uint256 amount) external {\n        if (amount == 0) {\n            revert ZeroAmount();\n        }\n\n        if (fromOperator == toOperator) {\n            revert InvalidDestination();\n        }\n\n        address sender = _msgSender();\n        uint256 max = votingStake(sender, fromOperator);\n\n        if (max == 0) {\n            revert ZeroVotingStake();\n        }\n\n        uint256 amountToTransfer = (amount > max) ? max : amount;\n\n        _updateCurrentUnclaimedRewards(sender, fromOperator, votingStake(sender, fromOperator));\n        _unstake(sender, sender, fromOperator, amountToTransfer);\n\n        _updateCurrentUnclaimedRewards(sender, toOperator, votingStake(sender, toOperator));\n        _stake(sender, sender, toOperator, amountToTransfer);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function unstake(address to, address operator, uint256 amount) external {\n        if (amount == 0) {\n            revert ZeroAmount();\n        }\n\n        address from = _msgSender();\n        CooldownSnapshot memory cooldownSnapshot = cooldowns[operator][from];\n        if (block.timestamp < cooldownSnapshot.timestamp + cooldownSeconds) {\n            revert InsufficientCooldown();\n        }\n\n        uint256 max = cooldownSnapshot.amount;\n        if (max == 0) {\n            revert ZeroUnstakeable();\n        }\n\n        _updateCurrentUnclaimedRewards(from, operator, votingStake(from, operator));\n\n        uint256 amountToUnstake = (amount > max) ? max : amount;\n\n        if (cooldownSnapshot.timestamp > 0) {\n            if (cooldownSnapshot.amount - amountToUnstake == 0) {\n                delete cooldowns[operator][from];\n            } else {\n                cooldowns[operator][from].amount -= uint216(amountToUnstake);\n            }\n            totalCooldownAmount -= amountToUnstake;\n            totalCooldownAmounts[operator] -= amountToUnstake;\n            if (isFrozenOperator(operator)) {\n                totalFrozenCooldownAmount -= amountToUnstake;\n            }\n        }\n        _unstake(from, to, operator, amountToUnstake);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function claimRewardsBatch(\n        uint16[] calldata ids_,\n        address[] calldata recipients_,\n        address[] calldata operators_,\n        uint256[] calldata amounts_\n    ) external {\n        // Check that all input arrays are of equal length\n        if (ids_.length != recipients_.length || ids_.length != operators_.length || ids_.length != amounts_.length) {\n            revert ArrayLengthMismatch();\n        }\n\n        // Proceed with claiming rewards for each set of parameters\n        for (uint256 i; i < ids_.length; ++i) {\n            claimRewards(ids_[i], recipients_[i], operators_[i], amounts_[i]);\n        }\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function claimRewards(uint16 distributionId, address to, address operator, uint256 amount)\n        public\n        onlyValidOperator(operator)\n        whenNotPaused\n    {\n        address from = _msgSender();\n        _updateCurrentUnclaimedRewards(from, operator, votingStake(from, operator));\n\n        bytes32 key = rewardBalanceKey(distributionId, operator, from);\n        uint256 unclaimedRewards = _rewardsBalances[key];\n\n        uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount;\n\n        // slither-disable-next-line incorrect-equality\n        if (amountToClaim == 0) {\n            revert ZeroAmount();\n        }\n\n        _rewardsBalances[key] = unclaimedRewards - amountToClaim;\n\n        emit RewardsClaimed(from, to, operator, amountToClaim);\n\n        DistributionData storage distribution = distributions[distributionId];\n\n        // slither-disable-next-line arbitrary-send-erc20\n        distribution.rewardToken.safeTransferFrom(distribution.rewardVault, to, amountToClaim);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function freezeOperator(address operator) external onlyOwner onlyOperatorNotFrozen(operator) {\n        // before freezing, all distributions should be updated\n        _updateAllDistribution(totalVotingStake());\n        _freezeOperator(operator);\n        totalFrozenAmount += totalSupply(operator);\n        totalFrozenCooldownAmount += totalCooldownAmounts[operator];\n        _clearVotes(operator);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function rewardBalance(uint16 distributionId, address operator, address staker) public view returns (uint256) {\n        return _rewardsBalances[rewardBalanceKey(distributionId, operator, staker)];\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function operatorFee(address operator)\n        public\n        view\n        returns (uint40 cooldownEndTimestamp, uint16 bps, uint16 pendingBPS)\n    {\n        Fee memory fee = operatorConfig.fees[operator];\n        cooldownEndTimestamp = fee.cooldownEndTimestamp;\n        bps = fee.bps;\n        pendingBPS = fee.pendingBPS;\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function isActiveOperator(address operator) public view returns (bool) {\n        return totalVotingStake(operator) >= minVotingStake && !isFrozenOperator(operator);\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function totalActiveOperators() public view returns (uint256) {\n        uint256 total;\n\n        // Note: Assume the total number of operator is small\n        address[] memory operatorArray = queryOperators(0, totalOperators());\n\n        for (uint256 i; i < operatorArray.length; ++i) {\n            if (isActiveOperator(operatorArray[i])) {\n                unchecked {\n                    ++total;\n                }\n            }\n        }\n        return total;\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function balanceOf(address staker, address operator) public view returns (uint256) {\n        return balanceOf(staker, addressToUint256(operator));\n    }\n\n    function totalVotingStake() public view returns (uint256) {\n        return totalStakedAmount + totalFrozenCooldownAmount - totalFrozenAmount - totalCooldownAmount;\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function totalVotingStake(address operator) public view returns (uint256) {\n        return isFrozenOperator(operator) ? 0 : totalSupply(operator) - totalCooldownAmounts[operator];\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function votingStake(address staker, address operator) public view returns (uint256) {\n        return isFrozenOperator(operator) ? 0 : balanceOf(staker, operator) - cooldowns[operator][staker].amount;\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function totalSupply(address operator) public view returns (uint256) {\n        return totalSupply(addressToUint256(operator));\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function activationThreshold() public view returns (uint256) {\n        return (totalActiveOperators() * 2) / 3;\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function isActiveAlert(uint128 voteCount) public view override(IStakedMultiToken, AlertSystem) returns (bool) {\n        return voteCount >= activationThreshold();\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function getAccruedRewards(uint16 distributionId, address staker, address operator)\n        external\n        view\n        returns (uint256)\n    {\n        DistributionData storage distribution = distributions[distributionId];\n\n        uint256 ditributionIndex = _getDistributionIndex(\n            distributionId, distribution.index, _lastUpdateTimestamp(distribution), totalVotingStake()\n        );\n        uint256 userIndex = distribution.userIndices[operator][staker];\n\n        uint256 accruedRewards = _getAccruedRewards(votingStake(staker, operator), ditributionIndex, userIndex);\n\n        return accruedRewards;\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function rewardBalanceKey(uint16 distributionId, address operator, address staker) public pure returns (bytes32) {\n        return keccak256(abi.encode(distributionId, operator, staker));\n    }\n\n    /// @inheritdoc IStakedMultiToken\n    function addressToUint256(address operator) public pure returns (uint256) {\n        return uint256(uint160(operator));\n    }\n\n    ///////////////////////\n    // Internal Functions\n    ///////////////////////\n\n    function _collectFee(uint16 distributionId, address operator, uint256 rewards)\n        internal\n        override\n        returns (uint256)\n    {\n        DistributionData storage distribution = distributions[distributionId];\n        IERC20 rewardToken = distribution.rewardToken;\n        address rewardVault = distribution.rewardVault;\n\n        // Calculate the protocol fee as a percentage of the rewards.\n        uint256 protocolFeeAmount = (rewards * protocolConfig.fee.bps) / MAX_BPS;\n        // Calculate the operator fee similarly as a percentage of the rewards.\n        uint256 operatorFeeAmount = (rewards * operatorConfig.fees[operator].bps) / MAX_BPS;\n\n        uint256 userRewards = rewards - (protocolFeeAmount + operatorFeeAmount);\n\n        // Emit an event for the fee collection, providing transparency and traceability.\n        emit CollectFee(distributionId, operator, protocolFeeAmount, operatorFeeAmount, userRewards);\n\n        // slither-disable-next-line arbitrary-send-erc20\n        rewardToken.safeTransferFrom(rewardVault, protocolConfig.vault, protocolFeeAmount);\n        // slither-disable-next-line arbitrary-send-erc20\n        rewardToken.safeTransferFrom(rewardVault, operator, operatorFeeAmount);\n\n        // Return the remaining rewards after deducting both the protocol and operator fees.\n        return userRewards;\n    }\n\n    function _setProtocolFeeBPS(uint16 feeBPS) internal {\n        protocolConfig.fee.bps = feeBPS;\n        emit SetProtocolFeeBPS(feeBPS);\n    }\n\n    function _setOperatorFeeBPS(address operator, uint16 feeBPS) internal {\n        operatorConfig.fees[operator].bps = feeBPS;\n        emit SetOperatorFeeBPS(operator, feeBPS);\n    }\n\n    function _stake(address from, address to, address operator, uint256 amount)\n        internal\n        onlyValidOperator(operator)\n        onlyOperatorNotFrozen(operator)\n    {\n        emit Stake(from, to, operator, amount);\n\n        // NOTE: Ensure users must transfer the stakedToken funds before receiving the funds and code execution from the receiver hook.\n        stakedToken.safeTransferFrom(from, address(this), amount);\n\n        _mint(to, addressToUint256(operator), amount, \"\");\n        totalStakedAmount += amount;\n    }\n\n    function _unstake(address from, address to, address operator, uint256 amount)\n        internal\n        onlyValidOperator(operator)\n    {\n        emit Unstake(from, to, operator, amount);\n\n        _burn(from, addressToUint256(operator), amount);\n        totalStakedAmount -= amount;\n        if (isFrozenOperator(operator)) {\n            totalFrozenAmount -= amount;\n        }\n\n        if (!isActiveOperator(operator)) {\n            _clearVotes(operator);\n        }\n\n        IERC20(stakedToken).safeTransfer(to, amount);\n    }\n\n    function _clearVotes(address operator) internal {\n        // clear all the votes where the alert is not valid yet.\n        bytes32[] memory hashes = votedAlerts[operator];\n        for (uint256 i; i < hashes.length; ++i) {\n            bytes32 messageHash = hashes[i];\n\n            AlertData storage currentAlert = alerts[messageHash];\n            // NOTE: vote count can be zero when admin has removed this alert\n            if (!currentAlert.isActive && currentAlert.voteCount > 0) {\n                currentAlert.voteCount--;\n                delete currentAlert.voted[currentAlert.resetCount][operator];\n            }\n        }\n        // reinitialize it\n        votedAlerts[operator] = new bytes32[](0);\n    }\n\n    function _vote(bytes32 messageHash, uint40 expiry, address nodeKey) internal override(AlertSystem) {\n        address operator = operators[nodeKey];\n\n        // Revert if the operator is frozen\n        if (isFrozenOperator(operator)) {\n            revert FrozenOperator();\n        }\n\n        // Revert if the operator has less stake than the minimum required to vote\n        if (totalVotingStake(operator) < minVotingStake) {\n            revert LessThanMinStakeToVote();\n        }\n\n        super._vote(messageHash, expiry, nodeKey);\n    }\n\n    /// @dev Updates the user state related with his accrued rewards\n    /// @param user Address of the user\n    /// @param operator The identifier of the staking pool\n    /// @param votingStake_ The current voting stake of the user\n    function _updateCurrentUnclaimedRewards(address user, address operator, uint256 votingStake_) internal {\n        for (uint16 distributionId = 1; distributionId <= totalDistributions; ++distributionId) {\n            uint256 accruedRewards = _updateUser(distributionId, user, operator, votingStake_, totalVotingStake());\n            if (accruedRewards != 0) {\n                bytes32 key = rewardBalanceKey(distributionId, operator, user);\n                _rewardsBalances[key] += accruedRewards;\n                emit RewardsAccrued(user, operator, accruedRewards);\n            }\n        }\n    }\n\n    function _update(address from, address to, uint256[] memory ids, uint256[] memory values)\n        internal\n        override\n        whenNotPaused\n    {\n        // When safeTransferFrom\n        // Update unclaimed rewards first\n        if (from != address(0) && to != address(0)) {\n            // Assume the length of ids and values are the same.\n            for (uint256 i; i < ids.length; ++i) {\n                address operator = address(uint160(ids[i]));\n\n                // Sender\n                _updateCurrentUnclaimedRewards(from, operator, votingStake(from, operator));\n\n                // Recipient\n                if (from != to) {\n                    _updateCurrentUnclaimedRewards(to, operator, votingStake(to, operator));\n                }\n            }\n        }\n\n        super._update(from, to, ids, values);\n\n        // NOTE: cooldown amount cannot be transferred.\n        // cooldown amount only can be unstaked.\n        // balance - cooldown amount = votingStake\n        for (uint256 i; i < ids.length; ++i) {\n            address operator = address(uint160(ids[i]));\n            CooldownSnapshot storage currentCooldown = cooldowns[operator][from];\n            // Make sure the cooldown amount is not greater than the balance\n            if (currentCooldown.amount > balanceOf(from, operator)) {\n                revert InsufficientAmount();\n            }\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error AddressInsufficientBalance(address account);\n\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedInnerCall();\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert AddressInsufficientBalance(address(this));\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert FailedInnerCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {FailedInnerCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert AddressInsufficientBalance(address(this));\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n     * unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {FailedInnerCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert FailedInnerCall();\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/token/ERC1155/extensions/ERC1155SupplyUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/ERC1155Supply.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC1155Upgradeable} from \"../ERC1155Upgradeable.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Extension of ERC1155 that adds tracking of total supply per id.\n *\n * Useful for scenarios where Fungible and Non-fungible tokens have to be\n * clearly identified. Note: While a totalSupply of 1 might mean the\n * corresponding is an NFT, there is no guarantees that no other token with the\n * same id are not going to be minted.\n *\n * NOTE: This contract implies a global limit of 2**256 - 1 to the number of tokens\n * that can be minted.\n *\n * CAUTION: This extension should not be added in an upgrade to an already deployed contract.\n */\nabstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC1155Supply\n    struct ERC1155SupplyStorage {\n        mapping(uint256 id => uint256) _totalSupply;\n        uint256 _totalSupplyAll;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC1155Supply\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC1155SupplyStorageLocation = 0x4a593662ee04d27b6a00ebb31be7fe0c102c2ade82a7c5d764f2df05dc4e2800;\n\n    function _getERC1155SupplyStorage() private pure returns (ERC1155SupplyStorage storage $) {\n        assembly {\n            $.slot := ERC1155SupplyStorageLocation\n        }\n    }\n\n    function __ERC1155Supply_init() internal onlyInitializing {\n    }\n\n    function __ERC1155Supply_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Total value of tokens in with a given id.\n     */\n    function totalSupply(uint256 id) public view virtual returns (uint256) {\n        ERC1155SupplyStorage storage $ = _getERC1155SupplyStorage();\n        return $._totalSupply[id];\n    }\n\n    /**\n     * @dev Total value of tokens.\n     */\n    function totalSupply() public view virtual returns (uint256) {\n        ERC1155SupplyStorage storage $ = _getERC1155SupplyStorage();\n        return $._totalSupplyAll;\n    }\n\n    /**\n     * @dev Indicates whether any token exist with a given id, or not.\n     */\n    function exists(uint256 id) public view virtual returns (bool) {\n        return totalSupply(id) > 0;\n    }\n\n    /**\n     * @dev See {ERC1155-_update}.\n     */\n    function _update(\n        address from,\n        address to,\n        uint256[] memory ids,\n        uint256[] memory values\n    ) internal virtual override {\n        ERC1155SupplyStorage storage $ = _getERC1155SupplyStorage();\n        super._update(from, to, ids, values);\n\n        if (from == address(0)) {\n            uint256 totalMintValue = 0;\n            for (uint256 i = 0; i < ids.length; ++i) {\n                uint256 value = values[i];\n                // Overflow check required: The rest of the code assumes that totalSupply never overflows\n                $._totalSupply[ids[i]] += value;\n                totalMintValue += value;\n            }\n            // Overflow check required: The rest of the code assumes that totalSupplyAll never overflows\n            $._totalSupplyAll += totalMintValue;\n        }\n\n        if (to == address(0)) {\n            uint256 totalBurnValue = 0;\n            for (uint256 i = 0; i < ids.length; ++i) {\n                uint256 value = values[i];\n\n                unchecked {\n                    // Overflow not possible: values[i] <= balanceOf(from, ids[i]) <= totalSupply(ids[i])\n                    $._totalSupply[ids[i]] -= value;\n                    // Overflow not possible: sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll\n                    totalBurnValue += value;\n                }\n            }\n            unchecked {\n                // Overflow not possible: totalBurnValue = sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll\n                $._totalSupplyAll -= totalBurnValue;\n            }\n        }\n    }\n}\n"
      },
      "src/interfaces/IStakedMultiToken.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity =0.8.23;\n\n/// @title IStakedMultiToken Interface\n/// @notice Interface for the Staked MultiToken system, allowing for token staking, operator management, and reward distribution.\ninterface IStakedMultiToken {\n    ////////////////\n    // Events\n    ////////////////\n\n    event OperatorRegistered(address operator);\n    event Stake(address indexed from, address indexed onBehalfOf, address operator, uint256 assets);\n\n    event RewardsAccrued(address user, address operator, uint256 amount);\n    event RewardsClaimed(address indexed from, address indexed to, address operator, uint256 amount);\n\n    event CooldownToUnstake(address indexed user, address indexed operator, uint256 amount);\n    event CooldownToUpdateProtocolFee(uint16 feeBPS, uint40 cooldownEndTimestamp);\n    event CooldownToUpdateOperatorFee(address operator, uint16 feeBPS, uint40 cooldownEndTimestamp);\n\n    event Unstake(address indexed from, address indexed to, address operator, uint256 assets);\n    event SetOperatorFeeBPS(address operator, uint16 feeBPS);\n    event SetProtocolFeeBPS(uint16 feeBPS);\n\n    event SetMinVotingStake(uint256 minVotingStake);\n    event SetCooldownSecForUnstaking(uint40 cooldownSeconds);\n    event SetCooldownSecForOperatorFee(uint40 cooldownSeconds);\n    event SetCooldownSecForProtocolFee(uint40 cooldownSeconds);\n    event CollectFee(\n        uint16 distributionId, address operator, uint256 protocolFee, uint256 operatorFee, uint256 userRewards\n    );\n\n    ////////////////\n    // Functions\n    ////////////////\n\n    /// @notice Registers a new operator and sets their fee in basis points\n    /// @param operator The address of the operator to register\n    /// @param feeBPS The fee in basis points\n    function registerOperator(address operator, uint16 feeBPS) external;\n\n    /// @notice Freezes an operator, preventing them from performing certain actions\n    /// @param operator The address of the operator to freeze\n    function freezeOperator(address operator) external;\n\n    /// @notice Gets the balance of a staker for a specific operator\n    /// @param staker The address of the staker\n    /// @param operator The address of the operator\n    /// @return The balance of staked tokens\n    function balanceOf(address staker, address operator) external view returns (uint256);\n\n    /// @notice Gets the voting stake of a staker for a specific operator\n    /// @param staker The address of the staker\n    /// @param operator The address of the operator\n    /// @return The voting stake amount\n    function votingStake(address staker, address operator) external view returns (uint256);\n\n    /// @notice Gets the total voting stake of a operator\n    /// @param operator The address of the operator\n    /// @return The total voting stake amount\n    function totalVotingStake(address operator) external view returns (uint256);\n\n    /// @notice Gets the total supply of staked tokens for a specific operator\n    /// @param operator The address of the operator\n    /// @return The total supply of staked tokens\n    function totalSupply(address operator) external view returns (uint256);\n\n    /// @notice Sets the minimum voting stake\n    /// @param minVotingStake_ The minimum voting stake\n    function setMinVotingStake(uint256 minVotingStake_) external;\n\n    /// @notice Sets the cooldown seconds for operator fee updates\n    /// @param cooldownSeconds_ The cooldown period in seconds\n    function setCooldownSecForOperatorFee(uint40 cooldownSeconds_) external;\n\n    /// @notice Sets the cooldown seconds for protocol fee updates\n    /// @param cooldownSeconds_ The cooldown period in seconds\n    function setCooldownSecForProtocolFee(uint40 cooldownSeconds_) external;\n\n    /// @notice Sets the general cooldown period in seconds\n    /// @param cooldownSeconds_ The cooldown period in seconds\n    function setCooldownSecForUnstaking(uint40 cooldownSeconds_) external;\n\n    /// @notice Initiates the cooldown period for protocol fee updates\n    /// @param feeBPS The fee in basis points\n    function cooldownToUpdateProtocolFee(uint16 feeBPS) external;\n\n    /// @notice Initiates the cooldown period for operator fee updates\n    /// @param feeBPS The fee in basis points\n    function cooldownToUpdateOperatorFee(uint16 feeBPS) external;\n\n    /// @notice Sets the protocol fee in basis points\n    function setProtocolFeeBPS() external;\n\n    /// @notice Sets the operator fee in basis points\n    function setOperatorFeeBPS() external;\n\n    /// @notice Claims accrued rewards for a staker\n    /// @param distributionId The distribution ID\n    /// @param to The address to send rewards to\n    /// @param operator The address of the operator\n    /// @param amount The amount of rewards to claim\n    function claimRewards(uint16 distributionId, address to, address operator, uint256 amount) external;\n\n    /// @notice Claims accrued rewards for multiple stakers in a single transaction.\n    /// @param ids Array of distribution IDs for which rewards are being claimed.\n    /// @param recipients Array of addresses to receive the claimed rewards, corresponding to each distribution ID.\n    /// @param operators Array of operator addresses associated with each reward distribution, managing the distribution rules and potentially fees.\n    /// @param amounts Array of amounts of rewards to be claimed for each distribution ID.\n    function claimRewardsBatch(\n        uint16[] calldata ids,\n        address[] calldata recipients,\n        address[] calldata operators,\n        uint256[] calldata amounts\n    ) external;\n\n    /// @notice Stakes tokens on behalf of a user\n    /// @param to The address on whose behalf tokens are being staked\n    /// @param operator The address of the operator\n    /// @param amount The amount of tokens to stake\n    function stake(address to, address operator, uint256 amount) external;\n\n    /// @notice Switches voting power from one operator to another for a specified amount.\n    /// @param fromOperator The address of the current operator from which the voting power is being moved.\n    /// @param toOperator The address of the new operator to which the voting power will be moved.\n    /// @param amount The amount of voting power to transfer.\n    function switchOperator(address fromOperator, address toOperator, uint256 amount) external;\n\n    /// @notice Initiates the cooldown period for a user's staked tokens\n    /// @param operator The address of the operator\n    /// @param amountToAdd The amount of tokens to cooldown. This is additive.\n    function cooldownToUnstake(address operator, uint256 amountToAdd) external;\n\n    /// @notice Unstakes tokens and stops earning rewards\n    /// @param to The address to unstake tokens to\n    /// @param operator The address of the operator\n    /// @param amount The amount of tokens to unstake\n    function unstake(address to, address operator, uint256 amount) external;\n\n    /// @notice Gets the accrued rewards for a staker within a specific distribution and operator context\n    /// @param distributionId The distribution ID for which to query rewards\n    /// @param staker The address of the staker\n    /// @param operator The address of the operator\n    /// @return The amount of accrued rewards\n    function getAccruedRewards(uint16 distributionId, address staker, address operator)\n        external\n        view\n        returns (uint256);\n\n    /// @notice Gets the reward balance for a specific distribution, operator, and staker combination\n    /// @param distributionId The ID of the distribution for which the reward balance is queried\n    /// @param operator The address of the operator\n    /// @param staker The address of the staker\n    /// @return The amount of accrued rewards\n    function rewardBalance(uint16 distributionId, address operator, address staker) external view returns (uint256);\n\n    /// Gets operator fee information\n    /// @param operator The address of the operator\n    function operatorFee(address operator)\n        external\n        view\n        returns (uint40 cooldownEndTimestamp, uint16 bps, uint16 pendingBPS);\n\n    /// @notice Checks if an operator is active based on their total voting stake.\n    /// @dev An operator is considered active if their total voting stake is at least the minimum required.\n    /// @param operator The address of the operator to check.\n    /// @return True if the operator's total voting stake is at least the minimum required, false otherwise.\n    function isActiveOperator(address operator) external view returns (bool);\n\n    /// @notice Counts the total number of active operators.\n    /// @dev Iterates through all operators and counts those that are active.\n    /// @return The total number of active operators.\n    function totalActiveOperators() external view returns (uint256);\n\n    /// @notice Calculates the activation threshold for alerts.\n    /// @dev The activation threshold is determined as two-thirds of the total number of active operators.\n    /// @return The calculated activation threshold.\n    function activationThreshold() external view returns (uint256);\n\n    /// @notice Determines if an alert is active based on the given vote count.\n    /// @dev An alert is considered active if the vote count meets or exceeds the activation threshold.\n    /// @param voteCount The number of votes to check against the activation threshold.\n    /// @return True if the vote count meets or exceeds the activation threshold, false otherwise.\n    function isActiveAlert(uint128 voteCount) external view returns (bool);\n\n    /// @notice Generates a unique key for a reward balance based on distribution ID, operator, and staker\n    /// @param distributionId The ID of the distribution\n    /// @param operator The address of the operator\n    /// @param staker The address of the staker\n    /// @return A unique key for querying reward balances\n    function rewardBalanceKey(uint16 distributionId, address operator, address staker)\n        external\n        pure\n        returns (bytes32);\n\n    /// @notice Converts an address to a `uint256` representation\n    /// @param operator The address to convert\n    /// @return The `uint256` representation of the address\n    function addressToUint256(address operator) external pure returns (uint256);\n}\n"
      },
      "src/RewardDistribution.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity =0.8.23;\n\nimport {SafeERC20, IERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ZeroAddress, InvalidDistributionStartTime, InvalidDistributionEndTime} from \"./Errors.sol\";\nimport {OperatorRegistry} from \"./OperatorRegistry.sol\";\nimport {IRewardDistribution} from \"./interfaces/IRewardDistribution.sol\";\n\nstruct DistributionData {\n    uint128 emissionPerSecond;\n    IERC20 rewardToken;\n    /// @dev Address to pull from the rewards, needs to have approved this contract\n    address rewardVault;\n    uint40 startTime;\n    uint40 endTime;\n    uint256 index;\n    uint40 updateTimestamp;\n    mapping(address => mapping(address => uint256)) userIndices;\n}\n\n/// @dev Accounting contract to manage staking distributions\n/// This is adapted from https://github.com/bgd-labs/aave-stk-v1-5/blob/8867dd5b1137d4d46acd9716fe98759cb16b1606/src/contracts/AaveDistributionManager.sol\n// solhint-disable not-rely-on-time\nabstract contract RewardDistribution is OperatorRegistry, IRewardDistribution {\n    using SafeERC20 for IERC20;\n\n    uint256 public constant PRECISION_FACTOR = 1e18;\n    uint16 public totalDistributions;\n\n    // Distribution ID => Distribution Data\n    mapping(uint16 => DistributionData) public distributions;\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    // slither-disable-next-line unused-state\n    uint256[48] private __gap;\n\n    modifier onlyValidDistributionEndTime(uint40 endTime) {\n        if (endTime < block.timestamp) {\n            revert InvalidDistributionEndTime();\n        }\n        _;\n    }\n\n    ///////////////////////\n    // External Functions\n    ///////////////////////\n\n    /// @inheritdoc IRewardDistribution\n    function createDistribution(\n        uint128 emissionPerSecond_,\n        uint40 startTime_,\n        uint40 endTime_,\n        IERC20 rewardToken_,\n        address rewardVault_\n    ) external onlyOwner onlyValidDistributionEndTime(endTime_) {\n        if (startTime_ <= block.timestamp) {\n            revert InvalidDistributionStartTime();\n        }\n\n        if (startTime_ >= endTime_) {\n            revert InvalidDistributionEndTime();\n        }\n\n        if (address(rewardToken_) == address(0)) {\n            revert ZeroAddress();\n        }\n        if (rewardVault_ == address(0)) {\n            revert ZeroAddress();\n        }\n\n        totalDistributions++;\n        uint16 distributionId = totalDistributions;\n\n        DistributionData storage distribution = distributions[distributionId];\n\n        distribution.emissionPerSecond = emissionPerSecond_;\n        distribution.startTime = startTime_;\n        distribution.endTime = endTime_;\n        distribution.rewardToken = rewardToken_;\n        distribution.rewardVault = rewardVault_;\n    }\n\n    /// @inheritdoc IRewardDistribution\n    function setDistributionEnd(uint16 distributionId, uint40 endTime)\n        external\n        onlyOwner\n        onlyValidDistributionEndTime(endTime)\n    {\n        DistributionData storage distribution = distributions[distributionId];\n\n        if (endTime <= distribution.startTime) {\n            revert InvalidDistributionEndTime();\n        }\n\n        distribution.endTime = endTime;\n    }\n\n    /// @inheritdoc IRewardDistribution\n    function distributionIndex(uint16 distributionId) external view returns (uint256) {\n        return distributions[distributionId].index;\n    }\n\n    /// @inheritdoc IRewardDistribution\n    function distributionUserIndex(uint16 distributionId, address operator, address staker)\n        external\n        view\n        returns (uint256)\n    {\n        return distributions[distributionId].userIndices[operator][staker];\n    }\n\n    ///////////////////////\n    // Internal Functions\n    ///////////////////////\n\n    /// @dev Updates the distribution index based on time elapsed and emission rate, respecting the distribution period and supply constraints.\n    /// @param distributionId Identifier for the specific distribution.\n    /// @param currentIndex The current index reflecting the accumulated distribution up to the last update.\n    /// @param lastUpdateTimestamp_ Timestamp of the last update, used to calculate time elapsed.\n    /// @param totalSupply The total token supply.\n    /// @return The updated index, or the current index if conditions prevent recalculation (e.g., no time elapsed, emission rate or total supply is zero, outside distribution period).\n    function _getDistributionIndex(\n        uint16 distributionId,\n        uint256 currentIndex,\n        uint40 lastUpdateTimestamp_,\n        uint256 totalSupply\n    ) internal view returns (uint256) {\n        DistributionData storage distribution = distributions[distributionId];\n        if (\n            // slither-disable-next-line incorrect-equality\n            lastUpdateTimestamp_ == block.timestamp || distribution.emissionPerSecond == 0 || totalSupply == 0\n                || block.timestamp < distribution.startTime || lastUpdateTimestamp_ >= distribution.endTime\n        ) {\n            return currentIndex;\n        }\n\n        uint256 currentTimestamp = block.timestamp > distribution.endTime ? distribution.endTime : block.timestamp;\n\n        uint256 timeDelta = currentTimestamp - lastUpdateTimestamp_;\n\n        uint256 newIndex = (distribution.emissionPerSecond * timeDelta * PRECISION_FACTOR) / totalSupply;\n\n        return newIndex + currentIndex;\n    }\n\n    /// @dev Iterates and updates each distribution's state for a given operator.\n    /// @param totalStaked Total amount staked, affecting distribution indices.\n    function _updateAllDistribution(uint256 totalStaked) internal {\n        for (uint16 distributionId = 1; distributionId <= totalDistributions; ++distributionId) {\n            _updateDistribution(distributionId, totalStaked);\n        }\n    }\n\n    /// @dev Updates the state of one distribution, mainly rewards index and timestamp\n    /// @param totalStaked Current total of staked assets for this distribution\n    /// @return The new distribution index\n    function _updateDistribution(uint16 distributionId, uint256 totalStaked) internal returns (uint256) {\n        DistributionData storage distribution = distributions[distributionId];\n\n        uint256 oldIndex = distribution.index;\n        uint40 lastUpdateTimestamp = _lastUpdateTimestamp(distribution);\n\n        // Note that it's inclusive\n        if (distribution.endTime <= lastUpdateTimestamp || block.timestamp <= lastUpdateTimestamp) {\n            return oldIndex;\n        }\n\n        uint256 newIndex = _getDistributionIndex(distributionId, oldIndex, lastUpdateTimestamp, totalStaked);\n\n        if (newIndex != oldIndex) {\n            distribution.index = newIndex;\n            emit DistributionIndexUpdated(distributionId, newIndex);\n        }\n\n        distribution.updateTimestamp = uint40(block.timestamp);\n\n        return newIndex;\n    }\n\n    /// @dev Updates the state of an user in a distribution\n    /// @param user The user's address\n    /// @param operator The id of the reference asset of the distribution\n    /// @param stakedByUser Amount of tokens staked by the user in the distribution at the moment\n    /// @param totalStaked Total tokens staked in the distribution\n    /// @return The accrued rewards for the user until the moment\n    function _updateUser(\n        uint16 distributionId,\n        address user,\n        address operator,\n        uint256 stakedByUser,\n        uint256 totalStaked\n    ) internal returns (uint256) {\n        DistributionData storage distribution = distributions[distributionId];\n\n        uint256 newIndex = _updateDistribution(distributionId, totalStaked);\n        uint256 userIndex = distribution.userIndices[operator][user];\n\n        uint256 accruedRewards = 0;\n\n        if (userIndex != newIndex) {\n            if (stakedByUser != 0) {\n                accruedRewards = _getAccruedRewards(stakedByUser, newIndex, userIndex);\n            }\n\n            distribution.userIndices[operator][user] = newIndex;\n            emit UserIndexUpdated(distributionId, user, operator, newIndex);\n        }\n\n        if (accruedRewards > 0) {\n            accruedRewards = _collectFee(distributionId, operator, accruedRewards);\n        }\n\n        return accruedRewards;\n    }\n\n    function _lastUpdateTimestamp(DistributionData storage distribution) internal view returns (uint40) {\n        return distribution.updateTimestamp < distribution.startTime\n            ? distribution.startTime\n            : distribution.updateTimestamp;\n    }\n\n    /// @dev Internal function for the calculation of user's rewards on a distribution\n    /// @param stakedByUser Amount staked by the user on a distribution\n    /// @param distributionIndex_ Current index of the distribution\n    /// @param userIndex Index stored for the user, representation his staking moment\n    /// @return The rewards\n    function _getAccruedRewards(uint256 stakedByUser, uint256 distributionIndex_, uint256 userIndex)\n        internal\n        pure\n        returns (uint256)\n    {\n        uint256 indexDelta = (distributionIndex_ - userIndex);\n        return (stakedByUser * indexDelta) / PRECISION_FACTOR;\n    }\n\n    /// @dev Collects fees from the rewards and distributes them to the protocol and the operator.\n    /// The fees are determined based on the `FEE_BPS` constant.\n    /// @param distributionId Distribution ID\n    /// @param operator The identifier of the asset or operation for which the fees are being collected.\n    /// @param rewards The total amount of rewards from which fees will be deducted.\n    /// @return The remaining rewards after deducting the protocol and operator fees.\n    function _collectFee(uint16 distributionId, address operator, uint256 rewards) internal virtual returns (uint256);\n}\n"
      },
      "src/AlertSystem.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\n// Copyright (c) 2024, Alt Research Ltd.\npragma solidity =0.8.23;\n\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nimport {\n    NotOperator,\n    AlreadyRegistered,\n    AlreadyAuthenticated,\n    AlreadyRemoved,\n    InvalidExpiryDuration,\n    InvalidStartIndex,\n    OperatorMismatch,\n    NodeKeyNotAuthenticated,\n    AlreadyVoted,\n    AlreadyActiveAlert\n} from \"./Errors.sol\";\nimport {IAlertSystem} from \"./interfaces/IAlertSystem.sol\";\nimport {OperatorRegistry} from \"./OperatorRegistry.sol\";\n\n// solhint-disable not-rely-on-time, var-name-mixedcase\nabstract contract AlertSystem is IAlertSystem, OperatorRegistry {\n    using EnumerableSet for EnumerableSet.Bytes32Set;\n\n    uint40 public constant MAX_EXPIRY = type(uint40).max;\n\n    // A struct for storing alert data\n    struct AlertData {\n        uint128 voteCount; // The total number of votes for this alert\n        uint40 expiry; // The timestamp when the alert was created\n        uint16 resetCount;\n        bool isActive;\n        // reset count => operator => voted\n        mapping(uint16 => mapping(address => bool)) voted; // Tracks whether an address has voted on this alert\n    }\n\n    EnumerableSet.Bytes32Set private _messageHashes;\n\n    uint16 public expiryDuration;\n\n    // Maps operator addresses to unique node keys for secure one-to-one authentication.\n    mapping(address => address) public nodeKeys;\n\n    // Maps node keys back to operators, ensuring each node is tied to a single operator.\n    mapping(address => address) public operators;\n\n    /// @notice hash of message to alert data\n    mapping(bytes32 => AlertData) public alerts;\n\n    /// @notice operator => voted alert message hashes\n    mapping(address => bytes32[]) public votedAlerts;\n\n    uint256[44] private __gap;\n\n    modifier onlyAuthenticatedNodeKey() {\n        if (!isAuthenticated(_msgSender())) {\n            revert NodeKeyNotAuthenticated();\n        }\n        _;\n    }\n\n    // solhint-disable-next-line func-name-mixedcase\n    function __AlertSystem_init(uint16 initialExpiryDuration_) internal onlyInitializing {\n        expiryDuration = initialExpiryDuration_;\n    }\n\n    ///////////////////////\n    // External Functions\n    ///////////////////////\n\n    /// @inheritdoc IAlertSystem\n    function removeAlert(bytes32 messageHash) external onlyOwner {\n        // slither-disable-next-line mapping-deletion\n        delete alerts[messageHash];\n        _messageHashes.remove(messageHash);\n        emit AlertRemoved(messageHash, _msgSender());\n    }\n\n    /// @inheritdoc IAlertSystem\n    function setExpiryDuration(uint16 duration) external onlyOwner {\n        expiryDuration = duration;\n        emit ExpiryDurationUpdated(duration, _msgSender());\n    }\n\n    /// @inheritdoc IAlertSystem\n    function registerNodeKey(address operator) external whenNotPaused {\n        if (!isOperator(operator)) {\n            revert NotOperator();\n        }\n\n        address nodeKey = _msgSender();\n\n        if (nodeKeys[operator] != address(0)) {\n            revert AlreadyRegistered();\n        }\n\n        operators[nodeKey] = operator;\n        emit NodeKeyRegistered(nodeKey, operator);\n    }\n\n    /// @inheritdoc IAlertSystem\n    function authenticateNodeKey(address nodeKey) external onlyOperator whenNotPaused {\n        address operator = _msgSender();\n\n        if (operators[nodeKey] != operator) {\n            revert OperatorMismatch();\n        }\n\n        if (nodeKeys[operator] == nodeKey) {\n            revert AlreadyAuthenticated();\n        }\n\n        nodeKeys[operator] = nodeKey;\n        emit NodeKeyAuthenticated(nodeKey, operator);\n    }\n\n    function removeNodeKey() external onlyOperator whenNotPaused {\n        address operator = _msgSender();\n        address oldNodeKey = nodeKeys[operator];\n\n        if (oldNodeKey == address(0)) {\n            revert AlreadyRemoved();\n        }\n\n        // Clear both\n        delete nodeKeys[operator];\n        delete operators[oldNodeKey];\n\n        emit NodeKeyRemoved(oldNodeKey, operator);\n    }\n\n    /// @inheritdoc IAlertSystem\n    function voteForBlockAlert(uint256 blockNumber) external whenNotPaused onlyAuthenticatedNodeKey {\n        // max expiry\n        uint40 expiry = type(uint40).max;\n        address nodeKey = _msgSender();\n        _vote(keccak256(abi.encode(blockNumber)), expiry, nodeKey);\n    }\n\n    /// @inheritdoc IAlertSystem\n    function voteForMessageAlert(string memory message) external whenNotPaused onlyAuthenticatedNodeKey {\n        uint40 expiry = uint40(block.timestamp) + uint40(expiryDuration);\n        address nodeKey = _msgSender();\n        _vote(keccak256(abi.encode(message)), expiry, nodeKey);\n    }\n    /// @inheritdoc IAlertSystem\n\n    function getVotedAlerts(address operator) external view returns (bytes32[] memory) {\n        return votedAlerts[operator];\n    }\n\n    /// @inheritdoc IAlertSystem\n    function isAuthenticated(address nodeKey) public view returns (bool) {\n        return nodeKeys[operators[nodeKey]] == nodeKey;\n    }\n\n    /// @inheritdoc IAlertSystem\n    function isActiveAlert(uint128 voteCount) public view virtual returns (bool);\n\n    /// @inheritdoc IAlertSystem\n    function totalAlerts() public view returns (uint256) {\n        return _messageHashes.length();\n    }\n\n    /// @inheritdoc IAlertSystem\n    function contains(bytes32 messageHash) public view returns (bool) {\n        return _messageHashes.contains(messageHash);\n    }\n\n    /// @inheritdoc IAlertSystem\n    function queryMessageHashes(uint256 start, uint256 querySize) external view returns (bytes32[] memory) {\n        uint256 length = totalAlerts();\n\n        if (start >= length) {\n            revert InvalidStartIndex();\n        }\n\n        uint256 end = start + querySize;\n\n        if (end > length) {\n            end = length;\n        }\n\n        bytes32[] memory output = new bytes32[](end - start);\n\n        for (uint256 i = start; i < end; ++i) {\n            output[i - start] = _messageHashes.at(i);\n        }\n\n        return output;\n    }\n\n    ///////////////////////\n    // Internal Functions\n    ///////////////////////\n\n    function _vote(bytes32 messageHash, uint40 expiry, address nodeKey) internal virtual {\n        AlertData storage currentAlert = alerts[messageHash];\n\n        if (currentAlert.isActive) {\n            revert AlreadyActiveAlert();\n        }\n\n        if (currentAlert.expiry != 0 && currentAlert.expiry < block.timestamp) {\n            currentAlert.resetCount++;\n            currentAlert.voteCount = 0;\n        }\n\n        address operator = operators[nodeKey];\n        uint16 resetCount = currentAlert.resetCount;\n        // Ensure voting can be done only once per operator per alert\n        if (currentAlert.voted[resetCount][operator]) {\n            revert AlreadyVoted();\n        }\n\n        // Mark the sender as having voted and increment the vote count\n        currentAlert.voted[resetCount][operator] = true;\n        currentAlert.voteCount++;\n        currentAlert.expiry = expiry;\n\n        bool isActive = isActiveAlert(currentAlert.voteCount);\n        currentAlert.isActive = isActive;\n\n        if (!contains(messageHash)) {\n            _messageHashes.add(messageHash);\n        }\n\n        emit AlertVoted(messageHash, operator, currentAlert.voteCount, isActive);\n\n        bytes32[] memory currentVotedAlerts = votedAlerts[operator];\n\n        bool voted;\n        for (uint256 i; i < currentVotedAlerts.length; ++i) {\n            if (messageHash == currentVotedAlerts[i]) {\n                voted = true;\n                break;\n            }\n        }\n\n        if (!voted) {\n            votedAlerts[operator].push(messageHash);\n        }\n    }\n}\n"
      },
      "src/OperatorRegistry.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\n// Copyright (c) 2024, Alt Research Ltd.\npragma solidity =0.8.23;\n\nimport {Ownable2StepUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\nimport {PausableUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport {IOperatorRegistry} from \"./interfaces/IOperatorRegistry.sol\";\nimport {FrozenOperator, NotOperator, InvalidStartIndex} from \"./Errors.sol\";\n\n// solhint-disable not-rely-on-time, var-name-mixedcase\nabstract contract OperatorRegistry is PausableUpgradeable, Ownable2StepUpgradeable, IOperatorRegistry {\n    using EnumerableSet for EnumerableSet.AddressSet;\n\n    /// @dev Set of operator address for enumeration\n    EnumerableSet.AddressSet private _operators;\n    mapping(address => bool) private frozenOperators;\n\n    uint256[48] private __gap;\n\n    modifier onlyOperator() {\n        if (!isOperator(_msgSender())) {\n            revert NotOperator();\n        }\n        _;\n    }\n\n    modifier onlyOperatorNotFrozen(address operator) {\n        // Revert if the operator is frozen\n        if (isFrozenOperator(operator)) {\n            revert FrozenOperator();\n        }\n        _;\n    }\n\n    ///////////////////////\n    // External Functions\n    ///////////////////////\n\n    /// @inheritdoc IOperatorRegistry\n    function pause() external onlyOwner {\n        _pause();\n    }\n\n    /// @inheritdoc IOperatorRegistry\n    function unpause() external onlyOwner {\n        _unpause();\n    }\n\n    /// @inheritdoc IOperatorRegistry\n    function totalOperators() public view returns (uint256) {\n        return _operators.length();\n    }\n\n    /// @inheritdoc IOperatorRegistry\n    function isOperator(address operator) public view returns (bool) {\n        return _operators.contains(operator);\n    }\n\n    /// @inheritdoc IOperatorRegistry\n    function queryOperators(uint256 start, uint256 querySize) public view returns (address[] memory) {\n        uint256 length = totalOperators();\n\n        if (start >= length) {\n            revert InvalidStartIndex();\n        }\n\n        uint256 end = start + querySize;\n\n        if (end > length) {\n            end = length;\n        }\n\n        address[] memory output = new address[](end - start);\n\n        for (uint256 i = start; i < end; ++i) {\n            output[i - start] = _operators.at(i);\n        }\n\n        return output;\n    }\n\n    function isFrozenOperator(address operator) public view returns (bool) {\n        return frozenOperators[operator];\n    }\n\n    ///////////////////////\n    // Internal Functions\n    ///////////////////////\n\n    function _addOperator(address operator) internal {\n        _operators.add(operator);\n        emit OperatorAdded(operator, _msgSender());\n    }\n\n    function _freezeOperator(address operator) internal {\n        frozenOperators[operator] = true;\n        emit Frozen(operator, _msgSender());\n    }\n}\n"
      },
      "src/Errors.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity =0.8.23;\n\nerror ArrayLengthMismatch();\nerror FrozenOperator();\nerror InsufficientAmount();\nerror ZeroVotingStake();\nerror ZeroAddress();\nerror NotOperator();\nerror NodeKeyNotAuthenticated();\nerror LessThanMinStakeToVote();\nerror AlreadyVoted();\nerror AlreadyActiveAlert();\nerror InvalidExpiryDuration();\nerror OperatorMismatch();\nerror InvalidStartIndex();\nerror InvalidStakingStartTime();\nerror InvalidDistributionStartTime();\nerror InvalidDistributionEndTime();\nerror AlreadyRegistered();\nerror AlreadyAuthenticated();\nerror AlreadyRemoved();\nerror InvalidBPS();\nerror ZeroExchangeRate();\nerror ZeroAmount();\nerror InvalidCooldownAmount();\nerror InsufficientCooldown();\nerror ZeroUnstakeable();\nerror InvalidDestination();\nerror GreaterThanMaxCooldownSec();\nerror StakingNotStartedYet();\nerror NotSupported();\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/token/ERC1155/ERC1155Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/ERC1155.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC1155} from \"@openzeppelin/contracts/token/ERC1155/IERC1155.sol\";\nimport {IERC1155Receiver} from \"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol\";\nimport {IERC1155MetadataURI} from \"@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ERC165Upgradeable} from \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport {Arrays} from \"@openzeppelin/contracts/utils/Arrays.sol\";\nimport {IERC1155Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the basic standard multi-token.\n * See https://eips.ethereum.org/EIPS/eip-1155\n * Originally based on code by Enjin: https://github.com/enjin/erc-1155\n */\nabstract contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155, IERC1155MetadataURI, IERC1155Errors {\n    using Arrays for uint256[];\n    using Arrays for address[];\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC1155\n    struct ERC1155Storage {\n        mapping(uint256 id => mapping(address account => uint256)) _balances;\n\n        mapping(address account => mapping(address operator => bool)) _operatorApprovals;\n\n        // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json\n        string _uri;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC1155\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC1155StorageLocation = 0x88be536d5240c274a3b1d3a1be54482fd9caa294f08c62a7cde569f49a3c4500;\n\n    function _getERC1155Storage() private pure returns (ERC1155Storage storage $) {\n        assembly {\n            $.slot := ERC1155StorageLocation\n        }\n    }\n\n    /**\n     * @dev See {_setURI}.\n     */\n    function __ERC1155_init(string memory uri_) internal onlyInitializing {\n        __ERC1155_init_unchained(uri_);\n    }\n\n    function __ERC1155_init_unchained(string memory uri_) internal onlyInitializing {\n        _setURI(uri_);\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC1155).interfaceId ||\n            interfaceId == type(IERC1155MetadataURI).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC1155MetadataURI-uri}.\n     *\n     * This implementation returns the same URI for *all* token types. It relies\n     * on the token type ID substitution mechanism\n     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].\n     *\n     * Clients calling this function must replace the `\\{id\\}` substring with the\n     * actual token type ID.\n     */\n    function uri(uint256 /* id */) public view virtual returns (string memory) {\n        ERC1155Storage storage $ = _getERC1155Storage();\n        return $._uri;\n    }\n\n    /**\n     * @dev See {IERC1155-balanceOf}.\n     */\n    function balanceOf(address account, uint256 id) public view virtual returns (uint256) {\n        ERC1155Storage storage $ = _getERC1155Storage();\n        return $._balances[id][account];\n    }\n\n    /**\n     * @dev See {IERC1155-balanceOfBatch}.\n     *\n     * Requirements:\n     *\n     * - `accounts` and `ids` must have the same length.\n     */\n    function balanceOfBatch(\n        address[] memory accounts,\n        uint256[] memory ids\n    ) public view virtual returns (uint256[] memory) {\n        if (accounts.length != ids.length) {\n            revert ERC1155InvalidArrayLength(ids.length, accounts.length);\n        }\n\n        uint256[] memory batchBalances = new uint256[](accounts.length);\n\n        for (uint256 i = 0; i < accounts.length; ++i) {\n            batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));\n        }\n\n        return batchBalances;\n    }\n\n    /**\n     * @dev See {IERC1155-setApprovalForAll}.\n     */\n    function setApprovalForAll(address operator, bool approved) public virtual {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /**\n     * @dev See {IERC1155-isApprovedForAll}.\n     */\n    function isApprovedForAll(address account, address operator) public view virtual returns (bool) {\n        ERC1155Storage storage $ = _getERC1155Storage();\n        return $._operatorApprovals[account][operator];\n    }\n\n    /**\n     * @dev See {IERC1155-safeTransferFrom}.\n     */\n    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {\n        address sender = _msgSender();\n        if (from != sender && !isApprovedForAll(from, sender)) {\n            revert ERC1155MissingApprovalForAll(sender, from);\n        }\n        _safeTransferFrom(from, to, id, value, data);\n    }\n\n    /**\n     * @dev See {IERC1155-safeBatchTransferFrom}.\n     */\n    function safeBatchTransferFrom(\n        address from,\n        address to,\n        uint256[] memory ids,\n        uint256[] memory values,\n        bytes memory data\n    ) public virtual {\n        address sender = _msgSender();\n        if (from != sender && !isApprovedForAll(from, sender)) {\n            revert ERC1155MissingApprovalForAll(sender, from);\n        }\n        _safeBatchTransferFrom(from, to, ids, values, data);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`\n     * (or `to`) is the zero address.\n     *\n     * Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.\n     *\n     * Requirements:\n     *\n     * - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}\n     *   or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.\n     * - `ids` and `values` must have the same length.\n     *\n     * NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.\n     */\n    function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {\n        ERC1155Storage storage $ = _getERC1155Storage();\n        if (ids.length != values.length) {\n            revert ERC1155InvalidArrayLength(ids.length, values.length);\n        }\n\n        address operator = _msgSender();\n\n        for (uint256 i = 0; i < ids.length; ++i) {\n            uint256 id = ids.unsafeMemoryAccess(i);\n            uint256 value = values.unsafeMemoryAccess(i);\n\n            if (from != address(0)) {\n                uint256 fromBalance = $._balances[id][from];\n                if (fromBalance < value) {\n                    revert ERC1155InsufficientBalance(from, fromBalance, value, id);\n                }\n                unchecked {\n                    // Overflow not possible: value <= fromBalance\n                    $._balances[id][from] = fromBalance - value;\n                }\n            }\n\n            if (to != address(0)) {\n                $._balances[id][to] += value;\n            }\n        }\n\n        if (ids.length == 1) {\n            uint256 id = ids.unsafeMemoryAccess(0);\n            uint256 value = values.unsafeMemoryAccess(0);\n            emit TransferSingle(operator, from, to, id, value);\n        } else {\n            emit TransferBatch(operator, from, to, ids, values);\n        }\n    }\n\n    /**\n     * @dev Version of {_update} that performs the token acceptance check by calling\n     * {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it\n     * contains code (eg. is a smart contract at the moment of execution).\n     *\n     * IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any\n     * update to the contract state after this function would break the check-effect-interaction pattern. Consider\n     * overriding {_update} instead.\n     */\n    function _updateWithAcceptanceCheck(\n        address from,\n        address to,\n        uint256[] memory ids,\n        uint256[] memory values,\n        bytes memory data\n    ) internal virtual {\n        _update(from, to, ids, values);\n        if (to != address(0)) {\n            address operator = _msgSender();\n            if (ids.length == 1) {\n                uint256 id = ids.unsafeMemoryAccess(0);\n                uint256 value = values.unsafeMemoryAccess(0);\n                _doSafeTransferAcceptanceCheck(operator, from, to, id, value, data);\n            } else {\n                _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, values, data);\n            }\n        }\n    }\n\n    /**\n     * @dev Transfers a `value` tokens of token type `id` from `from` to `to`.\n     *\n     * Emits a {TransferSingle} event.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of tokens of type `id` of at least `value` amount.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n     * acceptance magic value.\n     */\n    function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {\n        if (to == address(0)) {\n            revert ERC1155InvalidReceiver(address(0));\n        }\n        if (from == address(0)) {\n            revert ERC1155InvalidSender(address(0));\n        }\n        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);\n        _updateWithAcceptanceCheck(from, to, ids, values, data);\n    }\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.\n     *\n     * Emits a {TransferBatch} event.\n     *\n     * Requirements:\n     *\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n     * acceptance magic value.\n     * - `ids` and `values` must have the same length.\n     */\n    function _safeBatchTransferFrom(\n        address from,\n        address to,\n        uint256[] memory ids,\n        uint256[] memory values,\n        bytes memory data\n    ) internal {\n        if (to == address(0)) {\n            revert ERC1155InvalidReceiver(address(0));\n        }\n        if (from == address(0)) {\n            revert ERC1155InvalidSender(address(0));\n        }\n        _updateWithAcceptanceCheck(from, to, ids, values, data);\n    }\n\n    /**\n     * @dev Sets a new URI for all token types, by relying on the token type ID\n     * substitution mechanism\n     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].\n     *\n     * By this mechanism, any occurrence of the `\\{id\\}` substring in either the\n     * URI or any of the values in the JSON file at said URI will be replaced by\n     * clients with the token type ID.\n     *\n     * For example, the `https://token-cdn-domain/\\{id\\}.json` URI would be\n     * interpreted by clients as\n     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`\n     * for token type ID 0x4cce0.\n     *\n     * See {uri}.\n     *\n     * Because these URIs cannot be meaningfully represented by the {URI} event,\n     * this function emits no events.\n     */\n    function _setURI(string memory newuri) internal virtual {\n        ERC1155Storage storage $ = _getERC1155Storage();\n        $._uri = newuri;\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.\n     *\n     * Emits a {TransferSingle} event.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n     * acceptance magic value.\n     */\n    function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {\n        if (to == address(0)) {\n            revert ERC1155InvalidReceiver(address(0));\n        }\n        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);\n        _updateWithAcceptanceCheck(address(0), to, ids, values, data);\n    }\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.\n     *\n     * Emits a {TransferBatch} event.\n     *\n     * Requirements:\n     *\n     * - `ids` and `values` must have the same length.\n     * - `to` cannot be the zero address.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n     * acceptance magic value.\n     */\n    function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {\n        if (to == address(0)) {\n            revert ERC1155InvalidReceiver(address(0));\n        }\n        _updateWithAcceptanceCheck(address(0), to, ids, values, data);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens of type `id` from `from`\n     *\n     * Emits a {TransferSingle} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `from` must have at least `value` amount of tokens of type `id`.\n     */\n    function _burn(address from, uint256 id, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC1155InvalidSender(address(0));\n        }\n        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);\n        _updateWithAcceptanceCheck(from, address(0), ids, values, \"\");\n    }\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.\n     *\n     * Emits a {TransferBatch} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `from` must have at least `value` amount of tokens of type `id`.\n     * - `ids` and `values` must have the same length.\n     */\n    function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {\n        if (from == address(0)) {\n            revert ERC1155InvalidSender(address(0));\n        }\n        _updateWithAcceptanceCheck(from, address(0), ids, values, \"\");\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Emits an {ApprovalForAll} event.\n     *\n     * Requirements:\n     *\n     * - `operator` cannot be the zero address.\n     */\n    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n        ERC1155Storage storage $ = _getERC1155Storage();\n        if (operator == address(0)) {\n            revert ERC1155InvalidOperator(address(0));\n        }\n        $._operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Performs an acceptance check by calling {IERC1155-onERC1155Received} on the `to` address\n     * if it contains code at the moment of execution.\n     */\n    function _doSafeTransferAcceptanceCheck(\n        address operator,\n        address from,\n        address to,\n        uint256 id,\n        uint256 value,\n        bytes memory data\n    ) private {\n        if (to.code.length > 0) {\n            try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {\n                if (response != IERC1155Receiver.onERC1155Received.selector) {\n                    // Tokens rejected\n                    revert ERC1155InvalidReceiver(to);\n                }\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    // non-ERC1155Receiver implementer\n                    revert ERC1155InvalidReceiver(to);\n                } else {\n                    /// @solidity memory-safe-assembly\n                    assembly {\n                        revert(add(32, reason), mload(reason))\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * @dev Performs a batch acceptance check by calling {IERC1155-onERC1155BatchReceived} on the `to` address\n     * if it contains code at the moment of execution.\n     */\n    function _doSafeBatchTransferAcceptanceCheck(\n        address operator,\n        address from,\n        address to,\n        uint256[] memory ids,\n        uint256[] memory values,\n        bytes memory data\n    ) private {\n        if (to.code.length > 0) {\n            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (\n                bytes4 response\n            ) {\n                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {\n                    // Tokens rejected\n                    revert ERC1155InvalidReceiver(to);\n                }\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    // non-ERC1155Receiver implementer\n                    revert ERC1155InvalidReceiver(to);\n                } else {\n                    /// @solidity memory-safe-assembly\n                    assembly {\n                        revert(add(32, reason), mload(reason))\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * @dev Creates an array in memory with only one value for each of the elements provided.\n     */\n    function _asSingletonArrays(\n        uint256 element1,\n        uint256 element2\n    ) private pure returns (uint256[] memory array1, uint256[] memory array2) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Load the free memory pointer\n            array1 := mload(0x40)\n            // Set array length to 1\n            mstore(array1, 1)\n            // Store the single element at the next word after the length (where content starts)\n            mstore(add(array1, 0x20), element1)\n\n            // Repeat for next array locating it right after the first array\n            array2 := add(array1, 0x40)\n            mstore(array2, 1)\n            mstore(add(array2, 0x20), element2)\n\n            // Update the free memory pointer by pointing after the second array\n            mstore(0x40, add(array2, 0x40))\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reininitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\n        }\n        $._initialized = 1;\n        if (isTopLevelCall) {\n            $._initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            $._initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\n        $._initialized = version;\n        $._initializing = true;\n        _;\n        $._initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\n        }\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        assembly {\n            $.slot := INITIALIZABLE_STORAGE\n        }\n    }\n}\n"
      },
      "src/interfaces/IRewardDistribution.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity =0.8.23;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/// @title Interface for RewardDistribution\n/// @notice This interface outlines the public and external functions for managing distribution of rewards in a staking contract.\ninterface IRewardDistribution {\n    ////////////////\n    // Events\n    ////////////////\n\n    /// @notice Indicates a distribution index was updated\n    /// @dev This event should be emitted when a distribution's index is updated\n    /// @param distributionID The ID of the distribution being updated\n    /// @param index The new index after the update\n    event DistributionIndexUpdated(uint256 indexed distributionID, uint256 index);\n\n    /// @notice Indicates a user's index in a distribution was updated\n    /// @dev This event should be emitted when a user's index within a distribution is updated\n    /// @param distributionID The ID of the distribution being referenced\n    /// @param user The address of the user for whom the index was updated\n    /// @param operator The address of the operator associated with the distribution\n    /// @param index The new user-specific index after the update\n    event UserIndexUpdated(\n        uint256 indexed distributionID, address indexed user, address indexed operator, uint256 index\n    );\n\n    ////////////////\n    // Functions\n    ////////////////\n\n    /// @notice Creates a new distribution\n    /// @param emissionPerSecond The amount of reward token emitted per second\n    /// @param startTime The start time of the distribution in UNIX timestamp\n    /// @param endTime The end time of the distribution in UNIX timestamp\n    /// @param rewardToken The ERC20 token to be used as the reward. The rewardToken must be strictly ERC-20 compliant.\n    /// @param rewardVault The address from which the reward tokens will be distributed\n    /// @dev Emits a DistributionIndexUpdated event on success\n    function createDistribution(\n        uint128 emissionPerSecond,\n        uint40 startTime,\n        uint40 endTime,\n        IERC20 rewardToken,\n        address rewardVault\n    ) external;\n\n    /// @notice Sets the end time for an existing distribution\n    /// @param distributionId The ID of the distribution to be modified\n    /// @param endTime The new end time for the distribution\n    /// @dev This action can only be performed by the owner of the contract\n    function setDistributionEnd(uint16 distributionId, uint40 endTime) external;\n\n    /// @notice Gets the current index of a distribution for an operator\n    /// @param distributionId The ID of the distribution\n    /// @return The current index of the distribution\n    function distributionIndex(uint16 distributionId) external view returns (uint256);\n\n    /// @notice Gets the user-specific index within a distribution for an operator-staker pair\n    /// @param distributionId The ID of the distribution\n    /// @param operator The address of the operator\n    /// @param staker The address of the staker\n    /// @return The current user-specific index within the distribution\n    function distributionUserIndex(uint16 distributionId, address operator, address staker)\n        external\n        view\n        returns (uint256);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position is the index of the value in the `values` array plus 1.\n        // Position 0 is used to mean a value is not in the set.\n        mapping(bytes32 value => uint256) _positions;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._positions[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We cache the value's position to prevent multiple reads from the same storage slot\n        uint256 position = set._positions[value];\n\n        if (position != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 valueIndex = position - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (valueIndex != lastIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the lastValue to the index where the value to delete is\n                set._values[valueIndex] = lastValue;\n                // Update the tracked position of the lastValue (that was just moved)\n                set._positions[lastValue] = position;\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the tracked position for the deleted slot\n            delete set._positions[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._positions[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "src/interfaces/IAlertSystem.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\n// Copyright (c) 2024, Alt Research Ltd.\npragma solidity =0.8.23;\n\n/// @title Interface for AlertSystem\n/// @notice This interface outlines the functionalities for managing alerts and votes in a contract system.\ninterface IAlertSystem {\n    ///////////////////////\n    // Events\n    ///////////////////////\n\n    /// @notice Emitted when the expiry duration is updated\n    /// @param duration The new expiry duration\n    /// @param admin The admin who updated the duration\n    event ExpiryDurationUpdated(uint16 duration, address admin);\n\n    /// @notice Emitted when an alert is removed\n    /// @param messageHash The hash of the message corresponding to the removed alert\n    /// @param admin The admin who removed the alert\n    event AlertRemoved(bytes32 messageHash, address admin);\n\n    /// @notice Emitted when a vote is cast for an alert\n    /// @param messageHash The hash of the message corresponding to the alert voted on\n    /// @param operator The operator address\n    /// @param voteCount The current vote count after the vote\n    /// @param isActive Whether the alert is active after the vote\n    event AlertVoted(bytes32 messageHash, address operator, uint128 voteCount, bool isActive);\n\n    /// @notice Emitted when a node key is registered for an operator\n    /// @param nodeKey The node key that is registered\n    /// @param operator The operator associated with the node key\n    event NodeKeyRegistered(address nodeKey, address operator);\n\n    /// @notice Emitted when a node key is authenticated\n    /// @param nodeKey The node key authenticated\n    /// @param operator The operator associated with the node key\n    event NodeKeyAuthenticated(address nodeKey, address operator);\n\n    /// @notice Emitted when a node key is removed\n    /// @param nodeKey The node key removed\n    /// @param operator The operator associated with the node key\n    event NodeKeyRemoved(address nodeKey, address operator);\n\n    ///////////////////////\n    // External Functions\n    ///////////////////////\n\n    /// @notice Removes an alert from the system\n    /// @param messageHash The hash of the message corresponding to the alert to remove\n    function removeAlert(bytes32 messageHash) external;\n\n    /// @notice Sets the expiry duration for alerts\n    /// @param duration The new expiry duration\n    function setExpiryDuration(uint16 duration) external;\n\n    /// @notice Registers a node key for an operator\n    /// @param operator The operator associated with the node key\n    function registerNodeKey(address operator) external;\n\n    /// @notice Authenticates a previously set node key, allowing it to participate in alert votes\n    /// @param nodeKey The node key to authenticate\n    function authenticateNodeKey(address nodeKey) external;\n\n    /// @notice Removes the currently authenticated node key\n    function removeNodeKey() external;\n\n    /// @notice Votes for a block alert using the caller's node key\n    /// @param blockNumber The block number to associate with the alert\n    function voteForBlockAlert(uint256 blockNumber) external;\n\n    /// @notice Votes for a message alert using the caller's node key\n    /// @param message The message to associate with the alert\n    function voteForMessageAlert(string calldata message) external;\n\n    ///////////////////////\n    // View Functions\n    ///////////////////////\n\n    /// @notice Checks if the given node key is authenticated\n    /// @param nodeKey The address of the node key to verify authentication.\n    /// @return bool Returns true if the node key is authenticated, false otherwise.\n    function isAuthenticated(address nodeKey) external view returns (bool);\n\n    /// @notice Gets a list of alerts voted on by a nodeKey\n    /// @param nodeKey The node key to query for voted alerts\n    /// @return An array of message hashes corresponding to alerts voted on by the node key\n    function getVotedAlerts(address nodeKey) external view returns (bytes32[] memory);\n\n    /// @notice Checks whether an alert with a given vote count is considered active\n    /// @param voteCount The vote count of the alert\n    /// @return True if the alert is active, false otherwise\n    function isActiveAlert(uint128 voteCount) external view returns (bool);\n\n    /// @notice Returns the total number of alerts in the system\n    /// @return The total number of alerts\n    function totalAlerts() external view returns (uint256);\n\n    /// @notice Checks if a specific alert exists in the system\n    /// @param messageHash The hash of the message corresponding to the alert\n    /// @return True if the alert exists, false otherwise\n    function contains(bytes32 messageHash) external view returns (bool);\n\n    /// @notice Queries a range of message hashes from the system\n    /// @param start The start index for querying\n    /// @param querySize The number of message hashes to query\n    /// @return An array of message hashes\n    function queryMessageHashes(uint256 start, uint256 querySize) external view returns (bytes32[] memory);\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.20;\n\nimport {OwnableUpgradeable} from \"./OwnableUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step\n    struct Ownable2StepStorage {\n        address _pendingOwner;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Ownable2Step\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;\n\n    function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {\n        assembly {\n            $.slot := Ownable2StepStorageLocation\n        }\n    }\n\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n    function __Ownable2Step_init() internal onlyInitializing {\n    }\n\n    function __Ownable2Step_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Returns the address of the pending owner.\n     */\n    function pendingOwner() public view virtual returns (address) {\n        Ownable2StepStorage storage $ = _getOwnable2StepStorage();\n        return $._pendingOwner;\n    }\n\n    /**\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\n        Ownable2StepStorage storage $ = _getOwnable2StepStorage();\n        $._pendingOwner = newOwner;\n        emit OwnershipTransferStarted(owner(), newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual override {\n        Ownable2StepStorage storage $ = _getOwnable2StepStorage();\n        delete $._pendingOwner;\n        super._transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev The new owner accepts the ownership transfer.\n     */\n    function acceptOwnership() public virtual {\n        address sender = _msgSender();\n        if (pendingOwner() != sender) {\n            revert OwnableUnauthorizedAccount(sender);\n        }\n        _transferOwnership(sender);\n    }\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable\n    struct PausableStorage {\n        bool _paused;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Pausable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;\n\n    function _getPausableStorage() private pure returns (PausableStorage storage $) {\n        assembly {\n            $.slot := PausableStorageLocation\n        }\n    }\n\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    /**\n     * @dev The operation failed because the contract is paused.\n     */\n    error EnforcedPause();\n\n    /**\n     * @dev The operation failed because the contract is not paused.\n     */\n    error ExpectedPause();\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    function __Pausable_init() internal onlyInitializing {\n        __Pausable_init_unchained();\n    }\n\n    function __Pausable_init_unchained() internal onlyInitializing {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = false;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        PausableStorage storage $ = _getPausableStorage();\n        return $._paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        if (paused()) {\n            revert EnforcedPause();\n        }\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        if (!paused()) {\n            revert ExpectedPause();\n        }\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = false;\n        emit Unpaused(_msgSender());\n    }\n}\n"
      },
      "src/interfaces/IOperatorRegistry.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\n// Copyright (c) 2024, Alt Research Ltd.\npragma solidity =0.8.23;\n\n/// @title Interface for OperatorRegistry\n/// @notice This interface outlines the functionalities for managing and querying operators in a contract.\ninterface IOperatorRegistry {\n    ////////////////\n    // Events\n    ////////////////\n\n    /// @notice Emitted when a new operator is added\n    /// @param operator The address of the operator added\n    event OperatorAdded(address operator, address owner);\n\n    /// @notice Emitted when an operator is frozen\n    /// @param operator The address of the operator frozen\n    /// @param owner The address of the owner who froze the operator\n    event Frozen(address operator, address owner);\n\n    ////////////////\n    // Functions\n    ////////////////\n\n    /// @notice Triggers the stopped state.\n    function pause() external;\n\n    /// @notice Returns to normal state.\n    function unpause() external;\n\n    /// @notice Returns the total number of operators\n    /// @return The total number of operators\n    function totalOperators() external view returns (uint256);\n\n    /// @notice Checks if the given address is an operator\n    /// @param operator The address to check\n    /// @return True if the address is an operator, false otherwise\n    function isOperator(address operator) external view returns (bool);\n\n    /// @notice Returns an array of operator addresses starting from the specified index up to the query size\n    /// @param start The start index to retrieve operator addresses\n    /// @param querySize The number of operator addresses to retrieve\n    /// @return An array of operator addresses\n    function queryOperators(uint256 start, uint256 querySize) external view returns (address[] memory);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n */\ninterface IERC1155 is IERC165 {\n    /**\n     * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.\n     */\n    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n    /**\n     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n     * transfers.\n     */\n    event TransferBatch(\n        address indexed operator,\n        address indexed from,\n        address indexed to,\n        uint256[] ids,\n        uint256[] values\n    );\n\n    /**\n     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n     * `approved`.\n     */\n    event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n    /**\n     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n     *\n     * If an {URI} event was emitted for `id`, the standard\n     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n     * returned by {IERC1155MetadataURI-uri}.\n     */\n    event URI(string value, uint256 indexed id);\n\n    /**\n     * @dev Returns the value of tokens of token type `id` owned by `account`.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function balanceOf(address account, uint256 id) external view returns (uint256);\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n     *\n     * Requirements:\n     *\n     * - `accounts` and `ids` must have the same length.\n     */\n    function balanceOfBatch(\n        address[] calldata accounts,\n        uint256[] calldata ids\n    ) external view returns (uint256[] memory);\n\n    /**\n     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n     *\n     * Emits an {ApprovalForAll} event.\n     *\n     * Requirements:\n     *\n     * - `operator` cannot be the caller.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n     *\n     * See {setApprovalForAll}.\n     */\n    function isApprovedForAll(address account, address operator) external view returns (bool);\n\n    /**\n     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.\n     *\n     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens\n     * to an untrusted contract, when invoking {onERC1155Received} on the receiver.\n     * Ensure to follow the checks-effects-interactions pattern and consider employing\n     * reentrancy guards when interacting with untrusted contracts.\n     *\n     * Emits a {TransferSingle} event.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n     * - `from` must have a balance of tokens of type `id` of at least `value` amount.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n     * acceptance magic value.\n     */\n    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n     *\n     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens\n     * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.\n     * Ensure to follow the checks-effects-interactions pattern and consider employing\n     * reentrancy guards when interacting with untrusted contracts.\n     *\n     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.\n     *\n     * Requirements:\n     *\n     * - `ids` and `values` must have the same length.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n     * acceptance magic value.\n     */\n    function safeBatchTransferFrom(\n        address from,\n        address to,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external;\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface that must be implemented by smart contracts in order to receive\n * ERC-1155 token transfers.\n */\ninterface IERC1155Receiver is IERC165 {\n    /**\n     * @dev Handles the receipt of a single ERC1155 token type. This function is\n     * called at the end of a `safeTransferFrom` after the balance has been updated.\n     *\n     * NOTE: To accept the transfer, this must return\n     * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n     * (i.e. 0xf23a6e61, or its own function selector).\n     *\n     * @param operator The address which initiated the transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param id The ID of the token being transferred\n     * @param value The amount of tokens being transferred\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n     */\n    function onERC1155Received(\n        address operator,\n        address from,\n        uint256 id,\n        uint256 value,\n        bytes calldata data\n    ) external returns (bytes4);\n\n    /**\n     * @dev Handles the receipt of a multiple ERC1155 token types. This function\n     * is called at the end of a `safeBatchTransferFrom` after the balances have\n     * been updated.\n     *\n     * NOTE: To accept the transfer(s), this must return\n     * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n     * (i.e. 0xbc197c81, or its own function selector).\n     *\n     * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param ids An array containing ids of each token being transferred (order and length must match values array)\n     * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n     */\n    function onERC1155BatchReceived(\n        address operator,\n        address from,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC1155} from \"../IERC1155.sol\";\n\n/**\n * @dev Interface of the optional ERC1155MetadataExtension interface, as defined\n * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].\n */\ninterface IERC1155MetadataURI is IERC1155 {\n    /**\n     * @dev Returns the URI for token type `id`.\n     *\n     * If the `\\{id\\}` substring is present in the URI, it must be replaced by\n     * clients with the actual token type ID.\n     */\n    function uri(uint256 id) external view returns (string memory);\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Arrays.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Arrays.sol)\n\npragma solidity ^0.8.20;\n\nimport {StorageSlot} from \"./StorageSlot.sol\";\nimport {Math} from \"./math/Math.sol\";\n\n/**\n * @dev Collection of functions related to array types.\n */\nlibrary Arrays {\n    using StorageSlot for bytes32;\n\n    /**\n     * @dev Searches a sorted `array` and returns the first index that contains\n     * a value greater or equal to `element`. If no such index exists (i.e. all\n     * values in the array are strictly less than `element`), the array length is\n     * returned. Time complexity O(log n).\n     *\n     * `array` is expected to be sorted in ascending order, and to contain no\n     * repeated elements.\n     */\n    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {\n        uint256 low = 0;\n        uint256 high = array.length;\n\n        if (high == 0) {\n            return 0;\n        }\n\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n\n            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\n            // because Math.average rounds towards zero (it does integer division with truncation).\n            if (unsafeAccess(array, mid).value > element) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.\n        if (low > 0 && unsafeAccess(array, low - 1).value == element) {\n            return low - 1;\n        } else {\n            return low;\n        }\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {\n        bytes32 slot;\n        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`\n        // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0, arr.slot)\n            slot := add(keccak256(0, 0x20), pos)\n        }\n        return slot.getAddressSlot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {\n        bytes32 slot;\n        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`\n        // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0, arr.slot)\n            slot := add(keccak256(0, 0x20), pos)\n        }\n        return slot.getBytes32Slot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {\n        bytes32 slot;\n        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`\n        // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0, arr.slot)\n            slot := add(keccak256(0, 0x20), pos)\n        }\n        return slot.getUint256Slot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {\n        assembly {\n            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))\n        }\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {\n        assembly {\n            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable\n    struct OwnableStorage {\n        address _owner;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Ownable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;\n\n    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {\n        assembly {\n            $.slot := OwnableStorageLocation\n        }\n    }\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    function __Ownable_init(address initialOwner) internal onlyInitializing {\n        __Ownable_init_unchained(initialOwner);\n    }\n\n    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        OwnableStorage storage $ = _getOwnableStorage();\n        return $._owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        OwnableStorage storage $ = _getOwnableStorage();\n        address oldOwner = $._owner;\n        $._owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Muldiv operation overflow.\n     */\n    error MathOverflowedMulDiv();\n\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            return a / b;\n        }\n\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            if (denominator <= prod1) {\n                revert MathOverflowedMulDiv();\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
        "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
        "forge-std/=lib/forge-std/src/",
        "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": false,
      "libraries": {}
    }
  }}