Перейти к содержимому
Проверенный контрактЧастичноеBUSL-1.1

UpgradeMultisig

Адрес0xdcba7059b6312db0d3d7cdb3ca8a5ba21d931f2e
Баланс

0 ETH

 

Транзакций

7

 

Компилятор

solc 0.8.22

 

Тот же код

ещё 1 контракт

 

Подробности

Компилятор
solc 0.8.22+commit.4fc1097e
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
paris
Лицензия
BUSL-1.1
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 377 656
Транзакция создания
0x35e7819bc8…ff48208ad0
Библиотеки
contracts/multisig/UpgradeMultisig.sol:ApprovalLibrary0x2ff0…492ba0contracts/multisig/UpgradeMultisig.sol:ManagementRequestLibrary0x1f5a…c4befecontracts/multisig/UpgradeMultisig.sol:ReleaseManagementLibrary0x9f35…3e745acontracts/multisig/UpgradeMultisig.sol:ConstructorValidationLibrary0x2a77…57820ccontracts/multisig/UpgradeMultisig.sol:RenounceRoleValidationLibrary0x3537…4ff06a

34 файла

contracts/multisig/UpgradeMultisig.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {
    AccessControlEnumerable
} from "@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";

import {ApprovalLibrary} from "contracts/multisig/libraries/ApprovalLibrary.sol";
import {
    ConstructorValidationLibrary
} from "contracts/multisig/libraries/ConstructorValidationLibrary.sol";
import {ManagementRequestLibrary} from "contracts/multisig/libraries/ManagementRequestLibrary.sol";
import {ReleaseManagementLibrary} from "contracts/multisig/libraries/ReleaseManagementLibrary.sol";
import {
    RenounceRoleValidationLibrary
} from "contracts/multisig/libraries/RenounceRoleValidationLibrary.sol";

/**
 * @title UpgradeMultisig
 * @notice Multisig contract for managing smart contract upgrades with a threshold-based approval system.
 *
 * @dev ROLES:
 * - UPGRADE_PROPOSAL_OFFICER_ROLE: Can submit releases and management requests. Cannot approve or execute.
 *   Deployed with at least 2 operators; operators are added and removed through management requests.
 *   Removing or renouncing can never leave fewer than 2, so a lost key can always be replaced by another
 *   operator (add the replacement first THEN remove). Each operator can submit at most once per RATE_LIMIT.
 *   SECURITY NOTE: Operator keys must be well-protected (hardware wallet, MPC recommended).
 *   A compromised operator can temporarily delay operations by submitting requests that must be
 *   rejected, but cannot approve or execute any changes. Approvers can always reject bad requests.
 *
 * - UPGRADE_APPROVAL_OFFICER_ROLE: Can approve/reject releases and management requests. Threshold approvals
 *   start the timelock. Cannot submit requests.
 *
 * - ARKIS_SECURITY_OFFICER_ROLE: Can reject releases (emergency rejection capability).
 *
 * @dev REQUEST FLOW:
 * 1. Only ONE pending release OR management request can exist at a time (prevents spam/DoS)
 * 2. Submitting a management request auto-rejects any pending release that hasn't started timelock
 * 3. Releases cannot be submitted while any management request is pending (including during timelock)
 * 4. This ensures management requests (e.g., RemoveOperator) complete without operator interference
 * 5. Execution is permissionless after timelock passes - anyone can call executeRelease/executeManagementRequest
 *
 * @dev TIMELOCK:
 * - Timelock starts when threshold approvals are reached
 * - During timelock, the request cannot be modified but can still be rejected
 * - After timelock passes, anyone can execute the request
 */
contract UpgradeMultisig is IUpgradeMultisig, AccessControlEnumerable {
    bytes32 public constant UPGRADE_PROPOSAL_OFFICER_ROLE =
        keccak256("Upgrade Proposal Officer Role");
    bytes32 public constant UPGRADE_APPROVAL_OFFICER_ROLE =
        keccak256("Upgrade Approval Officer Role");
    bytes32 public constant ARKIS_SECURITY_OFFICER_ROLE = keccak256("Arkis Security Officer Role");
    uint256 public constant RATE_LIMIT = 5 minutes;

    address public immutable pauser;
    address public immutable proxyAdmin;
    address public immutable compiler;
    uint80 public nonce;
    uint8 public threshold;
    uint128 public timelockDuration;

    uint80 public lastExecutedNonce;

    mapping(bytes32 id => Release release) public releases;
    mapping(bytes32 releaseId => mapping(address approver => bool approved))
        public releaseApprovals;
    bytes32 public pendingReleaseId;

    mapping(bytes32 id => ManagementRequest request) public managementRequests;
    bytes32 public pendingManagementRequestId;

    mapping(address operator => uint256 lastProposed) public rateLimitRegister;

    modifier rateLimit() {
        uint256 lastProposed = rateLimitRegister[msg.sender];
        if (block.timestamp < lastProposed + RATE_LIMIT) {
            revert IUpgradeMultisig.RateLimit(msg.sender, lastProposed);
        }
        rateLimitRegister[msg.sender] = block.timestamp;
        _;
    }

    constructor(
        address[] memory _operators,
        address _pauser,
        address _proxyAdmin,
        address _compiler,
        address[] memory _initialApprovers,
        address _initialSecurityOfficer,
        uint8 _threshold,
        uint128 _timelockDuration
    ) {
        ConstructorValidationLibrary.validateConstructorParams(
            _operators,
            _pauser,
            _proxyAdmin,
            _compiler,
            _initialApprovers,
            _initialSecurityOfficer,
            _threshold,
            _timelockDuration
        );
        if (_initialSecurityOfficer == address(this)) revert IUpgradeMultisig.InvalidAddress();

        pauser = _pauser;
        proxyAdmin = _proxyAdmin;
        compiler = _compiler;
        threshold = _threshold;
        timelockDuration = _timelockDuration;

        for (uint256 i = 0; i < _operators.length; i++) {
            _grantRole(UPGRADE_PROPOSAL_OFFICER_ROLE, _operators[i]);
        }

        for (uint256 i = 0; i < _initialApprovers.length; i++) {
            _grantRole(UPGRADE_APPROVAL_OFFICER_ROLE, _initialApprovers[i]);
        }

        _grantRole(ARKIS_SECURITY_OFFICER_ROLE, _initialSecurityOfficer);
    }

    function submitRelease(
        IUpgradeMultisig.ReleaseData calldata releaseData,
        bytes32 releaseHash
    )
        external
        override
        onlyRole(UPGRADE_PROPOSAL_OFFICER_ROLE)
        rateLimit
        returns (bytes32 releaseId)
    {
        (releaseId, nonce) = ReleaseManagementLibrary.submitRelease(
            releases,
            pendingReleaseId,
            pendingManagementRequestId,
            nonce,
            proxyAdmin,
            releaseData,
            releaseHash,
            address(this)
        );
        pendingReleaseId = releaseId;
    }

    function approveRelease(
        bytes32 releaseId
    ) external override onlyRole(UPGRADE_APPROVAL_OFFICER_ROLE) {
        ReleaseManagementLibrary.approveRelease(
            releases,
            releaseApprovals,
            releaseId,
            threshold,
            timelockDuration,
            lastExecutedNonce,
            this
        );
    }

    function rejectRelease(bytes32 releaseId) external override {
        uint80 rejectedNonce = ReleaseManagementLibrary.rejectRelease(releases, releaseId, this);
        pendingReleaseId = bytes32(0);
        lastExecutedNonce = rejectedNonce;
    }

    function executeRelease(bytes32 releaseId) external payable override {
        Release storage release = releases[releaseId];

        lastExecutedNonce = ReleaseManagementLibrary.executeRelease(
            release,
            pauser,
            proxyAdmin,
            compiler
        );
        pendingReleaseId = bytes32(0);

        emit ReleaseExecuted(releaseId, msg.sender, block.timestamp);
    }

    function submitManagementRequest(
        ManagementRequestType requestType,
        bytes calldata requestData
    )
        external
        override
        onlyRole(UPGRADE_PROPOSAL_OFFICER_ROLE)
        rateLimit
        returns (bytes32 requestId)
    {
        // Auto-reject pending release when submitting a management request
        (uint80 rejectedNonce, bool wasRejected) = ReleaseManagementLibrary.rejectPendingRelease(
            releases,
            pendingReleaseId
        );
        if (wasRejected) {
            pendingReleaseId = bytes32(0);
            lastExecutedNonce = rejectedNonce;
        }

        if (pendingManagementRequestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestPending();
        }

        ManagementRequestLibrary.validateRequest(requestType, requestData, this);

        ManagementRequestLibrary.RequestSubmissionResult memory result = ManagementRequestLibrary
            .submitManagementRequest(
                managementRequests,
                nonce,
                threshold,
                requestType,
                requestData,
                address(this),
                this
            );

        requestId = result.requestId;
        nonce = result.newNonce;
        pendingManagementRequestId = result.newPendingRequestId;

        ManagementRequestLibrary.emitRequestSubmitted(
            requestType,
            requestId,
            requestData,
            msg.sender
        );
    }

    function approveManagementRequest(
        bytes32 requestId
    ) external override onlyRole(UPGRADE_APPROVAL_OFFICER_ROLE) {
        ManagementRequest storage request = managementRequests[requestId];
        ManagementRequestLibrary.validateForApproval(request);

        bytes32 newPendingRequestId = ApprovalLibrary.processManagementRequestApproval(
            request,
            msg.sender,
            threshold,
            pendingManagementRequestId,
            requestId,
            this,
            timelockDuration,
            lastExecutedNonce
        );

        pendingManagementRequestId = newPendingRequestId;
    }

    function rejectManagementRequest(
        bytes32 requestId
    ) external override onlyRole(UPGRADE_APPROVAL_OFFICER_ROLE) {
        ManagementRequest storage request = managementRequests[requestId];
        ManagementRequestLibrary.validateForRejection(request);

        (bool wasRejected, bytes32 newPendingRequestId, uint80 rejectedNonce) = ApprovalLibrary
            .processManagementRequestRejection(
                request,
                msg.sender,
                threshold,
                pendingManagementRequestId,
                requestId,
                this
            );

        pendingManagementRequestId = newPendingRequestId;
        if (wasRejected) {
            lastExecutedNonce = rejectedNonce;
        }
    }

    function executeManagementRequest(bytes32 requestId) external override {
        ManagementRequest storage request = managementRequests[requestId];

        (uint256 approvalCount, ) = ApprovalLibrary.getManagementRequestCounts(
            request,
            AccessControlEnumerable(address(this))
        );

        ManagementRequestLibrary.validateExecution(request, threshold, approvalCount);

        _executeManagementRequest(requestId);
    }

    function getApprovers() external view override returns (address[] memory) {
        uint256 count = getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE);
        address[] memory approversList = new address[](count);
        for (uint256 i = 0; i < count; i++) {
            approversList[i] = getRoleMember(UPGRADE_APPROVAL_OFFICER_ROLE, i);
        }
        return approversList;
    }

    function getManagementRequestInfo(
        bytes32 requestId
    )
        external
        view
        override
        returns (
            ManagementRequestType requestType,
            address targetApprover,
            uint8 newThreshold,
            address targetOperator,
            uint128 newTimelockDuration,
            address targetContract,
            address newOwner,
            Status status
        )
    {
        ManagementRequest storage request = managementRequests[requestId];
        return (
            request.requestType,
            request.targetApprover,
            request.newThreshold,
            request.targetOperator,
            request.newTimelockDuration,
            request.targetContract,
            request.newOwner,
            request.status
        );
    }

    function getManagementRequestTargetContracts(
        bytes32 requestId
    ) external view override returns (address[] memory) {
        return managementRequests[requestId].targetContracts;
    }

    function getManagementRequestApprovalStatus(
        bytes32 requestId,
        address approver
    ) external view override returns (bool approved, bool rejected) {
        ManagementRequest storage request = managementRequests[requestId];
        approved = request.approvals[approver];
        rejected = request.rejections[approver];
    }

    /**
     * @dev Override renounceRole to prevent bricking scenarios:
     * - Cannot renounce UPGRADE_APPROVAL_OFFICER_ROLE if it would drop below threshold
     * - Cannot renounce UPGRADE_PROPOSAL_OFFICER_ROLE if it's the last operator
     * - Cannot renounce ARKIS_SECURITY_OFFICER_ROLE if it's the last security officer
     * - Cannot renounce UPGRADE_APPROVAL_OFFICER_ROLE while any management request is pending
     * - Cannot renounce UPGRADE_PROPOSAL_OFFICER_ROLE while a RemoveOperator request is pending
     *
     * NOTE: If revokeRole is ever exposed or admin-enabled, the same guard must be
     * applied to approver revocation during pending management requests to prevent
     * stuck requests where approval counts drop below threshold.
     */
    function renounceRole(
        bytes32 role,
        address callerConfirmation
    ) public override(AccessControl, IAccessControl) {
        RenounceRoleValidationLibrary.validateRenounceRole(
            role,
            getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE),
            getRoleMemberCount(UPGRADE_PROPOSAL_OFFICER_ROLE),
            getRoleMemberCount(ARKIS_SECURITY_OFFICER_ROLE),
            threshold
        );
        if (pendingManagementRequestId != bytes32(0)) {
            ManagementRequest storage pendingRequest = managementRequests[
                pendingManagementRequestId
            ];
            if (pendingRequest.status == Status.Pending) {
                if (role == UPGRADE_APPROVAL_OFFICER_ROLE) {
                    revert CannotRenounceWhileManagementRequestPending();
                }
                if (
                    role == ARKIS_SECURITY_OFFICER_ROLE &&
                    pendingRequest.requestType == ManagementRequestType.RemoveSecurityOfficer
                ) {
                    revert CannotRenounceWhileManagementRequestPending();
                }
                if (
                    role == UPGRADE_PROPOSAL_OFFICER_ROLE &&
                    pendingRequest.requestType == ManagementRequestType.RemoveOperator
                ) {
                    revert CannotRenounceWhileManagementRequestPending();
                }
            }
        }

        super.renounceRole(role, callerConfirmation);
    }

    function _executeManagementRequest(bytes32 requestId) internal {
        ManagementRequest storage request = managementRequests[requestId];

        ManagementRequestLibrary.ExecutionResult memory result = ManagementRequestLibrary.execute(
            request,
            pendingManagementRequestId,
            lastExecutedNonce,
            threshold,
            timelockDuration
        );

        lastExecutedNonce = result.newLastExecutedNonce;
        pendingManagementRequestId = result.newPendingRequestId;

        _executeRequestAction(requestId, request);

        emit ManagementRequestExecuted(requestId, msg.sender, block.timestamp);
    }

    function _executeRequestAction(bytes32 requestId, ManagementRequest storage request) private {
        ManagementRequestType reqType = request.requestType;

        if (reqType == ManagementRequestType.AddApprover) {
            _grantRole(UPGRADE_APPROVAL_OFFICER_ROLE, request.targetApprover);
            emit ApproverAdded(requestId, request.targetApprover);
        } else if (reqType == ManagementRequestType.RemoveApprover) {
            _revokeRole(UPGRADE_APPROVAL_OFFICER_ROLE, request.targetApprover);
            emit ApproverRemoved(requestId, request.targetApprover);
        } else if (reqType == ManagementRequestType.ChangeThreshold) {
            uint8 oldThreshold = threshold;
            threshold = request.newThreshold;
            emit ThresholdChanged(requestId, oldThreshold, request.newThreshold);
        } else if (reqType == ManagementRequestType.AddOperator) {
            _grantRole(UPGRADE_PROPOSAL_OFFICER_ROLE, request.targetOperator);
            emit OperatorAdded(requestId, request.targetOperator);
        } else if (reqType == ManagementRequestType.RemoveOperator) {
            if (
                getRoleMemberCount(UPGRADE_PROPOSAL_OFFICER_ROLE) <=
                ManagementRequestLibrary.MIN_OPERATORS
            ) {
                revert IUpgradeMultisig.InsufficientOperators();
            }
            _revokeRole(UPGRADE_PROPOSAL_OFFICER_ROLE, request.targetOperator);
            emit OperatorRemoved(requestId, request.targetOperator);
        } else if (reqType == ManagementRequestType.ChangeTimelock) {
            uint128 oldTimelock = timelockDuration;
            timelockDuration = request.newTimelockDuration;
            emit TimelockChanged(requestId, oldTimelock, request.newTimelockDuration);
        } else if (reqType == ManagementRequestType.AddSecurityOfficer) {
            _grantRole(ARKIS_SECURITY_OFFICER_ROLE, request.targetApprover);
            emit SecurityOfficerAdded(requestId, request.targetApprover);
        } else if (reqType == ManagementRequestType.RemoveSecurityOfficer) {
            if (getRoleMemberCount(ARKIS_SECURITY_OFFICER_ROLE) <= 1) {
                revert IUpgradeMultisig.CannotRemoveLastSecurityOfficer();
            }
            _revokeRole(ARKIS_SECURITY_OFFICER_ROLE, request.targetApprover);
            emit SecurityOfficerRemoved(requestId, request.targetApprover);
        } else if (reqType == ManagementRequestType.RenounceOwnership) {
            _renounceOwnership(requestId, request.targetContract);
        } else if (reqType == ManagementRequestType.TransferOwnership) {
            address[] storage targets = request.targetContracts;
            for (uint256 i = 0; i < targets.length; i++) {
                Ownable(targets[i]).transferOwnership(request.newOwner);
                emit OwnershipTransferred(requestId, targets[i], request.newOwner);
            }
        } else {
            revert IUpgradeMultisig.InvalidManagementRequestType();
        }
    }

    /**
     * @dev Renounces ownership of a target contract.
     *      For EIP-2535 diamonds (detected via facets() function), uses transferOwnership(address(0))
     *      since diamonds doesnt't have renounceOwnership() per IERC173.
     *      For OZ Ownable contracts, uses renounceOwnership().
     */
    function _renounceOwnership(bytes32 requestId, address targetContract) private {
        if (_isDiamond(targetContract)) {
            Ownable(targetContract).transferOwnership(address(0));
        } else {
            Ownable(targetContract).renounceOwnership();
        }
        emit OwnershipRenounced(requestId, targetContract);
    }

    /**
     * @dev Checks if a contract is an EIP-2535 diamond by probing for facets()
     */
    function _isDiamond(address target) private view returns (bool) {
        (bool success, ) = target.staticcall(abi.encodeWithSelector(0x7a0ed627)); // facets()
        return success;
    }
}

@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/access/AccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

@openzeppelin/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlEnumerable.sol)

pragma solidity ^0.8.20;

import {IAccessControlEnumerable} from "./IAccessControlEnumerable.sol";
import {AccessControl} from "../AccessControl.sol";
import {EnumerableSet} from "../../utils/structs/EnumerableSet.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
    using EnumerableSet for EnumerableSet.AddressSet;

    mapping(bytes32 role => EnumerableSet.AddressSet) private _roleMembers;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {AccessControl-_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        bool granted = super._grantRole(role, account);
        if (granted) {
            _roleMembers[role].add(account);
        }
        return granted;
    }

    /**
     * @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        bool revoked = super._revokeRole(role, account);
        if (revoked) {
            _roleMembers[role].remove(account);
        }
        return revoked;
    }
}

@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlEnumerable.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "../IAccessControl.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

@openzeppelin/contracts/utils/structs/EnumerableSet.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

contracts/interfaces/base/CommonErrors.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

/**
 * @notice An error indicating that the amount for the specified token is zero.
 * @param token The address of the token with a zero amount.
 */
error AmountMustNotBeZero(address token);

/**
 * @notice An error indicating that an address must not be zero.
 */
error AddressMustNotBeZero();

/**
 * @notice An error indicating that an array must not be empty.
 */
error ArrayMustNotBeEmpty();

/**
 * @notice An error indicating that an string must not be empty.
 */
error StringMustNotBeEmpty();

/**
 * @notice An error indicating storage is already up to date and doesn't need further processing.
 * @dev This error is thrown when attempting to update an entity(s) that is(are) already up to date.
 */
error AlreadyUpToDate();

/**
 * @notice An error indicating that an action is unauthorized for the specified account.
 * @param account The address of the unauthorized account.
 */
error UnauthorizedAccount(address account);

/**
 * @notice An error indicating that the min amount out must not be zero.
 */
error MinAmountOutMustNotBeZero();

/**
 * @notice An error indicating that the threshold exceeds the maximum allowed value.
 */

contracts/interfaces/base/IERC165Extended.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

/* solhint-disable no-unused-import */
import {
    IERC165
} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
/* solhint-enable no-unused-import */

/**
 * @notice An error indicating that an address does not support the expected interface
 * @param implementation The address that does not implement the required interface
 */
error UnsupportedInterface(address implementation);

/**
 * @dev Extended interface of the ERC165 standard to ensure compatibility
 * with Diamond facets as defined in EIP-2535.
 *
 * This interface extends the basic ERC165 mechanism to provide additional
 * flexibility for querying supported interfaces, which can then be
 * dynamically resolved by one of facets in a Diamond.
 */
interface IERC165Extended {
    /**
     * @notice Checks if the given interface ID is supported by the contract.
     * @param interfaceId The ID of the interface to query.
     * @return isSupported Boolean value indicating whether the interface is supported.
     */
    function supportsInterfaceExtended(bytes4 interfaceId) external pure returns (bool isSupported);
}

contracts/interfaces/base/pauser/IPausable.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;

/**
 * @dev Interface for contracts that can be paused or unpaused.
 * This interface provides the methods to pause and unpause the contract
 * as well as check its paused status. It also includes the definition of
 * the `PAUSER_ROLE` that is required to perform the pause/unpause actions.
 */
interface IPausable {
    /**
     * @notice Pauses the contract.
     * @dev Can only be called by an address with the `PAUSER_ROLE`.
     *      This function will halt any operations that are paused in the contract.
     */
    function pause() external;

    /**
     * @notice Unpauses the contract.
     * @dev Can only be called by an address with the `PAUSER_ROLE`.
     *      This function will resume any operations that were paused in the contract.
     */
    function unpause() external;

    /**
     * @notice Returns whether the contract is paused.
     * @return bool True if the contract is paused, false otherwise.
     * @dev This function checks the contract's paused status, which is typically
     *      managed by an internal flag set by the `pause` and `unpause` functions.
     */
    function paused() external view returns (bool);

    /**
     * @notice Returns the role identifier for the `PAUSER_ROLE`.
     * @return bytes32 The role identifier for the `PAUSER_ROLE`.
     * @dev The `PAUSER_ROLE` is required for the caller to invoke the `pause` or `unpause` functions.
     */
    /* solhint-disable-next-line func-name-mixedcase */
    function PAUSER_ROLE() external view returns (bytes32);
}

contracts/interfaces/base/proxy/IBeacon.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

interface IBeacon {
    error InvalidImplementation(address implementation);

    /**
     * This upgrade will affect all Beacon Proxies that use this Beacon
     * @param newImplementation New implementation to delegate calls from Beacon Proxies
     */
    function setImplementation(address newImplementation) external;

    /**
     * Returns address of the current used by Beacon Proxies
     */
    function implementation() external view returns (address);
}

contracts/interfaces/compiler/ILiquidityPoolsController.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {Status} from "../compliance/IWhitelistingController.sol";

/**
 * @notice Represents a record for an evaluator associated with a specific protocol.
 * @param protocol The name of the protocol that the evaluator is associated with.
 * @param evaluator The address of the evaluator.
 */
struct EvaluatorRecord {
    string protocol;
    address evaluator;
}

/**
 * @title WhitelistingBytesRecord
 * @notice A struct used to store encoded pool data and its support status.
 * @dev This struct is employed in the [`ILiquidityPoolsController`](/interfaces/compiler/ILiquidityPoolsController.sol/interface.ILiquidityPoolsController.html) interface.
 * @dev `encoded`: Encoded pool data. The encoding depends on the underlying protocol.
 * For example UniswapV3 protocol expects this as `(address token0, address token1, uint24 fee)`.
 * To find out which encoding does `ProtocolName` expects,
 * check `{ProtocolName}LiquidityPoolsRepository.initializePool()`
 * @dev `supported`: Indicates whether the pool is supported.
 */
struct WhitelistingBytesRecord {
    bytes encoded;
    bool supported;
}

/**
 * @title ILiquidityPoolsController
 * @notice Interface for managing liquidity pools and their support status for different protocols.
 */
interface ILiquidityPoolsController {
    /**
     * @notice Emitted when an evaluator is updated for a specific protocol.
     * @param protocol The name of the protocol associated with the updated evaluator.
     * @param evaluator The address of the updated evaluator.
     */
    event EvaluatorUpdated(string protocol, address evaluator);

    /**
     * @dev Emitted when the support status of a pool changes.
     * @param protocol The `protocol` identifier.
     * @param encodedPool The encoded pool data.
     * @param poolId The unique identifier of the pool.
     * @param supported Whether the pool is supported or not.
     */
    event PoolSupportChanged(
        string protocol,
        bytes encodedPool,
        uint256 indexed poolId,
        bool supported
    );

    /**
     * @notice Updates the evaluators for the specified protocols.
     * @dev This function allows updating the evaluators by passing an array of [`EvaluatorRecord`](#evaluatorrecord) structs.
     * @param records An array of [`EvaluatorRecord`](#evaluatorrecord) structs, each containing the protocol name and the new evaluator address.
     */
    function updateEvaluators(EvaluatorRecord[] calldata records) external;

    /**
     * @notice Update the support status of multiple liquidity pools for a specific protocol.
     * @dev Reverts with an [`AlreadyUpToDate`](/interfaces/base/CommonErrors.sol/error.AlreadyUpToDate.html) error if status didn't change for any given pool.
     * @dev Emits a [`PoolSupportChanged`](#poolsupportchanged) event for each pool.
     * @param _protocol The `protocol` identifier.
     * @param _pools An array of [`WhitelistingBytesRecord`](/interfaces/compiler/ILiquidityPoolsController.sol/struct.WhitelistingBytesRecord.html#whitelistingbytesrecord) structs containing pool data and support status.
     */
    function updatePoolsSupport(
        string calldata _protocol,
        WhitelistingBytesRecord[] calldata _pools
    ) external;

    /**
     * @notice Returns the role identifier required to manage all master set whitelists.
     * @return A bytes32 value representing the ARKIS_WHITELIST_OFFICER_ROLE.
     */
    /* solhint-disable-next-line func-name-mixedcase*/
    function ARKIS_WHITELIST_OFFICER_ROLE() external view returns (bytes32);

    /* solhint-disable ordering */
    /**
     * @notice Retrieves the evaluator address for a given protocol.
     * @dev This function returns the address of the evaluator associated with the specified protocol.
     * @param protocol The name of the protocol for which to retrieve the evaluator address.
     * @return The address of the evaluator associated with the specified protocol.
     */
    function getProtocolEvaluator(string calldata protocol) external view returns (address);

    /**
     * @notice Get the status of a specific pool and its associated protocol.
     * @param _protocol The `protocol` identifier.
     * @param _poolId The unique identifier of the pool.
     * @return poolStatus_ The [`Status`](/interfaces/compliance/IWhitelistingController.sol/enum.Status.html)
     *  of the pool.
     */
    function getPoolStatus(
        string calldata _protocol,
        uint256 _poolId
    ) external returns (Status poolStatus_);

    /**
     * @notice Get the unique identifier (pool ID) of a specific pool.
     * @param _protocol The `protocol` identifier.
     * @param _encodedPool The encoded pool data. The encoding depends on the underlying protocol.
     * For example UniswapV3 protocol expects this as (address token0, address token1, uint24 fee).
     * To find out which encoding does `ProtocolName` expects,
     * check {ProtocolName}LiquidityPoolsRepository.getPoolIdFromTokens()
     * @dev `supported`: Indicates whether the pool is supported.

     * @return poolId_ The unique identifier of the pool.
     */
    function getPoolId(
        string calldata _protocol,
        bytes calldata _encodedPool
    ) external returns (uint256 poolId_);
    /* solhint-enable ordering */
}

contracts/interfaces/compliance/IWhitelistingController.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {IERC165Extended} from "../base/IERC165Extended.sol";
import {IWhitelistingControllerAgreement} from "./IWhitelistingControllerAgreement.sol";

/**
 * @title Status
 * @notice Enum representing status of a record (e.g., token, protocol, operator)
 *  used for operation validation.
 * @notice Validators must adhere to the following rules for different operations and contexts:
 *  1) For exchanges: `operator`, `pool`, and `input token` *MAY* be either supported or suspended, but the `output token` *MUST* be supported.
 *  2) For deposits: `operator`, `pool`, and every `token` in the `pool` *MUST* be supported.
 *  3) For withdrawals: `operator`, `pool`, and each `token` *MAY* be either supported or suspended.
 *
 * @dev **Note** that deposit denotes **all** ways of acquiring liquidity such
 * as token deposit, LP tokens stake, NFT mint etc.
 */
enum Status {
    Undefined,
    Supported,
    Suspended
}

/**
 * @title WhitelistingAddressRecord
 * @notice A struct to store an address and its support status.
 * @dev This struct stores an address and its support status.
 * @dev `source`: The address to be stored.
 * @dev `supported`: Indicates whether the address is supported or not.
 */
struct WhitelistingAddressRecord {
    address source;
    bool supported;
}

/**
 * @title WhitelistingTokenRecord
 * @notice This struct stores an address and its support status for whitelisting, collateral and leverage.
 * @dev `source`: The address of the token.
 * @dev `supported`: Whether the token can be received from a protocol trades.
 */
struct WhitelistingTokenRecord {
    address source;
    bool supported;
}

/**
 * @title TreasuryStorage
 * @notice ERC-7201 namespaced storage for the protocol treasury address.
 * @dev `treasury`: The address that receives protocol fees on close.
 */
struct TreasuryStorage {
    address treasury;
}

/**
 * @notice An error indicating that a token is not supported by the whitelisting controller.
 * @dev This error is thrown when an unsupported token is used.
 * @dev `token`: The address of the unsupported token.
 */
error TokenIsNotSupported(address token);

/**
 * @notice An error indicating that a token is suspended by the whitelisting controller.
 * @dev This error is thrown when a suspended token is used.
 * @dev `token`: The address of the suspended token.
 */
error TokenIsSuspended(address token);

/**
 * @notice An error indicating that an operator is not supported by the whitelisting controller.
 * @dev This error is thrown when an unsupported operator is used.
 * @dev `operator`: The address of the unsupported operator.
 */
error OperatorIsNotSupported(address operator);

/**
 * @notice An error indicating that an operator is suspended by the whitelisting controller.
 * @dev This error is thrown when a suspended operator is used.
 * @dev `operator`: The address of the suspended operator.
 */
error OperatorIsSuspended(address operator);

/**
 * @notice An error indicating that a protocol is not supported by the whitelisting controller.
 * @dev This error is thrown when an unsupported protocol is used.
 * @dev `protocol`: The identification string of the unsupported protocol.
 */
error ProtocolIsNotSupported(bytes31 protocolNameHash);

/**
 * @notice An error indicating that a protocol is suspended by the whitelisting controller.
 * @dev This error is thrown when a suspended protocol is used.
 * @dev `protocol`: The identification string of the unsupported protocol.
 */
error ProtocolIsSuspended(bytes31 protocolNameHash);

interface ITenant {
    function factory() external view returns (address);
}

/**
 * @title IWhitelistingController
 * @notice Interface for managing whitelisting of tokens, protocols, and operators.
 */
interface IWhitelistingController is IWhitelistingControllerAgreement, IERC165Extended {
    /**
     * @dev Emitted when the support status of a protocol changes.
     * @dev `protocol`: The identification string of the protocol.
     * @dev `supported`: Whether the protocol is supported or not.
     */
    event ProtocolSupportChanged(string indexed protocol, bool supported);

    /**
     * @dev Emitted when the support status of a token changes.
     * @dev `token`: The address of the token.
     * @dev `supported`: Whether the token is supported or not.
     */
    event TokenSupportChanged(address indexed token, bool supported);

    /**
     * @dev Emitted when the support status of an operator changes for a specific protocol.
     * @dev `protocol`: The identification string of the protocol.
     * @dev `operator`: The address of the operator.
     * @dev `supported`: Whether the operator is supported or not.
     */
    event OperatorSupportChanged(string indexed protocol, address indexed operator, bool supported);

    /**
     * @dev Emitted when the protocol treasury address is changed.
     * @dev `previousTreasury`: The treasury address before the change.
     * @dev `newTreasury`: The treasury address after the change.
     */
    event TreasuryChanged(address indexed previousTreasury, address indexed newTreasury);

    /**
     * @notice Reverts when the agreement was deployed by a different factory version.
     * @dev This error is used by the `onlyAgreementFactory` modifier to prevent
     *      `addTokens` and `addOperators` calls from wrong factory.
     * @param factory The address of the factory attempting to interact.
     * @param agreement The agreement contract whose associated factory version did not match the caller.
     */
    error AgreementFactoryVersionMismatch(address factory, address agreement);

    /**
     * @notice Reverts when the caller contract supports a prohibited interface.
     * @dev This error is used by the `notMarginAccount` modifier to prevent
     *      function calls from contracts that implement the `IAccount` interface.
     * @param caller The address of the caller contract
     */
    error CallerSupportsForbiddenInterface(address caller);

    /**
     * @notice An error indicating that the provided address is not a valid token address.
     * @dev This error is thrown when the address does not conform to the expected token interface.
     * @param token The address that failed the token validation check.
     */
    error InvalidTokenAddress(address token);

    /**
     * @notice Update the support status of multiple tokens.
     * @dev Emits a [`TokenSupportChanged()`](#tokensupportchanged) event for each token whose status changed.
     * @dev Reverts with an [`AlreadyUpToDate()`](/interfaces/base/CommonErrors.sol/error.AlreadyUpToDate.html)
     *  error if no token status changed.
     * @param _tokens An array of [`WhitelistingTokenRecord`](./struct.WhitelistingTokenRecord.html)
     * structs containing token addresses and support.
     */
    function updateTokensSupport(WhitelistingTokenRecord[] calldata _tokens) external;

    /**
     * @notice Update the support status of a protocol.
     * @dev Emits a [`ProtocolSupportChanged()`](#protocolsupportchanged) event.
     * @dev Reverts with an [`AlreadyUpToDate()`](/interfaces/base/CommonErrors.sol/error.AlreadyUpToDate.html)
     *  error if protocol status is up to date.
     * @param _protocol The identification string of the protocol.
     * @param _supported Whether the protocol is supported or not.
     */
    function updateProtocolSupport(string calldata _protocol, bool _supported) external;

    /**
     * @notice Update the support status of multiple operators for a specific protocol.
     * @dev Emits a [`OperatorSupportChanged()`](#operatorsupportchanged) event for each token whose status changed.
     * @dev Reverts with an [`AlreadyUpToDate()`](/interfaces/base/CommonErrors.sol/error.AlreadyUpToDate.html)
     *  error if no operator status changed.
     * @param _protocol The identification string of the protocol.
     * @param _operators An array of `WhitelistingAddressRecord` structs containing operator addresses and support statuses.
     */
    function updateOperatorsSupport(
        string calldata _protocol,
        WhitelistingAddressRecord[] calldata _operators
    ) external;

    /**
     * @notice Sets the protocol treasury address.
     * @dev Only callable by an account with `ARKIS_SECURITY_OFFICER_ROLE`.
     *  Emits a [`TreasuryChanged()`](#treasurychanged) event.
     * @param newTreasury The new treasury address.
     */
    function setTreasury(address newTreasury) external;

    /**
     * @notice Returns the role identifier required to manage all master set whitelists.
     * @return A bytes32 value representing the ARKIS_WHITELIST_OFFICER_ROLE.
     */
    /* solhint-disable-next-line func-name-mixedcase*/
    function ARKIS_WHITELIST_OFFICER_ROLE() external view returns (bytes32);

    /**
     * @notice Returns the support status of a token.
     * @param _token The address of the token.
     * @return The [`Status`](./enum.Status.html) of the token.
     */
    function getTokenStatus(address _token) external view returns (Status);

    /**
     * @notice Checks whether a specific token is supported by a tenant.
     * @dev This function returns a boolean indicating if the given token is supported by the specified tenant.
     * @param tenant The address of the tenant to check.
     * @param token The address of the token to check for support.
     * @return A boolean value indicating whether the token is supported by the tenant.
     */
    function getTokenSupport(address tenant, address token) external view returns (bool);

    /**
     * @notice Retrieves the list of tokens supported by a specific tenant.
     * @dev This function returns an array of token addresses that are supported by the specified tenant.
     * @param tenant The address of the tenant whose supported tokens are to be retrieved.
     * @return An array of addresses representing the tokens supported by the tenant.
     */
    function getTokens(address tenant) external view returns (address[] memory);

    /**
     * @notice Returns the support status of a protocol.
     * @param protocol The identification string of the protocol.
     * @return The [`Status`](./enum.Status.html)
     *  of the protocol.
     */
    function getProtocolStatus(string calldata protocol) external view returns (Status);

    /**
     * @notice Returns the support status of an operator for a specific protocol.
     * @param _operator The address of the operator.
     * @return operatorStatus_ The [`Status`](./enum.Status.html)
     *  of the operator.
     * @return protocolStatus_ The [`Status`](./enum.Status.html)
     *  of the protocol.
     */
    function getOperatorStatus(
        address _operator
    ) external view returns (Status operatorStatus_, Status protocolStatus_);

    /**
     * @notice Returns role identifier for unpause operators
     * @return bytes32 keccak256 hash of ARKIS_SECURITY_OFFICER_ROLE
     */
    /* solhint-disable-next-line func-name-mixedcase*/
    function ARKIS_SECURITY_OFFICER_ROLE() external view returns (bytes32);

    /**
     * @notice Returns the protocol treasury address that receives protocol fees on close.
     * @return The treasury address.
     */
    function treasury() external view returns (address);
}

contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

/**
 * @title IWhitelistingControllerAgreement
 * @notice Interface for managing whitelisting of tokens and operators for Agreements.
 */
interface IWhitelistingControllerAgreement {
    /**
     * @notice Emitted when a new token is added for a specific tenant.
     * @param tenant The address of the tenant to whom the token is added.
     * @param token The address of the token that has been added.
     */
    event TokenAdded(address tenant, address token);

    /**
     * @notice Emitted when a new operator is added for a specific tenant.
     * @param tenant The address of the tenant to whom the operator is added.
     * @param operator The address of the operator that has been added.
     */
    event OperatorAdded(address tenant, address operator);

    /**
     * @notice Adds a list of tokens to the specified tenant.
     * @param tenant The address of the tenant to which the tokens will be added.
     * @param tokens An array of addresses representing the tokens to be added.
     * @dev This function can be used to update the list of supported tokens for a given tenant.
     */
    function addTokens(address tenant, address[] calldata tokens) external;

    /**
     * @notice Adds a list of operators to the specified tenant.
     * @param tenant The address of the tenant to which the operators will be added.
     * @param operators An array of addresses representing the operators to be added.
     * @dev This function updates the list of authorized operators for a given tenant.
     */
    function addOperators(address tenant, address[] calldata operators) external;

    /**
     * @notice Returns the address of the agreement factory contract.
     * @return The address of the agreement factory.
     * @dev The agreement factory is used to create and manage agreements.
     */
    function agreementFactory() external view returns (address);

    /**
     * @notice Returns the address of the agreement V2 factory contract.
     * @return The address of the agreement V2 factory.
     * @dev The agreement V2 factory is used to create and manage agreements V2.
     */
    function agreementV2Factory() external view returns (address);

    /**
     * @notice Checks if a specific token is supported for a given tenant.
     * @param tenant The address of the tenant whose supported tokens are being queried.
     * @param token The address of the token to check for support.
     * @return A boolean indicating whether the token is supported by the tenant.
     * @dev This function will return `true` if the token is supported, and `false` otherwise.
     */
    function getTokenSupport(address tenant, address token) external view returns (bool);

    /**
     * @notice Retrieves a list of tokens supported by a specific tenant.
     * @param tenant The address of the tenant whose supported tokens are being queried.
     * @return An array of token addresses supported by the specified tenant.
     * @dev This function returns an array containing the addresses of tokens that the tenant supports.
     *      It is a view function and does not modify the contract state.
     */
    function getTokens(address tenant) external view returns (address[] memory);

    /**
     * @notice Checks if a specific operator is supported by a given tenant.
     * @param tenant The address of the tenant whose supported operators are being queried.
     * @param operator The address of the operator to check for support.
     * @return A boolean value indicating whether the operator is supported by the tenant.
     * @dev This function returns `true` if the operator is supported by the specified tenant, and `false` otherwise.
     *      It is a view function and does not modify the contract state.
     */
    function getOperatorSupport(address tenant, address operator) external view returns (bool);

    /**
     * @notice Retrieves the list of operators associated with a specific tenant.
     * @param tenant The address of the tenant whose operators are being queried.
     * @return A dynamically-sized array of addresses representing the operators associated with the tenant.
     * @dev This function is a view function and does not modify the contract state.
     */
    function getOperators(address tenant) external view returns (address[] memory);
}

contracts/interfaces/diamond/IDiamondCut.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;

interface IDiamondCut {
    enum FacetCutAction {
        Add,
        Replace,
        Remove
    }

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external;
}

contracts/interfaces/multisig/IProxyAdmin.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

interface IProxyAdmin {
    function upgrade(address proxy, address implementation) external;

    function upgradeAndCall(
        address proxy,
        address implementation,
        bytes calldata data
    ) external payable;

    function getProxyAdmin(address proxy) external view returns (address);

    function getProxyImplementation(address proxy) external view returns (address);
}

contracts/interfaces/multisig/ITransparentUpgradeableProxy.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

/**
 * @title ITransparentUpgradeableProxy
 * @dev Interface for transparent upgradeable proxy
 */
interface ITransparentUpgradeableProxy {
    function implementation() external view returns (address);

    function admin() external view returns (address);
}

contracts/interfaces/multisig/IUpgradeMultisig.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {EvaluatorRecord} from "contracts/interfaces/compiler/ILiquidityPoolsController.sol";
import {IDiamondCut} from "contracts/interfaces/diamond/IDiamondCut.sol";

/**
 * @title IUpgradeMultisig
 * @dev Interface for multisig contract managing smart contract upgrades
 * @notice Operators submit releases, approvers approve, then anyone executes after the timelock
 */
interface IUpgradeMultisig {
    // ============ Structs ============

    struct BeaconUpgrade {
        address beacon;
        address newImplementation;
    }

    struct ProxyUpgrade {
        address proxy;
        address newImplementation;
        bytes initData;
        uint256 value;
    }

    struct DiamondCut {
        address diamond;
        IDiamondCut.FacetCut[] cuts;
        address init;
        bytes initData;
    }

    struct EvaluatorUpdate {
        EvaluatorRecord[] records;
    }

    struct ReleaseData {
        BeaconUpgrade[] beaconUpgrades;
        ProxyUpgrade[] proxyUpgrades;
        DiamondCut[] diamondCuts;
        EvaluatorUpdate[] evaluatorUpdates;
    }

    enum ManagementRequestType {
        AddApprover,
        RemoveApprover,
        ChangeThreshold,
        AddOperator,
        RemoveOperator,
        ChangeTimelock,
        AddSecurityOfficer,
        RemoveSecurityOfficer,
        RenounceOwnership,
        TransferOwnership
    }

    enum Status {
        Pending,
        Executed,
        Rejected
    }

    struct ManagementRequest {
        bytes32 requestId;
        address targetApprover;
        uint80 nonce;
        uint8 newThreshold;
        ManagementRequestType requestType;
        uint128 newTimelockDuration;
        Status status;
        address targetOperator;
        address targetContract;
        address[] targetContracts;
        address newOwner;
        uint128 timelockDuration;
        uint256 timelockStart;
        mapping(address => bool) approvals;
        mapping(address => bool) rejections;
    }

    struct Release {
        address operator;
        uint80 nonce;
        Status status;
        uint128 timelockDuration;
        uint256 timelockStart;
        BeaconUpgrade[] beaconUpgrades;
        ProxyUpgrade[] proxyUpgrades;
        DiamondCut[] diamondCuts;
        EvaluatorUpdate[] evaluatorUpdates;
    }

    // ============ Events ============

    /**
     * @dev Emitted when a new release is submitted
     * @param releaseId The unique identifier for the release
     * @param operator The address of the operator who submitted the release
     * @param releaseHash The hash of the release data (keccak256(abi.encode(releaseData)))
     * @param beaconCount Number of beacon upgrades in the release
     * @param proxyCount Number of proxy upgrades in the release
     * @param diamondCount Number of diamond cuts in the release
     * @param evaluatorCount Number of evaluator updates in the release
     * @param timestamp Block timestamp when the release was submitted
     */
    event ReleaseSubmitted(
        bytes32 indexed releaseId,
        address indexed operator,
        bytes32 releaseHash,
        uint256 beaconCount,
        uint256 proxyCount,
        uint256 diamondCount,
        uint256 evaluatorCount,
        uint256 timestamp
    );

    /**
     * @dev Emitted when a release is approved by a signer
     * @param releaseId The unique identifier for the release
     * @param approver The address of the signer who approved
     * @param timestamp Block timestamp when the release was approved
     */
    event ReleaseApproved(bytes32 indexed releaseId, address indexed approver, uint256 timestamp);

    /**
     * @dev Emitted when a release is rejected by a signer
     * @param releaseId The unique identifier for the release
     * @param rejector The address of the signer who rejected
     * @param timestamp Block timestamp when the release was rejected
     */
    event ReleaseRejected(bytes32 indexed releaseId, address indexed rejector, uint256 timestamp);

    /**
     * @dev Emitted when a release is ready for execution (threshold approvals reached)
     * @param releaseId The unique identifier for the release
     * @param timestamp Block timestamp when the release became ready for execution
     */
    event ReleaseTimelockStarted(bytes32 indexed releaseId, uint256 timestamp);

    /**
     * @dev Emitted when a release is executed
     * @param releaseId The unique identifier for the release
     * @param executor The address of the executor
     * @param timestamp Block timestamp when the release was executed
     */
    event ReleaseExecuted(bytes32 indexed releaseId, address indexed executor, uint256 timestamp);

    event AddApproverRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed approver,
        uint256 timestamp
    );
    event RemoveApproverRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed approver,
        uint256 timestamp
    );
    event ChangeThresholdRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        uint8 newThreshold,
        uint256 timestamp
    );
    event AddOperatorRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed targetOperator,
        uint256 timestamp
    );
    event RemoveOperatorRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed targetOperator,
        uint256 timestamp
    );
    event ChangeTimelockRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        uint128 newTimelockDuration,
        uint256 timestamp
    );
    event ManagementRequestApproved(
        bytes32 indexed requestId,
        address indexed approver,
        uint256 timestamp
    );
    event ManagementRequestRejected(
        bytes32 indexed requestId,
        address indexed rejector,
        uint256 timestamp
    );
    /**
     * @dev Emitted when a management request rejection threshold is reached and the request is finalized as rejected
     * @param requestId The unique identifier for the management request
     * @param timestamp Block timestamp when the rejection threshold was reached
     */
    event ManagementRequestRejectionThresholdReached(bytes32 indexed requestId, uint256 timestamp);
    event ManagementRequestTimelockStarted(bytes32 indexed requestId, uint256 timestamp);
    event ManagementRequestExecuted(
        bytes32 indexed requestId,
        address indexed executor,
        uint256 timestamp
    );
    event ApproverAdded(bytes32 indexed requestId, address indexed approver);
    event ApproverRemoved(bytes32 indexed requestId, address indexed approver);
    event ThresholdChanged(bytes32 indexed requestId, uint8 oldThreshold, uint8 newThreshold);
    event OperatorAdded(bytes32 indexed requestId, address indexed operator);
    event OperatorRemoved(bytes32 indexed requestId, address indexed operator);
    event TimelockChanged(bytes32 indexed requestId, uint128 oldTimelock, uint128 newTimelock);
    event AddSecurityOfficerRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed securityOfficer,
        uint256 timestamp
    );
    event RemoveSecurityOfficerRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed securityOfficer,
        uint256 timestamp
    );
    event SecurityOfficerAdded(bytes32 indexed requestId, address indexed securityOfficer);
    event SecurityOfficerRemoved(bytes32 indexed requestId, address indexed securityOfficer);
    event RenounceOwnershipRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed targetContract,
        uint256 timestamp
    );
    event OwnershipRenounced(bytes32 indexed requestId, address indexed targetContract);
    event TransferOwnershipRequestSubmitted(
        bytes32 indexed requestId,
        address indexed operator,
        address indexed newOwner,
        address[] targetContracts,
        uint256 timestamp
    );
    event OwnershipTransferred(
        bytes32 indexed requestId,
        address indexed targetContract,
        address indexed newOwner
    );

    // ============ Errors ============

    /**
     * @dev Thrown when an unauthorized signer attempts to perform an action
     */
    error UnauthorizedSigner();

    /**
     * @dev Thrown when attempting to create a release that already exists
     */
    error ReleaseAlreadyExists();

    /**
     * @dev Thrown when attempting to perform an action on a non-existent release
     */
    error ReleaseDoesNotExist();

    /**
     * @dev Thrown when attempting to perform an action on an already executed release
     */
    error ReleaseAlreadyExecuted();

    /**
     * @dev Thrown when attempting to perform an action on a rejected release
     */
    error CannotApproveRejectedRelease();

    /**
     * @dev Thrown when attempting to reject a release that is already rejected
     */
    error ReleaseAlreadyRejected();

    /**
     * @dev Thrown when attempting to execute a rejected release
     */
    error CannotExecuteRejectedRelease();

    /**
     * @dev Thrown when attempting to approve a release that has already been approved
     */
    error AlreadyApproved();

    /**
     * @dev Thrown when attempting to perform an action that requires approval but hasn't been approved
     */
    error NotApproved();

    /**
     * @dev Thrown when an invalid address is provided (zero address or duplicate addresses)
     */
    error InvalidAddress();

    /**
     * @dev Thrown when initData is provided but is invalid:
     * - Shorter than 4 bytes (minimum function selector size)
     * - Not properly ABI-encoded (length % 32 != 4, i.e., must be 4 bytes selector + 32-byte aligned parameters)
     */
    error InvalidInitData();

    /**
     * @dev Thrown when a proxy is not an EIP-1967 proxy (implementation slot is zero)
     */
    error NotEip1967Proxy();

    /**
     * @dev Thrown when a proxy's admin doesn't match the expected proxyAdmin
     */
    error WrongAdmin();

    /**
     * @dev Thrown when attempting to submit an empty release
     */
    error EmptyRelease();

    error ManagementRequestAlreadyExists();
    error ManagementRequestDoesNotExist();
    error ManagementRequestAlreadyExecuted();
    error ManagementRequestAlreadyRejected();
    error CannotApproveRejectedManagementRequest();
    error CannotExecuteRejectedManagementRequest();
    error CannotRejectAfterApproving();
    error CannotApproveAfterRejecting();
    error CannotRenounceBelowThreshold();
    error InsufficientOperators();
    error InvalidThreshold();
    error ApproverAlreadyExists();
    error ApproverDoesNotExist();
    error ApproverCannotBeOperator();
    error CannotRenounceWhileManagementRequestPending();
    error InsufficientApprovers();
    error InsufficientApprovals();
    error InsufficientValue(uint256 required, uint256 provided);
    error OperatorAlreadyExists();
    error OperatorDoesNotExist();
    error RateLimit(address operator, uint256 lastProposed);
    error OperatorCannotBeApprover();
    error EmptyTargetContracts();
    error AddressesNotAscending(address previous, address current);
    error InvalidManagementRequestType();
    error SecurityOfficerAlreadyExists();
    error SecurityOfficerDoesNotExist();
    error CannotRemoveLastSecurityOfficer();
    error CannotRenounceLastSecurityOfficer();
    error InvalidReleaseHash();
    error TimelockNotPassed();

    /**
     * @dev Thrown when a target contract does not implement Ownable (no owner() function)
     * @param target The address that is not Ownable
     */
    error NotOwnable(address target);

    /**
     * @dev Thrown when the multisig is not the owner of the target contract
     * @param target The target contract address
     * @param expectedOwner The expected owner (multisig address)
     * @param actualOwner The actual owner of the contract
     */
    error NotOwner(address target, address expectedOwner, address actualOwner);

    /**
     * @dev Thrown when timelock duration would cause overflow or is invalid
     */
    error InvalidTimelockDuration();
    error ReleaseNotReady();
    error ManagementRequestNotReady();

    /**
     * @dev Thrown when attempting to execute a release out of order
     * @param expectedNonce The expected nonce for the next release
     * @param actualNonce The nonce of the release being executed
     */
    error ReleaseOutOfOrder(uint80 expectedNonce, uint80 actualNonce);

    /**
     * @dev Thrown when attempting to execute a management request out of order
     * @param expectedNonce The expected nonce for the next management request
     * @param actualNonce The nonce of the management request being executed
     */
    error ManagementRequestOutOfOrder(uint80 expectedNonce, uint80 actualNonce);

    /**
     * @dev Thrown when attempting to submit a release while a management request is pending
     */
    error ManagementRequestPending();

    /**
     * @dev Thrown when attempting to submit a management request while a release is pending
     */
    error ReleasePending();

    /**
     * @dev Thrown when a beacon upgrade fails during execution
     * @param index The index of the failed upgrade in the beaconUpgrades array
     * @param beacon The address of the beacon that failed to upgrade
     * @param reason The original error reason bytes
     */
    error BeaconUpgradeFailed(uint256 index, address beacon, bytes reason);

    /**
     * @dev Thrown when beacon upgrade validation fails after execution
     * @param index The index of the failed upgrade in the beaconUpgrades array
     * @param beacon The address of the beacon that failed validation
     * @param expectedImplementation The expected implementation address
     * @param actualImplementation The actual implementation address returned by beacon.implementation()
     */
    error BeaconUpgradeValidationFailed(
        uint256 index,
        address beacon,
        address expectedImplementation,
        address actualImplementation
    );

    /**
     * @dev Thrown when a proxy upgrade fails during execution
     * @param index The index of the failed upgrade in the proxyUpgrades array
     * @param proxy The address of the proxy that failed to upgrade
     * @param isUpgradeAndCall Whether this was an upgradeAndCall operation
     * @param reason The original error reason bytes
     */
    error ProxyUpgradeFailed(uint256 index, address proxy, bool isUpgradeAndCall, bytes reason);

    /**
     * @dev Thrown when proxy upgrade validation fails after execution
     * @param index The index of the failed upgrade in the proxyUpgrades array
     * @param proxy The address of the proxy that failed validation
     * @param isUpgradeAndCall Whether this was an upgradeAndCall operation
     * @param expectedImplementation The expected implementation address
     * @param actualImplementation The actual implementation address returned by proxy.implementation()
     */
    error ProxyUpgradeValidationFailed(
        uint256 index,
        address proxy,
        bool isUpgradeAndCall,
        address expectedImplementation,
        address actualImplementation
    );

    /**
     * @dev Thrown when a proxy admin slot validation fails after upgrade
     * @param index The index of the failed upgrade in the proxyUpgrades array
     * @param proxy The address of the proxy that failed validation
     * @param expectedAdmin The expected admin address (proxyAdmin)
     * @param actualAdmin The actual admin address after upgrade
     */
    error ProxyAdminValidationFailed(
        uint256 index,
        address proxy,
        address expectedAdmin,
        address actualAdmin
    );

    /**
     * @dev Thrown when a diamond cut fails during execution
     * @param index The index of the failed cut in the diamondCuts array
     * @param diamond The address of the diamond that failed to cut
     * @param reason The original error reason bytes
     */
    error DiamondCutFailed(uint256 index, address diamond, bytes reason);

    /**
     * @dev Thrown when an evaluator update fails during execution
     * @param index The index of the failed update in the evaluatorUpdates array
     * @param reason The original error reason bytes
     */
    error EvaluatorUpdateFailed(uint256 index, bytes reason);

    /**
     * @dev Thrown when diamond cut validation fails after execution
     * @param cutIndex The index of the failed cut in the diamondCuts array
     * @param diamond The address of the diamond that failed validation
     * @param facetCutIndex The index of the facet cut within the cuts array
     * @param selectorIndex The index of the selector within the functionSelectors array
     * @param selector The function selector that failed validation
     * @param action The FacetCutAction (Add/Replace/Remove)
     * @param expectedFacet The expected facet address
     * @param actualFacet The actual facet address returned by facetAddress(selector)
     */
    error DiamondCutValidationFailed(
        uint256 cutIndex,
        address diamond,
        uint256 facetCutIndex,
        uint256 selectorIndex,
        bytes4 selector,
        IDiamondCut.FacetCutAction action,
        address expectedFacet,
        address actualFacet
    );

    /**
     * @dev Thrown when a diamond doesn't support IDiamondLoupe interface
     */
    error InvalidDiamond();

    /**
     * @dev Thrown when FacetCutAction enum value is out of bounds
     */
    error InvalidFacetCutAction();

    /**
     * @dev Thrown when a selector appears multiple times in a diamond cut batch
     */
    error DuplicateSelector(bytes4 selector);

    /**
     * @dev Thrown when a selector is bytes4(0)
     */
    error InvalidSelector();

    /**
     * @dev Thrown when trying to add a selector that already exists
     */
    error SelectorAlreadyExists(bytes4 selector);

    /**
     * @dev Thrown when trying to replace/remove a selector that doesn't exist
     */
    error SelectorDoesNotExist(bytes4 selector);

    /**
     * @dev Thrown when trying to remove an immutable selector (implemented directly in diamond)
     */
    error SelectorImmutable(bytes4 selector);

    /**
     * @dev Thrown when init and initData are not coherent
     */
    error InvalidInitCoherence();

    // ============ Functions ============

    /**
     * @dev Submit a new release with upgrade operations
     * @param releaseData Struct containing all upgrade operations
     * @param releaseHash Hash of the release data for validation
     * @return releaseId The generated release ID
     */
    function submitRelease(
        ReleaseData calldata releaseData,
        bytes32 releaseHash
    ) external returns (bytes32 releaseId);

    /**
     * @dev Approve a release
     * @param releaseId The release ID to approve
     */
    function approveRelease(bytes32 releaseId) external;

    /**
     * @dev Execute an approved release after timelock period
     * @param releaseId The release ID to execute
     */
    function executeRelease(bytes32 releaseId) external payable;

    /**
     * @dev Reject a release (clears all approvals)
     * @param releaseId The release ID to reject
     */
    function rejectRelease(bytes32 releaseId) external;

    // ============ Management Functions ============

    /**
     * @dev Submit a management request (generic function for all request types)
     * @param requestType The type of management request to submit
     * @param requestData ABI-encoded request parameters:
     *   - AddApprover: abi.encode(address _approver)
     *   - RemoveApprover: abi.encode(address _approver)
     *   - ChangeThreshold: abi.encode(uint8 _newThreshold)
     *   - AddOperator: abi.encode(address _operator)
     *   - RemoveOperator: abi.encode(address _operator)
     *   - ChangeTimelock: abi.encode(uint128 _newTimelockDuration)
     *   - AddSecurityOfficer: abi.encode(address _securityOfficer)
     *   - RemoveSecurityOfficer: abi.encode(address _securityOfficer)
     *   - RenounceOwnership: abi.encode(address _targetContract)
     *   - TransferOwnership: abi.encode(address[] _targetContracts, address _newOwner), targets strictly ascending
     * @return requestId The unique identifier for the management request
     */
    function submitManagementRequest(
        ManagementRequestType requestType,
        bytes calldata requestData
    ) external returns (bytes32 requestId);

    /**
     * @dev Approve a management request
     * @param requestId The management request ID to approve
     */
    function approveManagementRequest(bytes32 requestId) external;

    /**
     * @dev Reject a management request
     * @param requestId The management request ID to reject
     */
    function rejectManagementRequest(bytes32 requestId) external;

    /**
     * @dev Execute an approved management request after timelock period
     * @param requestId The management request ID to execute
     */
    function executeManagementRequest(bytes32 requestId) external;

    // ============ View Functions ============

    /**
     * @dev Get the list of approvers
     * @return Array of approver addresses
     */
    function getApprovers() external view returns (address[] memory);

    /**
     * @dev Get management request information
     * @param requestId The management request ID
     * @return requestType The type of management request
     * @return targetApprover The target approver (for add/remove operations)
     * @return newThreshold The new threshold (for threshold change operations)
     * @return targetOperator The operator to add or remove (for operator operations)
     * @return newTimelockDuration The new timelock duration (for timelock change operations)
     * @return targetContract The target contract address (for renounce ownership operations)
     * @return newOwner The new owner (for transfer ownership operations)
     * @return status The status of the request (Pending, Executed, or Rejected)
     */
    function getManagementRequestInfo(
        bytes32 requestId
    )
        external
        view
        returns (
            ManagementRequestType requestType,
            address targetApprover,
            uint8 newThreshold,
            address targetOperator,
            uint128 newTimelockDuration,
            address targetContract,
            address newOwner,
            Status status
        );

    /**
     * @dev Get the target contracts of a transfer ownership request
     * @param requestId The management request ID
     * @return The contracts whose ownership the request transfers
     */
    function getManagementRequestTargetContracts(
        bytes32 requestId
    ) external view returns (address[] memory);

    /**
     * @dev Get management request approval and rejection status
     * @param requestId The management request ID
     * @param approver The approver address to check
     * @return approved Whether the approver has approved this management request
     * @return rejected Whether the approver has rejected this management request
     */
    function getManagementRequestApprovalStatus(
        bytes32 requestId,
        address approver
    ) external view returns (bool approved, bool rejected);
}

contracts/interfaces/pauser/IPauser.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;

import {
    IAccessControl
} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
/* solhint-disable-next-line no-unused-import */
import {IPausable} from "../base/pauser/IPausable.sol";

/**
 * @dev Interface for the Pauser contract, which manages the list of pausable contracts.
 * It provides functions for adding/removing contracts from the pausables list, as well as pausing and unpausing them.
 * The appropriate roles must be granted to perform these actions.
 */
interface IPauser is IAccessControl {
    /**
     * @notice Emitted when a contract fails to pause during the operation.
     * @param target The address of the contract that failed to pause.
     * @param reason The reason why the contract could not be paused.
     * @dev Emitted when a target's pause function call fails, either due to a revert or other issues.
     */
    event FailedToPause(address target, bytes reason);

    /**
     * @notice Emitted when a contract fails to unpause during the operation.
     * @param target The address of the contract that failed to unpause.
     * @param reason The reason why the contract could not be unpaused.
     * @dev Emitted when a target's unpause function call fails, either due to a revert or other issues.
     */
    event FailedToUnpause(address target, bytes reason);

    /**
     * @notice Emitted when a contract is successfully added to the list of pausables.
     * @param pausable The address of the contract that was added to the pausables list.
     */
    event PausableAdded(address pausable);

    /**
     * @notice Emitted when a contract is successfully removed from the list of pausables.
     * @param pausable The address of the contract that was removed from the pausables list.
     */
    event PausableRemoved(address pausable);

    /**
     * @notice Error thrown when the contract does not have the required Pauser role, or if the role check fails.
     * @param pausable The address of the contract missing the Pauser role or causing the role check failure.
     * @dev Thrown when the role check fails, such as when `hasRole()` is unavailable or the address is not a contract.
     */
    error MissingPauserRole(address pausable);

    /**
     * @notice Registers new pausable contracts
     * @param pausablesAdd Array of contract addresses implementing IPausable
     * @dev Requires ARKIS_SECURITY_OFFICER_ROLE
     * @dev Verifies each contract implements PAUSER_ROLE for this contract
     */
    function add(address[] calldata pausablesAdd) external;

    /**
     * @notice Removes multiple contracts from the list of pausables.
     * @param pausablesRemove An array of addresses of contracts to remove from the pausables list.
     * @dev Requires the caller to have the `DEFAULT_ADMIN_ROLE`.
     * @dev Reverts if no contracts are removed.
     *      Emits `PausableRemoved` for each contract removed successfully.
     */
    function remove(address[] calldata pausablesRemove) external;

    /**
     * @notice Pauses all contracts in the list of pausables.
     * @dev Requires the caller to have the `ARKIS_ALERT_OPERATOR_ROLE`.
     *      Emits `FailedToPause` for each contract that fails to pause.
     */
    function pauseAll() external;

    /**
     * @notice Unpauses all contracts in the list of pausables.
     * @dev Requires the caller to have the `ARKIS_SECURITY_OFFICER_ROLE`.
     *      Emits `FailedToUnpause` for each contract that fails to unpause.
     */
    function unpauseAll() external;

    /**
     * @notice Pauses every pausable that is not already paused.
     * @dev Requires the caller to have the `MULTISIG_ROLE`.
     * Reverts if any pausable fails to pause.
     */
    function multiSignaturePauseAll() external;

    /**
     * @notice Unpauses every pausable that is currently paused.
     * @dev Requires the caller to have the `MULTISIG_ROLE`.
     * Reverts if any pausable fails to unpause.
     */
    function multiSignatureUnpauseAll() external;

    /**
     * @notice Returns a list of all pausable contracts.
     * @return pausableList An array of addresses of all the pausables.
     */
    function pausables() external view returns (address[] memory pausableList);

    /* solhint-disable func-name-mixedcase */
    /**
     * @notice Returns role identifier for deployment operators
     * @return bytes32 keccak256 hash of ARKIS_DEPLOYMENT_OPERATOR_ROLE
     */
    function ARKIS_DEPLOYMENT_OPERATOR_ROLE() external view returns (bytes32);

    /**
     * @notice Returns role identifier for pause operators
     * @return bytes32 keccak256 hash of ARKIS_ALERT_OPERATOR_ROLE
     */
    function ARKIS_ALERT_OPERATOR_ROLE() external view returns (bytes32);

    /**
     * @notice Returns role identifier for unpause operators
     * @return bytes32 keccak256 hash of ARKIS_SECURITY_OFFICER_ROLE
     */
    function ARKIS_SECURITY_OFFICER_ROLE() external view returns (bytes32);
    /* solhint-enable func-name-mixedcase */
}

contracts/multisig/libraries/ApprovalLibrary.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {
    AccessControlEnumerable
} from "@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol";
import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";

/**
 * @title ApprovalLibrary
 * @notice Library for managing approvals and counting approvals for releases and management requests
 */
library ApprovalLibrary {
    bytes32 public constant UPGRADE_APPROVAL_OFFICER_ROLE =
        keccak256("Upgrade Approval Officer Role");

    /**
     * @notice Process management request approval
     * @param request The management request
     * @param approver The approver address
     * @param threshold The approval threshold
     * @param pendingManagementRequestId The current pending management request ID
     * @param requestId The request ID
     * @param accessControl The AccessControlEnumerable contract
     * @param timelockDuration The timelock duration to apply
     * @param lastExecutedNonce The last executed nonce for ordering validation
     * @return newPendingRequestId The new pending management request ID
     */
    function processManagementRequestApproval(
        IUpgradeMultisig.ManagementRequest storage request,
        address approver,
        uint8 threshold,
        bytes32 pendingManagementRequestId,
        bytes32 requestId,
        AccessControlEnumerable accessControl,
        uint128 timelockDuration,
        uint80 lastExecutedNonce
    ) external returns (bytes32 newPendingRequestId) {
        if (request.approvals[approver]) {
            revert IUpgradeMultisig.AlreadyApproved();
        }

        if (request.rejections[approver]) {
            revert IUpgradeMultisig.CannotApproveAfterRejecting();
        }

        request.approvals[approver] = true;
        emit IUpgradeMultisig.ManagementRequestApproved(requestId, approver, block.timestamp);

        uint256 approvalCount = 0;
        uint256 approverCount = accessControl.getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE);
        for (uint256 i = 0; i < approverCount; i++) {
            address approverAddr = accessControl.getRoleMember(UPGRADE_APPROVAL_OFFICER_ROLE, i);
            if (request.approvals[approverAddr]) {
                approvalCount++;
            }
        }

        if (approvalCount >= threshold && request.status != IUpgradeMultisig.Status.Rejected) {
            // NOTE: timelockStart is set exactly once and never cleared. If approvals later drop
            // below threshold (e.g., via rejection which silently withdraws a prior approval) and
            // then rise again, the original timelock deadline persists. This is intentional behavior
            // but means the Security Officer's review window may be shorter than timelockDuration
            // if approvals are withdrawn and later refilled. Monitor for approvers who reject after
            // previously approving, as this pattern could compress the SO's reaction window.
            if (request.timelockStart == 0) {
                // solhint-disable-next-line no-empty-blocks
                if (lastExecutedNonce == 0 && request.nonce == 0) {
                    // First execution - allow nonce 0
                } else if (request.nonce != lastExecutedNonce + 1) {
                    revert IUpgradeMultisig.ManagementRequestOutOfOrder(
                        lastExecutedNonce + 1,
                        request.nonce
                    );
                }

                request.timelockStart = block.timestamp;
                request.timelockDuration = timelockDuration;
                emit IUpgradeMultisig.ManagementRequestTimelockStarted(requestId, block.timestamp);
            }
        }
        newPendingRequestId = pendingManagementRequestId;
    }

    /**
     * @notice Process management request rejection
     * @param request The management request
     * @param rejector The rejector address
     * @param threshold The approval threshold
     * @param pendingManagementRequestId The current pending management request ID
     * @param requestId The request ID
     * @param accessControl The AccessControlEnumerable contract
     * @return wasRejected Whether the request was rejected (threshold reached)
     * @return newPendingRequestId The new pending management request ID (bytes32(0) if rejected)
     * @return rejectedNonce The nonce of the rejected request (to advance lastExecutedNonce)
     */
    function processManagementRequestRejection(
        IUpgradeMultisig.ManagementRequest storage request,
        address rejector,
        uint8 threshold,
        bytes32 pendingManagementRequestId,
        bytes32 requestId,
        AccessControlEnumerable accessControl
    ) external returns (bool wasRejected, bytes32 newPendingRequestId, uint80 rejectedNonce) {
        if (request.rejections[rejector]) {
            revert IUpgradeMultisig.ManagementRequestAlreadyRejected();
        }

        // NOTE: Rejection silently withdraws any prior approval from this rejector. This can drop
        // the approval count below threshold without resetting timelockStart (see note above).
        // This behavior is to be monitored as it can compress the Security Officer's review window.
        if (request.approvals[rejector]) {
            request.approvals[rejector] = false;
        }

        request.rejections[rejector] = true;
        emit IUpgradeMultisig.ManagementRequestRejected(requestId, rejector, block.timestamp);

        uint256 rejectionCount = 0;
        uint256 approverCount = accessControl.getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE);
        for (uint256 i = 0; i < approverCount; i++) {
            address approverAddr = accessControl.getRoleMember(UPGRADE_APPROVAL_OFFICER_ROLE, i);
            if (request.rejections[approverAddr]) {
                rejectionCount++;
            }
        }

        if (rejectionCount >= threshold) {
            request.status = IUpgradeMultisig.Status.Rejected;
            emit IUpgradeMultisig.ManagementRequestRejectionThresholdReached(
                requestId,
                block.timestamp
            );
            rejectedNonce = request.nonce;
            if (pendingManagementRequestId == requestId) {
                newPendingRequestId = bytes32(0);
            } else {
                newPendingRequestId = pendingManagementRequestId;
            }
            wasRejected = true;
        } else {
            newPendingRequestId = pendingManagementRequestId;
        }
    }

    /**
     * @notice Get the approval count for a release
     * @param releaseApprovals Mapping of release approvals
     * @param releaseId The release ID
     * @param accessControl The AccessControlEnumerable contract to query role members
     * @return approvalCount The number of approvals
     */
    function getReleaseApprovalCount(
        mapping(bytes32 => mapping(address => bool)) storage releaseApprovals,
        bytes32 releaseId,
        AccessControlEnumerable accessControl
    ) external view returns (uint256 approvalCount) {
        approvalCount = 0;
        uint256 approverCount = accessControl.getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE);
        for (uint256 i = 0; i < approverCount; i++) {
            address approver = accessControl.getRoleMember(UPGRADE_APPROVAL_OFFICER_ROLE, i);
            if (releaseApprovals[releaseId][approver]) {
                approvalCount++;
            }
        }
    }

    /**
     * @notice Get approval and rejection counts for a management request
     * @param request The management request
     * @param accessControl The AccessControlEnumerable contract to query role members
     * @return approvalCount The number of approvals
     * @return rejectionCount The number of rejections
     */
    function getManagementRequestCounts(
        IUpgradeMultisig.ManagementRequest storage request,
        AccessControlEnumerable accessControl
    ) external view returns (uint256 approvalCount, uint256 rejectionCount) {
        approvalCount = 0;
        rejectionCount = 0;
        uint256 approverCount = accessControl.getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE);

        for (uint256 i = 0; i < approverCount; i++) {
            address approver = accessControl.getRoleMember(UPGRADE_APPROVAL_OFFICER_ROLE, i);
            if (request.approvals[approver]) {
                approvalCount++;
            }
            if (request.rejections[approver]) {
                rejectionCount++;
            }
        }
    }
}

contracts/multisig/libraries/ConstructorValidationLibrary.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";

/**
 * @title ConstructorValidationLibrary
 * @notice Library for validating constructor parameters to reduce contract size
 */
library ConstructorValidationLibrary {
    uint128 public constant MIN_TIMELOCK_DURATION = 1 hours;
    uint128 public constant MAX_TIMELOCK_DURATION = 30 days;
    uint256 public constant MIN_OPERATORS = 2;

    /**
     * @notice Validate all constructor parameters
     * @param _operators Array of initial operator addresses, strictly ascending
     * @param _pauser The pauser address
     * @param _proxyAdmin The proxy admin address
     * @param _compiler The compiler address
     * @param _initialApprovers Array of initial approver addresses, strictly ascending
     * @param _initialSecurityOfficer The initial security officer address
     * @param _threshold The approval threshold
     * @param _timelockDuration The initial timelock duration
     */
    function validateConstructorParams(
        address[] calldata _operators,
        address _pauser,
        address _proxyAdmin,
        address _compiler,
        address[] calldata _initialApprovers,
        address _initialSecurityOfficer,
        uint8 _threshold,
        uint128 _timelockDuration
    ) external pure {
        if (
            _pauser == address(0) ||
            _proxyAdmin == address(0) ||
            _initialSecurityOfficer == address(0) ||
            _compiler == address(0)
        ) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        if (_initialApprovers.length == 0) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        if (_operators.length < MIN_OPERATORS) {
            revert IUpgradeMultisig.InsufficientOperators();
        }

        for (uint256 i = 0; i < _operators.length; i++) {
            if (_operators[i] == address(0)) {
                revert IUpgradeMultisig.InvalidAddress();
            }
            if (i > 0 && _operators[i] <= _operators[i - 1]) {
                revert IUpgradeMultisig.AddressesNotAscending(_operators[i - 1], _operators[i]);
            }
        }

        for (uint256 i = 0; i < _initialApprovers.length; i++) {
            if (_initialApprovers[i] == address(0)) {
                revert IUpgradeMultisig.InvalidAddress();
            }
            for (uint256 j = 0; j < _operators.length; j++) {
                if (_initialApprovers[i] == _operators[j]) {
                    revert IUpgradeMultisig.OperatorCannotBeApprover();
                }
            }
            if (i > 0 && _initialApprovers[i] <= _initialApprovers[i - 1]) {
                revert IUpgradeMultisig.AddressesNotAscending(
                    _initialApprovers[i - 1],
                    _initialApprovers[i]
                );
            }
        }

        if (_threshold == 0 || _threshold > _initialApprovers.length) {
            revert IUpgradeMultisig.InvalidThreshold();
        }

        if (
            _timelockDuration < MIN_TIMELOCK_DURATION || _timelockDuration > MAX_TIMELOCK_DURATION
        ) {
            revert IUpgradeMultisig.InvalidTimelockDuration();
        }
    }
}

contracts/multisig/libraries/ManagementRequestLibrary.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {
    AccessControlEnumerable
} from "@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";

/**
 * @title ManagementRequestLibrary
 * @notice Library for submitting, validating, and executing management requests
 */
library ManagementRequestLibrary {
    struct RequestSubmissionResult {
        bytes32 requestId;
        uint80 newNonce;
        bytes32 newPendingRequestId;
    }

    struct ExecutionResult {
        uint80 newLastExecutedNonce;
        bytes32 newPendingRequestId;
        uint8 newThreshold;
        uint128 newTimelockDuration;
    }

    bytes32 public constant UPGRADE_PROPOSAL_OFFICER_ROLE =
        keccak256("Upgrade Proposal Officer Role");
    bytes32 public constant UPGRADE_APPROVAL_OFFICER_ROLE =
        keccak256("Upgrade Approval Officer Role");
    bytes32 public constant ARKIS_SECURITY_OFFICER_ROLE = keccak256("Arkis Security Officer Role");
    uint128 public constant MIN_TIMELOCK_DURATION = 1 hours;
    uint128 public constant MAX_TIMELOCK_DURATION = 30 days;
    uint256 public constant MIN_OPERATORS = 2;

    /**
     * @notice Execute a management request
     */
    function execute(
        IUpgradeMultisig.ManagementRequest storage request,
        bytes32 pendingManagementRequestId,
        uint80 lastExecutedNonce,
        uint8 threshold,
        uint128 timelockDuration
    ) external returns (ExecutionResult memory result) {
        if (request.status == IUpgradeMultisig.Status.Rejected) {
            revert IUpgradeMultisig.CannotExecuteRejectedManagementRequest();
        }

        // Nonce ordering is enforced again at execution time.
        // Allow the special case of the first execution where both nonces are 0.
        // However, we keep a safety check for the first execution case
        // solhint-disable-next-line no-empty-blocks
        if (lastExecutedNonce == 0 && request.nonce == 0) {
            // First execution - allow nonce 0
        } else if (request.nonce != lastExecutedNonce + 1) {
            revert IUpgradeMultisig.ManagementRequestOutOfOrder(
                lastExecutedNonce + 1,
                request.nonce
            );
        }

        request.status = IUpgradeMultisig.Status.Executed;
        result.newLastExecutedNonce = request.nonce;
        if (pendingManagementRequestId == request.requestId) {
            result.newPendingRequestId = bytes32(0);
        } else {
            result.newPendingRequestId = pendingManagementRequestId;
        }
        result.newThreshold = threshold;
        result.newTimelockDuration = timelockDuration;
    }

    /**
     * @notice Emit the appropriate event for a management request submission
     */
    function emitRequestSubmitted(
        IUpgradeMultisig.ManagementRequestType requestType,
        bytes32 requestId,
        bytes calldata requestData,
        address submitter
    ) external {
        if (requestType == IUpgradeMultisig.ManagementRequestType.AddApprover) {
            address _approver = abi.decode(requestData, (address));
            emit IUpgradeMultisig.AddApproverRequestSubmitted(
                requestId,
                submitter,
                _approver,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveApprover) {
            address _approver = abi.decode(requestData, (address));
            emit IUpgradeMultisig.RemoveApproverRequestSubmitted(
                requestId,
                submitter,
                _approver,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.ChangeThreshold) {
            uint8 _newThreshold = abi.decode(requestData, (uint8));
            emit IUpgradeMultisig.ChangeThresholdRequestSubmitted(
                requestId,
                submitter,
                _newThreshold,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.AddOperator) {
            address _operator = abi.decode(requestData, (address));
            emit IUpgradeMultisig.AddOperatorRequestSubmitted(
                requestId,
                submitter,
                _operator,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveOperator) {
            address _operator = abi.decode(requestData, (address));
            emit IUpgradeMultisig.RemoveOperatorRequestSubmitted(
                requestId,
                submitter,
                _operator,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.ChangeTimelock) {
            uint128 _newTimelockDuration = abi.decode(requestData, (uint128));
            emit IUpgradeMultisig.ChangeTimelockRequestSubmitted(
                requestId,
                submitter,
                _newTimelockDuration,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.AddSecurityOfficer) {
            address _securityOfficer = abi.decode(requestData, (address));
            emit IUpgradeMultisig.AddSecurityOfficerRequestSubmitted(
                requestId,
                submitter,
                _securityOfficer,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveSecurityOfficer) {
            address _securityOfficer = abi.decode(requestData, (address));
            emit IUpgradeMultisig.RemoveSecurityOfficerRequestSubmitted(
                requestId,
                submitter,
                _securityOfficer,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RenounceOwnership) {
            address _targetContract = abi.decode(requestData, (address));
            emit IUpgradeMultisig.RenounceOwnershipRequestSubmitted(
                requestId,
                submitter,
                _targetContract,
                block.timestamp
            );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.TransferOwnership) {
            (address[] memory _targetContracts, address _newOwner) = abi.decode(
                requestData,
                (address[], address)
            );
            emit IUpgradeMultisig.TransferOwnershipRequestSubmitted(
                requestId,
                submitter,
                _newOwner,
                _targetContracts,
                block.timestamp
            );
        }
    }

    /**
     * @notice Generic function to submit any type of management request
     * @dev Routes to the appropriate specific function based on requestType
     */
    function submitManagementRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        uint8 threshold,
        IUpgradeMultisig.ManagementRequestType requestType,
        bytes calldata requestData,
        address multisigAddress,
        AccessControlEnumerable accessControl
    ) external returns (RequestSubmissionResult memory result) {
        if (requestType == IUpgradeMultisig.ManagementRequestType.AddApprover) {
            address _approver = abi.decode(requestData, (address));
            return submitAddApproverRequest(managementRequests, nonce, _approver, multisigAddress);
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveApprover) {
            address _approver = abi.decode(requestData, (address));
            return
                submitRemoveApproverRequest(
                    managementRequests,
                    nonce,
                    threshold,
                    _approver,
                    multisigAddress,
                    accessControl
                );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.ChangeThreshold) {
            uint8 _newThreshold = abi.decode(requestData, (uint8));
            return
                submitChangeThresholdRequest(
                    managementRequests,
                    nonce,
                    _newThreshold,
                    multisigAddress,
                    accessControl
                );
        } else if (
            requestType == IUpgradeMultisig.ManagementRequestType.AddOperator ||
            requestType == IUpgradeMultisig.ManagementRequestType.RemoveOperator
        ) {
            address _operator = abi.decode(requestData, (address));
            return
                submitOperatorRequest(
                    managementRequests,
                    nonce,
                    requestType,
                    _operator,
                    multisigAddress,
                    accessControl
                );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.ChangeTimelock) {
            uint128 _newTimelockDuration = abi.decode(requestData, (uint128));
            return
                submitChangeTimelockRequest(
                    managementRequests,
                    nonce,
                    _newTimelockDuration,
                    multisigAddress
                );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.AddSecurityOfficer) {
            address _securityOfficer = abi.decode(requestData, (address));
            return
                submitAddSecurityOfficerRequest(
                    managementRequests,
                    nonce,
                    _securityOfficer,
                    multisigAddress
                );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveSecurityOfficer) {
            address _securityOfficer = abi.decode(requestData, (address));
            return
                submitRemoveSecurityOfficerRequest(
                    managementRequests,
                    nonce,
                    _securityOfficer,
                    multisigAddress,
                    accessControl
                );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RenounceOwnership) {
            address _targetContract = abi.decode(requestData, (address));
            return
                submitRenounceOwnershipRequest(
                    managementRequests,
                    nonce,
                    _targetContract,
                    multisigAddress
                );
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.TransferOwnership) {
            (address[] memory _targetContracts, address _newOwner) = abi.decode(
                requestData,
                (address[], address)
            );
            return
                submitTransferOwnershipRequest(
                    managementRequests,
                    nonce,
                    _targetContracts,
                    _newOwner,
                    multisigAddress
                );
        } else {
            revert IUpgradeMultisig.InvalidManagementRequestType();
        }
    }

    /**
     * @notice Validate management request based on type
     */
    function validateRequest(
        IUpgradeMultisig.ManagementRequestType requestType,
        bytes calldata requestData,
        AccessControlEnumerable accessControl
    ) external view {
        if (requestType == IUpgradeMultisig.ManagementRequestType.AddApprover) {
            address _approver = abi.decode(requestData, (address));
            if (accessControl.hasRole(UPGRADE_APPROVAL_OFFICER_ROLE, _approver)) {
                revert IUpgradeMultisig.ApproverAlreadyExists();
            }
            if (accessControl.hasRole(UPGRADE_PROPOSAL_OFFICER_ROLE, _approver)) {
                revert IUpgradeMultisig.OperatorCannotBeApprover();
            }
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveApprover) {
            address _approver = abi.decode(requestData, (address));
            if (!accessControl.hasRole(UPGRADE_APPROVAL_OFFICER_ROLE, _approver)) {
                revert IUpgradeMultisig.ApproverDoesNotExist();
            }
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.AddOperator) {
            address _operator = abi.decode(requestData, (address));
            if (accessControl.hasRole(UPGRADE_PROPOSAL_OFFICER_ROLE, _operator)) {
                revert IUpgradeMultisig.OperatorAlreadyExists();
            }
            if (accessControl.hasRole(UPGRADE_APPROVAL_OFFICER_ROLE, _operator)) {
                revert IUpgradeMultisig.ApproverCannotBeOperator();
            }
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveOperator) {
            address _operator = abi.decode(requestData, (address));
            if (!accessControl.hasRole(UPGRADE_PROPOSAL_OFFICER_ROLE, _operator)) {
                revert IUpgradeMultisig.OperatorDoesNotExist();
            }
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.AddSecurityOfficer) {
            address _securityOfficer = abi.decode(requestData, (address));
            if (_securityOfficer == address(accessControl)) {
                revert IUpgradeMultisig.InvalidAddress();
            }
            if (accessControl.hasRole(ARKIS_SECURITY_OFFICER_ROLE, _securityOfficer)) {
                revert IUpgradeMultisig.SecurityOfficerAlreadyExists();
            }
        } else if (requestType == IUpgradeMultisig.ManagementRequestType.RemoveSecurityOfficer) {
            address _securityOfficer = abi.decode(requestData, (address));
            if (!accessControl.hasRole(ARKIS_SECURITY_OFFICER_ROLE, _securityOfficer)) {
                revert IUpgradeMultisig.SecurityOfficerDoesNotExist();
            }
        }
    }

    /**
     * @notice Validate that a management request exists and can be approved
     */
    function validateForApproval(IUpgradeMultisig.ManagementRequest storage request) external view {
        if (request.requestId == bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestDoesNotExist();
        }
        if (request.status == IUpgradeMultisig.Status.Executed) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExecuted();
        }
        if (request.status == IUpgradeMultisig.Status.Rejected) {
            revert IUpgradeMultisig.CannotApproveRejectedManagementRequest();
        }
    }

    /**
     * @notice Validate that a management request exists and can be rejected
     */
    function validateForRejection(
        IUpgradeMultisig.ManagementRequest storage request
    ) external view {
        if (request.requestId == bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestDoesNotExist();
        }
        if (request.status == IUpgradeMultisig.Status.Executed) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExecuted();
        }
        if (request.status == IUpgradeMultisig.Status.Rejected) {
            revert IUpgradeMultisig.ManagementRequestAlreadyRejected();
        }
    }

    /**
     * @notice Validate that a management request can be executed (timelock must have passed)
     * @param request The management request to validate
     * @param threshold The current approval threshold
     * @param approvalCount The current number of approvals for the request
     */
    function validateExecution(
        IUpgradeMultisig.ManagementRequest storage request,
        uint8 threshold,
        uint256 approvalCount
    ) external view {
        if (request.requestId == bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestDoesNotExist();
        }

        if (request.status == IUpgradeMultisig.Status.Executed) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExecuted();
        } else if (request.status == IUpgradeMultisig.Status.Rejected) {
            revert IUpgradeMultisig.CannotExecuteRejectedManagementRequest();
        }

        if (approvalCount < threshold) {
            revert IUpgradeMultisig.InsufficientApprovals();
        }

        if (request.timelockStart == 0) {
            revert IUpgradeMultisig.ManagementRequestNotReady();
        }

        uint256 timelockEnd = request.timelockStart + request.timelockDuration;
        if (block.timestamp < timelockEnd) {
            revert IUpgradeMultisig.TimelockNotPassed();
        }
    }

    /**
     * @notice Submit an add approver request
     * @dev Internal function called by submitManagementRequest
     */
    function submitAddApproverRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        address _approver,
        address multisigAddress
    ) internal returns (RequestSubmissionResult memory result) {
        if (_approver == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.AddApprover,
                _approver
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.AddApprover;
        request.nonce = nonce;
        request.targetApprover = _approver;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit a remove approver request
     * @dev Internal function called by submitManagementRequest
     */
    function submitRemoveApproverRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        uint8 threshold,
        address _approver,
        address multisigAddress,
        AccessControlEnumerable accessControl
    ) internal returns (RequestSubmissionResult memory result) {
        if (_approver == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        if (accessControl.getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE) - 1 < threshold) {
            revert IUpgradeMultisig.InsufficientApprovers();
        }

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.RemoveApprover,
                _approver
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.RemoveApprover;
        request.nonce = nonce;
        request.targetApprover = _approver;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit a change threshold request
     * @dev Internal function called by submitManagementRequest
     */
    function submitChangeThresholdRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        uint8 _newThreshold,
        address multisigAddress,
        AccessControlEnumerable accessControl
    ) internal returns (RequestSubmissionResult memory result) {
        if (_newThreshold == 0) {
            revert IUpgradeMultisig.InvalidThreshold();
        }
        if (_newThreshold > accessControl.getRoleMemberCount(UPGRADE_APPROVAL_OFFICER_ROLE)) {
            revert IUpgradeMultisig.InsufficientApprovers();
        }

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.ChangeThreshold,
                _newThreshold
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.ChangeThreshold;
        request.nonce = nonce;
        request.newThreshold = _newThreshold;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit an add or remove operator request
     * @dev Internal function called by submitManagementRequest
     * @dev A removal must leave at least MIN_OPERATORS, so a lost key can always be replaced by another
     *      operator: add the replacement first, then remove
     */
    function submitOperatorRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        IUpgradeMultisig.ManagementRequestType requestType,
        address _operator,
        address multisigAddress,
        AccessControlEnumerable accessControl
    ) internal returns (RequestSubmissionResult memory result) {
        if (_operator == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        if (
            requestType == IUpgradeMultisig.ManagementRequestType.RemoveOperator &&
            accessControl.getRoleMemberCount(UPGRADE_PROPOSAL_OFFICER_ROLE) <= MIN_OPERATORS
        ) {
            revert IUpgradeMultisig.InsufficientOperators();
        }

        result.requestId = keccak256(abi.encode(multisigAddress, nonce, requestType, _operator));

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = requestType;
        request.nonce = nonce;
        request.targetOperator = _operator;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit a change timelock request
     * @dev Internal function called by submitManagementRequest
     */
    function submitChangeTimelockRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        uint128 _newTimelockDuration,
        address multisigAddress
    ) internal returns (RequestSubmissionResult memory result) {
        if (
            _newTimelockDuration < MIN_TIMELOCK_DURATION ||
            _newTimelockDuration > MAX_TIMELOCK_DURATION
        ) {
            revert IUpgradeMultisig.InvalidTimelockDuration();
        }

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.ChangeTimelock,
                _newTimelockDuration
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.ChangeTimelock;
        request.nonce = nonce;
        request.newTimelockDuration = _newTimelockDuration;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit an add security officer request
     * @dev Internal function called by submitManagementRequest
     */
    function submitAddSecurityOfficerRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        address _securityOfficer,
        address multisigAddress
    ) internal returns (RequestSubmissionResult memory result) {
        if (_securityOfficer == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.AddSecurityOfficer,
                _securityOfficer
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.AddSecurityOfficer;
        request.nonce = nonce;
        request.targetApprover = _securityOfficer;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit a remove security officer request
     * @dev Internal function called by submitManagementRequest
     * @dev Prevents removing the last security officer to maintain emergency rejection capability
     */
    function submitRemoveSecurityOfficerRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        address _securityOfficer,
        address multisigAddress,
        AccessControlEnumerable accessControl
    ) internal returns (RequestSubmissionResult memory result) {
        if (_securityOfficer == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        // Prevent removing the last security officer
        // Security officers are required to reject timelocked releases
        if (accessControl.getRoleMemberCount(ARKIS_SECURITY_OFFICER_ROLE) <= 1) {
            revert IUpgradeMultisig.CannotRemoveLastSecurityOfficer();
        }

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.RemoveSecurityOfficer,
                _securityOfficer
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.RemoveSecurityOfficer;
        request.nonce = nonce;
        request.targetApprover = _securityOfficer;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit a renounce ownership request
     * @dev Internal function called by submitManagementRequest
     */
    function submitRenounceOwnershipRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        address _targetContract,
        address multisigAddress
    ) internal returns (RequestSubmissionResult memory result) {
        if (_targetContract == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        _validateOwnableTarget(_targetContract, multisigAddress);

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.RenounceOwnership,
                _targetContract
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.RenounceOwnership;
        request.nonce = nonce;
        request.targetContract = _targetContract;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Submit a transfer ownership request
     * @dev Internal function called by submitManagementRequest
     * @dev Targets must be strictly ascending, which also rules out duplicates.
     *      Every target must be owned by the multisig at submission. Only one request can be pending.
     */
    function submitTransferOwnershipRequest(
        mapping(bytes32 => IUpgradeMultisig.ManagementRequest) storage managementRequests,
        uint80 nonce,
        address[] memory _targetContracts,
        address _newOwner,
        address multisigAddress
    ) internal returns (RequestSubmissionResult memory result) {
        if (_targetContracts.length == 0) {
            revert IUpgradeMultisig.EmptyTargetContracts();
        }
        if (_newOwner == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }

        for (uint256 i = 0; i < _targetContracts.length; i++) {
            if (_targetContracts[i] == address(0)) {
                revert IUpgradeMultisig.InvalidAddress();
            }
            if (i > 0 && _targetContracts[i] <= _targetContracts[i - 1]) {
                revert IUpgradeMultisig.AddressesNotAscending(
                    _targetContracts[i - 1],
                    _targetContracts[i]
                );
            }
            _validateOwnableTarget(_targetContracts[i], multisigAddress);
        }

        result.requestId = keccak256(
            abi.encode(
                multisigAddress,
                nonce,
                IUpgradeMultisig.ManagementRequestType.TransferOwnership,
                _targetContracts,
                _newOwner
            )
        );

        if (managementRequests[result.requestId].requestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestAlreadyExists();
        }

        IUpgradeMultisig.ManagementRequest storage request = managementRequests[result.requestId];
        request.requestId = result.requestId;
        request.requestType = IUpgradeMultisig.ManagementRequestType.TransferOwnership;
        request.nonce = nonce;
        request.targetContracts = _targetContracts;
        request.newOwner = _newOwner;
        request.status = IUpgradeMultisig.Status.Pending;
        result.newPendingRequestId = result.requestId;
        result.newNonce = nonce + 1;
    }

    /**
     * @notice Validates that a target contract is Ownable and owned by the multisig
     * @dev Prevents stuck requests by validating upfront that:
     *      1. Target is a contract (not EOA)
     *      2. Target implements Ownable (has owner() function)
     *      3. Multisig is the current owner
     * @param _targetContract The contract to validate
     * @param multisigAddress The multisig address that should be the owner
     */
    function _validateOwnableTarget(address _targetContract, address multisigAddress) private view {
        if (_targetContract.code.length == 0) {
            revert IUpgradeMultisig.NotOwnable(_targetContract);
        }
        try Ownable(_targetContract).owner() returns (address currentOwner) {
            if (currentOwner != multisigAddress) {
                revert IUpgradeMultisig.NotOwner(_targetContract, multisigAddress, currentOwner);
            }
        } catch {
            revert IUpgradeMultisig.NotOwnable(_targetContract);
        }
    }
}

contracts/multisig/libraries/ReleaseExecutor.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {AlreadyUpToDate} from "contracts/interfaces/base/CommonErrors.sol";
import {IBeacon} from "contracts/interfaces/base/proxy/IBeacon.sol";
import {
    ILiquidityPoolsController
} from "contracts/interfaces/compiler/ILiquidityPoolsController.sol";
import {IDiamondCut} from "contracts/interfaces/diamond/IDiamondCut.sol";
import {IProxyAdmin} from "contracts/interfaces/multisig/IProxyAdmin.sol";
import {
    ITransparentUpgradeableProxy
} from "contracts/interfaces/multisig/ITransparentUpgradeableProxy.sol";
import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";

interface IDiamondLoupe {
    function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}

library ReleaseExecutor {
    function executeBeaconUpgrades(IUpgradeMultisig.BeaconUpgrade[] storage upgrades) external {
        uint256 len = upgrades.length;
        for (uint256 i = 0; i < len; i++) {
            address beacon = upgrades[i].beacon;
            address expectedImplementation = upgrades[i].newImplementation;

            // solhint-disable-next-line no-empty-blocks
            try IBeacon(beacon).setImplementation(expectedImplementation) {} catch (
                bytes memory reason
            ) {
                revert IUpgradeMultisig.BeaconUpgradeFailed(i, beacon, reason);
            }
        }
    }

    function executeProxyUpgrades(
        IUpgradeMultisig.ProxyUpgrade[] storage upgrades,
        address proxyAdmin
    ) external {
        uint256 len = upgrades.length;

        uint256 totalValueRequired = 0;
        for (uint256 i = 0; i < len; i++) {
            totalValueRequired += upgrades[i].value;
        }
        if (totalValueRequired > address(this).balance) {
            revert IUpgradeMultisig.InsufficientValue(totalValueRequired, address(this).balance);
        }

        for (uint256 i = 0; i < len; i++) {
            IUpgradeMultisig.ProxyUpgrade storage upgrade = upgrades[i];
            address proxy = upgrade.proxy;
            address expectedImplementation = upgrade.newImplementation;

            // Use upgrade when initData is empty and value is 0 to avoid delegatecall failures
            // If value > 0, must use upgradeAndCall (upgrade is not payable)
            // Fallback to upgradeAndCall if upgrade is not available (OZ v5 compatibility)
            if (upgrade.initData.length == 0 && upgrade.value == 0) {
                // Try upgrade first (available in OZ v4 and some custom ProxyAdmins)
                // solhint-disable-next-line no-empty-blocks
                try IProxyAdmin(proxyAdmin).upgrade(proxy, expectedImplementation) {} catch {
                    // Fallback to upgradeAndCall with empty data for OZ v5 compatibility
                    // Note: This may still fail if implementation doesn't handle empty delegatecalls
                    try
                        IProxyAdmin(proxyAdmin).upgradeAndCall{value: upgrade.value}(
                            proxy,
                            expectedImplementation,
                            upgrade.initData
                        )
                    // solhint-disable-next-line no-empty-blocks
                    {

                    } catch (bytes memory reason) {
                        revert IUpgradeMultisig.ProxyUpgradeFailed(i, proxy, true, reason);
                    }
                }
            } else {
                // Always use upgradeAndCall when initData is provided or value > 0
                try
                    IProxyAdmin(proxyAdmin).upgradeAndCall{value: upgrade.value}(
                        proxy,
                        expectedImplementation,
                        upgrade.initData
                    )
                // solhint-disable-next-line no-empty-blocks
                {

                } catch (bytes memory reason) {
                    revert IUpgradeMultisig.ProxyUpgradeFailed(i, proxy, true, reason);
                }
            }
        }
    }

    function executeDiamondCuts(IUpgradeMultisig.DiamondCut[] storage cuts) external {
        uint256 len = cuts.length;
        for (uint256 i = 0; i < len; i++) {
            address diamond = cuts[i].diamond;
            IDiamondCut.FacetCut[] storage facetCuts = cuts[i].cuts;

            try
                IDiamondCut(diamond).diamondCut(facetCuts, cuts[i].init, cuts[i].initData)
            // solhint-disable-next-line no-empty-blocks
            {

            } catch (bytes memory reason) {
                revert IUpgradeMultisig.DiamondCutFailed(i, diamond, reason);
            }
        }
    }

    function executeEvaluatorUpdates(
        IUpgradeMultisig.EvaluatorUpdate[] storage updates,
        address compiler
    ) external {
        uint256 len = updates.length;
        for (uint256 i = 0; i < len; i++) {
            IUpgradeMultisig.EvaluatorUpdate storage update = updates[i];

            // solhint-disable-next-line no-empty-blocks
            try ILiquidityPoolsController(compiler).updateEvaluators(update.records) {} catch (
                bytes memory reason
            ) {
                if (reason.length == 4 && bytes4(reason) == AlreadyUpToDate.selector) {
                    continue;
                }
                revert IUpgradeMultisig.EvaluatorUpdateFailed(i, reason);
            }
        }
    }

    function validateBeaconUpgrades(
        IUpgradeMultisig.BeaconUpgrade[] storage upgrades
    ) external view {
        uint256 len = upgrades.length;
        for (uint256 i = 0; i < len; i++) {
            _validateBeaconUpgrade(upgrades[i].beacon, upgrades[i].newImplementation, i);
        }
    }

    function validateProxyUpgrades(
        IUpgradeMultisig.ProxyUpgrade[] storage upgrades,
        address proxyAdmin
    ) external view {
        uint256 len = upgrades.length;
        for (uint256 i = 0; i < len; i++) {
            IUpgradeMultisig.ProxyUpgrade storage upgrade = upgrades[i];
            _validateProxyUpgrade(
                upgrade.proxy,
                upgrade.newImplementation,
                proxyAdmin,
                i,
                upgrade.initData.length > 0
            );
        }
    }

    function validateDiamondCuts(IUpgradeMultisig.DiamondCut[] storage cuts) external view {
        uint256 len = cuts.length;
        for (uint256 i = 0; i < len; i++) {
            _validateDiamondCut(cuts[i].diamond, cuts[i].cuts, i);
        }
    }

    function _validateBeaconUpgrade(
        address beacon,
        address expectedImplementation,
        uint256 upgradeIndex
    ) private view {
        address actualImplementation = IBeacon(beacon).implementation();
        if (actualImplementation != expectedImplementation) {
            revert IUpgradeMultisig.BeaconUpgradeValidationFailed(
                upgradeIndex,
                beacon,
                expectedImplementation,
                actualImplementation
            );
        }
    }

    function _validateProxyUpgrade(
        address proxy,
        address expectedImplementation,
        address proxyAdmin,
        uint256 upgradeIndex,
        bool isUpgradeAndCall
    ) private view {
        address actualImplementation;
        try IProxyAdmin(proxyAdmin).getProxyImplementation(proxy) returns (address implementation) {
            actualImplementation = implementation;
        } catch {
            // Fallback to direct call if ProxyAdmin doesn't support it
            try ITransparentUpgradeableProxy(proxy).implementation() returns (
                address implementation
            ) {
                actualImplementation = implementation;
            } catch {
                revert IUpgradeMultisig.ProxyUpgradeValidationFailed(
                    upgradeIndex,
                    proxy,
                    isUpgradeAndCall,
                    expectedImplementation,
                    address(0)
                );
            }
        }
        if (actualImplementation != expectedImplementation) {
            revert IUpgradeMultisig.ProxyUpgradeValidationFailed(
                upgradeIndex,
                proxy,
                isUpgradeAndCall,
                expectedImplementation,
                actualImplementation
            );
        }

        // Verify admin slot wasn't tampered with during upgradeAndCall
        address actualAdmin;
        try IProxyAdmin(proxyAdmin).getProxyAdmin(proxy) returns (address admin) {
            actualAdmin = admin;
        } catch {
            // Fallback to direct call if ProxyAdmin doesn't support it
            try ITransparentUpgradeableProxy(proxy).admin() returns (address admin) {
                actualAdmin = admin;
            } catch {
                revert IUpgradeMultisig.ProxyAdminValidationFailed(
                    upgradeIndex,
                    proxy,
                    proxyAdmin,
                    address(0)
                );
            }
        }
        if (actualAdmin != proxyAdmin) {
            revert IUpgradeMultisig.ProxyAdminValidationFailed(
                upgradeIndex,
                proxy,
                proxyAdmin,
                actualAdmin
            );
        }
    }

    function _validateDiamondCut(
        address diamond,
        IDiamondCut.FacetCut[] storage facetCuts,
        uint256 cutIndex
    ) private view {
        IDiamondLoupe loupe = IDiamondLoupe(diamond);

        for (uint256 i = 0; i < facetCuts.length; i++) {
            IDiamondCut.FacetCut storage facetCut = facetCuts[i];
            address expectedFacet = facetCut.facetAddress;

            for (uint256 j = 0; j < facetCut.functionSelectors.length; j++) {
                bytes4 selector = facetCut.functionSelectors[j];
                address actualFacet = loupe.facetAddress(selector);

                if (actualFacet != expectedFacet) {
                    revert IUpgradeMultisig.DiamondCutValidationFailed(
                        cutIndex,
                        diamond,
                        i,
                        j,
                        selector,
                        facetCut.action,
                        expectedFacet,
                        actualFacet
                    );
                }
            }
        }
    }
}

contracts/multisig/libraries/ReleaseManagementLibrary.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {
    AccessControlEnumerable
} from "@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol";

import {IPausable} from "contracts/interfaces/base/pauser/IPausable.sol";
import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";
import {IPauser} from "contracts/interfaces/pauser/IPauser.sol";

import {ApprovalLibrary} from "contracts/multisig/libraries/ApprovalLibrary.sol";
import {ReleaseExecutor} from "contracts/multisig/libraries/ReleaseExecutor.sol";
import {ReleaseValidator} from "contracts/multisig/libraries/ReleaseValidator.sol";

/**
 * @title ReleaseManagementLibrary
 * @notice Library for managing release lifecycle (submit, approve, reject, execute, validate)
 */
library ReleaseManagementLibrary {
    bytes32 public constant UPGRADE_APPROVAL_OFFICER_ROLE =
        keccak256("Upgrade Approval Officer Role");
    bytes32 public constant ARKIS_SECURITY_OFFICER_ROLE = keccak256("Arkis Security Officer Role");

    /**
     * @notice Submit a new release
     */
    function submitRelease(
        mapping(bytes32 => IUpgradeMultisig.Release) storage releases,
        bytes32 pendingReleaseId,
        bytes32 pendingManagementRequestId,
        uint80 nonce,
        address proxyAdmin,
        IUpgradeMultisig.ReleaseData calldata releaseData,
        bytes32 releaseHash,
        address multisigAddress
    ) external returns (bytes32 releaseId, uint80 newNonce) {
        _validateReleaseSubmission(
            pendingReleaseId,
            pendingManagementRequestId,
            releaseData,
            releaseHash
        );

        releaseId = keccak256(abi.encode(multisigAddress, nonce, releaseHash));

        if (releases[releaseId].operator != address(0)) {
            revert IUpgradeMultisig.ReleaseAlreadyExists();
        }

        ReleaseValidator.validate(
            releaseData.beaconUpgrades,
            releaseData.proxyUpgrades,
            releaseData.diamondCuts,
            releaseData.evaluatorUpdates,
            proxyAdmin
        );

        IUpgradeMultisig.Release storage release = releases[releaseId];
        release.operator = msg.sender;
        release.nonce = nonce;
        release.status = IUpgradeMultisig.Status.Pending;

        newNonce = nonce + 1;

        _copyReleaseData(release, releaseData);

        emit IUpgradeMultisig.ReleaseSubmitted(
            releaseId,
            msg.sender,
            releaseHash,
            releaseData.beaconUpgrades.length,
            releaseData.proxyUpgrades.length,
            releaseData.diamondCuts.length,
            releaseData.evaluatorUpdates.length,
            block.timestamp
        );
    }

    /**
     * @notice Approve a release
     */
    function approveRelease(
        mapping(bytes32 => IUpgradeMultisig.Release) storage releases,
        mapping(bytes32 => mapping(address => bool)) storage releaseApprovals,
        bytes32 releaseId,
        uint8 threshold,
        uint128 timelockDuration,
        uint80 lastExecutedNonce,
        AccessControlEnumerable accessControl
    ) external {
        if (releases[releaseId].operator == address(0)) {
            revert IUpgradeMultisig.ReleaseDoesNotExist();
        }

        IUpgradeMultisig.Release storage release = releases[releaseId];
        if (release.status == IUpgradeMultisig.Status.Executed) {
            revert IUpgradeMultisig.ReleaseAlreadyExecuted();
        } else if (release.status == IUpgradeMultisig.Status.Rejected) {
            revert IUpgradeMultisig.CannotApproveRejectedRelease();
        }

        if (releaseApprovals[releaseId][msg.sender]) {
            revert IUpgradeMultisig.AlreadyApproved();
        }

        releaseApprovals[releaseId][msg.sender] = true;
        emit IUpgradeMultisig.ReleaseApproved(releaseId, msg.sender, block.timestamp);

        uint256 approvalCount = ApprovalLibrary.getReleaseApprovalCount(
            releaseApprovals,
            releaseId,
            accessControl
        );

        if (approvalCount >= threshold && release.timelockStart == 0) {
            // solhint-disable-next-line no-empty-blocks
            if (lastExecutedNonce == 0 && release.nonce == 0) {
                // First execution - allow nonce 0
            } else if (release.nonce != lastExecutedNonce + 1) {
                revert IUpgradeMultisig.ReleaseOutOfOrder(lastExecutedNonce + 1, release.nonce);
            }

            release.timelockStart = block.timestamp;
            release.timelockDuration = timelockDuration;
            emit IUpgradeMultisig.ReleaseTimelockStarted(releaseId, block.timestamp);
        }
    }

    /**
     * @notice Reject a release
     * @return rejectedNonce The nonce of the rejected release (to advance lastExecutedNonce)
     */
    function rejectRelease(
        mapping(bytes32 => IUpgradeMultisig.Release) storage releases,
        bytes32 releaseId,
        AccessControlEnumerable accessControl
    ) external returns (uint80 rejectedNonce) {
        if (releases[releaseId].operator == address(0)) {
            revert IUpgradeMultisig.ReleaseDoesNotExist();
        }

        IUpgradeMultisig.Release storage release = releases[releaseId];
        if (release.status == IUpgradeMultisig.Status.Executed) {
            revert IUpgradeMultisig.ReleaseAlreadyExecuted();
        } else if (release.status == IUpgradeMultisig.Status.Rejected) {
            revert IUpgradeMultisig.ReleaseAlreadyRejected();
        }

        if (release.timelockStart > 0) {
            if (!accessControl.hasRole(ARKIS_SECURITY_OFFICER_ROLE, msg.sender)) {
                revert IUpgradeMultisig.UnauthorizedSigner();
            }
        } else {
            if (!accessControl.hasRole(UPGRADE_APPROVAL_OFFICER_ROLE, msg.sender)) {
                revert IUpgradeMultisig.UnauthorizedSigner();
            }
        }

        release.status = IUpgradeMultisig.Status.Rejected;
        rejectedNonce = release.nonce;

        emit IUpgradeMultisig.ReleaseRejected(releaseId, msg.sender, block.timestamp);
    }

    /**
     * @notice Reject pending release
     * @return rejectedNonce The nonce of the rejected release (to advance lastExecutedNonce), or 0 if no release was rejected
     * @return wasRejected Whether a release was actually rejected
     */
    function rejectPendingRelease(
        mapping(bytes32 => IUpgradeMultisig.Release) storage releases,
        bytes32 pendingReleaseId
    ) external returns (uint80 rejectedNonce, bool wasRejected) {
        if (pendingReleaseId != bytes32(0)) {
            IUpgradeMultisig.Release storage release = releases[pendingReleaseId];
            if (release.status == IUpgradeMultisig.Status.Pending) {
                if (release.timelockStart > 0) {
                    revert IUpgradeMultisig.ReleasePending();
                }
                release.status = IUpgradeMultisig.Status.Rejected;
                rejectedNonce = release.nonce;
                wasRejected = true;
                emit IUpgradeMultisig.ReleaseRejected(
                    pendingReleaseId,
                    address(0),
                    block.timestamp
                );
            }
        }
    }

    /**
     * @notice Execute a release
     * @return newLastExecutedNonce Latest used nonce for execution
     */
    function executeRelease(
        IUpgradeMultisig.Release storage release,
        address pauser,
        address proxyAdmin,
        address compiler
    ) external returns (uint80 newLastExecutedNonce) {
        validateExecution(release);

        release.status = IUpgradeMultisig.Status.Executed;
        newLastExecutedNonce = release.nonce;

        bool anyPausedBefore = false;
        try IPauser(pauser).pausables() returns (address[] memory pausableList) {
            for (uint256 i = 0; i < pausableList.length; i++) {
                try IPausable(pausableList[i]).paused() returns (bool isPaused) {
                    if (isPaused) {
                        anyPausedBefore = true;
                        break;
                    }
                    // solhint-disable-next-line no-empty-blocks
                } catch {}
            }
            // solhint-disable-next-line no-empty-blocks
        } catch {}
        IPauser(pauser).multiSignaturePauseAll();

        ReleaseExecutor.executeBeaconUpgrades(release.beaconUpgrades);
        ReleaseExecutor.executeProxyUpgrades(release.proxyUpgrades, proxyAdmin);
        ReleaseExecutor.executeDiamondCuts(release.diamondCuts);
        ReleaseExecutor.executeEvaluatorUpdates(release.evaluatorUpdates, compiler);

        if (!anyPausedBefore) {
            IPauser(pauser).multiSignatureUnpauseAll();
            ReleaseExecutor.validateBeaconUpgrades(release.beaconUpgrades);
        } else if (release.beaconUpgrades.length > 0) {
            IPauser(pauser).multiSignatureUnpauseAll();
            ReleaseExecutor.validateBeaconUpgrades(release.beaconUpgrades);
            IPauser(pauser).multiSignaturePauseAll();
        }

        ReleaseExecutor.validateProxyUpgrades(release.proxyUpgrades, proxyAdmin);
        ReleaseExecutor.validateDiamondCuts(release.diamondCuts);
    }

    /**
     * @notice Validate that a release can be executed (timelock must have passed)
     */
    function validateExecution(IUpgradeMultisig.Release storage release) internal view {
        if (release.operator == address(0)) {
            revert IUpgradeMultisig.ReleaseDoesNotExist();
        }

        if (release.status == IUpgradeMultisig.Status.Executed) {
            revert IUpgradeMultisig.ReleaseAlreadyExecuted();
        } else if (release.status == IUpgradeMultisig.Status.Rejected) {
            revert IUpgradeMultisig.CannotExecuteRejectedRelease();
        }

        if (release.timelockStart == 0) {
            revert IUpgradeMultisig.ReleaseNotReady();
        }

        uint256 timelockEnd = release.timelockStart + release.timelockDuration;
        if (block.timestamp < timelockEnd) {
            revert IUpgradeMultisig.TimelockNotPassed();
        }
    }

    /**
     * @notice Copy release data arrays from calldata to storage
     * @param release The release storage reference
     * @param releaseData The release data to copy
     */
    function _copyReleaseData(
        IUpgradeMultisig.Release storage release,
        IUpgradeMultisig.ReleaseData calldata releaseData
    ) private {
        for (uint256 i = 0; i < releaseData.beaconUpgrades.length; i++) {
            release.beaconUpgrades.push(releaseData.beaconUpgrades[i]);
        }

        for (uint256 i = 0; i < releaseData.proxyUpgrades.length; i++) {
            release.proxyUpgrades.push(releaseData.proxyUpgrades[i]);
        }

        for (uint256 i = 0; i < releaseData.diamondCuts.length; i++) {
            release.diamondCuts.push(releaseData.diamondCuts[i]);
        }

        for (uint256 i = 0; i < releaseData.evaluatorUpdates.length; i++) {
            release.evaluatorUpdates.push(releaseData.evaluatorUpdates[i]);
        }
    }

    /**
     * @notice Validate release data
     */
    function _validateReleaseSubmission(
        bytes32 pendingReleaseId,
        bytes32 pendingManagementRequestId,
        IUpgradeMultisig.ReleaseData calldata releaseData,
        bytes32 releaseHash
    ) private pure {
        if (pendingManagementRequestId != bytes32(0)) {
            revert IUpgradeMultisig.ManagementRequestPending();
        }

        if (pendingReleaseId != bytes32(0)) {
            revert IUpgradeMultisig.ReleasePending();
        }

        if (
            releaseData.beaconUpgrades.length == 0 &&
            releaseData.proxyUpgrades.length == 0 &&
            releaseData.diamondCuts.length == 0 &&
            releaseData.evaluatorUpdates.length == 0
        ) {
            revert IUpgradeMultisig.EmptyRelease();
        }

        bytes32 calculatedHash = keccak256(abi.encode(releaseData));
        if (calculatedHash != releaseHash) {
            revert IUpgradeMultisig.InvalidReleaseHash();
        }
    }
}

contracts/multisig/libraries/ReleaseValidator.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {Address} from "@openzeppelin/contracts/utils/Address.sol";

import {AlreadyUpToDate} from "contracts/interfaces/base/CommonErrors.sol";
import {IPausable} from "contracts/interfaces/base/pauser/IPausable.sol";
import {IBeacon} from "contracts/interfaces/base/proxy/IBeacon.sol";
import {IDiamondCut} from "contracts/interfaces/diamond/IDiamondCut.sol";
import {IProxyAdmin} from "contracts/interfaces/multisig/IProxyAdmin.sol";
import {
    ITransparentUpgradeableProxy
} from "contracts/interfaces/multisig/ITransparentUpgradeableProxy.sol";
import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";

interface IDiamondLoupe {
    struct Facet {
        address facetAddress;
        bytes4[] functionSelectors;
    }

    function facets() external view returns (Facet[] memory facets_);

    function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}

library ReleaseValidator {
    function validate(
        IUpgradeMultisig.BeaconUpgrade[] calldata beaconUpgrades,
        IUpgradeMultisig.ProxyUpgrade[] calldata proxyUpgrades,
        IUpgradeMultisig.DiamondCut[] calldata diamondCuts,
        IUpgradeMultisig.EvaluatorUpdate[] calldata evaluatorUpdates,
        address proxyAdmin
    ) external view {
        _validateBeaconUpgrades(beaconUpgrades);
        _validateProxyUpgrades(proxyUpgrades, proxyAdmin);
        _validateDiamondCuts(diamondCuts);
        _validateEvaluatorUpdates(evaluatorUpdates);
    }

    function _isContract(address addr) private view returns (bool) {
        return addr.code.length > 0;
    }

    function _validateBeaconUpgrades(
        IUpgradeMultisig.BeaconUpgrade[] calldata upgrades
    ) private view {
        uint256 len = upgrades.length;
        for (uint256 i = 0; i < len; i++) {
            if (upgrades[i].beacon == address(0) || upgrades[i].newImplementation == address(0)) {
                revert IUpgradeMultisig.InvalidAddress();
            }
            if (!_isContract(upgrades[i].beacon)) {
                revert Address.AddressEmptyCode(upgrades[i].beacon);
            }
            if (!_isContract(upgrades[i].newImplementation)) {
                revert Address.AddressEmptyCode(upgrades[i].newImplementation);
            }

            /// @dev We can't read a paused beacon, we rely on executeRelease detecting the no-op upgrade
            if (_isPaused(upgrades[i].beacon)) continue;

            address currentImplementation = IBeacon(upgrades[i].beacon).implementation();
            if (currentImplementation == address(0)) {
                revert IUpgradeMultisig.InvalidAddress();
            }
            if (currentImplementation == upgrades[i].newImplementation) {
                revert AlreadyUpToDate();
            }
        }
    }

    function _isPaused(address target) private view returns (bool paused) {
        try IPausable(target).paused() returns (bool isPaused) {
            paused = isPaused;
            // solhint-disable-next-line no-empty-blocks
        } catch {}
    }

    function _validateProxyUpgrades(
        IUpgradeMultisig.ProxyUpgrade[] calldata upgrades,
        address proxyAdmin
    ) private view {
        uint256 len = upgrades.length;
        for (uint256 i = 0; i < len; i++) {
            address proxy = upgrades[i].proxy;
            address newImplementation = upgrades[i].newImplementation;

            if (proxy == address(0) || newImplementation == address(0)) {
                revert IUpgradeMultisig.InvalidAddress();
            }
            if (!_isContract(proxy)) {
                revert Address.AddressEmptyCode(proxy);
            }
            if (!_isContract(newImplementation)) {
                revert Address.AddressEmptyCode(newImplementation);
            }
            if (
                upgrades[i].initData.length > 0 &&
                (upgrades[i].initData.length < 4 || upgrades[i].initData.length % 32 != 4)
            ) {
                revert IUpgradeMultisig.InvalidInitData();
            }

            // Use ProxyAdmin to get implementation and admin to avoid fallback delegation issues
            // Direct calls to proxy.admin() and proxy.implementation() can fail if the caller
            // is not the admin, as OptimizedTransparentProxy delegates to implementation via fallback
            address impl;
            try IProxyAdmin(proxyAdmin).getProxyImplementation(proxy) returns (
                address implementation
            ) {
                impl = implementation;
            } catch {
                // Fallback to direct call if ProxyAdmin doesn't support it
                try ITransparentUpgradeableProxy(proxy).implementation() returns (
                    address implementation
                ) {
                    impl = implementation;
                } catch {
                    revert IUpgradeMultisig.NotEip1967Proxy();
                }
            }
            if (impl == address(0)) {
                revert IUpgradeMultisig.NotEip1967Proxy();
            }

            address admin;
            try IProxyAdmin(proxyAdmin).getProxyAdmin(proxy) returns (address proxyAdmin_) {
                admin = proxyAdmin_;
            } catch {
                // Fallback to direct call if ProxyAdmin doesn't support it
                try ITransparentUpgradeableProxy(proxy).admin() returns (address proxyAdmin_) {
                    admin = proxyAdmin_;
                } catch {
                    revert IUpgradeMultisig.NotEip1967Proxy();
                }
            }
            if (admin != proxyAdmin) {
                revert IUpgradeMultisig.WrongAdmin();
            }

            if (impl == newImplementation) {
                revert AlreadyUpToDate();
            }
        }
    }

    function _validateDiamondCuts(IUpgradeMultisig.DiamondCut[] calldata cuts) private view {
        uint256 len = cuts.length;
        for (uint256 i = 0; i < len; i++) {
            _validateDiamondCut(cuts[i]);
        }
    }

    function _validateDiamondCut(IUpgradeMultisig.DiamondCut calldata cut) private view {
        if (cut.diamond == address(0)) {
            revert IUpgradeMultisig.InvalidAddress();
        }
        if (!_isContract(cut.diamond)) {
            revert Address.AddressEmptyCode(cut.diamond);
        }
        if (cut.cuts.length == 0) {
            revert IUpgradeMultisig.EmptyRelease();
        }

        // solhint-disable-next-line no-empty-blocks
        try IDiamondLoupe(cut.diamond).facets() returns (IDiamondLoupe.Facet[] memory) {
            // Success - diamond is valid
        } catch {
            revert IUpgradeMultisig.InvalidDiamond();
        }
        if (cut.init == address(0)) {
            if (cut.initData.length > 0) {
                revert IUpgradeMultisig.InvalidInitCoherence();
            }
        } else {
            if (cut.initData.length < 4 || cut.initData.length % 32 != 4) {
                revert IUpgradeMultisig.InvalidInitData();
            }
            if (!_isContract(cut.init)) {
                revert Address.AddressEmptyCode(cut.init);
            }
        }

        for (uint256 j = 0; j < cut.cuts.length; j++) {
            IDiamondCut.FacetCut calldata facetCut = cut.cuts[j];

            if (uint8(facetCut.action) > uint8(IDiamondCut.FacetCutAction.Remove)) {
                revert IUpgradeMultisig.InvalidFacetCutAction();
            }

            if (
                (facetCut.action == IDiamondCut.FacetCutAction.Add ||
                    facetCut.action == IDiamondCut.FacetCutAction.Replace) &&
                !_isContract(facetCut.facetAddress)
            ) {
                revert Address.AddressEmptyCode(facetCut.facetAddress);
            }
            if (
                facetCut.action == IDiamondCut.FacetCutAction.Remove &&
                facetCut.facetAddress != address(0)
            ) {
                revert IUpgradeMultisig.InvalidAddress();
            }

            if (facetCut.functionSelectors.length == 0) {
                revert IUpgradeMultisig.EmptyRelease();
            }

            for (uint256 k = 0; k < facetCut.functionSelectors.length; k++) {
                bytes4 selector = facetCut.functionSelectors[k];

                if (selector == bytes4(0)) {
                    revert IUpgradeMultisig.InvalidSelector();
                }

                for (uint256 prevCut = 0; prevCut < j; prevCut++) {
                    for (uint256 m = 0; m < cut.cuts[prevCut].functionSelectors.length; m++) {
                        if (cut.cuts[prevCut].functionSelectors[m] == selector) {
                            revert IUpgradeMultisig.DuplicateSelector(selector);
                        }
                    }
                }
                for (uint256 m = 0; m < k; m++) {
                    if (facetCut.functionSelectors[m] == selector) {
                        revert IUpgradeMultisig.DuplicateSelector(selector);
                    }
                }
            }
        }

        IDiamondLoupe loupe = IDiamondLoupe(cut.diamond);
        for (uint256 j = 0; j < cut.cuts.length; j++) {
            IDiamondCut.FacetCut calldata facetCut = cut.cuts[j];

            for (uint256 k = 0; k < facetCut.functionSelectors.length; k++) {
                bytes4 selector = facetCut.functionSelectors[k];
                address currentFacet;
                try loupe.facetAddress(selector) returns (address facet) {
                    currentFacet = facet;
                } catch {
                    currentFacet = address(0);
                }
                if (facetCut.action == IDiamondCut.FacetCutAction.Add) {
                    if (currentFacet != address(0)) {
                        revert IUpgradeMultisig.SelectorAlreadyExists(selector);
                    }
                } else if (facetCut.action == IDiamondCut.FacetCutAction.Replace) {
                    if (currentFacet == address(0)) {
                        revert IUpgradeMultisig.SelectorDoesNotExist(selector);
                    }
                    if (currentFacet == facetCut.facetAddress) {
                        revert AlreadyUpToDate();
                    }
                } else if (facetCut.action == IDiamondCut.FacetCutAction.Remove) {
                    if (currentFacet == address(0)) {
                        revert IUpgradeMultisig.SelectorDoesNotExist(selector);
                    }
                    if (currentFacet == cut.diamond) {
                        revert IUpgradeMultisig.SelectorImmutable(selector);
                    }
                }
            }
        }
    }

    function _validateEvaluatorUpdates(
        IUpgradeMultisig.EvaluatorUpdate[] calldata updates
    ) private view {
        uint256 len = updates.length;
        for (uint256 i = 0; i < len; i++) {
            if (updates[i].records.length == 0) {
                revert IUpgradeMultisig.EmptyRelease();
            }
            for (uint256 j = 0; j < updates[i].records.length; j++) {
                if (updates[i].records[j].evaluator == address(0)) {
                    revert IUpgradeMultisig.InvalidAddress();
                }
                if (!_isContract(updates[i].records[j].evaluator)) {
                    revert Address.AddressEmptyCode(updates[i].records[j].evaluator);
                }
                bytes memory protocolBytes = bytes(updates[i].records[j].protocol);
                if (protocolBytes.length == 0) {
                    revert IUpgradeMultisig.EmptyRelease();
                }
            }
        }
    }
}

contracts/multisig/libraries/RenounceRoleValidationLibrary.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;

import {IUpgradeMultisig} from "contracts/interfaces/multisig/IUpgradeMultisig.sol";

/**
 * @title RenounceRoleValidationLibrary
 * @notice Library for validating renounceRole operations
 */
library RenounceRoleValidationLibrary {
    bytes32 public constant UPGRADE_PROPOSAL_OFFICER_ROLE =
        keccak256("Upgrade Proposal Officer Role");
    bytes32 public constant UPGRADE_APPROVAL_OFFICER_ROLE =
        keccak256("Upgrade Approval Officer Role");
    bytes32 public constant ARKIS_SECURITY_OFFICER_ROLE = keccak256("Arkis Security Officer Role");
    uint256 public constant MIN_OPERATORS = 2;

    /**
     * @notice Validate if a role can be renounced
     * @param role The role to renounce
     * @param approverCount Current number of approvers
     * @param operatorCount Current number of operators
     * @param securityOfficerCount Current number of security officers
     * @param threshold Current threshold value
     */
    function validateRenounceRole(
        bytes32 role,
        uint256 approverCount,
        uint256 operatorCount,
        uint256 securityOfficerCount,
        uint8 threshold
    ) external pure {
        if (role == UPGRADE_APPROVAL_OFFICER_ROLE) {
            if (approverCount - 1 < threshold) {
                revert IUpgradeMultisig.CannotRenounceBelowThreshold();
            }
        } else if (role == UPGRADE_PROPOSAL_OFFICER_ROLE) {
            if (operatorCount <= MIN_OPERATORS) {
                revert IUpgradeMultisig.InsufficientOperators();
            }
        } else if (role == ARKIS_SECURITY_OFFICER_ROLE) {
            if (securityOfficerCount <= 1) {
                revert IUpgradeMultisig.CannotRenounceLastSecurityOfficer();
            }
        }
    }
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "libraries": {
    "contracts/multisig/UpgradeMultisig.sol": {
      "ApprovalLibrary": "0x2ff0f841fb81e87aec459d952354ea21c2492ba0",
      "ManagementRequestLibrary": "0x1f5a2885c2d5670c75f7c4a03fd1ef8a1bc4befe",
      "ReleaseManagementLibrary": "0x9f35ea3317718c3d1b82ace70cd1e27f913e745a",
      "ConstructorValidationLibrary": "0x2a7719cf300deca34b46f5013e3378131f57820c",
      "RenounceRoleValidationLibrary": "0x35375aa484d13b4921bfca0923a79f3d3b4ff06a"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.