Skip to content
Verified contractExactBUSL-1.1

Agreement

Address0xea28fd9f97a3f75c5eba1b7a48d020364b6719d8
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.22

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.22+commit.4fc1097e
Language
solidity
Optimization
Yes, 1,000,000 runs
EVM version
paris
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,391,853
Creation transaction
0x1e25952076…f857486015

44 files

contracts/agreement/Agreement.sol

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

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

import {IAgreement} from "contracts/interfaces/agreement/IAgreement.sol";
import {IAgreementFactory} from "contracts/interfaces/agreement/IAgreementFactory.sol";
import {AddressMustNotBeZero, AlreadyUpToDate} from "contracts/interfaces/base/CommonErrors.sol";
import {UnauthorizedAccount} from "contracts/interfaces/base/CommonErrors.sol";
import {
    IWhitelistingControllerAgreement
} from "contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol";

import {
    AgreementStaking,
    IAgreementStaking,
    IERC165,
    IERC165Extended,
    UnsupportedInterface
} from "./AgreementStaking.sol";

contract Agreement is IAgreement, AgreementStaking {
    using EnumerableSet for EnumerableSet.AddressSet;

    struct Storage {
        EnumerableSet.AddressSet collaterals;
    }

    // keccak256("Agreement storage slot V2")
    bytes32 internal constant STORAGE_SLOT =
        0xb5f4cc5a7cd363b5ed55ea1894fa138a4c87922a34ad0abe96a5a482e3110681;

    address internal immutable compliance;
    address public immutable override factory;

    modifier onlyFactory() {
        if (msg.sender != factory) revert UnauthorizedAccount(msg.sender);
        _;
    }

    constructor(
        address _factory,
        address _compliance,
        address _dispatcher,
        address _liquidator
    ) AgreementStaking(_dispatcher, _liquidator) {
        if (!IERC165(_factory).supportsInterface(type(IAgreementFactory).interfaceId))
            revert UnsupportedInterface(_factory);
        if (
            !IERC165Extended(_compliance).supportsInterfaceExtended(
                type(IWhitelistingControllerAgreement).interfaceId
            )
        ) revert UnsupportedInterface(_compliance);
        factory = _factory;
        compliance = _compliance;
    }

    function initialize(Metadata calldata metadata) external override initializer {
        __Staking_init(metadata.leverage, metadata.totalDepositThreshold, metadata.apy);

        _grantRole(DEFAULT_ADMIN_ROLE, factory);
        addCollaterals(metadata.collaterals);
        addLenders(metadata.lenders);
        addBorrowers(metadata.borrowers);
        emit Initialized(metadata.leverage);
    }

    function addCollaterals(address[] calldata tokens) public override onlyFactory {
        Storage storage $ = _storage();
        for (uint256 i = 0; i < tokens.length; i++) {
            if (tokens[i] == address(0)) revert AddressMustNotBeZero();
            if ($.collaterals.add(tokens[i])) emit CollateralAdded(tokens[i]);
            else revert AlreadyUpToDate();
        }
    }

    function addLenders(address[] calldata lenders) public override onlyFactory {
        for (uint256 i = 0; i < lenders.length; i++) {
            if (lenders[i] == address(0)) revert AddressMustNotBeZero();
            if (_grantRole(LENDER_ROLE, lenders[i])) emit LenderAdded(lenders[i]);
            else revert AlreadyUpToDate();
        }
    }

    function addBorrowers(address[] calldata borrowers) public override onlyFactory {
        for (uint256 i = 0; i < borrowers.length; i++) {
            if (borrowers[i] == address(0)) revert AddressMustNotBeZero();
            if (_grantRole(BORROWER_ROLE, borrowers[i])) emit BorrowerAdded(borrowers[i]);
            else revert AlreadyUpToDate();
        }
    }

    /* solhint-disable ordering */
    function removeCollaterals(address[] calldata tokens) external override onlyFactory {
        Storage storage $ = _storage();
        for (uint256 i = 0; i < tokens.length; i++) {
            if (tokens[i] == address(0)) revert AddressMustNotBeZero();
            if ($.collaterals.remove(tokens[i])) emit CollateralRemoved(tokens[i]);
            else revert AlreadyUpToDate();
        }
    }

    function removeLenders(address[] calldata lenders) external override onlyFactory {
        for (uint256 i = 0; i < lenders.length; i++) {
            if (lenders[i] == address(0)) revert AddressMustNotBeZero();
            if (_revokeRole(LENDER_ROLE, lenders[i])) emit LenderRemoved(lenders[i]);
            else revert AlreadyUpToDate();
        }
    }

    function removeBorrowers(address[] calldata borrowers) external override onlyFactory {
        for (uint256 i = 0; i < borrowers.length; i++) {
            if (borrowers[i] == address(0)) revert AddressMustNotBeZero();
            if (_revokeRole(BORROWER_ROLE, borrowers[i])) emit BorrowerRemoved(borrowers[i]);
            else revert AlreadyUpToDate();
        }
    }

    function setApy(uint32 apy) external override onlyFactory {
        _setApy(apy);
    }

    function setTotalDepositThreshold(uint256 threshold) external override onlyFactory {
        _setTotalDepositThreshold(threshold);
    }

    function suspend() external override onlyFactory {
        _pause();
    }

    function unsuspend() external override onlyFactory {
        _unpause();
    }

    function close() external override onlyFactory {
        _close();
    }

    /* solhint-enable ordering */

    function info()
        external
        view
        override
        returns (Metadata memory metadata, Whitelist memory whitelist)
    {
        Storage storage $ = _storage();
        (metadata.leverage, metadata.totalDepositThreshold, metadata.apy) = _info();
        metadata.collaterals = $.collaterals.values();
        metadata.lenders = _getRoleMembers(LENDER_ROLE);
        metadata.borrowers = _getRoleMembers(BORROWER_ROLE);
        IWhitelistingControllerAgreement wc = IWhitelistingControllerAgreement(compliance);
        whitelist = Whitelist(wc.getTokens(address(this)), wc.getOperators(address(this)));
        return (metadata, whitelist);
    }

    function closed() external view override returns (bool) {
        return _closed();
    }

    function suspended() external view override returns (bool) {
        return paused();
    }

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

    function _getRoleMembers(bytes32 role) private view returns (address[] memory members) {
        uint256 membersCount = getRoleMemberCount(role);
        members = new address[](membersCount);
        for (uint256 i = 0; i < membersCount; i++) {
            members[i] = getRoleMember(role, i);
        }
    }

    function _storage() private 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/extensions/AccessControlEnumerableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

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

    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControlEnumerable
    struct AccessControlEnumerableStorage {
        mapping(bytes32 role => EnumerableSet.AddressSet) _roleMembers;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlEnumerable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlEnumerableStorageLocation = 0xc1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e82371705932000;

    function _getAccessControlEnumerableStorage() private pure returns (AccessControlEnumerableStorage storage $) {
        assembly {
            $.slot := AccessControlEnumerableStorageLocation
        }
    }

    function __AccessControlEnumerable_init() internal onlyInitializing {
    }

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

@openzeppelin/contracts/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/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

contracts/agreement/AgreementStaking.sol

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

import {
    AccessControlEnumerableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
import {
    PausableUpgradeable
} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";

import {
    IAgreementStaking,
    IERC20,
    SafeERC20
} from "contracts/interfaces/agreement/IAgreementStaking.sol";
import {AlreadyUpToDate, UnauthorizedAccount} from "contracts/interfaces/base/CommonErrors.sol";
/* solhint-disable no-unused-import */
import {
    IERC165,
    IERC165Extended,
    UnsupportedInterface
} from "contracts/interfaces/base/IERC165Extended.sol";
/* solhint-enable no-unused-import */
import {LEGACY_DISPATCHER_INTERFACE_ID} from "contracts/interfaces/dispatcher/IDispatcher.sol";
import {ILiquidator} from "contracts/interfaces/liquidator/ILiquidator.sol";

abstract contract AgreementStaking is
    IAgreementStaking,
    AccessControlEnumerableUpgradeable,
    PausableUpgradeable
{
    using SafeERC20 for IERC20;

    uint256 private constant APY_DENOMINATOR = 10000;
    uint256 private constant TPS_DENOMINATOR = 1e20;
    uint256 private constant YEARLY_APY_DENOMINATOR = APY_DENOMINATOR * 365 days;

    // keccak256("Staking storage slot V1")
    bytes32 internal constant STORAGE_STAKING_SLOT =
        0x5204fd2fac2c0345365db838dc8fa2af114ff467bf5dfbe08be28a357503b509;

    bytes32 public constant override LENDER_ROLE = keccak256("Agreement Lender Role");
    bytes32 public constant override BORROWER_ROLE = keccak256("Agreement Borrower Role");

    address internal immutable dispatcher;
    address internal immutable liquidator;

    modifier onlyDispatcher() {
        if (msg.sender != dispatcher) revert UnauthorizedAccount(msg.sender);
        _;
    }

    modifier onlyDispatcherOrLiquidator(bool isLiquidation) {
        if (isLiquidation) {
            if (msg.sender != liquidator) revert UnauthorizedAccount(msg.sender);
        } else {
            if (msg.sender != dispatcher) revert UnauthorizedAccount(msg.sender);
        }
        _;
    }

    constructor(address _dispatcher, address _liquidator) {
        if (!IERC165Extended(_dispatcher).supportsInterfaceExtended(LEGACY_DISPATCHER_INTERFACE_ID))
            revert UnsupportedInterface(_dispatcher);
        if (!IERC165Extended(_liquidator).supportsInterfaceExtended(type(ILiquidator).interfaceId))
            revert UnsupportedInterface(_liquidator);
        dispatcher = _dispatcher;
        liquidator = _liquidator;
    }

    /* solhint-disable-next-line func-name-mixedcase */
    function __Staking_init(
        address token,
        uint256 threshold,
        uint32 apy
    ) internal onlyInitializing {
        __Pausable_init();
        StorageStaking storage $ = _storageStaking();
        _setApy($, apy);
        $.token = IERC20(token);
        if (threshold > 0) $.totalDepositThreshold = threshold;
    }

    /* solhint-disable-next-line ordering */
    function deposit(uint128 amount) external override whenNotPaused onlyRole(LENDER_ROLE) {
        StorageStaking storage $ = _storageStaking();
        _requireNotClosed($);
        if (amount + $.totalDeposited > $.totalDepositThreshold) {
            revert TotalDepositThresholdExceeded();
        }
        _checkpoint($, msg.sender);
        $.token.safeTransferFrom(msg.sender, address(this), amount);
        $.users[msg.sender].balance += amount;
        $.totalDeposited += amount;
        emit Deposited(msg.sender, amount);
    }

    function withdraw(uint128 amount) external override whenNotPaused {
        StorageStaking storage $ = _storageStaking();
        if (amount > $.users[msg.sender].balance) {
            revert WithdrawAmountExceedsBalance();
        }
        // `_checkpoint` will be called in `_claim` method
        _claim($);

        // We adjust withdraw amount for cases where expected accrued
        // rewards are less than actual pending rewards due to several
        // blocks mined after the function call was constructed.
        //
        // In future versions new withdrawal options will be introduced.
        uint256 poolBalance = $.token.balanceOf(address(this));
        if (uint256(amount) > poolBalance) {
            amount = uint128(poolBalance);
        }

        $.users[msg.sender].balance -= amount;
        $.totalDeposited -= amount;
        emit Withdrawn(msg.sender, amount);
        _safeTransfer($, msg.sender, amount);
    }

    function claim() external override {
        _claim(_storageStaking());
    }

    function borrow(
        address borrower,
        uint192 amount
    ) external override whenNotPaused onlyDispatcher {
        StorageStaking storage $ = _storageStaking();
        _requireNotClosed($);
        _checkpoint($);
        if ($.debts[borrower].timestamp != 0) revert MustRepayPreviousDebtFirst();
        /* solhint-disable-next-line not-rely-on-time */
        $.debts[borrower] = Debt(uint128(amount), uint64(block.timestamp));
        $.utilization += amount;
        _safeTransfer($, msg.sender, amount);
        emit Borrowed(amount);
    }

    function repay(
        address borrower,
        uint256 balance,
        bool isLiquidation
    ) external override onlyDispatcherOrLiquidator(isLiquidation) {
        StorageStaking storage $ = _storageStaking();
        uint256 borrowed = $.debts[borrower].borrowed;
        uint256 due = borrowed + _pendingInterest($, borrower);

        if (balance < due) {
            if (isLiquidation) {
                emit BadLiquidation(due - balance);
                due = balance;
            } else {
                revert InsufficientRepayment(due, balance);
            }
        }
        _checkpoint($);
        $.utilization -= borrowed;
        delete $.debts[borrower];
        $.token.safeTransferFrom(msg.sender, address(this), due);
        emit Repaid(due);
    }

    function enforceCanBorrow(address user) external view override whenNotPaused {
        _requireNotClosed(_storageStaking());
        if (!hasRole(BORROWER_ROLE, user)) revert UserCannotBorrow(user);
    }

    function pendingInterest(address borrower) external view override returns (uint256) {
        return _pendingInterest(_storageStaking(), borrower);
    }

    function pendingRewards(address lender) external view override returns (uint128) {
        StorageStaking storage $ = _storageStaking();
        return _pendingRewards($, lender, _pendingTPS($));
    }

    function balanceOf(address lender) external view override returns (uint256) {
        return _storageStaking().users[lender].balance;
    }

    function debtBalanceOf(address borrower) external view override returns (uint256) {
        return _storageStaking().debts[borrower].borrowed;
    }

    function interestDue() external view override returns (uint256) {
        StorageStaking storage $ = _storageStaking();
        return ((_pendingTPS($) - $.tps) * $.totalDeposited) / TPS_DENOMINATOR;
    }

    function leverage() external view override returns (address) {
        return address(_storageStaking().token);
    }

    function totalBorrowed() external view override returns (uint256) {
        return _storageStaking().utilization;
    }

    function totalDeposited() external view override returns (uint256) {
        return _storageStaking().totalDeposited;
    }

    function _closed() internal view returns (bool) {
        return _storageStaking().closed;
    }

    function _info() internal view returns (address, uint256, uint32) {
        StorageStaking storage $ = _storageStaking();
        return (address($.token), $.totalDepositThreshold, $.apy);
    }

    function _requireNotClosed(StorageStaking storage $) internal view {
        if ($.closed) revert AgreementClosed();
    }

    function _setApy(uint32 apy) internal {
        _setApy(_storageStaking(), apy);
    }

    function _setTotalDepositThreshold(uint256 threshold) internal {
        _storageStaking().totalDepositThreshold = threshold;
    }

    function _claim(StorageStaking storage $) private {
        _checkpoint($, msg.sender);
        User storage user = $.users[msg.sender];
        uint128 amount = user.rewards;

        // We allow user to get portion of the interest.
        uint256 poolBalance = $.token.balanceOf(address(this));
        if (amount > poolBalance) {
            amount = uint128(poolBalance);
        }

        if (amount > 0) {
            user.rewards -= amount;
            _safeTransfer($, msg.sender, amount);
            emit Claimed(msg.sender, amount);
        }
    }

    function _checkpoint(StorageStaking storage $) private {
        $.tps = _pendingTPS($);
        /* solhint-disable-next-line not-rely-on-time */
        $.lastCheckpoint = uint64(block.timestamp);
    }

    function _checkpoint(StorageStaking storage $, address _user) private {
        _checkpoint($);
        User storage user = $.users[_user];
        user.rewards = _pendingRewards($, _user, $.tps);
        user.tps = $.tps;
    }

    function _close() internal {
        StorageStaking storage $ = _storageStaking();
        if ($.utilization > 0) {
            revert AgreementHasActiveDebt();
        }
        if ($.closed) revert AlreadyUpToDate();
        $.closed = true;
        emit Closed(address(this));
    }

    function _pendingTPS(StorageStaking storage $) private view returns (uint256) {
        if ($.totalDeposited == 0) return $.tps;
        /* solhint-disable-next-line not-rely-on-time */
        uint256 secondsPassed = block.timestamp - $.lastCheckpoint;

        // We need double rounding here to avoid situations where borrowers repay less
        // than we due to lenders. With division in formulas a surplus is unavoidable,
        // but it has to be in favor of the pool and not the lender because in latter
        // case we simply cannot pay off.
        uint256 r1 = ($.apy * secondsPassed * $.utilization) / YEARLY_APY_DENOMINATOR;
        uint256 r2 = (r1 * TPS_DENOMINATOR) / $.totalDeposited;

        return $.tps + r2;
    }

    function _pendingInterest(
        StorageStaking storage $,
        address borrower
    ) private view returns (uint256) {
        Debt storage debt = $.debts[borrower];
        /* solhint-disable-next-line not-rely-on-time */
        uint256 secondsPassed = block.timestamp - debt.timestamp;
        return (debt.borrowed * secondsPassed * $.apy) / YEARLY_APY_DENOMINATOR;
    }

    function _pendingRewards(
        StorageStaking storage $,
        address _user,
        uint256 tps
    ) private view returns (uint128) {
        User storage user = $.users[_user];
        return user.rewards + uint128(((tps - user.tps) * user.balance) / TPS_DENOMINATOR);
    }

    function _safeTransfer(StorageStaking storage $, address to, uint256 amount) private {
        if (amount > $.token.balanceOf(address(this))) {
            revert WithdrawalIsNotPossibleNow();
        }
        $.token.safeTransfer(to, amount);
    }

    function _setApy(StorageStaking storage $, uint32 apy) private {
        if ($.utilization > 0) revert ActiveLoans();
        if ($.apy == apy) revert AlreadyUpToDate();
        emit ApyChanged($.apy, apy);
        $.apy = apy;
    }

    function _storageStaking() private pure returns (StorageStaking storage $) {
        assembly {
            $.slot := STORAGE_STAKING_SLOT
        }
    }
}

contracts/dispatcher/libraries/EnvelopeRunner.sol

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

import {IJitCompiler, Script} from "contracts/interfaces/compiler/IJitCompiler.sol";
import {CrossChainActionIsForbidden, Envelope} from "contracts/interfaces/dispatcher/Envelope.sol";
import {Command, CommandExecutor} from "contracts/libraries/CommandLibrary.sol";

library EnvelopeRunner {
    using CommandExecutor for Command[];

    /**
     * @dev This error should never happen, it is needed
     * for preventing underestimation on "eth_estimateGas".
     */
    error OutOfGas();

    function run(
        Envelope[] calldata self,
        address jitCompiler,
        bytes32 chainNameHash
    ) internal returns (uint256 numberOfFailures) {
        for (uint256 i; i < self.length; i++) {
            numberOfFailures += self[i].run(jitCompiler, chainNameHash) ? 0 : 1;
        }
    }

    function run(
        Envelope calldata self,
        address jitCompiler,
        bytes32 chainNameHash
    ) internal returns (bool success) {
        IJitCompiler compiler = IJitCompiler(jitCompiler);

        if (!self.isChainEq(chainNameHash)) {
            revert CrossChainActionIsForbidden();
        }

        for (uint256 i; i < self.content.length; i++) {
            if (!run(compiler, self.content[i])) return success = false;
        }

        return success = true;
    }

    function isChainEq(Envelope calldata self, bytes32 chainNameHash) internal pure returns (bool) {
        return keccak256(bytes(self.route.destination)) == chainNameHash;
    }

    function run(IJitCompiler compiler, Script calldata script) private returns (bool success) {
        Command[] memory cmds = compiler.compile(script);
        if (script.canFail) {
            uint256 gasBefore = gasleft();
            /* solhint-disable-next-line no-empty-blocks */
            try cmds.execute() {} catch {
                // NOTE: Since we allow silent fail here, this revert is
                // required to prevent the underestimation of gas in the
                // context of EIP-150. The "all but one 64th" rule, along
                // with the way most clients estimate gas, may produce an
                // out-of-gas error at the callee contract but success at
                // the caller contract. For example, if we have a single
                // instruction to execute, and after executing this
                // instruction, the remaining work will consume 5000 gas,
                // the instruction will only receive at most 5000*63 gas.
                // Therefore, if the actual requirements are higher, it
                // will fail at the random opcode. The remaining work
                // will be finished (since we still have at least 5000*1
                // gas), and overall transaction success will be achieved,
                // making the gas estimator happy.
                //
                // The proportion for comparing the gasleft (to check that
                // the call has not consumed all the gas passed) is in practice
                // 1 to 16-32, but we take twice as much just in case.
                if (gasleft() < gasBefore / 8) revert OutOfGas();
                return false;
            }
        } else {
            cmds.execute();
        }

        return true;
    }
}

contracts/dispatcher/libraries/PackageRunner.sol

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

import {Package} from "contracts/interfaces/dispatcher/Package.sol";
import {Command, SafeCall} from "contracts/libraries/SafeCall.sol";
import {CrossChainActionIsForbidden, Envelope, EnvelopeRunner} from "./EnvelopeRunner.sol";

library PackageRunner {
    using SafeCall for Command[];
    using EnvelopeRunner for Envelope[];

    function run(
        Package calldata self,
        address compiler,
        bytes32 chainNameHash
    ) internal returns (uint256 numberOfFailures) {
        if (self.action.isChainEq(chainNameHash)) {
            bool actionSuccess = self.action.run(compiler, chainNameHash);
            if (actionSuccess) {
                numberOfFailures += self.onComplete.run(compiler, chainNameHash);
            } else {
                numberOfFailures++;
            }
        } else {
            revert CrossChainActionIsForbidden();
        }
    }
}

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

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

import {IAgreementFactoryInitializer} from "./IAgreementFactoryInitializer.sol";
import {IAgreementInitializer} from "./IAgreementInitializer.sol";

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

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

    /**
     * @notice Adds collateral tokens to an existing agreement.
     * @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.
     * @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.
     * @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.
     * @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.
     * @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.
     * @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.
     * @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.
     * @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.
     * @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.
     * @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.
     * @param agreement The address of the agreement to be suspended.
     */
    function suspend(address agreement) external;

    /**
     * @notice Unsuspend an existing agreement.
     * @param agreement The address of the agreement to unsuspend.
     */
    function unsuspend(address agreement) external;

    /**
     * @notice Close an existing agreement.
     * @param agreement The address of the agreement to close.
     */
    function close(address agreement) 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);
}

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/agreement/IAgreementStaking.sol

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

/* solhint-disable-next-line no-unused-import */
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/**
 * @title IAgreementStaking
 * @notice Interface for staking operations within an agreement, including deposit, withdrawal, and rewards management.
 */
interface IAgreementStaking {
    struct User {
        uint128 balance;
        uint128 rewards;
        uint256 tps;
    }

    struct Debt {
        uint192 borrowed;
        uint64 timestamp;
    }

    struct StorageStaking {
        IERC20 token;
        uint64 lastCheckpoint;
        uint32 apy;
        uint256 tps;
        uint256 utilization;
        uint256 totalDeposited;
        uint256 totalDepositThreshold;
        mapping(address => User) users;
        mapping(address => Debt) debts;
        bool closed;
    }

    /**
     * @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 shortfall The amount that is short to cover the liquidation.
     */
    event BadLiquidation(uint256 shortfall);

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

    /**
     * @notice Emitted when rewards are claimed.
     * @param recipient The address of the recipient claiming rewards.
     * @param amount The amount of rewards claimed.
     * @dev Emitted by the [`claim()`](#claim) function.
     */
    event Claimed(address indexed recipient, uint256 amount);

    /* @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 tokens are deposited into the staking contract.
     * @param depositor The address of the depositor.
     * @param amount The amount of tokens deposited.
     * @dev Emitted by the [`deposit()`](#deposit) function.
     */
    event Deposited(address indexed depositor, uint256 amount);

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

    /**
     * @notice Emitted when tokens are withdrawn from the staking contract.
     * @param recipient The address of the recipient.
     * @param amount The amount of tokens withdrawn.
     * @dev Emitted by the [`withdraw()`](#withdraw) function.
     */
    event Withdrawn(address indexed recipient, uint256 amount);

    /**
     * @notice Thrown when there are active loans on setApy().
     * */
    error ActiveLoans();

    /**
     * @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 OR a deposit/mint attempt occurs while there is outstanding debt
     * @dev This error is thrown by the [`_close()`](#_close), [`mint()`](#borrow), [`deposit()`](#deposit) functions
     */
    error AgreementHasActiveDebt();

    /**
     * @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 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 total deposit threshold has been exceeded.
     * @dev Thrown by the [`deposit()`](#deposit) function.
     */
    error TotalDepositThresholdExceeded();

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

    /**
     * @notice Error indicating that the requested withdrawal amount exceeds the user's balance.
     * @dev Thrown by the [`withdraw()`](#withdraw) function.
     */
    error WithdrawAmountExceedsBalance();

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

    /**
     * @notice Allows whitelisted addresses to deposit tokens into the staking contract.
     * @dev Throws a [`TotalDepositThresholdExceeded()`](#totaldepositthresholdexceeded) error if the deposit exceeds the maximum allowed total.
     * @dev Emits a [`Deposited()`](#deposited) event upon successful deposit.
     * @param amount The amount of tokens to deposit.
     */
    function deposit(uint128 amount) external;

    /**
     * @notice Allows users to withdraw tokens from the staking contract.
     * @dev Throws a [`WithdrawAmountExceedsBalance()`](#withdrawamountexceedsbalance) error if the user’s balance is insufficient.
     * @dev Emits a [`Withdrawn()`](#withdrawn) event upon successful withdrawal.
     * @param amount The amount of tokens to withdraw. This amount will be adjusted
     * by taking pool's balance into account as the rewards will be claimed automatically.
     */
    function withdraw(uint128 amount) external;

    /**
     * @notice Allows users to claim their pending rewards.
     * @dev Throws a [`NoPendingRewards()`](#nopendingrewards) error if no rewards are available (see [`pendingRewards()`](#pendingrewards)).
     * @dev Emits a [`Claimed()`](#claimed) event upon successful claim.
     */
    function claim() external;

    /**
     * @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 [`WithdrawalIsNotPossibleNow()`](#withdrawalisnotpossiblenow) 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 shortfall)`](#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;

    /* 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 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 the balance of underlying tokens owned by a specific user in the staking contract.
     * @param lender The address of the user.
     * @return balance The user's underlying token balance.
     */
    function balanceOf(address lender) external view returns (uint256 balance);

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

    /**
     * @notice Returns the total interest due across all deposits in the agreement.
     * @dev Uses the difference between the current and stored token-per-share (TPS) values to compute the interest.
     * @return The total amount of interest due.
     */
    function interestDue() external view returns (uint256);

    /**
     * @notice Returns the leverage token used in the agreement.
     * @return The leverage token address.
     */
    function leverage() external view returns (address);

    /**
     * @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 pending rewards for a given user.
     * @param lender The address of the user.
     * @return rewards The amount of tokens the user can claim.
     */
    function pendingRewards(address lender) external view returns (uint128 rewards);

    /**
     * @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 total amount of tokens currently deposited in the agreement.
     * @dev A portion of this may be allocated as leverage for margin accounts.
     * @return The total amount of deposited tokens.
     */
    function totalDeposited() external view returns (uint256);
}

contracts/interfaces/base/CommonErrors.sol

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

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

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

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

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

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

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

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

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

contracts/interfaces/base/IERC165Extended.sol

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

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

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

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

contracts/interfaces/base/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/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/compiler/IJitCompiler.sol

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

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

import {IDecreasePositionEvaluator} from "./adapters/IDecreasePositionEvaluator.sol";
import {IExchangeEvaluator} from "./adapters/IExchangeEvaluator.sol";
import {IIncreasePositionEvaluator} from "./adapters/IIncreasePositionEvaluator.sol";
import {Command} from "./Command.sol";
import {Script} from "./Script.sol";

/**
 * @title IJitCompiler
 * @notice Compiles a script or an instruction into an array of [Commands](/interfaces/compiler/Command.sol/struct.Command.html) using protocol evaluator matching `protocol` field in the underlying instruction.
 */
interface IJitCompiler is IERC165Extended {
    /**
     * @notice Instruction designed to increase:
     *  1. Caller's magnitude of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
     *  2. Callee's balance of token(s).
     * @notice and decrease:
     *  1. Caller's balance of token(s).
     *  2. (*Optional*) callee's supply of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
     * @dev This instruction will be evaluated in [IncreasePositionEvaluator](../adapters/IIncreasePositionEvaluator.sol/interface.IIncreasePositionEvaluator.html).
     * @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
     * @dev `request` The [`IncreasePositionRequest`](../adapters/IIncreasePositionEvaluator.sol/interface.IIncreasePositionEvaluator.html#increasepositionrequest) containing all information required for instruction evaluation.
     */
    struct IncreasePositionInstruction {
        string protocol;
        IIncreasePositionEvaluator.IncreasePositionRequest request;
    }

    /**
     * @notice Instruction designed to increase:
     *  1. Caller's balance of token(s).
     *  2. (*Optional*) callee's supply of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
     * @notice and decrease:
     *  1. Caller's magnitude of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
     *  2. Callee's balance of token(s).
     * @dev This instruction will be evaluated in [DecreasePositionEvaluator](../adapters/IDecreasePositionEvaluator.sol/interface.IDecreasePositionEvaluator.html).
     * @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
     * @dev `request` The [`DecreasePositionRequest`](../adapters/IDecreasePositionEvaluator.sol/interface.IDecreasePositionEvaluator.html#decreasepositionrequest) containing all information required for instruction evaluation.
     */
    struct DecreasePositionInstruction {
        string protocol;
        IDecreasePositionEvaluator.DecreasePositionRequest request;
    }

    /**
     * @notice Instruction designed to increase:
     *  1. (*Optional*) caller's balance of output token.
     *  2. Callee's balance of input token.
     * @notice and decrease:
     *  1. Caller's balance of input token.
     *  2. (*Optional*) callee's balance of output token.
     * @dev This instruction will be evaluated in [ExchangeEvaluator](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html).
     * @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
     * @dev `request` The [`ExchangeRequest`](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html#exchangerequest) containing all information required for instruction evaluation.
     */
    struct ExchangeInstruction {
        string protocol;
        IExchangeEvaluator.ExchangeRequest request;
    }

    /**
     * @notice Instruction designed to increase:
     *  1. (*Optional*) caller's balance of output token.
     *  2. Callee's balance of input token.
     * @notice and decrease:
     *  1. Caller's balance of input token.
     *  2. (*Optional*) callee's balance of output token.
     * @dev This instruction will be evaluated in [ExchangeEvaluator](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html).
     * @dev **Important note:** this instruction has an identical structure to [ExchangeInstruction](#exchangeinstruction), but differs from it in that [ExchangeInstruction](#exchangeinstruction) is static and [ExchangeAllInstruction](#exchangeallinstruction) is dynamic. This means that the `amountIn` field will be set at runtime by the compiler to the caller's balance by the input token.
     * @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
     * @dev `request` The [`ExchangeRequest`](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html#exchangerequest) containing all information required for instruction evaluation. The `amountIn` field will be set at runtime by the compiler to the caller's balance by the input token.
     */
    struct ExchangeAllInstruction {
        string protocol;
        IExchangeEvaluator.ExchangeRequest request;
    }

    /**
     * @notice Compiles a [Script](../Script.sol/struct.Script.html).
     * @dev **Important note:** don't put two instructions to the same script if one depend on the other because content of the script will be compiled at once meaning that balance changes will be applied only after the compilation of the entire script. If you have two instructions and one depends on the other, put them into different scripts.
     * @param script Script to compile
     * @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
     */
    function compile(Script calldata script) external returns (Command[] memory);

    /**
     * @notice Compiles an increase position instruction.
     * @param instruction The [`IncreasePositionInstruction`](#increasepositioninstruction) struct.
     * @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
     */
    function compileIncreasePositionInstruction(
        IncreasePositionInstruction calldata instruction
    ) external returns (Command[] memory);

    /**
     * @notice Compiles a decrease position instruction.
     * @param instruction The [`DecreasePositionInstruction`](#decreasepositioninstruction) struct.
     * @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
     */
    function compileDecreasePositionInstruction(
        DecreasePositionInstruction calldata instruction
    ) external returns (Command[] memory);

    /**
     * @notice Compiles an exchange instruction.
     * @param instruction The [`ExchangeInstruction`](#exchangeinstruction) struct.
     * @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
     */
    function compileExchangeInstruction(
        ExchangeInstruction calldata instruction
    ) external returns (Command[] memory);

    /**
     * @notice Sets the `amountIn` field to the balance of the caller by the input token and compiles an underlying exchange instruction.
     * @dev `amountIn` will be overridden with the balance of the caller by the input token.
     * @param instruction The [`ExchangeAllInstruction`](#exchangeallinstruction) struct.
     * @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
     */
    function compileExchangeAllInstruction(
        ExchangeAllInstruction calldata instruction
    ) external returns (Command[] memory);
}

contracts/interfaces/compiler/Script.sol

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

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

/**
 * @title Script
 * @notice A structure defining a script with various instructions for a JIT compiler.
 * @notice The [JIT compiler](../IJitCompiler.sol/interface.IJitCompiler.html)
 * will compile it the following way:
 *  1. Flatten content's instructions arrays into a single-dimensional array: `flattened =
 *  [...increasePositionInstructions, ...decreasePositionInstructions,
      ...exchangeInstructions, ...exchangeAllInstructions]`.
 *  2. Execute `flattened[PC]` where `PC = sequence[i]` where `i` is the
 *    index of current loop iteration, starting from `i = 0`.
 *  3. Increment current loop iteration index: `i = i + 1`.
 *  4. If `i < length(flattened)` go to step 2.
 *
 * @dev `canFail` Determines whether the script can silently fail. If true
 * transaction will not be reverted but execution will be terminated.
 * @dev `sequence` Auto-incrementing read-only program counter. Determines the
 * order of execution of the instruction within the script.
 * @dev `increasePositionInstructions` An array of
 * [`IncreasePositionInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#increasepositioninstruction).
 * @dev `decreasePositionInstructions` An array of
 * [`DecreasePositionInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#decreasepositioninstruction).
 * @dev `exchangeInstructions` An array of
 * [`ExchangeInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#exchangeinstruction).
 * @dev `exchangeAllInstructions` An array of
 * [`ExchangeAllInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#exchangeallinstruction).
 */
struct Script {
    bool canFail;
    uint256[] sequence;
    IJitCompiler.IncreasePositionInstruction[] increasePositionInstructions;
    IJitCompiler.DecreasePositionInstruction[] decreasePositionInstructions;
    IJitCompiler.ExchangeInstruction[] exchangeInstructions;
    IJitCompiler.ExchangeAllInstruction[] exchangeAllInstructions;
}

contracts/interfaces/compiler/adapters/IDecreasePositionEvaluator.sol

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

import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {Command} from "../Command.sol";
import {PositionDescriptor} from "./PositionDescriptor.sol";

interface IDecreasePositionEvaluator {
    /**
     * @notice Request structure for decreasing a position.
     * @dev `descriptor`: The [`PositionDescriptor`](/interfaces/compiler/adapters/PositionDescriptor.sol/struct.PositionDescriptor.html)
     *  struct.
     * @dev `liquidity`: Abstract amount that can be interpreted differently in different protocols (e.g., amount of LP tokens to burn).
     * @dev `minOutput`: [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) array with minimum amounts that must be retrieved from the position.
     */
    struct DecreasePositionRequest {
        PositionDescriptor descriptor;
        uint256 liquidity;
        Asset[] minOutput;
    }

    /**
     * @notice Evaluate a decrease position request.
     * @param _operator Address which initiated the request
     * @param _request The [`DecreasePositionRequest`](#decreasepositionrequest) struct containing decrease position details.
     * @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
     */
    function evaluate(
        address _operator,
        DecreasePositionRequest calldata _request
    ) external returns (Command[] memory cmds_);
}

contracts/interfaces/compiler/adapters/IExchangeEvaluator.sol

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

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

/**
 * @title IExchangeEvaluator
 * @notice Interface for compiling commands for token exchanges for different protocols.
 */
interface IExchangeEvaluator {
    /**
     * @notice Structure for an exchange token request.
     * @dev `path`: Encoded path of tokens to follow in the exchange, including pool identifiers.
     * 20 bytes(tokenA) + 4 byte(poolId_A_B) + 20 bytes(tokenB) + ...
     * ... + 4 byte(poolId_N-1_N) + 20 bytes(tokenN).
     * @dev `extraData`: Additional data specific to a particular protocol, such as the response from a 1Inch Exchange API.
     * @dev `amountIn`: The amount of tokenA to spend.
     * @dev `minAmountOut`: The minimum amount of tokenN to receive.
     * @dev `recipient`: The recipient of tokenN.
     */
    struct ExchangeRequest {
        bytes path;
        bytes extraData;
        uint256 amountIn;
        uint256 minAmountOut;
        address recipient;
    }

    /**
     * @notice Constructs an exchange token request.
     * @param _operator Address which initiated the request
     * @param _request The [`ExchangeRequest`](#exchangerequest) struct containing exchange token details.
     * @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
     */
    function evaluate(
        address _operator,
        ExchangeRequest calldata _request
    ) external view returns (Command[] memory cmds_);
}

contracts/interfaces/compiler/adapters/IIncreasePositionEvaluator.sol

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

import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {Command} from "../Command.sol";
import {PositionDescriptor} from "./PositionDescriptor.sol";

interface IIncreasePositionEvaluator {
    /**
     * @notice Structure for an increase position request.
     * @dev `descriptor`: The [`PositionDescriptor`](/interfaces/compiler/adapters/PositionDescriptor.sol/struct.PositionDescriptor.html)
     *  struct.
     * @dev `input`: An array of [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the token-amounts that will be added to the position.
     * @dev `minLiquidityOut`: An abstract amount that can be interpreted differently in different protocols (e.g., minimum amount of LP tokens to receive).
     */
    struct IncreasePositionRequest {
        PositionDescriptor descriptor;
        Asset[] input;
        uint256 minLiquidityOut;
    }

    /**
     * @notice Evaluate a increase position request.
     * @param _operator Address which initiated the request
     * @param _request The [`IncreasePositionRequest`](#increasepositionrequest) struct containing increase position details.
     * @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
     */
    function evaluate(
        address _operator,
        IncreasePositionRequest calldata _request
    ) external returns (Command[] memory cmds_);
}

contracts/interfaces/compiler/adapters/PositionDescriptor.sol

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

// TODO CRYPTO-145: Possibly move into appropriate interface?
/**
 * @notice Used to determine the required position for an operation.
 * @dev `poolId`: An identifier that is unique within a single protocol.
 * @dev `extraData`: Additional data used to specify the position, for example
 * this is used in OneInchV5Evaluator to pass swap tx generated via 1inch API.
 */
struct PositionDescriptor {
    uint256 poolId;
    bytes extraData;
}

contracts/interfaces/compliance/Asset.sol

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

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

/**
 * @title Asset
 * @dev Represents an asset with its token address and the amount.
 * @param token The address of the asset's token.
 * @param amount The amount of the asset.
 */
struct Asset {
    address token;
    uint256 amount;
}

using AssetLibrary for Asset 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/interfaces/dispatcher/Envelope.sol

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

import {Script} from "contracts/interfaces/compiler/Script.sol";
import {EnvelopeRunner} from "contracts/dispatcher/libraries/EnvelopeRunner.sol";

/**
 * @title Route
 * @notice Part of the [envelope](/interfaces/dispatcher/Envelope.sol/struct.Envelope.html)
 * @notice At **routing** level we define `protocol` name where **content**
 * should be executed as well as through which `protocol` **content** should
 * be delivered to the target ledger if chain did not matched.
 * @dev The `protocol` through which **content** should be delivered.
 * @dev The `destination` chain of the **content**.
 */
struct Route {
    string protocol;
    string destination;
}

/**
 * @title Envelope
 * @notice Part of the [syntax tree](/interfaces/dispatcher/index.html#syntax-tree-for-allocation--liquidation)
 * @notice Along with **routing** this struct holds **content** containing
 * [scripts](/interfaces/compiler/Script.sol/struct.Script.html)
 * with actual business logic.
 * @dev The [route](/interfaces/dispatcher/Envelope.sol/struct.Route.html) of the **content**
 * @dev The `content` field holds an array of [`Scripts`](/interfaces/compiler/Script.sol/struct.Script.html)
 * that should be executed at the `route.destination`.
 */
struct Envelope {
    Route route;
    Script[] content;
}

using EnvelopeRunner for Envelope global;

/**
 * @dev Error indicating that cross-chain actions are forbidden.
 */
error CrossChainActionIsForbidden();

contracts/interfaces/dispatcher/IDispatcher.sol

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

import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {IERC165Extended} from "../base/IERC165Extended.sol";

// EIP-165 id of the currently-deployed Dispatcher. Dependents validate this id so they accept the
// on-chain Dispatcher before it is upgraded.
bytes4 constant LEGACY_DISPATCHER_INTERFACE_ID = 0x130927ef;

/**
 * @title Dispatcher
 * @notice The facade for communication between margin engine backend and margin engine smart contracts module.
 * @notice This contract is responsible for handling [account registration](#registermarginaccount), [leverage allocation](#submitplan), [account close](#tryclosemarginaccount) and [account liquidation](#tryclosemarginaccount).
 */
interface IDispatcher is IERC165Extended {
    /**
     * @notice Error thrown when account closure fails due to outstanding debt
     * @param account The account address
     * @param agreement The agreement address
     */
    error DebtNotRepaid(address account, address agreement);

    /**
     * @notice Error thrown when dispatcher has insufficient swept leverage to repay account debt.
     * @param account The account address.
     * @param agreement The agreement address.
     * @param required The total repayment amount required, including pending interest.
     * @param available The leverage balance swept to dispatcher and available for repayment.
     */
    error InsufficientLeverageForRepayment(
        address account,
        address agreement,
        uint256 required,
        uint256 available
    );

    /**
     * @notice Error thrown when a non-zero protocol fee is charged but no treasury is configured.
     * @param compliance The compliance contract whose treasury is unset.
     */
    error TreasuryNotSet(address compliance);

    /**
     * @notice The leverage amount cannot be recorded without truncation.
     * @dev `account`: The account being allocated.
     * @dev `amount`: The leverage amount registered for the account.
     * @dev `limit`: The largest amount an Agreement can record.
     */
    error LeverageAmountTooLarge(address account, uint256 amount, uint256 limit);

    /**
     * @notice Registers a new margin account and transfers collateral from the caller to this account.
     * @param agreement The address of the agreement associated with the margin account.
     * @param collateral An array of [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the collateral to be transferred to the new margin account.
     * @param leverage An [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the leverage associated with the margin account.
     * @return account The address of the newly registered margin account.
     * @dev The function will revert if any of the following conditions are not met:
     * - leverage or any collateral tokens amount is zero
     * - The leverage token is not registered in agreement or not approved for transfer to this contract.
     * - The collateral tokens are not registered in agreement or not approved for transfer to this contract.
     *
     * Emits:
     * - `AccountBorrowed` from the [AccountFactory](../interfaces/marginAccount/IAccountFactory.sol) interface.
     * - `AccountDeployed` from the [AccountFactory](../interfaces/marginAccount/IAccountFactory.sol) interface if the object pool is empty.
     *
     * The newly registered margin account will also emit `AccountRegistered` as defined in the [Account](../interfaces/marginAccount/IAccount.sol) interface.
     */
    function registerAccount(
        address agreement,
        Asset[] calldata collateral,
        Asset calldata leverage
    ) external returns (address account);

    /**
     * @notice Borrows leverage from the agreement registered in the margin account and opens it.
     * @param account The registered margin account to allocate leverage for.
     */
    function allocateAccount(address payable account) external;

    /**
     * @notice Closes margin account by sweeping specified tokens, repaying debt and accrued
     * interest, transferring the protocol fee to the treasury and returning leftovers to the owner.
     * @dev The protocol fee is computed off-chain and supplied by the caller. It is denominated in
     * the leverage token and is included in the funds the account must hold to be closeable.
     * @param account The margin account to close.
     * @param tokens The list of ERC20 tokens expected to be swept from the margin account.
     * @param protocolFee The protocol fee (in the leverage token) to transfer to the treasury.
     */
    function closeAccount(
        address payable account,
        address[] calldata tokens,
        uint256 protocolFee
    ) external;

    /**
     * @notice Cancels a registered account that was never allocated and returns its collateral.
     * @dev Only callable by an address with the
     *  [ARKIS_RISK_OPERATOR_ROLE](#arkis_risk_operator_role).
     *  The account must be in the REGISTERED state and carries no debt so the listed balances are
     *  returned to its owner and the account goes back to the factory.
     * @param account The account to cancel.
     * @param tokens The list of token balances to return to the owner.
     */
    function cancelAccount(address payable account, address[] calldata tokens) external;

    /**
     * @notice Supplies registered margin account with leverage.
     * @dev Will revert if either account already opened, [invalid leverage token supplied](/interfaces/dispatcher/IDispatcher.sol/interface.IDispatcher.html#invalidleveragesupplied) or too much supplied
     * @param leverage Full or partial amount of leverage to supply.
     */
    function supplyAccount(address payable account, Asset calldata leverage) 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 role identifier for the Margin Account Supplier.
     * @dev This role is used to manage permissions to supply Margin Accounts, in Dispatcher Module in this context.
     * @return A bytes32 value representing the MARGIN_ACCOUNT_SUPPLIER_ROLE.
     */
    /* solhint-disable-next-line func-name-mixedcase */
    function MARGIN_ACCOUNT_SUPPLIER_ROLE() external view returns (bytes32);
}

contracts/interfaces/dispatcher/Package.sol

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

import {PackageRunner} from "contracts/dispatcher/libraries/PackageRunner.sol";
import {Envelope} from "./Envelope.sol";

/**
 * @title Package
 * @notice Part of the [syntax tree](/interfaces/dispatcher/index.html#syntax-tree-for-allocation--liquidation)
 * @notice **Automation** part of the syntax tree which defines an `action` with attached to it callback `onComplete`.
 * The callback will only be run if action succeeded.
 * @dev The `action` field represents the primary action in the [`Envelope`](../Envelope.sol/struct.Envelope.html) struct to be executed.
 * @dev The `onComplete` array is composed of [`Envelope`](../Envelope.sol/struct.Envelope.html) structs that will be executed after the primary action completes.
 */
struct Package {
    Envelope action;
    Envelope[] onComplete;
}

using PackageRunner for Package global;

contracts/interfaces/liquidator/ILiquidator.sol

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

import {IERC165Extended} from "../base/IERC165Extended.sol";
import {Package} from "../dispatcher/Package.sol";

interface ILiquidator is IERC165Extended {
    /**
     * @notice Error thrown when account liquidation fails due to outstanding debt
     * @param account The account address
     * @param agreement The agreement address
     */
    error DebtNotRepaid(address account, address agreement);

    /**
     * @notice Switches margin account to the `suspended` state and
     * tries to execute provided plan's action on the account. Can be called
     * multiple times if the account's closing was not successful
     * @dev Will not revert if action execution on margin account failed
     * therefore all the changes from successful scripts will be applied
     * after transaction. Account will remain in the suspended state and
     * will wait till successful closing.
     * @param liquidationPlan `action` will be executed on the account and
     * `onComplete` callback will be run on this contract (if `action` succeeded).
     */
    function liquidateAccount(
        address payable account,
        Package calldata liquidationPlan
    ) external returns (bool success);

    /**
     * @notice Returns the role identifier for the Arkis Liquidation Operator.
     * @dev This role manages permissions related to Arkis Liquidation's functions.
     *      It allows the address holding this role to:
     *      - Liquidate unhealthy margin accounts
     * @return A bytes32 value representing the ARKIS_LIQUIDATION_OPERATOR_ROLE.
     */
    /* solhint-disable-next-line func-name-mixedcase */
    function ARKIS_LIQUIDATION_OPERATOR_ROLE() external view returns (bytes32);
}

contracts/libraries/Address.sol

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

library Address {
    address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    function set(bytes32 _slot, address _value) internal {
        assembly {
            sstore(_slot, _value)
        }
    }

    function get(bytes32 _slot) internal view returns (address result_) {
        assembly {
            result_ := sload(_slot)
        }
    }

    function isEth(address _token) internal pure returns (bool) {
        return _token == ETH || _token == address(0);
    }

    function sort(address _a, address _b) internal pure returns (address, address) {
        return _a < _b ? (_a, _b) : (_b, _a);
    }

    function sort(address[4] memory _array) internal pure returns (address[4] memory _sorted) {
        // Sorting network for the array of length 4
        (_sorted[0], _sorted[1]) = sort(_array[0], _array[1]);
        (_sorted[2], _sorted[3]) = sort(_array[2], _array[3]);

        (_sorted[0], _sorted[2]) = sort(_sorted[0], _sorted[2]);
        (_sorted[1], _sorted[3]) = sort(_sorted[1], _sorted[3]);
        (_sorted[1], _sorted[2]) = sort(_sorted[1], _sorted[2]);
    }
}

contracts/libraries/AssetLibrary.sol

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

import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";

import {AmountMustNotBeZero} from "contracts/interfaces/base/CommonErrors.sol";
import {Asset} from "contracts/interfaces/compliance/Asset.sol";

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

library AssetLibrary {
    using SafeTransferLib for address;
    using Address for address;

    error NotEnoughReceived(address token, uint256 expected, uint256 received);

    function forward(Asset calldata self, address _to) internal {
        if (self.amount == 0) revert AmountMustNotBeZero(self.token);

        if (self.token.isEth()) _to.safeTransferETH(self.amount);
        else self.token.safeTransferFrom(msg.sender, _to, self.amount);
    }

    function approve(Asset calldata self, address to) internal {
        self.token.safeApprove(to, self.amount);
    }

    function receiveFrom(Asset storage self, address from) internal {
        self.token.safeTransferFrom(from, address(this), self.amount);
    }

    function receiveFrom(Asset calldata self, address from) internal {
        self.token.safeTransferFrom(from, address(this), self.amount);
    }

    function enforceReceived(Asset calldata self) internal view {
        if (self.amount == 0) revert AmountMustNotBeZero(self.token);

        uint256 balance = self.token.isEth()
            ? address(this).balance
            : self.token.balanceOf(address(this));

        if (balance < self.amount) revert NotEnoughReceived(self.token, self.amount, balance);
    }
}

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

solady/src/utils/SafeTransferLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Caution! This library won't check that a token has code, responsibility is delegated to the caller.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH
    /// that disallows any storage writes.
    uint256 internal constant _GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    /// Multiply by a small constant (e.g. 2), if needed.
    uint256 internal constant _GAS_STIPEND_NO_GRIEF = 100000;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` (in wei) ETH to `to`.
    /// Reverts upon failure.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, amount, 0, 0, 0, 0)) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    /// The `gasStipend` can be set to a low enough value to prevent
    /// storage writes or gas griefing.
    ///
    /// If sending via the normal procedure fails, force sends the ETH by
    /// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
    ///
    /// Reverts if the current contract has insufficient balance.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // If insufficient balance, revert.
            if lt(selfbalance(), amount) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(gasStipend, to, amount, 0, 0, 0, 0)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                // We can directly use `SELFDESTRUCT` in the contract creation.
                // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
                if iszero(create(amount, 0x0b, 0x16)) {
                    // For better gas estimation.
                    if iszero(gt(gas(), 1000000)) { revert(0, 0) }
                }
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a gas stipend
    /// equal to `_GAS_STIPEND_NO_GRIEF`. This gas stipend is a reasonable default
    /// for 99% of cases and can be overriden with the three-argument version of this
    /// function if necessary.
    ///
    /// If sending via the normal procedure fails, force sends the ETH by
    /// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
    ///
    /// Reverts if the current contract has insufficient balance.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        // Manually inlined because the compiler doesn't inline functions with branches.
        /// @solidity memory-safe-assembly
        assembly {
            // If insufficient balance, revert.
            if lt(selfbalance(), amount) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(_GAS_STIPEND_NO_GRIEF, to, amount, 0, 0, 0, 0)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                // We can directly use `SELFDESTRUCT` in the contract creation.
                // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
                if iszero(create(amount, 0x0b, 0x16)) {
                    // For better gas estimation.
                    if iszero(gt(gas(), 1000000)) { revert(0, 0) }
                }
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    /// The `gasStipend` can be set to a low enough value to prevent
    /// storage writes or gas griefing.
    ///
    /// Simply use `gasleft()` for `gasStipend` if you don't need a gas stipend.
    ///
    /// Note: Does NOT revert upon failure.
    /// Returns whether the transfer of ETH is successful instead.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and check if it succeeded or not.
            success := call(gasStipend, to, amount, 0, 0, 0, 0)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.

            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            // Store the function selector of `transferFrom(address,address,uint256)`.
            mstore(0x0c, 0x23b872dd000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.

            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            // Store the function selector of `balanceOf(address)`.
            mstore(0x0c, 0x70a08231000000000000000000000000)
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Store the function selector of `transferFrom(address,address,uint256)`.
            mstore(0x00, 0x23b872dd)
            // The `amount` argument is already written to the memory word at 0x6c.
            amount := mload(0x60)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // Store the function selector of `transfer(address,uint256)`.
            mstore(0x00, 0xa9059cbb000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x14, to) // Store the `to` argument.
            // The `amount` argument is already written to the memory word at 0x34.
            amount := mload(0x34)
            // Store the function selector of `transfer(address,uint256)`.
            mstore(0x00, 0xa9059cbb000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // Store the function selector of `approve(address,uint256)`.
            mstore(0x00, 0x095ea7b3000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `ApproveFailed()`.
                mstore(0x00, 0x3e3f8f73)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            // Store the function selector of `balanceOf(address)`.
            mstore(0x00, 0x70a08231000000000000000000000000)
            amount :=
                mul(
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 1000000,
    "details": {
      "yulDetails": {
        "optimizerSteps": "u"
      }
    },
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.