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

AgreementV2Factory

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

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.22

 

Тот же код

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

 

Подробности

Компилятор
solc 0.8.22+commit.4fc1097e
Язык
solidity
Оптимизация
Да, 1 000 000 прогонов
Версия EVM
paris
Лицензия
BUSL-1.1
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 391 830
Транзакция создания
0x702259ac71…d04e624047

33 файла

contracts/agreementV2/AgreementV2Factory.sol

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

import {
    IERC165
} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";

import {IAgreement} from "contracts/interfaces/agreement/IAgreement.sol";
import {IAgreementV2} from "contracts/interfaces/agreementV2/IAgreementV2.sol";
import {
    IAgreementInitializer,
    IAgreementV2Factory,
    IAgreementV2Initializer
} from "contracts/interfaces/agreementV2/IAgreementV2Factory.sol";
import {IAgreementV2Staking} from "contracts/interfaces/agreementV2/IAgreementV2Staking.sol";
import {ISuspendable} from "contracts/interfaces/base/ISuspendable.sol";
import {
    IWhitelistingControllerAgreement
} from "contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol";

import {BeaconUpgradeable} from "contracts/base/proxy/BeaconUpgradeable.sol";
import {ImmutableBeaconProxy} from "contracts/base/proxy/ImmutableBeaconProxy.sol";

contract AgreementV2Factory is IAgreementV2Factory, BeaconUpgradeable {
    using Clones for address;
    struct Storage {
        address agreementPrototype;
        address compliance;
        mapping(address => bool) agreements;
    }

    // keccak256(abi.encode(uint256(keccak256("agreement.factory.v2")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 internal constant STORAGE_SLOT =
        0x604c9e60cf27c767ab6c42426d9271b3ec78b86a0c7d63bf42698a9a0502f200;
    bytes32 public constant override ARKIS_RISK_OPERATOR_ROLE =
        keccak256("Arkis Risk Operator Role");

    modifier onlyValidAgreement(address agreement) {
        if (!_storage().agreements[agreement]) revert InvalidAgreement(agreement);
        _;
    }

    function initialize(address riskOperator, address _compliance) external override initializer {
        __Ownable_init(msg.sender);
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(ARKIS_RISK_OPERATOR_ROLE, riskOperator);
        _storage().compliance = _compliance;
    }

    function setImplementation(address implementation) external override whenPaused onlyOwner {
        if (!IERC165(implementation).supportsInterface(type(IAgreementV2Staking).interfaceId))
            revert InvalidImplementation(implementation);
        _setImplementation(implementation);
        Storage storage $ = _storage();
        if ($.agreementPrototype == address(0))
            $.agreementPrototype = address(new ImmutableBeaconProxy(new bytes(0)));
    }

    function createAgreement(
        IAgreementInitializer.Metadata calldata metadata,
        IAgreementInitializer.Whitelist calldata whitelist,
        IAgreementV2Initializer.LPTokenMetadata calldata lpTokenMetadata
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        returns (address agreement)
    {
        if (
            bytes(lpTokenMetadata.name).length == 0 ||
            bytes(lpTokenMetadata.name).length > 31 ||
            bytes(lpTokenMetadata.symbol).length == 0 ||
            bytes(lpTokenMetadata.symbol).length > 31
        ) {
            revert InvalidStringLength();
        }
        Storage storage $ = _storage();
        agreement = $.agreementPrototype.clone();
        IAgreementV2Initializer(agreement).initialize(metadata, lpTokenMetadata);
        IWhitelistingControllerAgreement wc = IWhitelistingControllerAgreement($.compliance);
        wc.addTokens(agreement, whitelist.tokens);
        wc.addOperators(agreement, whitelist.operators);
        $.agreements[agreement] = true;
        emit AgreementCreated(agreement);
    }

    function addCollaterals(
        address agreement,
        address[] calldata tokens
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).addCollaterals(tokens);
    }

    function addLenders(
        address agreement,
        address[] calldata lenders
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).addLenders(lenders);
    }

    function addBorrowers(
        address agreement,
        address[] calldata borrowers
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).addBorrowers(borrowers);
    }

    function addTokens(
        address agreement,
        address[] calldata tokens
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IWhitelistingControllerAgreement(_storage().compliance).addTokens(agreement, tokens);
    }

    function addOperators(
        address agreement,
        address[] calldata operators
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IWhitelistingControllerAgreement(_storage().compliance).addOperators(agreement, operators);
    }

    function removeCollaterals(
        address agreement,
        address[] calldata tokens
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).removeCollaterals(tokens);
    }

    function removeLenders(
        address agreement,
        address[] calldata lenders
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).removeLenders(lenders);
    }

    function removeBorrowers(
        address agreement,
        address[] calldata borrowers
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).removeBorrowers(borrowers);
    }

    function setApy(
        address agreement,
        uint32 apy
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).setApy(apy);
    }

    function setTotalDepositThreshold(
        address agreement,
        uint256 threshold
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        IAgreement(agreement).setTotalDepositThreshold(threshold);
    }

    function suspend(
        address agreement
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        ISuspendable(agreement).suspend();
    }

    function unsuspend(
        address agreement
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        ISuspendable(agreement).unsuspend();
    }

    function close(
        address agreement
    )
        external
        override
        whenNotPaused
        onlyRole(ARKIS_RISK_OPERATOR_ROLE)
        onlyValidAgreement(agreement)
    {
        ISuspendable(agreement).close();
    }

    function migrateAgreementAccounting(address[] calldata agreements) external override onlyOwner {
        uint256 length = agreements.length;
        for (uint256 i = 0; i < length; i++) {
            address agreement = agreements[i];
            if (!_storage().agreements[agreement]) revert InvalidAgreement(agreement);
            IAgreementV2(agreement).migrateInternalAccounting();
        }
    }

    function agreementPrototype() external view override returns (address) {
        return _storage().agreementPrototype;
    }

    function compliance() external view override returns (address) {
        return _storage().compliance;
    }

    function hasAgreement(address agreement) external view override returns (bool) {
        return _storage().agreements[agreement];
    }

    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAgreementV2Factory).interfaceId;
    }

    function _storage() internal pure returns (Storage storage $) {
        assembly {
            $.slot := STORAGE_SLOT
        }
    }
}

@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/access/OwnableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @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.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        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) {
        OwnableStorage storage $ = _getOwnableStorage();
        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 {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@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/PausableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}

@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/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/proxy/Clones.sol

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

pragma solidity ^0.8.20;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev A clone instance deployment failed.
     */
    error ERC1167FailedCreateClone();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

@openzeppelin/contracts/proxy/Proxy.sol

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

pragma solidity ^0.8.20;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
     * function and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@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/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);
}

contracts/base/pauser/Pausable.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.22;

import {
    AccessControlUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {PausableBase} from "contracts/base/pauser/base/PausableBase.sol";

contract Pausable is PausableBase, AccessControlUpgradeable {
    function _checkRole(
        bytes32 role
    ) internal view override(AccessControlUpgradeable, PausableBase) {
        AccessControlUpgradeable._checkRole(role);
    }
}

contracts/base/pauser/base/PausableBase.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.22;

import {
    PausableUpgradeable
} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {IPausable} from "contracts/interfaces/base/pauser/IPausable.sol";

abstract contract PausableBase is IPausable, PausableUpgradeable {
    bytes32 public constant override PAUSER_ROLE = keccak256("Pauser Role");

    modifier onlyPauserRole() {
        _checkRole(PAUSER_ROLE);
        _;
    }

    function pause() external override onlyPauserRole {
        _pause();
    }

    function unpause() external override onlyPauserRole {
        _unpause();
    }

    function paused() public view override(IPausable, PausableUpgradeable) returns (bool) {
        return PausableUpgradeable.paused();
    }

    /*
     * @dev Contracts inheriting from PausableBase should inherit OpenZeppelin's AccessControlUpgradeable
     *      override and implement _checkRole()
     */
    /* solhint-disable-next-line no-empty-blocks */
    function _checkRole(bytes32 role) internal view virtual {}
}

contracts/base/proxy/BeaconImplementation.sol

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

import {AlreadyUpToDate} from "contracts/interfaces/base/CommonErrors.sol";

abstract contract BeaconImplementation {
    // keccak256("Implementation slot inside BeaconImplementation")
    bytes32 internal constant IMPLEMENTATION_SLOT =
        0x5a8947f50575ddcaa31a5721cef4bf0d765e78dbe7d7a1182efca602a9dfd034;

    function _setImplementation(address newImpl) internal {
        address impl;
        assembly {
            impl := sload(IMPLEMENTATION_SLOT)
        }
        if (impl == newImpl) revert AlreadyUpToDate();
        assembly {
            sstore(IMPLEMENTATION_SLOT, newImpl)
        }
    }

    function _implementation() internal view returns (address impl) {
        assembly {
            impl := sload(IMPLEMENTATION_SLOT)
        }
    }
}

contracts/base/proxy/BeaconUpgradeable.sol

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

import {
    OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

import {IBeacon} from "contracts/interfaces/base/proxy/IBeacon.sol";

import {Pausable} from "contracts/base/pauser/Pausable.sol";

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

abstract contract BeaconUpgradeable is IBeacon, BeaconImplementation, OwnableUpgradeable, Pausable {
    /* @dev Implementation is not set in the BeaconUpgradeable,
     *   contracts inheriting from this contract should override and implement setImplementation()
     */
    /* solhint-disable-next-line no-empty-blocks */
    function setImplementation(address newImplementation) external virtual override whenPaused {}

    function implementation() external view override whenNotPaused returns (address) {
        return _implementation();
    }
}

contracts/base/proxy/ImmutableBeaconProxy.sol

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

import {Proxy} from "@openzeppelin/contracts/proxy/Proxy.sol";
import {IBeacon} from "contracts/interfaces/base/proxy/IBeacon.sol";
import {SafeCall} from "contracts/libraries/SafeCall.sol";

contract ImmutableBeaconProxy is Proxy {
    using {SafeCall.safeDelegateCall} for address;

    address private immutable beacon;

    error BeaconCallFailed();
    error BeaconReturnedUnexpectedNumberOfBytes(uint256);
    error BeaconReturnedAddressZero();

    constructor(bytes memory initDataWithSelector) {
        beacon = msg.sender;

        if (initDataWithSelector.length > 0) {
            _implementation().safeDelegateCall(initDataWithSelector);
        }
    }

    function _implementation() internal view override returns (address impl) {
        (bool success, bytes memory result) = beacon.staticcall(
            abi.encodeWithSelector(IBeacon.implementation.selector)
        );

        if (!success) revert BeaconCallFailed();
        if (result.length != 32) revert BeaconReturnedUnexpectedNumberOfBytes(result.length);

        impl = abi.decode(result, (address));
        if (impl == address(0)) revert BeaconReturnedAddressZero();
    }
}

contracts/interfaces/agreement/IAgreement.sol

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

import {ISuspendable} from "contracts/interfaces/base/ISuspendable.sol";
import {IAgreementInitializer} from "./IAgreementInitializer.sol";

/**
 * @title IAgreement
 * @notice Interface for managing agreements, including adding/removing collateral, lenders, and borrowers.
 * @dev Inherits ISuspendable and IAgreementInitializer.
 */
interface IAgreement is ISuspendable, IAgreementInitializer {
    /**
     * @notice Emitted when a borrower is added to the agreement.
     * @param account The address of the borrower.
     */
    event BorrowerAdded(address account);

    /**
     * @notice Emitted when a borrower is removed from the agreement.
     * @param account The address of the borrower.
     */
    event BorrowerRemoved(address account);

    /**
     * @notice Emitted when collateral is added to the agreement.
     * @param token The address of the collateral token.
     */
    event CollateralAdded(address token);

    /**
     * @notice Emitted when collateral is removed from the agreement.
     * @param token The address of the collateral token.
     */
    event CollateralRemoved(address token);

    /**
     * @notice Emitted when the agreement is initialized.
     * @param leverage The address of the leverage contract.
     */
    event Initialized(address leverage);

    /**
     * @notice Emitted when a lender is added to the agreement.
     * @param account The address of the lender.
     */
    event LenderAdded(address account);

    /**
     * @notice Emitted when a lender is removed from the agreement.
     * @param account The address of the lender.
     */
    event LenderRemoved(address account);

    /**
     * @notice Adds collateral tokens to the agreement.
     * @param tokens An array of addresses of the collateral tokens to be added.
     */
    function addCollaterals(address[] calldata tokens) external;

    /**
     * @notice Adds lenders to the agreement.
     * @param lenders An array of addresses of the lenders to be added.
     */
    function addLenders(address[] calldata lenders) external;

    /**
     * @notice Adds borrowers to the agreement.
     * @param borrowers An array of addresses of the borrowers to be added.
     */
    function addBorrowers(address[] calldata borrowers) external;

    /**
     * @notice Removes collateral from the agreement.
     * @param tokens An array of addresses of the collateral tokens to remove.
     */
    function removeCollaterals(address[] calldata tokens) external;

    /**
     * @notice Removes lenders from the agreement.
     * @param lenders An array of addresses of the lenders to remove.
     */
    function removeLenders(address[] calldata lenders) external;

    /**
     * @notice Removes borrowers from the agreement.
     * @param borrowers An array of addresses of the borrowers to remove.
     */
    function removeBorrowers(address[] calldata borrowers) external;

    /**
     * @notice Sets the annual percentage yield (APY) for the agreement.
     * @dev This function allows the contract to update the APY value, which affects the interest calculations.
     * @param apy The new APY value to be set (in basis points, where 10,000 equals 100%).
     */
    function setApy(uint32 apy) external;

    /**
     * @notice Sets the threshold for the total amount of tokens that can be deposited.
     * @dev Can be called by authorized accounts to define the maximum allowed total deposit.
     * @param threshold The maximum deposit threshold.
     */
    function setTotalDepositThreshold(uint256 threshold) external;

    /**
     * @notice Returns the metadata and whitelist information of the agreement.
     * @return A tuple containing the [Metadata](../IAgreementInitializer.sol/interface.IAgreementInitializer.html#metadata) and [Whitelist](../IAgreementInitializer.sol/interface.IAgreementInitializer.html#whitelist) structs.
     */
    function info() external view returns (Metadata memory, Whitelist memory);

    /**
     * @notice Returns the address of the factory contract for version tracking.
     * @return The address of the factory contract.
     */
    function factory() external view returns (address);
}

contracts/interfaces/agreement/IAgreementFactoryInitializer.sol

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

interface IAgreementFactoryInitializer {
    /**
     * @notice Initializes the agreement factory contract with the specified admin and compliance address.
     * @param admin The address of the admin who will have administrative control over the contract.
     * @param compliance The address of the compliance contract to be associated with the agreement factory.
     * @dev This function sets up the initial administrative and compliance addresses for the factory.
     * It is intended to be called once during the deployment or setup of the factory.
     */
    function initialize(address admin, address compliance) external;
}

contracts/interfaces/agreement/IAgreementInitializer.sol

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

interface IAgreementInitializer {
    /**
     * @notice Contains metadata required for initializing an agreement.
     * @param leverage The address of the token utilized as leverage in the agreement.
     * @param apy The annual percentage yield (APY) for the agreement, expressed in basis points (where 10,000 equals 100%).
     * @param totalDepositThreshold The maximum threshold value for total deposits permitted in the agreement.
     * @param collaterals An array of addresses representing the collateral tokens associated with the agreement.
     * @param lenders An array of addresses representing the lenders involved in the agreement.
     * @param borrowers An array of addresses representing the borrowers participating in the agreement.
     */
    struct Metadata {
        address leverage;
        uint32 apy;
        uint256 totalDepositThreshold;
        address[] collaterals;
        address[] lenders;
        address[] borrowers;
    }

    /**
     * @notice Contains the whitelist of tokens and operators for the agreement.
     * @param tokens An array of addresses of the whitelisted tokens.
     * @param operators An array of addresses of the whitelisted operators.
     */
    struct Whitelist {
        address[] tokens;
        address[] operators;
    }

    /**
     * @notice Initializes the agreement with metadata.
     * @param metadata_ The metadata to initialize the agreement.
     */
    function initialize(Metadata calldata metadata_) external;
}

contracts/interfaces/agreementV2/IAgreementV2.sol

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

import {ISuspendable} from "contracts/interfaces/base/ISuspendable.sol";
import {IAgreementInitializer, IAgreementV2Initializer} from "./IAgreementV2Initializer.sol";

/// @notice Thrown when the threshold exceeds the maximum allowed value.
error ThresholdExceedsMaximum();

/**
 * @title IAgreement
 * @notice Interface for managing agreements, including adding/removing collateral, lenders, and borrowers.
 * @dev Inherits ISuspendable and IAgreementV2Initializer.
 */
interface IAgreementV2 is ISuspendable, IAgreementV2Initializer {
    /**
     * @notice Emitted when a borrower is added to the agreement.
     * @param account The address of the borrower.
     */
    event BorrowerAdded(address account);

    /**
     * @notice Emitted when a borrower is removed from the agreement.
     * @param account The address of the borrower.
     */
    event BorrowerRemoved(address account);

    /**
     * @notice Emitted when collateral is added to the agreement.
     * @param token The address of the collateral token.
     */
    event CollateralAdded(address token);

    /**
     * @notice Emitted when collateral is removed from the agreement.
     * @param token The address of the collateral token.
     */
    event CollateralRemoved(address token);

    /**
     * @notice Emitted when the agreement is initialized.
     * @param leverage The address of the leverage contract.
     */
    event Initialized(address leverage);

    /**
     * @notice Emitted when a lender is added to the agreement.
     * @param account The address of the lender.
     */
    event LenderAdded(address account);

    /**
     * @notice Emitted when a lender is removed from the agreement.
     * @param account The address of the lender.
     */
    event LenderRemoved(address account);

    /**
     * @notice Adds collateral tokens to the agreement.
     * @param tokens An array of addresses of the collateral tokens to be added.
     */
    function addCollaterals(address[] calldata tokens) external;

    /**
     * @notice Adds lenders to the agreement.
     * @param lenders An array of addresses of the lenders to be added.
     */
    function addLenders(address[] calldata lenders) external;

    /**
     * @notice Adds borrowers to the agreement.
     * @param borrowers An array of addresses of the borrowers to be added.
     */
    function addBorrowers(address[] calldata borrowers) external;

    /**
     * @notice Removes collateral from the agreement.
     * @param tokens An array of addresses of the collateral tokens to remove.
     */
    function removeCollaterals(address[] calldata tokens) external;

    /**
     * @notice Removes lenders from the agreement.
     * @param lenders An array of addresses of the lenders to remove.
     */
    function removeLenders(address[] calldata lenders) external;

    /**
     * @notice Removes borrowers from the agreement.
     * @param borrowers An array of addresses of the borrowers to remove.
     */
    function removeBorrowers(address[] calldata borrowers) external;

    /**
     * @notice Sets the annual percentage yield (APY) for the agreement.
     * @dev This function allows the contract to update the APY value, which affects the interest calculations.
     * @param apy The new APY value to be set (in basis points, where 10,000 equals 100%).
     */
    function setApy(uint32 apy) external;

    /**
     * @notice Sets the threshold for the total amount of tokens that can be deposited.
     * @dev Can be called by authorized accounts to define the maximum allowed total deposit.
     * @param threshold The maximum deposit threshold.
     */
    function setTotalDepositThreshold(uint256 threshold) external;

    /**
     * @notice Migrates internal accounting from deprecated exchangeRate to lastTotalAssets.
     * @dev This function can only be called once (reinitializer(2)) and must be called by the factory.
     */
    function migrateInternalAccounting() external;

    /**
     * @notice Returns the metadata and whitelist information of the agreement.
     * @return A tuple containing the [Metadata](../IAgreementInitializer.sol/interface.IAgreementInitializer.html#metadata) and [Whitelist](../IAgreementInitializer.sol/interface.IAgreementInitializer.html#whitelist) structs.
     */
    function info()
        external
        view
        returns (IAgreementInitializer.Metadata memory, IAgreementInitializer.Whitelist memory);

    /**
     * @notice Returns the address of the factory contract for version tracking.
     * @return The address of the factory contract.
     */
    function factory() external view returns (address);
}

contracts/interfaces/agreementV2/IAgreementV2Factory.sol

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

import {
    IAgreementFactoryInitializer
} from "contracts/interfaces/agreement/IAgreementFactoryInitializer.sol";
import {
    IAgreementInitializer,
    IAgreementV2Initializer
} from "contracts/interfaces/agreementV2/IAgreementV2Initializer.sol";

/**
 * @title IAgreementV2Factory
 * @notice Interface for the AgreementV2 Factory, responsible for creating and managing agreements.
 * @dev Inherits from IAgreementFactoryInitializer.
 */
interface IAgreementV2Factory is IAgreementFactoryInitializer {
    /**
     * @notice Emitted when a new agreement is created.
     * @param agreement The address of the newly created agreement.
     */
    event AgreementCreated(address agreement);

    /**
     * @notice Thrown when a provided string does not meet the required length constraints.
     * @dev This error is thrown by `createAgreement()` if the `name` or `symbol` have a length of 0 or exceed 31 characters.
     */
    error InvalidStringLength();

    /**
     * @notice Thrown when attempting to interact with an agreement that does not exist in the agreements mapping.
     * @dev This error is thrown when the provided agreement address is not found in the agreements mapping.
     *      Ensures that only agreements deployed by this factory can be managed through its functions.
     * @param agreement The address of the agreement provided.
     */
    error InvalidAgreement(address agreement);

    /**
     * @notice Creates a new agreement with the specified metadata and whitelist.
     * @param metadata The [Metadata](./IAgreementV2Initializer.sol/interface.IAgreementV2Initializer.html#metadata) struct containing details about the agreement.
     * @param whitelist The [Whitelist](./IAgreementV2Initializer.sol/interface.IAgreementV2Initializer.html#whitelist) struct containing tokens and operators to be whitelisted in the agreement.
     * @param lpTokenMetadata The [LPTokenMetadata](./IAgreementV2Initializer.sol/interface.IAgreementV2Initializer.html#lpTokenMetadata) struct containing metadata for the LP token associated with the agreement.
     * @return agreement The address of the newly created agreement.
     */
    function createAgreement(
        IAgreementInitializer.Metadata calldata metadata,
        IAgreementInitializer.Whitelist calldata whitelist,
        IAgreementV2Initializer.LPTokenMetadata calldata lpTokenMetadata
    ) external returns (address agreement);

    /**
     * @notice Adds collateral tokens to an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param tokens The array of addresses representing the collateral tokens to add.
     */
    function addCollaterals(address agreement, address[] calldata tokens) external;

    /**
     * @notice Adds lenders to an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param lenders The array of addresses representing the lenders to add.
     */
    function addLenders(address agreement, address[] calldata lenders) external;

    /**
     * @notice Adds borrowers to an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param borrowers The array of addresses representing the borrowers to add.
     */
    function addBorrowers(address agreement, address[] calldata borrowers) external;

    /**
     * @notice Adds tokens to the whitelist of an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param tokens The array of addresses representing the tokens to add to the whitelist.
     */
    function addTokens(address agreement, address[] calldata tokens) external;

    /**
     * @notice Adds operators to the whitelist of an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param operators The array of addresses representing the operators to add to the whitelist.
     */
    function addOperators(address agreement, address[] calldata operators) external;

    /**
     * @notice Removes collateral tokens from an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param tokens The array of addresses representing the collateral tokens to remove.
     */
    function removeCollaterals(address agreement, address[] calldata tokens) external;

    /**
     * @notice Removes lenders from an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param lenders The array of addresses representing the lenders to remove.
     */
    function removeLenders(address agreement, address[] calldata lenders) external;

    /**
     * @notice Removes borrowers from an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param borrowers The array of addresses representing the borrowers to remove.
     */
    function removeBorrowers(address agreement, address[] calldata borrowers) external;

    /**
     * @notice Sets the annual percentage yield (APY) for a specific agreement.
     * @dev This function allows updating the APY for the given agreement, influencing the interest calculations for that agreement.
     *      Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement for which the APY is being set.
     * @param apy The new APY value to be set (in basis points, where 10,000 equals 100%).
     */
    function setApy(address agreement, uint32 apy) external;

    /**
     * @notice Sets the threshold on the total deposit for an agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement.
     * @param threshold The new threshold value for the total deposit.
     */
    function setTotalDepositThreshold(address agreement, uint256 threshold) external;

    /**
     * @notice Suspends an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement to be suspended.
     */
    function suspend(address agreement) external;

    /**
     * @notice Unsuspend an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement to unsuspend.
     */
    function unsuspend(address agreement) external;

    /**
     * @notice Close an existing agreement.
     * @dev Reverts with {InvalidAgreement} if the agreement address is not trusted.
     * @param agreement The address of the agreement to close.
     */
    function close(address agreement) external;

    /**
     * @notice Migrates accounting for multiple agreements from exchangeRate to lastTotalAssets model
     * @dev Only callable when factory is paused (during maintenance window)
     * @param agreements Array of agreement addresses to migrate
     */
    function migrateAgreementAccounting(address[] calldata agreements) external;

    /**
     * @notice Returns the role identifier for the Arkis Risk Operator.
     * @dev This role manages permissions related to Arkis Risk Operator's functions.
     *      It allows the address holding this role to:
     *      - Control the state of agreements and margin accounts.
     *      - Trigger automatic and manual liquidations initiated by the Arkis Risk Operator.
     *      - Respond to collected approvals according to predefined policies.
     * @return A bytes32 value representing the ARKIS_RISK_OPERATOR_ROLE.
     */
    /* solhint-disable-next-line func-name-mixedcase */
    function ARKIS_RISK_OPERATOR_ROLE() external view returns (bytes32);

    /**
     * @notice Returns the address of the agreement prototype.
     * @return The address of the ImmutableBeaconProxy agreement prototype.
     */
    function agreementPrototype() external view returns (address);

    /**
     * @notice Returns the address of the compliance contract.
     * @return The address of the compliance contract.
     */
    function compliance() external view returns (address);

    /**
     * @notice Checks if an agreement exists.
     * @param agreement The address of the agreement to check.
     * @return A boolean indicating whether the agreement exists or not.
     */
    function hasAgreement(address agreement) external view returns (bool);
}

contracts/interfaces/agreementV2/IAgreementV2Initializer.sol

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

import {IAgreementInitializer} from "contracts/interfaces/agreement/IAgreementInitializer.sol";

interface IAgreementV2Initializer {
    /**
     * @notice Contains metadata for the LP token associated with the agreement.
     * @param name The name of the LP token.
     * @param symbol The symbol of the LP token.
     */
    struct LPTokenMetadata {
        string name;
        string symbol;
    }

    /**
     * @notice Initializes the agreement with metadata.
     * @param metadata The metadata to initialize the agreement.
     */
    function initialize(
        IAgreementInitializer.Metadata calldata metadata,
        LPTokenMetadata calldata lpTokenMetadata
    ) external;
}

contracts/interfaces/agreementV2/IAgreementV2Staking.sol

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

bytes4 constant LEGACY_AGREEMENT_V2_STAKING_INTERFACE_ID = 0x5eb1b31c;

interface IAgreementV2Staking {
    struct DebtV2 {
        uint192 borrowed;
        uint64 timestamp;
        uint256 interestIndex;
    }

    struct StorageStakingV2 {
        uint192 totalDepositThreshold;
        uint64 lastCheckpoint;
        uint192 utilization;
        uint32 apy;
        bool closed;
        uint256 interestIndex;
        /* solhint-disable-next-line var-name-mixedcase */
        uint256 __gap__exchangeRate;
        mapping(address => DebtV2) debts;
        uint256 lastTotalAssets;
        uint256 totalBadDebt;
    }

    /**
     * @notice Emitted when APY is updated
     * @param oldApy Previous APY value
     * @param newApy New APY value
     */
    event ApyChanged(uint32 oldApy, uint32 newApy);

    /**
     * @notice Emitted when a liquidation occurs but funds are insufficient to fully cover the amount required.
     * @param badDebt The amount that is short to cover the liquidation.
     */
    event BadLiquidation(uint256 badDebt);

    /**
     * @notice Emitted when tokens are borrowed from the agreement.
     * @param borrower The address of the borrower.
     * @param amount The amount of tokens borrowed.
     * @dev Emitted by the [`borrow()`](#borrow) function.
     */
    event Borrowed(address borrower, uint192 amount);

    /**
     * @notice Emitted when the exchange rate is updated.
     * @param interestIndex The new interest index.
     * @param exchangeRate The new exchange rate.
     */
    event Checkpoint(uint256 interestIndex, uint256 exchangeRate);

    /* @notice Emitted when an agreement is closed.
     * @param agreement The address of the agreement that has been closed.
     */
    event Closed(address agreement);

    /**
     * @notice Emitted when a badDebt from a bad liquidation is voluntarily repaid.
     * @param from The address that transferred the recovery funds.
     * @param amount The amount applied against the outstanding badDebt.
     */
    event BadDebtRepaid(address indexed from, uint256 amount);

    /**
     * @notice Emitted when tokens are repaid to the agreement.
     * @param borrower The address of the borrower.
     * @param due The amount of tokens repaid.
     * @dev Emitted by the [`repay()`](#repay) function.
     */
    event Repaid(address borrower, uint256 due);

    /**
     * @notice Emitted when deposit threshold is updated
     * @param newThreshold New maximum deposit limit
     */
    event TotalDepositThresholdUpdated(uint192 newThreshold);

    /**
     * @notice Thrown when an operation is attempted on a closed staking contract.
     * @dev This error is thrown when [`deposit()`](#deposit), [`borrow()`](#borrow) functions are called after the staking contract has been closed.
     */
    error AgreementClosed();

    /**
     * @notice Thrown when attempting to close the agreement while there is outstanding debt.
     * @dev This error is thrown by the [`_close()`](#_close)
     */
    error AgreementHasActiveDebt();

    /**
     * @notice Error indicating withdraw/borrow is not possible due to insufficient liquidity.
     * @dev Thrown by the [`borrow()`](#borrow) function.
     */
    error AmountExceedsPoolBalance();

    /**
     * @notice Error indicating that the provided APY is invalid.
     * @dev Thrown when the APY is set to a value 0% or greater than 999.99%.
     */
    error InvalidApy();

    /**
     * @notice Thrown when the provided repayment amount is insufficient to cover
     * the borrower's debt and when it is not a liquidation.
     * @param required The total amount required to fully repay the debt, including any accrued interest.
     * @param provided The amount of tokens provided for repayment, which was insufficient.
     */
    error InsufficientRepayment(uint256 required, uint256 provided);

    /**
     * @notice Thrown when attempting to recover a badDebt while none is outstanding.
     * @dev Thrown by the [`repayBadDebt()`](#repaybaddebt) function.
     */
    error NoBadDebt();

    /**
     * @notice Error indicating that the user must repay their existing debt before incurring additional debt.
     * @dev Reverts if a borrower attempts to take on new debt without fully repaying their previous outstanding debt.
     */
    error MustRepayPreviousDebtFirst();

    /**
     * @notice Error indicating that the user has no active debt.
     * @param borrower The address of the user attempting to repay.
     */
    error NoActiveDebt(address borrower);

    /**
     * @notice Error thrown when a user is not allowed to borrow.
     * @dev Thrown if the address lacks the [BORROWER_ROLE](#borrower_role).
     * @param user The address of the user attempting to borrow.
     */
    error UserCannotBorrow(address user);

    /* solhint-disable func-name-mixedcase */
    /**
     * @notice Returns the role identifier for the lender.
     * @return A bytes32 value representing the [LENDER_ROLE](#lender_role).
     */
    function LENDER_ROLE() external view returns (bytes32);

    /**
     * @notice Returns the role identifier for the borrower.
     * @return A bytes32 value representing the [BORROWER_ROLE](#borrower_role).
     */
    function BORROWER_ROLE() external view returns (bytes32);

    /* solhint-enable func-name-mixedcase */

    /**
     * @notice Allows the margin engine to update the pool's state by recalculating the interest index and total assets.
     * @dev Updates interestIndex, lastTotalAssets, and lastCheckpoint based on elapsed time and utilization.
     */
    function checkpoint() external; // solhint-disable-line ordering

    /**
     * @notice Allows the margin engine to borrow tokens on behalf of the borrower from the agreement.
     * @dev Throws [UserCannotBorrow](#usercannotborrow) if the address lacks the [LENDER_ROLE](#lender_role).
     * @dev Reverts with a [`AmountExceedsPoolBalance()`](#amountexceedspoolbalance) error if the agreement's token balance is insufficient for the requested amount.
     * @dev Emits a [`Borrowed()`](#borrowed) event upon successful borrowing.
     * @param borrower The address of the borrower on whose behalf tokens are being borrowed.
     * @param amount The amount of tokens to borrow.
     */
    function borrow(address borrower, uint192 amount) external;

    /**
     * @notice Allows the margin engine to repay tokens on behalf of the borrower to the agreement.
     * @dev This function repays the borrower's debt and updates the staking state accordingly.
     * If the `balance` provided is insufficient to fully cover the debt and `isLiquidation` is **true**,
     * then partial repayment will be done and a [`BadLiquidation(uint256 badDebt)`](#badliquidation)
     * event will be emitted.
     * If the `balance` provided is insufficient to fully cover the debt and `isLiquidation` is **false**,
     * then the transaction will be reverted with a custom error
     * [`InsufficientRepayment(uint256 required, uint256 provided)`](#insufficientrepayment).
     * @dev Emits a [`Repaid(uint256 amount)`](#repaid) event with actual amount of token transferred.
     * @param borrower The address of the borrower whose debt is being repaid.
     * @param balance The amount of tokens provided for repayment, leverage.balanceOf(dispatcher) at the moment.
     * @param isLiquidation A boolean indicating whether this repayment is part of a liquidation process.
     * If true and the balance is insufficient, a partial repayment (bad liquidation) occur.
     */
    function repay(address borrower, uint256 balance, bool isLiquidation) external;

    /**
     * @notice Returns the debt balance owed by a specific borrower in the staking contract.
     * @param borrower The address of the borrower.
     * @return debtBalance The debt balance of the borrower.
     */
    function debtBalanceOf(address borrower) external view returns (uint256);

    /**
     * @notice Verifies if a user can borrow from the agreement.
     * @dev Throws [UserCannotBorrow](#usercannotborrow) if the address lacks the [BORROWER_ROLE](#borrower_role).
     * @param user The address of the user to verify.
     */
    function enforceCanBorrow(address user) external view;

    /**
     * @notice Returns current exchange rate between LP tokens and underlying assets
     * @return exchangeRate Exchange rate as fixed-point number
     */
    function exchangeRate() external view returns (uint256);

    /**
     * @notice Returns the pending interest accrued by a borrower.
     * @param borrower The address of the borrower whose pending interest is being queried.
     * @return The amount of interest accrued by the borrower.
     */
    function pendingInterest(address borrower) external view returns (uint256);

    /**
     * @notice Returns the total amount of tokens currently borrowed from the agreement.
     * @return The total amount of borrowed tokens.
     */
    function totalBorrowed() external view returns (uint256);

    /**
     * @notice Returns the outstanding badDebt left by bad liquidations, net of recoveries.
     * @return The amount of bad debt still to be recovered.
     */
    function totalBadDebt() external view returns (uint256);

    /**
     * @notice Voluntarily repays the full outstanding badDebt from a bad liquidation.
     * @dev Permissionless. Pulls the entire outstanding badDebt from the caller, credits it back
     * to total assets so the LP token price recovers and zeroes the badDebt. There is no partial
     * recovery: the amount is fixed at the booked loss so the LP price cannot be pushed past it.
     * @dev Reverts [`NoBadDebt()`](#nobaddebt) when there is nothing to recover.
     * @dev Emits a [`BadDebtRepaid()`](#baddebtrepaid) event.
     */
    function repayBadDebt() external;
}

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/ISuspendable.sol

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

interface ISuspendable {
    function suspend() external;

    function unsuspend() external;

    function close() external;

    function suspended() external view returns (bool);

    function closed() external view returns (bool);
}

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/Command.sol

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

import {CommandLibrary} from "contracts/libraries/CommandLibrary.sol";

/**
 * @title Command
 * @notice Contains arguments for a low-level call.
 * @dev This struct allows deferring the call's execution, suspending it by passing it to another function or contract.
 * @dev `target` The address to be called.
 * @dev `value` Value to send in the call.
 * @dev `payload` Encoded call with function selector and arguments.
 */
struct Command {
    address target;
    uint256 value;
    bytes payload;
}

using CommandLibrary for Command global;

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/libraries/CommandLibrary.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Command} from "contracts/interfaces/compiler/Command.sol";
import {SafeCall} from "contracts/libraries/SafeCall.sol";

/**
 * @notice Utility to convert often-used methods into a Command object
 */
library CommandPresets {
    function approve(
        address _token,
        address _to,
        uint256 _amount
    ) internal pure returns (Command[] memory result_) {
        result_ = new Command[](2);
        result_[0] = Command(_token, 0, abi.encodeCall(IERC20.approve, (_to, 0)));
        result_[1] = Command(_token, 0, abi.encodeCall(IERC20.approve, (_to, _amount)));
    }

    function transfer(
        address _token,
        address _to,
        uint256 _amount
    ) internal pure returns (Command memory cmd_) {
        cmd_.target = _token;
        cmd_.payload = abi.encodeCall(IERC20.transfer, (_to, _amount));
    }
}

library CommandExecutor {
    using SafeCall for Command[];

    function execute(Command[] calldata _cmds) external {
        _cmds.safeCallAll();
    }
}

library CommandLibrary {
    using CommandLibrary for Command[];

    function last(Command[] memory _self) internal pure returns (Command memory) {
        return _self[_self.length - 1];
    }

    function asArray(Command memory _self) internal pure returns (Command[] memory result_) {
        result_ = new Command[](1);
        result_[0] = _self;
    }

    function append(
        Command[] memory _self,
        Command[] memory _cmds
    ) internal pure returns (Command[] memory result_) {
        result_ = new Command[](_self.length + _cmds.length);
        uint256 i;
        for (; i < _self.length; i++) {
            result_[i] = _self[i];
        }
        for (; i < result_.length; i++) {
            result_[i] = _cmds[i - _self.length];
        }
    }

    function push(
        Command[] memory _self,
        Command memory _cmd
    ) internal pure returns (Command[] memory result_) {
        result_ = new Command[](_self.length + 1);
        for (uint256 i; i < _self.length; i++) {
            result_[i] = _self[i];
        }
        result_[_self.length] = _cmd;
    }

    function populateWithApprove(
        Command memory _self,
        address _token,
        uint256 _amount
    ) internal pure returns (Command[] memory result_) {
        if (_amount != 0) {
            result_ = CommandPresets.approve(_token, _self.target, _amount).push(_self);
        } else {
            result_ = _self.asArray();
        }
    }
}

contracts/libraries/SafeCall.sol

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

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

/**
 * @notice Safe methods performing a low-level calls that revert
 * if the call was not successful
 */
library SafeCall {
    using Address for address;

    function safeCallAll(Command[] memory _cmds) internal {
        for (uint256 i; i < _cmds.length; i++) {
            safeCall(_cmds[i]);
        }
    }

    function safeCall(Command memory _cmd) internal returns (bytes memory result_) {
        result_ = safeCall(_cmd.target, _cmd.value, _cmd.payload);
    }

    function safeCall(address _target, bytes memory _data) internal returns (bytes memory result_) {
        result_ = safeCall(_target, 0, _data);
    }

    function safeCall(
        address _target,
        uint256 _value,
        bytes memory _data
    ) internal returns (bytes memory result_) {
        result_ = _target.functionCallWithValue(_data, _value);
    }

    function safeDelegateCall(
        address _target,
        bytes memory _data
    ) internal returns (bytes memory result_) {
        result_ = _target.functionDelegateCall(_data);
    }
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 1000000,
    "details": {
      "yulDetails": {
        "optimizerSteps": "u"
      }
    },
    "enabled": true
  },
  "evmVersion": "paris"
}

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

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