Skip to content
Verified contractExactMIT

CollateralFixedTermFactory

Address0xcc2af6b6b3a888d96166205b9ba27d7dba3a67de
Balance

0 ETH

 

Transactions

8

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,083,956
Creation transaction
0xe90f1b81dd…58e8e1f41b

54 files

src/factory/CollateralFixedTermFactory.sol

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

import {
    IAccountableCollateralFixedTerm,
    CollateralFixedTermInitParams
} from "../interfaces/IAccountableCollateralFixedTerm.sol";

import {FailedDeployment, Unauthorized} from "../constants/Errors.sol";
import {StrategyFactoryBase} from "./StrategyFactoryBase.sol";

import {AccountableCollateralFixedTerm} from "../strategies/AccountableCollateralFixedTerm.sol";
import {LoanEscrow} from "../modules/LoanEscrow.sol";
import {ICollateralFixedTermFactory, CollateralFixedTermFactoryParams} from "../interfaces/IStrategyFactory.sol";

import {Create2} from "@openzeppelin/contracts/utils/Create2.sol";
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";

/// @title CollateralFixedTermFactory
/// @notice Factory contract for creating collateral fixed-term loans
/// @custom:security-contact [email protected]
contract CollateralFixedTermFactory is ICollateralFixedTermFactory, StrategyFactoryBase {
    string private constant NO_ESCROW = "no escrow on strategy";

    address private _strategyBeingCreated;

    constructor(address globals_, address owner_) StrategyFactoryBase(globals_, owner_) {}

    /// @inheritdoc ICollateralFixedTermFactory
    function createCollateralFixedTerm(CollateralFixedTermFactoryParams memory params)
        external
        whenNotPaused
        onlyVerified
        onlyWhitelistedAsset(params.asset)
        returns (address strategyProxy, address vault, address escrow)
    {
        bytes memory strategyInitData = abi.encode(
            strategyImplementation,
            abi.encodeCall(
                AccountableCollateralFixedTerm.initialize,
                (CollateralFixedTermInitParams({
                        asset: params.asset,
                        loanToken: params.loanToken,
                        globals: globals,
                        feeManager: feeManager,
                        investmentManager: params.investmentManager,
                        permissionLevel: params.permissionLevel,
                        name: params.name,
                        symbol: params.symbol
                    }))
            )
        );

        bytes memory proxyBytecode = abi.encodePacked(type(ERC1967Proxy).creationCode, strategyInitData);
        _strategyBeingCreated = Create2.computeAddress(params.salt, keccak256(proxyBytecode));
        strategyProxy = Create2.deploy(0, params.salt, proxyBytecode);

        vault = IAccountableCollateralFixedTerm(strategyProxy).vault();
        if (vault == address(0)) revert FailedDeployment(NO_VAULT);

        escrow = IAccountableCollateralFixedTerm(strategyProxy).escrow();
        if (escrow == address(0)) revert FailedDeployment(NO_ESCROW);

        strategyProxies.push(strategyProxy);
        strategyVaults[strategyProxy] = vault;

        emit CollateralFixedTermCreated(strategyProxy, vault, escrow);
    }

    /// @notice Deploys an escrow only for the strategy currently being created
    function createLoanEscrow(address loanToken, address share) external returns (address escrow) {
        if (msg.sender != _strategyBeingCreated) revert Unauthorized();
        _strategyBeingCreated = address(0);

        address implementation = address(new LoanEscrow());
        escrow = address(
            new ERC1967Proxy(implementation, abi.encodeCall(LoanEscrow.initialize, (loanToken, share, msg.sender)))
        );
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/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
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol

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

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC1967-compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/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());
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol

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

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol

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

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol

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

pragma solidity ^0.8.20;

import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";

/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy {
    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
     * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    constructor(address implementation, bytes memory _data) payable {
        ERC1967Utils.upgradeToAndCall(implementation, _data);
    }

    /**
     * @dev Returns the current implementation address.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
     */
    function _implementation() internal view virtual override returns (address) {
        return ERC1967Utils.getImplementation();
    }
}

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

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

pragma solidity ^0.8.20;

import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 */
library ERC1967Utils {
    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/Proxy.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

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

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts/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);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/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);
}

lib/openzeppelin-contracts/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;
    }
}

lib/openzeppelin-contracts/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();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Create2.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev Not enough balance for performing a CREATE2 deploy.
     */
    error Create2InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @dev The deployment failed.
     */
    error Create2FailedDeployment();

    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        if (address(this).balance < amount) {
            revert Create2InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        /// @solidity memory-safe-assembly
        assembly {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        if (addr == address(0)) {
            revert Create2FailedDeployment();
        }
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := keccak256(start, 85)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Pausable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.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 Pausable is Context {
    bool private _paused;

    /**
     * @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.
     */
    constructor() {
        _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) {
        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 {
        _paused = true;
        emit Paused(_msgSender());
    }

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

lib/openzeppelin-contracts/contracts/utils/ShortStrings.sol

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

pragma solidity ^0.8.20;

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

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Strings.sol

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol

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

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol

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

pragma solidity ^0.8.20;

import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
 * Argent and Safe Wallet (previously Gnosis Safe).
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        (address recovered, ECDSA.RecoverError error, ) = ECDSA.tryRecover(hash, signature);
        return
            (error == ECDSA.RecoverError.NoError && recovered == signer) ||
            isValidERC1271SignatureNow(signer, hash, signature);
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

lib/openzeppelin-contracts/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);
}

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

src/access/Authorizable.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import "../constants/Errors.sol";

import {IAuthorizable, TxAuthData, VerifyManyData} from "../interfaces/IAccess.sol";

import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

/// @title Authorizable - A signature based transaction authorization mechanism
/// @notice This contract is used to authorize transactions using a signature
/// @dev See IAuthorizable for detailed interface documentation
/// @custom:security-contact [email protected]
abstract contract Authorizable is IAuthorizable, EIP712 {
    /// @notice EIP-712 typehash for TxAuthData
    bytes32 private constant _TXAUTH_TYPEHASH = keccak256(
        "TxAuthData(bytes functionCallData,address contractAddress,address account,uint256 nonce,uint256 blockExpiration)"
    );

    constructor() EIP712("Authorizable", "1") {}

    /// @notice These are used to decompose msgData
    uint256 private constant _BYTES_32_LENGTH = 32;

    /// @notice This is the length for the expected signature
    uint256 private constant _SIGNATURE_LENGTH = 65;

    /// @notice The offset for the extra data in the calldata
    uint256 private constant _EXTRA_DATA_LENGTH = _SIGNATURE_LENGTH + _BYTES_32_LENGTH;

    /// @notice The address of the off-chain signer
    address public signer;

    /// @notice Mapping to track the nonces to prevent replay attacks
    /// @dev Maps a user address to their current nonce
    mapping(address user => uint256 nonce) public nonces;

    /// @inheritdoc IAuthorizable
    function setSigner(address signer_) public virtual {
        if (signer_ == address(0)) revert ZeroAddress();
        _setSigner(signer_);
    }

    /// @inheritdoc IAuthorizable
    function getMessageHash(TxAuthData calldata txAuthData) public view returns (bytes32) {
        return _getTypedDataHash(txAuthData);
    }

    /// @dev Verify transaction authentication data
    /// @param account The account that is being verified
    /// @param msgData The message data of the transaction
    /// @return True if the transaction authentication data is valid, reverts otherwise
    function _verify(address account, bytes calldata msgData) internal returns (bool) {
        address signer_ = signer;

        if (account == address(0)) revert ZeroAddress();
        if (signer_ == address(0)) revert InvalidSigner();
        if (msgData.length < _EXTRA_DATA_LENGTH) revert InvalidMsgDataLength();

        bytes calldata argsWithSelector = msgData[:msgData.length - _EXTRA_DATA_LENGTH];

        uint256 blockExpiration =
            uint256(bytes32(msgData[msgData.length - _EXTRA_DATA_LENGTH:msgData.length - _SIGNATURE_LENGTH]));

        bytes calldata signature = msgData[msgData.length - _SIGNATURE_LENGTH:];

        if (block.number >= blockExpiration) revert InvalidBlockExpiration();

        uint256 nonce = nonces[account]++;

        TxAuthData memory txAuthData = TxAuthData({
            functionCallData: argsWithSelector,
            contractAddress: address(this),
            account: account,
            nonce: nonce,
            blockExpiration: blockExpiration
        });

        bytes32 digest = _getTypedDataHash(txAuthData);

        emit TxAuthDataVerified(block.chainid, nonce, blockExpiration, address(this), account, argsWithSelector);

        if (!SignatureChecker.isValidSignatureNow(signer_, digest, signature)) revert InvalidSignature();

        return true;
    }

    /// @dev Verify transaction authentication data for multiple accounts
    /// @param accounts Array of accounts that are being verified in the transaction
    /// @param msgData [functionCallData][blockExpiration][signature1][signature2]...[signatureN][length]
    /// @return True if all transaction authentication data is valid, false otherwise
    function _verifyMany(address[] memory accounts, bytes calldata msgData) internal returns (bool) {
        address signer_ = signer;

        if (signer_ == address(0)) revert InvalidSigner();
        if (accounts.length == 0) revert EmptyAccountsArray();
        if (msgData.length < _EXTRA_DATA_LENGTH) revert InvalidMsgDataLength();

        VerifyManyData memory data = _parseVerifyManyData(accounts, msgData);

        if (block.number >= data.blockExpiration) revert InvalidBlockExpiration();

        for (uint256 i = 0; i < accounts.length; i++) {
            if (accounts[i] == address(0)) revert ZeroAddress();

            if (!_verifySingle(signer_, accounts[i], data, i, msgData)) {
                revert InvalidSignature();
            }
        }
        return true;
    }

    /// @dev Parse msgData for _verifyMany function
    function _parseVerifyManyData(address[] memory accounts, bytes calldata msgData)
        private
        pure
        returns (VerifyManyData memory data)
    {
        data.numSignatures = uint256(bytes32(msgData[msgData.length - _BYTES_32_LENGTH:]));
        if (data.numSignatures != accounts.length) revert ArrayLengthMismatch();

        uint256 extraDataLength = _BYTES_32_LENGTH + (data.numSignatures * _SIGNATURE_LENGTH) + _BYTES_32_LENGTH;
        if (msgData.length < extraDataLength) revert InvalidMsgDataLength();

        data.argsWithSelector = msgData[:msgData.length - extraDataLength];

        uint256 blockExpirationStart = msgData.length - extraDataLength;
        data.blockExpiration = uint256(bytes32(msgData[blockExpirationStart:blockExpirationStart + _BYTES_32_LENGTH]));
        data.signaturesStart = blockExpirationStart + _BYTES_32_LENGTH;
    }

    /// @dev Verify a single signature within verifyMany
    function _verifySingle(address signer_, address account, VerifyManyData memory data, uint256 index, bytes calldata msgData)
        private
        returns (bool)
    {
        uint256 nonce = nonces[account]++;

        bytes32 digest = _getTypedDataHash(
            TxAuthData({
                functionCallData: data.argsWithSelector,
                contractAddress: address(this),
                account: account,
                nonce: nonce,
                blockExpiration: data.blockExpiration
            })
        );

        emit TxAuthDataVerified(
            block.chainid, nonce, data.blockExpiration, address(this), account, data.argsWithSelector
        );

        bytes calldata signature = msgData[
            data.signaturesStart + (index * _SIGNATURE_LENGTH):data.signaturesStart + ((index + 1) * _SIGNATURE_LENGTH)
        ];

        return SignatureChecker.isValidSignatureNow(signer_, digest, signature);
    }

    /// @dev Compute EIP-712 typed data digest for TxAuthData
    function _getTypedDataHash(TxAuthData memory txAuthData) internal view returns (bytes32) {
        bytes32 structHash = keccak256(
            abi.encode(
                _TXAUTH_TYPEHASH,
                keccak256(txAuthData.functionCallData),
                txAuthData.contractAddress,
                txAuthData.account,
                txAuthData.nonce,
                txAuthData.blockExpiration
            )
        );
        return _hashTypedDataV4(structHash);
    }

    /// @dev Sets the signer address
    function _setSigner(address signer_) internal {
        address oldSigner = signer;
        signer = signer_;
        emit SignerChanged(oldSigner, signer_);
    }
}

src/constants/Errors.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

// ========================================================================== //
//                             Authorization Errors                           //
// ========================================================================== //

/// @notice Error thrown when unauthorized
error Unauthorized();

/// @notice Thrown when a signature verification fails due to invalid signer
error InvalidSigner();

/// @notice Thrown when a nonce verification fails due to invalid nonce
error InvalidNonce();

/// @notice Thrown when an operation is attempted with invalid operator permissions
error InvalidOperator();

/// @notice Error thrown when invalid pending borrower is provided
error InvalidPendingBorrower();

/// @notice Thrown when KYC status is not verified
error KYCNotVerified();

/// @notice Thrown when a block expiration is invalid (e.g. in the past)
error InvalidBlockExpiration();

/// @notice Thrown when a signature verification fails
error InvalidSignature();

/// @notice Thrown when a message data length is invalid
error InvalidMsgDataLength();

/// @notice Thrown when an accounts array is empty
error EmptyAccountsArray();

/// @notice Error thrown when the state is invalid
error InvalidState();

/// @notice Error thrown when a value is invalid
error InvalidValue();

// ========================================================================== //
//                             Vault operations errors                        //
// ========================================================================== //

/// @notice Error thrown when trying to cancel a redeem request failed
error CancelRedeemRequestFailed();

/// @notice Error thrown when deposit amount exceeds max deposit
error ExceedsMaxDeposit();

/// @notice Error thrown when assets exceed redemption limits
error ExceedsRedeemLimit();

/// @notice Error thrown when redeem amount exceeds max redeem
error ExceedsMaxRedeem();

/// @notice Error thrown when deposit/withdraw amount is insufficient
error InsufficientAmount();

/// @notice Error thrown when redeem share amount is insufficient
error InsufficientShares();

/// @notice Error thrown when no redeem request exists
error NoRedeemRequest();

/// @notice Error thrown when no pending redeem request exists
error NoPendingRedeemRequest();

/// @notice Thrown when attempting to transfer shares that are not transferable
error SharesNotTransferable();

/// @notice Error thrown when withdrawal queue is not empty
error WithdrawalQueueNotEmpty();

/// @notice Error thrown when no queue request exists
error NoQueueRequest();

/// @notice Error thrown when redeem amount exceeds liquidity
error InsufficientLiquidity();

/// @notice Error thrown when asset is not whitelisted
error AssetNotWhitelisted();

/// @notice Thrown when cancellation requests are not accepted
error CancellationNotAllowed();

/// @notice Thrown when a cancellation is already pending for the request
error CancelAlreadyPending();

/// @notice Thrown when approving a request with no pending cancellation
error CancelNotPending();

/// @notice Thrown when settling an epoch that is not in `Passed` status
error EpochNotPassed();

/// @notice Thrown when cancelling a request whose epoch is no longer `Open`
error EpochNotOpen();

/// @notice Thrown when the request id does not exist
error RequestNotFound();

/// @notice Thrown when acting on a request that is already settled or refunded
error AlreadyFinalized();

/// @notice Thrown when a refund is not permitted (epoch still open, or self-refund in a healthy fund)
error NotRefundable();

/// @notice Thrown by the recovery path when no NAV was published since the open epoch opened
error NoMissedNavUpdate();

/// @notice Thrown when a gateway is deployed with signature authentication not supported
error SigAuthNotSupported();

/// @notice Thrown when wiring a gateway whose strategy does not point back to the current strategy
error GatewayStrategyMismatch();

/// @notice Error thrown when deregistering a vault that still has staked shares
error VaultNotEmpty();

/// @notice Thrown when updateTerms attempts to increase minRedeem
error MinRedeemTooHigh();

/// @notice Thrown when updateTerms attempts to increase depositPeriod
error DepositPeriodTooLong();

// ========================================================================== //
//                             Loan operations errors                         //
// ========================================================================== //

/// @notice Error thrown when loan terms are already set
error LoanTermsAlreadySet();

/// @notice Error thrown when loan terms are not set
error LoanTermsNotSet();

/// @notice Error thrown when loan is ongoing
error LoanOngoing();

/// @notice Error thrown when loan is not ongoing
error LoanNotOngoing();

/// @notice Error thrown when the loan escrow has already completed its single funding round
error AlreadyFunded();

/// @notice Error thrown when loan is not in default
error LoanNotInDefault();

/// @notice Error thrown when default is already pending
error DefaultAlreadyPending();

/// @notice Error thrown when loan terms are not met
error LoanTermsNotMet();

/// @notice Error thrown when loan has not matured
error LoanNotMatured();

/// @notice Error thrown when loan has not been repaid
error LoanNotRepaid();

/// @notice Error thrown when repayment terms are not met
error LoanCannotBeRepaid();

/// @notice Error thrown when there are outstanding interest payments
error OutstandingInterestPayments();

/// @notice Thrown when an operation is attempted with invalid controller permissions
error InvalidController();

/// @notice Thrown when an operation is attempted with invalid interval duration pair
error InvalidIntervalDurationPair();

/// @notice Thrown when an operation is attempted with invalid interval length
error InvalidIntervalLength();

/// @notice Thrown when an operation is attempted with invalid withdrawal period
error InvalidWithdrawalPeriod();

/// @notice Error thrown when capacity is set to a lower value than acceptable
error CapacityTooLow();

/// @notice Error thrown when accept grace period is longer than acceptable for the loan
error AcceptGracePeriodTooLong();

/// @notice Error thrown when a threshold exceeds the max bound
error ThresholdTooHigh();

/// @notice Error thrown when attempting to pay when no payment is due
error NoPaymentDue();

/// @notice Error thrown when NAV is stale
error NAVGracePeriodExpired();

/// @notice Error thrown when DVN measurement is stale relative to state changes
error StaleMeasurement();

/// @notice Error thrown when early exit debt mismatch
error EarlyExitDebtMismatch();

/// @notice Thrown when an account has no claimed balance
error NothingToRepay();

/// @notice Invalid grace period for reclaiming shares after loan repayment
error InvalidGracePeriod();

/// @notice Thrown when an LP attempts to reclaim shares before the grace period expires
error GracePeriodNotExpired();

/// @notice Thrown when an LP is notified of their repayment status more than once
error AlreadyNotified();

/// @notice Thrown when an LP attempts to reclaim shares but has no shares to reclaim
error NothingToReclaim();

/// @notice Thrown when an LP attempts to reclaim shares but he wants to reclaim more than the outstanding debt
error ExceedsOutstanding();

/// @notice Thrown when an LP has no loanClaimed balance
error AlreadyRepaid();

/// @notice Thrown when loanToken collides with the vault share token or underlying asset
error InvalidLoanToken();

// ========================================================================== //
//                            General errors                                  //
// ========================================================================== //

/// @notice Thrown when an index is out of bounds
error OutOfBounds();

/// @notice Thrown when an invalid range is provided
error InvalidRange();

/// @notice Thrown when an input address is address(0)
error ZeroAddress();

/// @notice Thrown when a value is zero
error ZeroValue();

/// @notice Thrown when deployment of a loan proxy contract fails
/// @param reason The reason for the failed deployment
error FailedDeployment(string reason);

/// @notice Thrown when a deposit is not allowed
error DepositNotAllowed();

/// @notice Thrown when a deposit's controller is not the configured deposit gateway
error DepositNotFromGateway();

/// @notice Thrown when a redeem is not allowed
error RedeemNotAllowed();

/// @notice Thrown when input arrays lengths don't match
error ArrayLengthMismatch();

/// @notice Error thrown when an operation is not required/allowed for the current permission level
error PermissionLevelMismatch();

/// @notice Error thrown when an operation is not supported by the strategy
error NotSupportedByStrategy();

/// @notice Thrown when a claim is not allwed
error ClaimNotAllowed();

/// @notice Thrown when a repay is not allowed
error RepayNotAllowed();

/// @notice Thrown when escrow was already set
error EscrowAlreadySet();

// ========================================================================== //
//                            Fee Manager errors                              //
// ========================================================================== //

/// @notice Error thrown when manager split is invalid
error InvalidManagerSplit();

/// @notice Error thrown when prepayment fee is invalid
error InvalidPrepaymentFee();

/// @notice Error thrown when establishment and management fees are set together
error InvalidFeeStructure();

/// @notice Error thrown when establishment fee is invalid
error InvalidEstablishmentFee();

/// @notice Error thrown when performance fee is invalid
error InvalidPerformanceFee();

/// @notice Error thrown when management fee is invalid
error InvalidManagementFee();

// ========================================================================== //
//                            Rewards errors                                  //
// ========================================================================== //

/// @notice Error thrown when a root is already set
error RootAlreadySet();

/// @notice Error thrown when no root is set
error RootNotSet();

/// @notice Error thrown when a root is already pending
error RootAlreadyPending();

/// @notice Error thrown when no pending root is set
error NoPendingRoot();

/// @notice Error thrown when timelock is not expired
error TimelockNotExpired();

/// @notice Error thrown when a proof is invalid
error InvalidProof();

/// @notice Error thrown when the amount to claim is not enough
error NotEnoughClaimableAmount();

/// @notice Error thrown when an invalid rewards type is provided
error InvalidRewardsType();

// ========================================================================== //
//                            Rate change errors                              //
// ========================================================================== //

/// @notice Error thrown when rollback window has expired
error RollbackWindowExpired();

/// @notice Error thrown when rate is too high
error RateTooHigh();

// ========================================================================== //
//                            Publisher errors                                 //
// ========================================================================== //

/// @notice Error thrown when threshold is too high
error InvalidThreshold();

/// @notice Error thrown when the threshold is not reached
error ThresholdNotReached();

/// @notice Error thrown when no batch has been published yet
error NoBatchPublished();

/// @notice Error thrown when request targets wrong batch
error InvalidBatchId();

/// @notice Error thrown when a publish request has expired (too stale)
error RequestExpired();

/// @notice Error thrown when too many pending requests exist
error TooManyRequests();

/// @notice Error thrown when deviation from previous value is too high
error DeviationTooHigh();

/// @notice Error thrown when request timestamp is in the future
error InvalidTimestamp();

/// @notice Error thrown when NAV grace period is invalid
error InvalidNavGracePeriod();

/// @notice Error thrown when instant-redeem max age is invalid (must be 0 or < navGracePeriod unless disabled)
error InvalidInstantRedeemMaxAge();

src/factory/StrategyFactoryBase.sol

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

import {IStrategyFactoryBase} from "../interfaces/IStrategyFactory.sol";

import {Authorizable} from "../access/Authorizable.sol";
import {InvalidRange, OutOfBounds, KYCNotVerified, AssetNotWhitelisted, Unauthorized} from "../constants/Errors.sol";

import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";

abstract contract StrategyFactoryBase is IStrategyFactoryBase, Ownable2Step, Pausable, Authorizable {
    string internal constant NO_VAULT = "no vault on strategy";
    string internal constant NO_REWARDS = "no rewards on strategy";
    string internal constant ZERO_LOAN_PROXY_ADDRESS = "zero loan proxy address";

    /// @notice Whether asset whitelisting is enabled
    bool public enableWhitelist;

    /// @notice The global registry address
    address public globals;

    /// @notice The fee manager address for created loans
    address public feeManager;

    /// @notice The implementation contract for an Accountable strategy
    address public strategyImplementation;

    /// @notice Array of all created strategy proxy addresses
    address[] public strategyProxies;

    /// @notice Mapping of assets to whether they are whitelisted or not
    mapping(address asset => bool whitelisted) public assetStatus;

    /// @notice Mapping of strategy addresses to their associated vault addresses
    mapping(address strategy => address vault) public strategyVaults;

    modifier onlyVerified() {
        if (signer != address(0)) {
            if (!_verify(msg.sender, msg.data)) revert KYCNotVerified();
        }
        _;
    }

    modifier onlyWhitelistedAsset(address asset) {
        if (enableWhitelist) {
            if (!assetStatus[asset]) revert AssetNotWhitelisted();
        }
        _;
    }

    /// @notice Initializes the factory with a global registry address
    /// @param globals_ The global registry address
    constructor(address globals_, address owner_) Ownable(owner_) {
        globals = globals_;
    }

    /// @inheritdoc IStrategyFactoryBase
    function setGlobals(address globals_) external onlyOwner {
        address oldGlobals = globals;
        globals = globals_;
        emit GlobalsSet(oldGlobals, globals);
    }

    /// @inheritdoc IStrategyFactoryBase
    function setFeeManager(address feeManager_) external onlyOwner {
        address oldFeeManager = feeManager;
        feeManager = feeManager_;
        emit FeeManagerSet(oldFeeManager, feeManager);
    }

    function setSigner(address signer_) public override onlyOwner {
        super.setSigner(signer_);
    }

    /// @inheritdoc IStrategyFactoryBase
    function setStrategyImplementation(address strategyImplementation_) external onlyOwner {
        address oldStrategyImplementation = strategyImplementation;
        strategyImplementation = strategyImplementation_;
        emit StrategyImplementationSet(oldStrategyImplementation, strategyImplementation);
    }

    /// @inheritdoc IStrategyFactoryBase
    function setWhitelist(bool enable) external onlyOwner {
        enableWhitelist = enable;
        emit WhitelistSet(enableWhitelist);
    }

    /// @inheritdoc IStrategyFactoryBase
    function setAssetWhitelist(address asset) external onlyOwner {
        assetStatus[asset] = !assetStatus[asset];
        emit AssetWhitelistSet(asset, assetStatus[asset]);
    }

    /// @inheritdoc IStrategyFactoryBase
    function getStrategyVault(address strategy_) external view returns (address) {
        return strategyVaults[strategy_];
    }

    /// @inheritdoc IStrategyFactoryBase
    function getStrategiesPaginated(uint256 start, uint256 end) external view returns (address[] memory) {
        if (start > end) revert InvalidRange();
        if (end > strategyProxies.length) revert OutOfBounds();

        uint256 len = end - start;
        address[] memory result = new address[](len);

        for (uint256 i = 0; i < len;) {
            result[i] = strategyProxies[start + i];
            unchecked {
                ++i;
            }
        }
        return result;
    }

    /// @inheritdoc IStrategyFactoryBase
    function getStrategiesCount() external view returns (uint256) {
        return strategyProxies.length;
    }

    /// @notice Pauses strategy creation
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Unpauses strategy creation
    function unpause() external onlyOwner {
        _unpause();
    }

    /// @dev Prevents renouncement of ownership
    function renounceOwnership() public virtual override onlyOwner {
        revert Unauthorized();
    }
}

src/interfaces/IAccess.sol

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

/// @notice Struct containing transaction authentication data (EIP-712 typed)
/// @dev Chain ID is part of the EIP-712 domain separator, not this struct
struct TxAuthData {
    /// @notice The calldata of the function being called (selector + encoded args)
    bytes functionCallData;
    /// @notice The address of the contract where the transaction is being executed
    address contractAddress;
    /// @notice The address of the account executing/controlling the transaction
    address account;
    /// @notice The per-account nonce (prevents replay)
    uint256 nonce;
    /// @notice The block number after which the transaction is considered expired
    uint256 blockExpiration;
}

/// @notice Struct containing verification data for verifyMany function
struct VerifyManyData {
    /// @notice The function call data extracted from msgData
    bytes argsWithSelector;
    /// @notice The block expiration timestamp
    uint256 blockExpiration;
    /// @notice The start position of signatures in msgData
    uint256 signaturesStart;
    /// @notice The number of signatures to verify
    uint256 numSignatures;
}

/// @notice Enum representing different permission levels
enum PermissionLevel {
    /// @notice No permission
    None,
    /// @notice KYC based permission
    KYC,
    /// @notice Whitelist based permission
    Whitelist
}

/// @title Whitelistable Interface
/// @notice Interface for managing whitelisted accounts
interface IWhitelistable {
    /// @notice Emitted when allowed status is set for an account
    /// @param account The address of the account
    /// @param allowed The allowed status
    event AllowedSet(address indexed account, bool allowed);

    /// @notice Set allowed accounts
    /// @param accounts Array of account addresses
    /// @param allowed Array of allowed status corresponding to acounts
    function setAllowed(address[] calldata accounts, bool[] calldata allowed) external;

    /// @notice Check if an account is allowed
    /// @param account The address to check allowed status for
    /// @return bool True if the account is allowed, false otherwise
    function allowed(address account) external view returns (bool);

    /// @notice Check if multiple accounts are allowed
    /// @param accounts Array of account addresses
    /// @return bool True if the accounts are allowed, false otherwise
    function allowedMany(address[] calldata accounts) external view returns (bool);
}

/// @title Authorizable Interface
/// @notice Interface for managing authorizable accounts
interface IAuthorizable {
    /// @notice Emitted when the signer address is changed
    /// @param oldSigner The old signer address
    /// @param newSigner The new signer address
    event SignerChanged(address indexed oldSigner, address indexed newSigner);

    /// @notice Emitted when a transaction authentication data is verified
    /// @param chainID The chain ID where the transaction is intended to be processed
    /// @param nonce The nonce of the user being verified to prevent replay attacks
    /// @param blockExpiration The block number after which the transaction is considered expired
    /// @param contractAddress The address of the contract where the transaction is being executed
    /// @param userAddress The address of the user executing the transaction
    /// @param functionCallData The calldata of the function being called
    event TxAuthDataVerified(
        uint256 chainID,
        uint256 nonce,
        uint256 blockExpiration,
        address indexed contractAddress,
        address indexed userAddress,
        bytes functionCallData
    );

    /// @notice Set the signer address
    /// @param signer The address of the signer
    function setSigner(address signer) external;

    /// @notice Get the signer address
    /// @return The signer address
    function signer() external view returns (address);

    /// @notice Get the nonce for a given user
    /// @param user The address of the user
    /// @return The nonce of the user
    function nonces(address user) external view returns (uint256);

    /// @notice Get the message hash for a given transaction authentication data
    /// @param txAuthData The transaction authentication data
    /// @return The message hash
    function getMessageHash(TxAuthData calldata txAuthData) external view returns (bytes32);
}

/// @title Access Interface
/// @notice Interface for managing access to a contract
interface IAccess is IAuthorizable, IWhitelistable {
    /// @notice Get the permission level for the loan
    /// @return The permission level enum value
    function permissionLevel() external view returns (PermissionLevel);
}

src/interfaces/IAccountableAsyncVault.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

/// @notice Struct tracking vault state for a controller
struct VaultState {
    /// @notice Maximum shares that can be minted
    uint256 maxMint;
    /// @notice Maximum assets that can be withdrawn
    uint256 maxWithdraw;
    /// @notice Total accumulated assets unclaimed
    uint256 depositAssets;
    /// @notice Total accumulated shares unclaimed
    uint256 redeemShares;
    /// @notice Share price floored for deposit
    uint256 depositPrice;
    /// @notice Share price ceiled for mint
    uint256 mintPrice;
    /// @notice Share price floored for redeem
    uint256 redeemPrice;
    /// @notice Share price ceiled for withdraw
    uint256 withdrawPrice;
    /// @notice Pending deposit amount
    uint256 pendingDepositRequest;
    /// @notice Pending redeem amount
    uint256 pendingRedeemRequest;
}

interface IControllerOperator {
    /// @notice Emitted when an operator's approval status is updated
    /// @param controller The controller address that approved/revoked
    /// @param operator The operator address being approved/revoked
    /// @param approved The new approval status
    event OperatorSet(address indexed controller, address indexed operator, bool approved);

    /// @notice Sets or revokes operator approval for a caller
    /// @param operator The address to set approval for
    /// @param approved True to approve, false to revoke
    /// @return bool True if successful
    function setOperator(address operator, bool approved) external returns (bool);

    /// @notice Checks if an address is an approved operator for a controller
    /// @param controller The controller address to check
    /// @param operator The operator address to check
    /// @return status True if operator is approved for controller
    function isOperator(address controller, address operator) external view returns (bool status);
}

interface IAsyncDeposit {
    /// @notice Emitted when a deposit request is created
    /// @param controller The controller address for the deposit
    /// @param owner The owner address that will receive shares
    /// @param requestId The unique ID for tracking the request
    /// @param sender The address that initiated the request
    /// @param assets The amount of assets being deposited
    event DepositRequest(
        address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 assets
    );

    /// @notice Requests a deposit of assets
    /// @param assets Amount of assets to deposit
    /// @param controller Address controlling the deposit
    /// @param owner Address that will own the shares
    /// @return uint256 Request ID for tracking the deposit
    function requestDeposit(uint256 assets, address controller, address owner) external returns (uint256);

    /// @notice Gets pending deposit amount for a request
    /// @param requestId ID of the deposit request
    /// @param controller Controller address for the request
    /// @return uint256 Amount of assets pending deposit
    function pendingDepositRequest(uint256 requestId, address controller) external view returns (uint256);

    /// @notice Gets claimable deposit amount for a request
    /// @param requestId ID of the deposit request
    /// @param controller Controller address for the request
    /// @return uint256 Amount of assets claimable
    function claimableDepositRequest(uint256 requestId, address controller) external view returns (uint256);
}

interface IAsyncRedeem {
    /// @notice Emitted when a redeem request is created
    /// @param controller The controller address for the redemption
    /// @param owner The owner of the shares being redeemed
    /// @param requestId The unique ID for tracking the request
    /// @param sender The address that initiated the request
    /// @param assets The amount of assets being redeemed
    event RedeemRequest(
        address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 assets
    );

    /// @notice Requests redemption of shares
    /// @param shares Amount of shares to redeem
    /// @param controller Controller address for redemption
    /// @param owner Owner of the shares
    /// @return uint256 Request ID for tracking redemption
    function requestRedeem(uint256 shares, address controller, address owner) external returns (uint256);

    /// @notice Gets pending redeem amount for a request
    /// @param requestId ID of the redeem request
    /// @param controller Controller address for the request
    /// @return uint256 Amount of shares pending redemption
    function pendingRedeemRequest(uint256 requestId, address controller) external view returns (uint256);

    /// @notice Gets claimable redeem amount for a request
    /// @param requestId ID of the redeem request
    /// @param controller Controller address for the request
    /// @return uint256 Amount of shares claimable
    function claimableRedeemRequest(uint256 requestId, address controller) external view returns (uint256);
}

interface IAsyncCancelDeposit {
    /// @notice Emitted when a deposit request is cancelled
    /// @param controller The controller address for the deposit
    /// @param receiver The address that received the cancelled deposit
    /// @param requestId The ID of the cancelled request
    /// @param sender The address that initiated the cancellation
    event CancelDepositRequest(address indexed controller, address indexed receiver, uint256 requestId, address sender);

    /// @notice Cancels a pending deposit request
    /// @param controller Controller address for the request
    /// @param receiver The address that received the cancelled deposit
    function cancelDepositRequest(address controller, address receiver) external;
}

interface IAsyncCancelRedeem {
    /// @notice Emitted when a redeem request is cancelled
    /// @param controller The controller address for the redemption
    /// @param receiver The address that received the cancelled redeem
    /// @param requestId The ID of the cancelled request
    /// @param sender The address that initiated the cancellation
    event CancelRedeemRequest(address indexed controller, address indexed receiver, uint256 requestId, address sender);

    /// @notice Cancels a pending redeem request
    /// @param controller Controller address for the request
    /// @param receiver The address that received the cancelled redeem
    function cancelRedeemRequest(address controller, address receiver) external;
}

interface IAccountableVault is IERC20, IERC20Metadata, IERC4626, IControllerOperator {
    /// @notice Emitted when assets are locked in the vault
    /// @param caller The address that locked the assets
    /// @param assets The amount of assets locked
    event LockAssets(address indexed caller, uint256 assets);

    /// @notice Emitted when locked assets are released
    /// @param caller The address that released the assets
    /// @param assets The amount of assets released
    event ReleaseAssets(address indexed caller, uint256 assets);

    /// @notice Emitted when shares transferability is changed
    /// @param oldStatus The old transferability status
    /// @param newStatus The new transferability status
    event SharesTransferableSet(bool oldStatus, bool newStatus);

    /// @notice Deposits assets and mints shares to receiver
    /// @dev Added for ERC7540 compatibility
    /// @param assets Amount of assets to deposit
    /// @param receiver Address receiving the shares
    /// @param controller Controller address for the deposit
    /// @return uint256 Amount of shares minted
    function deposit(uint256 assets, address receiver, address controller) external returns (uint256);

    /// @notice Mints exact amount of shares by depositing assets
    /// @dev Added for ERC7540 compatibility
    /// @param shares Amount of shares to mint
    /// @param receiver Address receiving the shares
    /// @param controller Controller address for the mint
    /// @return uint256 Amount of assets deposited
    function mint(uint256 shares, address receiver, address controller) external returns (uint256);

    /// @notice Locks assets in the vault
    /// @param assets Amount of assets to lock
    function lockAssets(uint256 assets, address sender) external;

    /// @notice Releases previously locked assets
    /// @param assets Amount of assets to release
    function releaseAssets(uint256 assets, address receiver) external;

    /// @notice Issues shares to a receiver
    /// @param shares Amount of shares to issue
    /// @param receiver Address to receive the shares
    function mintShares(uint256 shares, address receiver) external;

    /// @notice Repossesses shares from a sender
    /// @param shares Amount of shares to repossess
    /// @param sender Address to repossess the shares from
    function burnShares(uint256 shares, address sender) external;

    /// @notice Forces a transfer of shares from one address to another
    /// @param from The address to transfer shares from
    /// @param to The address to transfer shares to
    /// @param shares The amount of shares to transfer
    function forceTransferShares(address from, address to, uint256 shares) external;

    /// @notice Sets the transferability of shares
    /// @param transferable True to set shares transferable, false to set them non-transferable
    function setSharesTransferable(bool transferable) external;

    /// @notice Checks if shares can be transferred
    /// @return bool True if shares are transferable
    function transferableShares() external view returns (bool);

    /// @notice Current asset share ratio
    /// @return uint256 Asset share ratio
    function assetShareRatio() external view returns (uint256);

    /// @notice Gets the current share price
    /// @return uint256 Price per share in assets
    function sharePrice() external view returns (uint256);

    /// @notice The share token address
    /// @return address Share token address
    function share() external view returns (address);

    /// @notice Gets the state of the vault
    /// @param controller The controller address for the vault
    /// @return state The state of the vault given the controller
    function getState(address controller) external view returns (VaultState memory state);
}

interface IAccountableAsyncRedeemVault is IAccountableVault, IAsyncRedeem, IAsyncCancelRedeem, IERC165 {
    /// @notice Emitted when a redeem becomes claimable
    /// @param controller The controller address for the redemption
    /// @param requestId The ID of the redeem request
    /// @param assets The amount of assets to be received
    /// @param shares The amount of shares redeemed
    event RedeemClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);
}

interface IAccountableAsyncVault is
    IAccountableVault,
    IAsyncDeposit,
    IAsyncRedeem,
    IAsyncCancelDeposit,
    IAsyncCancelRedeem,
    IERC165
{
    /// @notice Emitted when a deposit becomes claimable
    /// @param controller The controller address for the deposit
    /// @param requestId The ID of the deposit request
    /// @param assets The amount of assets deposited
    /// @param shares The amount of shares to be minted
    event DepositClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);

    /// @notice Emitted when a redeem becomes claimable
    /// @param controller The controller address for the redemption
    /// @param requestId The ID of the redeem request
    /// @param assets The amount of assets to be received
    /// @param shares The amount of shares redeemed
    event RedeemClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);
}

src/interfaces/IAccountableCollateralFixedTerm.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import {IAccountableLoan} from "./IAccountableStrategy.sol";
import {PermissionLevel} from "./IAccess.sol";

struct CollateralFixedTermInitParams {
    /// @notice The asset of the loan
    address asset;
    /// @notice The loan token distributed to LPs
    address loanToken;
    /// @notice The global registry address
    address globals;
    /// @notice The fee manager of the loan
    address feeManager;
    /// @notice The investment manager of the loan
    address investmentManager;
    /// @notice The permission level of the loan
    PermissionLevel permissionLevel;
    /// @notice The name of the share token
    string name;
    /// @notice The symbol of the share token
    string symbol;
}

interface IAccountableCollateralFixedTerm is IAccountableLoan {
    /// @notice Event emitted when the escrow contract is set
    /// @param escrow The address of the loan escrow contract
    event EscrowSet(address indexed escrow);

    /// @notice Event emitted when management fee shares are minted to a recipient
    /// @param receiver The address receiving the minted fee shares
    /// @param shares The amount of the shares minted
    event FeeSharesMinted(address indexed receiver, uint256 shares);

    /// @notice Event emitted when the loan is accepted by the borrower
    event LoanAccepted();

    /// @notice Event emitted when the loan is rejected after the acceptance deadline
    event LoanRejected();

    /// @notice Emitted when an implementation upgrade is proposed, starting the upgrade timelock
    /// @param newImplementation The proposed implementation
    /// @param readyAt The timestamp after which the upgrade can be executed
    event UpgradeProposed(address indexed newImplementation, uint256 readyAt);

    /// @notice Emitted when a pending implementation upgrade is cancelled
    /// @param newImplementation The implementation that was pending
    event UpgradeCancelled(address indexed newImplementation);

    /// @notice Emitted when the upfront management fee is collected at loan acceptance
    /// @param managerAmount The amount sent to the manager fee recipient
    /// @param protocolAmount The amount sent to the protocol treasury
    /// @param totalFee The total fee deducted from principal
    event UpfrontFeeCollected(uint256 managerAmount, uint256 protocolAmount, uint256 totalFee);

    /// @notice Accept the loan in locked mode, preventing further deposits
    function acceptLoanLocked() external;

    /// @notice Accept the loan in dynamic mode, allowing further deposits
    function acceptLoanDynamic() external;

    /// @notice Reject the loan after the acceptance grace period has elapsed
    function reject() external;

    /// @notice Claim accrued interest, always returns 0 for this strategy (no interest)
    function claimInterest() external returns (uint256);

    /// @notice Set the loan escrow contract address
    /// @param escrow_ The address of the loan escrow contract
    function setEscrow(address escrow_) external;

    /// @notice Get the loan escrow contract address
    /// @return The escrow address
    function escrow() external view returns (address);
}

src/interfaces/IAccountableStrategy.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

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

/// @notice Struct containing loan terms and state
struct Loan {
    /// @notice Minimum deposit amount allowed
    uint256 minDeposit;
    /// @notice Minimum redeem amount allowed
    uint256 minRedeem;
    /// @notice Maximum loan amount that can be drawn
    ///         The full threshold can be met after deposit period if the loan is not locked
    uint256 maxCapacity;
    /// @notice Minimum loan amount for the loan to be accepted
    ///         The threshold needs to be met during deposit period or loan can be rejected
    uint256 minCapacity;
    /// @notice Liquidity ratio that has to be maintained in the vault at all times
    ///         Expressed in basis points and cannot exceed 1e6, defaults to 0
    uint256 reserveThreshold;
    /// @notice Principal amount still to be repaid
    uint256 outstandingPrincipal;
    /// @notice Interest amount still to be paid
    uint256 outstandingInterest;
    /// @notice all funds accepted and available for borrowing
    uint256 drawableFunds;
    /// @notice Annual interest rate in basis points
    uint256 interestRate;
    /// @notice Late interest penalty in basis points
    uint256 lateInterestPenalty;
    /// @notice Total claimable interest available for users
    uint256 claimableInterest;
    /// @notice Time interval between interest payments
    uint256 interestInterval;
    /// @notice Time of loan start
    uint256 startTime;
    /// @notice Time of terms set
    uint256 termsSetTime;
    /// @notice Time of terms update
    uint256 termsUpdateTime;
    /// @notice Loan duration in seconds
    uint256 duration;
    /// @notice Deposit period in seconds
    uint256 depositPeriod;
    /// @notice Grace period after deposit period for borrower to accept loan
    uint256 acceptGracePeriod;
    /// @notice Withdrawal window period in seconds
    ///         If set it allows redemption requests
    uint256 withdrawalPeriod;
    /// @notice Late interest payment grace period in seconds
    ///         This is the time period before a loan is considered delinquent
    uint256 lateInterestGracePeriod;
}

/// @notice Struct containing loan terms
struct LoanTerms {
    /// @notice Minimum deposit amount allowed
    uint256 minDeposit;
    /// @notice Minimum redeem amount allowed
    uint256 minRedeem;
    /// @notice Maximum loan capacity
    uint256 maxCapacity;
    /// @notice Minimum loan capacity
    uint256 minCapacity;
    /// @notice Annual interest rate in basis points
    uint256 interestRate;
    /// @notice Late interest penalty in basis points
    uint256 lateInterestPenalty;
    /// @notice Late interest grace period in seconds
    uint256 lateInterestGracePeriod;
    /// @notice Time interval between interest payments
    uint256 interestInterval;
    /// @notice Duration of the loan in seconds
    uint256 duration;
    /// @notice Deposit period in seconds
    uint256 depositPeriod;
    /// @notice Grace period after deposit period for borrower to accept loan
    uint256 acceptGracePeriod;
    /// @notice Withdrawal window period in seconds
    uint256 withdrawalPeriod;
}

/// @notice Struct containing DVN proof data
struct DVNProof {
    /// @notice Merkle root of the DVN merkle tree
    bytes32 root;
    /// @notice Signature of the DVN payload
    bytes32 signature;
    /// @notice Message hash that was signed
    bytes32 messageHash;
}

/// @notice Enum representing different loan states
enum LoanState {
    /// @notice Loan terms are not set
    Initialized,
    /// @notice Loan terms are set
    TermsSet,
    /// @notice Loan is accepted by borrower and locked
    OngoingLocked,
    /// @notice Loan is accepted by borrower and dynamic deposits are allowed
    OngoingDynamic,
    /// @notice Loan is rejected
    Rejected,
    /// @notice Loan is repaid
    Repaid,
    /// @notice Loan is in default
    InDefault,
    /// @notice Loan is in default claims
    InDefaultClaims
}

/// @notice Interface for managing strategy vault hooks
interface IStrategyVaultHooks {
    /// @notice Hook for handling deposit requests
    /// @param share The address of the share token
    /// @param assets The amount of assets requested
    /// @param controller The address of the controller
    /// @param owner The address of the owner of the assets
    /// @return canFulfill Whether the deposit can be fulfilled instantly
    /// @return price The price of the share
    function onRequestDeposit(address share, uint256 assets, address controller, address owner)
        external
        returns (bool canFulfill, uint256 price);

    /// @notice Hook for handling redeem requests
    /// @param share The address of the share token
    /// @param shares The amount of shares requested
    /// @param controller The address of the controller
    /// @param owner The address of the owner of the shares
    /// @return canFulfill Whether the redeem can be fulfilled instantly
    /// @return price The price of the share
    function onRequestRedeem(address share, uint256 shares, address controller, address owner)
        external
        returns (bool canFulfill, uint256 price);

    /// @notice Hook for handling cancel deposit requests
    /// @param share The address of the share token
    /// @param controller The address of the controller
    /// @return canCancel Whether the deposit can be cancelled instantly
    function onCancelDepositRequest(address share, address controller) external returns (bool canCancel);

    /// @notice Hook for handling cancel redeem requests
    /// @param share The address of the share token
    /// @param controller The address of the controller
    /// @return canCancel Whether the redeem can be cancelled instantly
    function onCancelRedeemRequest(address share, address controller) external returns (bool canCancel);

    /// @notice Hook for handling deposit requests
    /// @param share The address of the share token
    /// @param assets The amount of assets to deposit
    /// @param receiver The address of the receiver
    /// @param controller The address of the controller
    function onDeposit(address share, uint256 assets, address receiver, address controller)
        external
        returns (uint256 price);

    /// @notice Hook for handling mint requests
    /// @param share The address of the share token
    /// @param shares The amount of shares to mint
    /// @param receiver The address of the receiver
    /// @param controller The address of the controller
    function onMint(address share, uint256 shares, address receiver, address controller)
        external
        returns (uint256 price);

    /// @notice Hook for handling redeem requests
    /// @param share The address of the share token
    /// @param shares The amount of shares to redeem
    /// @param receiver The address of the receiver
    function onRedeem(address share, uint256 shares, address receiver, address controller) external;

    /// @notice Hook for handling withdraw requests
    /// @param share The address of the share token
    /// @param assets The amount of assets to withdraw
    /// @param receiver The address of the receiver
    /// @param controller The address of the controller
    function onWithdraw(address share, uint256 assets, address receiver, address controller) external;

    /// @notice Hook for handling vault transfers
    /// @param from The address of the sender
    /// @param to The address of the receiver
    /// @param amount The amount of shares to transfer
    function onTransfer(address share, address from, address to, uint256 amount) external;

    /// @notice Operator authorization
    /// @param operator The address of the operator
    /// @dev Reverts for unauthorized operator. Operator should not be an input value of another call
    function authOperator(address operator) external;

    /// @notice Centralized share price
    /// @param share The address of the share token
    function sharePrice(address share) external view returns (uint256 price);

    /// @notice Centralized accrued assets
    /// @param share The address of the share token
    /// @return assets The accrued assets to be distributed
    function accruedAssets(address share) external view returns (uint256 assets);

    /// @notice Centralized max deposit capacity
    /// @param share The address of the share token
    /// @param controller The address of the controller
    /// @return maxAssets The maximum amount of assets that can be deposited
    function maxDeposit(address share, address controller) external view returns (uint256 maxAssets);

    /// @notice Centralized max redeem capacity
    /// @param share The address of the share token
    /// @param controller The address of the controller
    /// @return maxShares The maximum amount of shares that can be redeemed
    function maxRedeem(address share, address controller) external view returns (uint256 maxShares);
}

/// @notice Interface for managing fee manager hooks
interface IFeeManagerHooks {
    /// @notice Hook for handling fee structure changes
    function onFeeStructureChange() external;
}

interface IUpdateLateStatus {
    /// @notice Updates the late status of the loan
    function updateLateStatus() external;
}

/// @notice Interface for managing base strategy components
interface IAccountableStrategy is IStrategyVaultHooks, IFeeManagerHooks, IERC165 {
    /// @notice Event emitted when the borrower is changed
    event BorrowerChanged(address indexed oldBorrower, address indexed newBorrower);

    /// @notice Event emitted when the pending borrower is set
    event PendingBorrowerSet(address indexed pendingBorrower);

    /// @notice Event emitted when the safety module is set
    event SafetyModuleSet(address indexed safetyModule);

    /// @notice Event emitted when the investment manager is set
    event InvestmentManagerSet(address indexed investmentManager);

    /// @notice Event emitted when the proof signer is set
    event ProofSignerSet(address indexed proofSigner);

    /// @notice Event emitted when the DVN publisher is set
    event DVNPublisherSet(address indexed publisher);

    /// @notice Event emitted when the manager fee recipient is set
    event ManagerFeeRecipientSet(address indexed managerFeeRecipient);

    /// @notice Event emitted when the DVN proof is published
    event DVNProofPublished(bytes32 indexed root, bytes32 indexed signature, bytes32 indexed messageHash);

    /// @notice Event emitted when a rate is published
    event RatePublished(address indexed publisher, uint256 oldRate, uint256 newRate);

    /// @notice Event emitted when the default is rejected
    event LoanDefaultRejected();

    /// @notice Event emitted when the default is accepted
    event LoanDefaulted(uint256 principal, uint256 collateral);

    /// @notice Event emitted when the penalties enabled flag is set
    event PenaltiesEnabledSet(bool enabled);

    /// @notice Event emitted when the security admin enabled flag is set
    event SecurityAdminEnabledSet(bool enabled);

    /// @notice Event emitted when the operations admin enabled flag is set
    event OperationsAdminEnabledSet(bool enabled);

    /// @notice Event emitted when the reserve threshold is set
    event ReserveThresholdSet(uint256 threshold);

    /// @notice Event emitted when the rewards distributor is set
    event RewardsDistributorSet(address indexed rewardsDistributor);

    /// @notice Event emitted when the price oracle is set
    event PriceOracleSet(address indexed priceOracle);

    /// @notice Set a new pending borrower
    /// @param newBorrower Address of the new pending borrower
    function setPendingBorrower(address newBorrower) external;

    /// @notice Accept the borrower role as pending borrower
    function acceptBorrowerRole() external;

    /// @notice Set a new safety module contract
    /// @dev It can act as a factory in a deploy-and-set manner
    /// @param safetyModule Address of the new safety module
    function setSafetyModule(address safetyModule) external;

    /// @notice Set a new rewards distributor contract
    /// @dev It can act as a factory in a deploy-and-set manner
    /// @param rewards Address of the new rewards distributor
    function setRewardsDistributor(address rewards) external;

    /// @notice Set a new price oracle contract
    /// @param priceOracle Address of the new price oracle
    function setPriceOracle(address priceOracle) external;

    /// @notice Set a new investment manager contract
    /// @param investmentManager Address of the new investment manager
    function setInvestmentManager(address investmentManager) external;

    /// @notice Set the auth signer address
    /// @dev This is function relays data to the vault's access module
    ///      It sets the kyc verification signer when permission level is `KYC`
    /// @param authSigner Address of the new auth signer
    function setAuthSigner(address authSigner) external;

    /// @notice Set the lenders addresses and permissions
    /// @dev This is function relays data to the vault's access module
    ///      It whitelists lenders when permission level is `Whitelist`
    /// @param lenders Addresses of the lenders to be whitelisted
    /// @param allowed Whether the lenders are allowed to perform actions
    function setLenders(address[] calldata lenders, bool[] calldata allowed) external;

    /// @notice Set the proof signer address
    /// @param proofSigner Address of the new proof signer
    function setProofSigner(address proofSigner) external;

    /// @notice Set the DVN publisher address
    /// @param publisher Address of the new DVN publisher
    function setDVNPublisher(address publisher) external;

    /// @notice Set the manager fee recipient address
    /// @param managerFeeRecipient Address of the new manager fee recipient
    function setManagerFeeRecipient(address managerFeeRecipient) external;

    /// @notice Publish a new DVN proof
    /// @param proof Latest DVN proof data
    function publishDVNProof(DVNProof memory proof) external;

    /// @notice Publish a new rate
    /// @param newRate The new rate to publish (can be interest rate, NAV etc.)
    /// @param measuredAt The timestamp of the measurement being published
    function publishRate(uint256 newRate, uint256 measuredAt) external;

    /// @notice Accept the default of the loan
    function acceptDefault() external;

    /// @notice Reject the default of the loan
    function rejectDefault() external;

    /// @notice Set the penalties enabled flag
    /// @param enabled Whether penalties are enabled
    function setPenaltiesEnabled(bool enabled) external;

    /// @notice Set the security admin enabled flag
    /// @param enabled Whether security admin is enabled
    function setSecurityAdminEnabled(bool enabled) external;

    /// @notice Set the operations admin enabled flag
    /// @param enabled Whether operations admin is enabled
    function setOperationsAdminEnabled(bool enabled) external;

    /// @notice Set the shares transferable flag
    /// @param transferable Whether shares are transferable
    function setSharesTransferable(bool transferable) external;

    /// @notice Set the min reserve threshold required in the vault
    /// @param threshold The threshold expressed in basis points
    function setReserveThreshold(uint256 threshold) external;

    /// @notice Get the global registry contract address
    /// @return The global registry address
    function globals() external view returns (address);

    /// @notice Get the current borrower address
    /// @return The borrower address
    function borrower() external view returns (address);

    /// @notice Get the pending borrower address
    /// @return The pending borrower address
    function pendingBorrower() external view returns (address);

    /// @notice Get the investment manager contract address
    /// @return The investment manager address
    function investmentManager() external view returns (address);

    /// @notice Get the fee manager contract address
    /// @return The fee manager address
    function feeManager() external view returns (address);

    /// @notice Get the safety module contract address
    /// @return The safety module address
    function safetyModule() external view returns (address);

    /// @notice Get the rewards distributor contract address
    /// @return The rewards distributor address
    function rewards() external view returns (address);

    /// @notice Get the price oracle contract address
    /// @return The price oracle address
    function priceOracle() external view returns (address);

    /// @notice Get the DVN publisher contract address
    /// @return The DVN publisher address
    function dvnPublisher() external view returns (address);

    /// @notice Get the manager fee recipient address
    /// @return The manager fee recipient address
    function managerFeeRecipient() external view returns (address);

    /// @notice Get the proof signer address
    /// @return The proof signer address
    /// @dev Returns the pub key of the node signing proofs
    function proofSigner() external view returns (address);

    /// @notice Get the vault contract address
    /// @return The vault address
    function vault() external view returns (address);

    /// @notice Get the current loan state
    /// @return The loan struct
    function loan() external view returns (Loan memory);

    /// @notice Get the DVN proof
    /// @return The latest DVN proof data
    function dvnProof() external view returns (DVNProof memory);

    /// @notice Get the loan state
    /// @return The loan state enum value
    function loanState() external view returns (LoanState);

    /// @notice Get the penalties enabled flag
    /// @return The penalties enabled flag
    function penaltiesEnabled() external view returns (bool);

    /// @notice Get the security admin enabled flag
    /// @return The security admin enabled flag
    function securityAdminEnabled() external view returns (bool);

    /// @notice Get the operations admin enabled flag
    /// @return The operations admin enabled flag
    function operationsAdminEnabled() external view returns (bool);

    /// @notice Get the precision for the strategy
    /// @return The precision
    function PRECISION() external view returns (uint256);

    /// @notice Get the basis points for the strategy
    /// @return The basis points
    function BASIS_POINTS() external view returns (uint256);

    /// @notice Get the version of the strategy
    /// @dev Increment when upgrading the strategy
    function version() external view returns (uint256);
}

/// @notice Interface for managing loan lifecycle and payments
interface IAccountableLoan is IAccountableStrategy {
    /// @notice Event emitted when the loan is initialized
    /// @param minCapacity The minimum loan capacity
    /// @param maxCapacity The maximum loan capacity
    /// @param interestRate The interest rate of the loan
    /// @param lateInterestPenalty The late interest penalty
    /// @param interestInterval The interest interval
    /// @param duration The duration of the loan
    event LoanTermsSet(
        uint256 minCapacity,
        uint256 maxCapacity,
        uint256 interestRate,
        uint256 lateInterestPenalty,
        uint256 interestInterval,
        uint256 duration
    );

    /// @notice Event emitted when the default is initiated
    event LoanDefaultInitiated();

    /// @notice Event emitted when a default is covered by safety collateral
    /// @param safetyModule The address of the safety module
    /// @param provider The address of the provider
    /// @param collateral The amount of collateral covered
    event DefaultCovered(address indexed safetyModule, address indexed provider, uint256 collateral);

    /// @notice Event emitted when funds are borrowed
    /// @param borrower The address of the borrower
    /// @param assets The amount of funds borrowed
    event Borrowed(address indexed borrower, uint256 assets);

    /// @notice Event emitted when the loan is repaid
    /// @param assets The amount of funds repaid
    event LoanRepaid(uint256 assets);

    /// @notice Event emitted when the loan is partially repaid
    /// @param amount The amount of funds repaid to close loan
    /// @param remainingInterest The remaining interest amount
    event LoanPrepaid(uint256 amount, uint256 remainingInterest);

    /// @notice Event emitted when interest is paid
    /// @param borrower The address of the borrower
    /// @param totalAmount The total amount paid
    /// @param interestPenalty The interest penalty amount paid
    /// @param performanceFee The performance fee amount paid
    /// @param managementFee The management fee amount paid
    /// @param paymentInterval The interval of the payment
    event InterestPaid(
        address indexed borrower,
        uint256 totalAmount,
        uint256 interestPenalty,
        uint256 performanceFee,
        uint256 establishmentFee,
        uint256 managementFee,
        uint256 paymentInterval
    );

    /// @notice Initialize a new loan with the given terms
    /// @param terms The loan terms to initialize with
    function setTerms(LoanTerms memory terms) external;

    /// @notice Update an existing loan with new terms
    /// @param terms The new loan terms to update to
    function updateTerms(LoanTerms memory terms) external;

    /// @notice Initialize loan default state
    function defaultLoan() external;

    /// @notice Cover the default of the loan
    /// @param assets The amount of assets to cover
    function coverDefault(uint256 assets) external;

    /// @notice Borrow funds from the loan
    /// @param assets The amount of funds to borrow
    function borrow(uint256 assets) external;

    /// @notice Repay the loan amount
    /// @param assets The amount of funds to repay
    function repay(uint256 assets) external;

    /// @notice Make a partial loan repayment
    function prepay() external;

    /// @notice Make an interest payment
    /// @param assets The interest amount to pay
    function pay(uint256 assets) external;

    /// @notice Get the period of time the loan has been delinquent
    /// @return The period of time the loan has been delinquent
    function timeDelinquent() external view returns (uint256);
}

src/interfaces/IAsyncVaultFactory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import {PermissionLevel} from "./IAccess.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title IAsyncVaultFactory
/// @notice Interface for creating async vaults
interface IAsyncVaultFactory {
    /// @notice Emitted when a new async redeem vault is created
    /// @param vault The address of the created vault
    event AsyncRedeemVaultCreated(address indexed vault);

    /// @notice Creates a new async redeem vault
    /// @param asset The asset token address for the vault
    /// @param proxy The proxy address for the vault
    /// @param sharesTransferable Whether shares are transferable
    /// @param permissionLevel The permission level for the vault
    /// @param name The name of the vault
    /// @param symbol The symbol of the vault
    /// @param precision The precision for the vault
    function createAsyncRedeemVault(
        IERC20 asset,
        address proxy,
        bool sharesTransferable,
        PermissionLevel permissionLevel,
        string memory name,
        string memory symbol,
        uint256 precision
    ) external returns (address);
}

src/interfaces/IFeeManager.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

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

/// @notice The fee structure for a strategy
struct FeeStructure {
    /// @notice The establishment fee
    uint256 establishmentFee;
    /// @notice The management fee
    uint256 managementFee;
    /// @notice The performance fee
    uint256 performanceFee;
    /// @notice The manager performance fee split
    uint256 managerPerformanceFeeSplit;
    /// @notice The manager management fee split
    uint256 managerManagementFeeSplit;
    /// @notice Whether to override the default fees
    bool overrideDefaults;
}

interface IFeeManager is IRecoverable, IERC165 {
    /// @notice An event that is emitted when fees are collected
    event Collected(address indexed asset, address indexed strategy, uint256 performanceFee, uint256 managementFee, uint256 establishmentFee);

    /// @notice An event that is emitted when protocol fees are withdrawn
    event Withdraw(address indexed asset, address indexed strategy, address indexed receiver, uint256 amount);

    /// @notice An event that is emitted when the fee structure is set
    event FeeStructureSet(address indexed strategy, FeeStructure feeStructure);

    /// @notice An event that is emitted when the pending fee structure is set
    event PendingFeeStructureSet(address indexed strategy, FeeStructure feeStructure);

    /// @notice An event that is emitted when the performance fee is set
    event PerformanceFeeSet(address indexed strategy, uint256 performanceFee);

    /// @notice An event that is emitted when the prepayment fee is set
    event PrepaymentFeeSet(address indexed strategy, uint256 prepaymentFee);

    /// @notice An event that is emitted when the treasury is set
    event TreasurySet(address indexed oldTreasury, address indexed newTreasury);

    /// @notice Collects strategy fees
    /// @param asset The address of the asset
    /// @param performanceFee The performance fee
    /// @param managementFee The management fee
    /// @param establishmentFee The establishment fee
    function collect(address asset, uint256 performanceFee, uint256 managementFee, uint256 establishmentFee) external;

    /// @notice Approves the pending fee structure
    /// @param strategy The address of the strategy
    function approvePendingFeeStructure(address strategy) external;

    /// @notice Withdraws protocol fees
    /// @param asset The address of the asset
    function withdrawProtocolFee(address asset) external;

    /// @notice Withdraws manager fees
    /// @param receiver The address of the receiver
    /// @param asset The address of the asset
    /// @param strategy The address of the strategy
    function withdrawManagerFee(address receiver, address asset, address strategy) external;

    /// @notice Sets the fee structure
    /// @param strategy The address of the strategy
    /// @param feeStructure The fee structure
    function setFeeStructure(address strategy, FeeStructure memory feeStructure) external;

    /// @notice Sets the pending fee structure
    /// @param strategy The address of the strategy
    /// @param feeStructure The fee structure
    function setPendingFeeStructure(address strategy, FeeStructure memory feeStructure) external;

    /// @notice Sets the performance fee
    /// @param strategy The address of the strategy
    /// @param performanceFee The performance fee
    function setPerformanceFee(address strategy, uint256 performanceFee) external;

    /// @notice Sets the prepayment fee
    /// @param strategy The address of the strategy
    /// @param prepaymentFee The prepayment fee
    function setPrepaymentFee(address strategy, uint256 prepaymentFee) external;

    /// @notice Sets the treasury
    /// @param treasury The address of the treasury
    function setTreasury(address treasury) external;

    /// @notice Returns the establishment fee
    /// @param strategy The address of the strategy
    /// @return The establishment fee
    function establishmentFee(address strategy) external view returns (uint256);

    /// @notice Returns the management fee
    /// @param strategy The address of the strategy
    /// @return The management fee
    function managementFee(address strategy) external view returns (uint256);

    /// @notice Returns the performance fee
    /// @param strategy The address of the strategy
    /// @return The performance fee
    function performanceFee(address strategy) external view returns (uint256);

    /// @notice Returns the manager split
    /// @param strategy The address of the strategy
    /// @param isPerformanceFee Whether the fee is a performance fee
    /// @return The manager split
    function managerSplit(address strategy, bool isPerformanceFee) external view returns (uint256);

    /// @notice Returns the protocol split
    /// @param strategy The address of the strategy
    /// @param isPerformanceFee Whether the fee is a performance fee
    /// @return The protocol split
    function protocolSplit(address strategy, bool isPerformanceFee) external view returns (uint256);

    /// @notice Returns the prepayment fee
    /// @param strategy The address of the strategy
    /// @return The prepayment fee
    function prepaymentFee(address strategy) external view returns (uint256);

    /// @notice Returns the fee structure
    /// @param strategy The address of the strategy
    /// @return The fees percentages for the strategy
    function feeStructure(address strategy) external view returns (FeeStructure memory);

    /// @notice Returns the pending fee structure
    /// @param strategy The address of the strategy
    /// @return The pending fee structure
    function pendingFeeStructure(address strategy) external view returns (FeeStructure memory);

    /// @notice Returns the treasury
    /// @return The treasury
    function treasury() external view returns (address);

    /// @notice Returns the manager fees
    /// @param manager The address of the manager
    /// @param asset The address of the asset
    /// @param strategy The address of the strategy
    /// @return The manager fees of a given strategy
    function managerFees(address manager, address asset, address strategy) external view returns (uint256);

    /// @notice Returns the total manager fees
    /// @param manager The address of the manager
    /// @param asset The address of the asset
    /// @param strategies The addresses of the strategies
    /// @return The total manager fees of a given asset and strategies
    function managerTotalFees(address manager, address asset, address[] calldata strategies)
        external
        view
        returns (uint256);

    /// @notice Returns the protocol fees
    /// @param asset The address of the asset
    /// @return The protocol fees
    function protocolFees(address asset) external view returns (uint256);

    /// @notice The basis points for the fee manager
    /// @return The basis points
    function BASIS_POINTS() external pure returns (uint256);
}

src/interfaces/IGlobalRegistry.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

interface IGlobalRegistry {
    /// @notice Emitted when the security admin is set
    /// @param securityAdmin The address of the security admin
    event SecurityAdminSet(address securityAdmin);

    /// @notice Emitted when the operations admin is set
    /// @param operationsAdmin The address of the operations admin
    event OperationsAdminSet(address operationsAdmin);

    /// @notice Emitted when the treasury is set
    /// @param treasury The address of the treasury
    event TreasurySet(address treasury);

    /// @notice Emitted when the vault factory is set
    /// @param vaultFactory The address of the vault factory
    event VaultFactorySet(address vaultFactory);

    /// @notice Emitted when the rewards factory is set
    /// @param rewardsFactory The address of the rewards factory
    event RewardsFactorySet(address rewardsFactory);

    /// @notice Sets the security admin
    /// @param securityAdmin The address of the security admin
    function setSecurityAdmin(address securityAdmin) external;

    /// @notice Sets the operations admin
    /// @param operationsAdmin The address of the operations admin
    function setOperationsAdmin(address operationsAdmin) external;

    /// @notice Sets the treasury
    /// @param treasury The address of the treasury
    function setTreasury(address treasury) external;

    /// @notice Sets the vault factory
    /// @param vaultFactory The address of the vault factory
    function setVaultFactory(address vaultFactory) external;

    /// @notice Sets the rewards factory
    /// @param rewardsFactory The address of the rewards factory
    function setRewardsFactory(address rewardsFactory) external;

    /// @notice Protocol security admin
    /// @return The address of the Accountablesecurity admin
    function securityAdmin() external view returns (address);

    /// @notice Protocol operations admin
    /// @return The address of the Accountable operations admin
    function operationsAdmin() external view returns (address);

    /// @notice Protocol treasury
    /// @return The address of the treasury
    function treasury() external view returns (address);

    /// @notice Vault factory
    /// @return The address of the vault factory
    function vaultFactory() external view returns (address);

    /// @notice Rewards distributor factory
    /// @return The address of the rewards factory
    function rewardsFactory() external view returns (address);
}

src/interfaces/ILoanEscrow.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import {IRecoverable} from "./IRecoverable.sol";
import {Loan, LoanState} from "./IAccountableStrategy.sol";

/// @notice Minimal view of strategy used by the escrow
interface IEscrowStrategy {
    /// @notice The state of the loan
    function loanState() external view returns (LoanState);
    /// @notice The loan of the strategy
    function loan() external view returns (Loan memory);
    /// @notice The investment manager of the strategy
    function investmentManager() external view returns (address);
}

interface ILoanEscrow is IRecoverable {
    /// @notice Emitted when funds are funded into the escrow
    /// @param amount The amount of loan tokens funded
    /// @param accLoanPerShare The updated accumulator after funding
    event Funded(uint256 amount, uint256 accLoanPerShare);

    /// @notice Emitted when an LP claims their entitlement
    /// @param account The address of the LP
    /// @param loanAmount The amount of loan tokens claimed
    /// @param shareAmount The amount of shares locked as collateral
    event Claimed(address indexed account, uint256 loanAmount, uint256 shareAmount);

    /// @notice Emitted when an LP repays their debt and recovers shares
    /// @param account The address of the LP
    /// @param loanAmount The amount of loan tokens repaid
    /// @param shareAmount The amount of shares returned to the LP
    event Repaid(address indexed account, uint256 loanAmount, uint256 shareAmount);

    /// @notice Emitted when the reclaim grace period is set
    /// @param period The new reclaim grace period in seconds
    event ReclaimGracePeriodSet(uint256 period);

    /// @notice Emitted when an LP is notified of their repayment status
    /// @param timestamp The timestamp of the notification
    /// @param reservedLoanTokenCleared The amount of reserved loan tokens that were released
    event RepaidNotified(uint256 timestamp, uint256 reservedLoanTokenCleared);

    /// @notice Emitted when an LP reclaims their shares after the grace period
    /// @param account The address of the LP
    /// @param shareAmount The amount of shares reclaimed
    /// @param loanClaimed The outstanding loan debt
    /// @param pendingLoan The unclaimed loan tokens
    event SharesReclaimed(address indexed account, uint256 shareAmount, uint256 loanClaimed, uint256 pendingLoan);

    /// @notice Emitted when tokens are recovered from the escrow
    /// @param token The recovered token
    /// @param to The recipient of the recovered tokens
    /// @param amount The amount recovered
    event TokensRecovered(address indexed token, address indexed to, uint256 amount);

    /// @notice Emitted when all collateral shares are seized on default
    /// @param sharesSeized The total amount of shares seized
    /// @param reservedLoanTokenCleared The amount of reserved loan tokens that were released
    event Seized(uint256 sharesSeized, uint256 reservedLoanTokenCleared);

    /// @notice Emitted when an implementation upgrade is proposed, starting the upgrade timelock
    /// @param newImplementation The proposed implementation
    /// @param readyAt The timestamp after which the upgrade can be executed
    event UpgradeProposed(address indexed newImplementation, uint256 readyAt);

    /// @notice Emitted when a pending implementation upgrade is cancelled
    /// @param newImplementation The implementation that was pending
    event UpgradeCancelled(address indexed newImplementation);

    /// @notice Fund the escrow with loan tokens and update the accumulator
    /// @param amount The amount of loan tokens to distribute
    function fund(uint256 amount) external;

    /// @notice Whether any funding round has been executed
    function funded() external view returns (bool);

    /// @notice Claim pending entitlement, locking shares as collateral
    /// @return amount The amount of loan tokens claimed
    function claim() external returns (uint256 amount);

    /// @notice Repay outstanding debt (fully or partially) and recover proportional locked shares
    /// @param amount The amount of loan tokens to repay
    /// @return shareAmount The amount of shares returned to the caller
    function repay(uint256 amount) external returns (uint256 shareAmount);

    /// @notice Settle an account's accumulator checkpoint without claiming
    /// @param account The address to settle
    function settleAccount(address account) external;

    /// @notice Notify the escrow that the loan has been repaid
    function notifyRepaid() external;

    /// @notice Reclaim shares after the grace period if debt is not repaid
    /// @param account The address of the LP reclaiming shares
    function reclaimShares(address account) external;

    /// @notice Reclaim shares for multiple accounts after the grace period if debt is not repaid
    /// @param accounts The addresses of the LPs reclaiming shares
    function reclaimSharesInBulk(address[] calldata accounts) external;

    /// @notice Set the reclaim grace period for LPs to reclaim shares after loan repayment
    /// @param period The new reclaim grace period in seconds
    function setReclaimGracePeriod(uint256 period) external;

    /// @notice Seize all locked collateral shares on default
    /// @return sharesSeized The amount of shares seized
    function seize() external returns (uint256 sharesSeized);

    /// @notice The loan token distributed to LPs
    function loanToken() external view returns (address);

    /// @notice The vault share token used as collateral
    function share() external view returns (address);

    /// @notice The governing strategy used for state gating
    function strategy() external view returns (address);

    /// @notice Global accumulator of loan tokens per share, scaled by PRECISION
    function accLoanPerShare() external view returns (uint256);

    /// @notice Last-seen accumulator value per account
    function userIndex(address) external view returns (uint256);

    /// @notice Cumulative loan tokens claimed by an account
    function loanClaimed(address) external view returns (uint256);

    /// @notice Shares currently locked in escrow as collateral for an account
    function sharesHeld(address) external view returns (uint256);

    /// @notice The total number of shares locked in escrow
    function totalSharesHeld() external view returns (uint256);

    /// @notice Whether an account has fully repaid their loan debt
    function repaid(address) external view returns (bool);

    /// @notice Pending claimable loan tokens for an account based on current accumulator
    function pending(address account) external view returns (uint256);

    /// @notice Total share entitlement for an account (wallet balance + escrowed shares)
    function entitled(address account) external view returns (uint256);

    /// @notice Repaid timestamp of the loan, used to calculate reclaim grace period
    /// @return The timestamp when the loan was repaid
    function repaidAt() external view returns (uint256);

    /// @notice The reclaim grace period for LPs to reclaim shares after loan repayment
    /// @return The reclaim grace period in seconds
    function reclaimGracePeriod() external view returns (uint256);

    /// @notice Pending unclaimed loan tokens saved from prior transfers, claimable on next claim()
    /// @param account The address to query
    /// @return The pending unclaimed loan token amount
    function pendingLoan(address account) external view returns (uint256);

    /// @notice Whether share transfers to escrow are currently allowed
    function shareTransfersAllowed() external view returns (bool);

    /// @notice Whether claims are currently allowed (loan is ongoing)
    function isClaimAllowed() external view returns (bool);
}

src/interfaces/ILoanEscrowDeployer.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

/// @notice One-shot factory callback used while initializing a collateral fixed-term strategy
interface ILoanEscrowDeployer {
    /// @notice Deploys the escrow for the strategy currently being created
    /// @param loanToken The token distributed to vault LPs
    /// @param share The vault share token locked as collateral
    /// @return escrow The deployed escrow address
    function createLoanEscrow(address loanToken, address share) external returns (address escrow);
}

src/interfaces/IRecoverable.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

/// @notice Interface for recoverable tokens
interface IRecoverable {
    /// @notice Recovers tokens from the contract
    /// @param token The address of the token to recover
    /// @param to The address to send the recovered tokens to
    /// @param amount The amount of tokens to recover
    function recoverTokens(address token, address to, uint256 amount) external;
}

src/interfaces/IRewards.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

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

/// @notice Pending root for rewards distribution
struct PendingRoot {
    /// @notice The root of the merkle tree
    bytes32 root;
    /// @notice The timestamp when the root is valid at
    uint256 validAt;
}

/// @notice Reward struct
struct Reward {
    /// @notice The total amount of reward assets without accrued rewards
    uint256 totalWithoutRewards;
    /// @notice The total amount of reward assets borrowed
    /// @dev This amount is an always increasing counter
    uint256 totalBorrowed;
    /// @notice The total amount of reward assets repaid
    /// @dev This amount is an always increasing counter
    /// @dev The delta between repaid and borrowed can be used to calculate performance
    /// @dev Greater repaid amount means a positive performance that returned profits to the strategy
    /// @dev In cases of negative delta, the offset from accrued rewards can compensate for the negative returns
    uint256 totalRepaid;
}

/// @notice The type of rewards distribution
/// @dev Used for integrators to determine the type of rewards distribution
enum RewardsType {
    /// @notice No rewards distribution
    None,
    /// @notice Rewards distribution via merkle proofs
    Merkle,
    /// @notice Rewards distribution via strategy
    Strategy
}

/// @notice Base interface for rewards modules
interface IRewardsBase is IRecoverable, IERC165 {
    /// @notice Emitted when rewards are locked
    /// @param amount The amount of rewards locked
    /// @param asset The address of the asset being locked
    /// @param owner The address of the asset owner
    event RewardLocked(uint256 amount, address indexed asset, address indexed owner);

    /// @notice Emitted when rewards are borrowed
    /// @param amount The amount of rewards borrowed
    /// @param asset The address of the asset being borrowed
    /// @param receiver The address of the receiver
    event RewardBorrowed(uint256 amount, address indexed asset, address indexed receiver);

    /// @notice Emitted when rewards are repaid
    /// @param amount The amount of rewards repaid
    /// @param asset The address of the asset being repaid
    /// @param owner The address of the owner of the rewards
    event RewardRepaid(uint256 amount, address indexed asset, address indexed owner);

    /// @notice Emitted when rewards are added
    /// @param amount The amount of rewards added
    /// @param asset The address of the asset being added
    /// @param owner The address of the asset owner
    event RewardAdded(uint256 amount, address indexed asset, address indexed owner);

    /// @notice Emitted when an updater is set
    /// @param updater The address of the updater
    /// @param allowed Whether the updater is allowed
    event UpdaterSet(address indexed updater, bool allowed);

    /// @notice Locks underlying rewards in the rewards module
    /// @param amount The amount of rewards to lock
    /// @param asset The address of the asset being locked
    /// @param owner The address of the asset owner
    /// @dev This MUST be a strategy downstream authorized call
    /// @dev This MUST revert for rewards distributions that don't require locked underlying asset
    function lock(uint256 amount, address asset, address owner) external;

    /// @notice Borrows underlying rewards from the rewards module
    /// @param amount The amount of rewards to borrow
    /// @param asset The address of the asset being borrowed
    /// @param receiver The address of the receiver
    function borrow(uint256 amount, address asset, address receiver) external;

    /// @notice Repays underlying rewards to the rewards module
    /// @param amount The amount of rewards to repay
    /// @param asset The address of the asset being repaid
    /// @param owner The address of the owner of the rewards
    function repay(uint256 amount, address asset, address owner) external;

    /// @notice Adds rewards to the rewards module
    /// @param amounts The amounts of rewards to add
    /// @param assets The addresses of the assets being added
    /// @param owner The address of the owner of the rewards
    function addRewards(uint256[] calldata amounts, address[] calldata assets, address owner) external;

    /// @notice Adds a reward to the rewards module
    /// @param amount The amount of rewards to add
    /// @param asset The address of the asset being added
    /// @param owner The address of the owner of the rewards
    /// @dev This assumes the root will be set independently
    function addReward(uint256 amount, address asset, address owner) external;

    /// @notice Returns the total value locked in the rewards module
    /// @return tvl The total value locked in the rewards module
    function rewardState(address asset) external view returns (Reward memory);

    /// @notice Sets an updater
    /// @param updater The address of the updater
    /// @param allowed Whether the updater is allowed
    function setUpdater(address updater, bool allowed) external;

    /// @notice Returns the strategy address
    /// @return strategy The strategy address
    function strategy() external view returns (address);

    /// @notice Returns whether an updater is allowed
    /// @param updater The address of the updater
    /// @return allowed Whether the updater is allowed
    function updaters(address updater) external view returns (bool);

    /// @notice Returns the total rewards for an asset
    /// @param asset The address of the asset
    /// @return totalRewards The total rewards for an asset
    function totalRewards(address asset) external view returns (uint256);
}

/// @notice Base interface for rewards distributor
interface IRewardsDistributorBase {
    /// @notice Emitted when a user claims rewards
    /// @param account The address of the user who claims rewards
    /// @param asset The address of the asset being claimed
    /// @param amount The amount of rewards claimed
    event Claimed(address indexed account, address indexed asset, uint256 amount);

    /// @notice Claims available rewards
    /// @param account The address of the user who claims rewards
    /// @param asset The address of the asset being claimed
    /// @param claimable The amount of rewards claimable
    /// @param proof The proof of the merkle tree
    /// @return amount The amount of rewards claimed
    /// @dev Can be an authorized call depending on distribution model
    function claim(address account, address asset, uint256 claimable, bytes32[] calldata proof)
        external
        returns (uint256 amount);

    /// @notice Returns the amount of rewards claimed for an account and asset
    /// @param account The address of the user who claims rewards
    /// @param asset The address of the asset being claimed
    /// @return amount The amount of rewards claimed
    function claimed(address account, address asset) external view returns (uint256 amount);
}

/// @notice Interface for rewards distributor with merkle proofs
interface IRewardsDistributorMerkle is IRewardsDistributorBase {
    /// @notice Emitted when the root is set
    /// @param oldRoot The old root
    /// @param newRoot The new root
    event RootSet(bytes32 indexed oldRoot, bytes32 indexed newRoot);

    /// @notice Emitted when the timelock is set
    /// @param timelock The timelock
    event TimelockSet(uint256 timelock);

    /// @notice Emitted when a pending root is set
    /// @param updater The address of the updater who set the pending root
    /// @param root The root of the pending root
    event PendingRootSet(address indexed updater, bytes32 indexed root);

    /// @notice Emitted when a pending root is revoked
    /// @param updater The address of the updater who revoked the pending root
    event PendingRootRevoked(address indexed updater);

    /// @notice Sets the root
    /// @param root The root
    function setRoot(bytes32 root) external;

    /// @notice Submits a pending root
    /// @param root The root
    function submitRoot(bytes32 root) external;

    /// @notice Accepts a pending root
    function acceptRoot() external;

    /// @notice Revokes a pending root
    function revokePendingRoot() external;

    /// @notice Sets the timelock
    /// @param timelock The timelock
    function setTimelock(uint256 timelock) external;

    /// @notice Returns the root
    /// @return root The root
    function root() external view returns (bytes32);

    /// @notice Returns the pending root
    /// @return pendingRoot The pending root
    function pendingRoot() external view returns (PendingRoot memory);

    /// @notice Returns the timelock
    /// @return timelock The timelock
    function timelock() external view returns (uint256);
}

interface IRewardsDistributorStrategy is IRewardsDistributorBase {}

src/interfaces/IStrategyFactory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import {RewardsType} from "../interfaces/IRewards.sol";
import {PermissionLevel} from "../interfaces/IAccess.sol";
import {ILoanEscrowDeployer} from "./ILoanEscrowDeployer.sol";

interface IStrategyFactoryBase {
    /// @notice Emitted when the fee manager address is updated
    /// @param oldFeeManager The previous fee manager address
    /// @param newFeeManager The new fee manager address
    event FeeManagerSet(address oldFeeManager, address newFeeManager);

    /// @notice Emitted when the strategy implementation address is updated
    /// @param oldStrategyImplementation The previous implementation address
    /// @param newStrategyImplementation The new implementation address
    event StrategyImplementationSet(address oldStrategyImplementation, address newStrategyImplementation);

    /// @notice Emitted when the vault factory address is updated
    /// @param oldVaultFactory The previous vault factory address
    /// @param newVaultFactory The new vault factory address
    event VaultFactorySet(address oldVaultFactory, address newVaultFactory);

    /// @notice Emitted when the rewards factory address is updated
    /// @param oldRewardsFactory The previous rewards factory address
    /// @param newRewardsFactory The new rewards factory address
    event RewardsFactorySet(address oldRewardsFactory, address newRewardsFactory);

    /// @notice Emitted when the global registry address is updated
    /// @param oldGlobals The previous global registry address
    /// @param newGlobals The new global registry address
    event GlobalsSet(address oldGlobals, address newGlobals);

    /// @notice Emitted when an asset is added to the whitelist
    /// @param asset The asset address
    /// @param status Whether the asset is whitelisted or not
    event AssetWhitelistSet(address asset, bool status);

    /// @notice Emitted when the whitelist status is updated
    /// @param status The new whitelist status
    event WhitelistSet(bool status);

    /// @notice Sets a new global registry address
    /// @param globals The new global registry address
    function setGlobals(address globals) external;

    /// @notice Sets a new fee manager address
    /// @param feeManager The new fee manager address
    function setFeeManager(address feeManager) external;

    /// @notice Sets a new strategy implementation address
    /// @param strategyImplementation The new implementation address
    function setStrategyImplementation(address strategyImplementation) external;

    /// @notice Sets a new asset whitelist or change the whitelist status if the asset is already whitelisted
    /// @param asset The asset address
    function setAssetWhitelist(address asset) external;

    /// @notice Sets the whitelist status
    /// @param status The new whitelist status
    function setWhitelist(bool status) external;

    /// @notice Returns whether asset whitelisting is enabled
    /// @return Whether asset whitelisting is enabled
    function enableWhitelist() external view returns (bool);

    /// @notice Returns the global registry address
    /// @return The global registry address
    function globals() external view returns (address);

    /// @notice Returns the fee manager address
    /// @return The fee manager address
    function feeManager() external view returns (address);

    /// @notice Returns the strategy implementation address
    /// @return The strategy implementation address
    function strategyImplementation() external view returns (address);

    /// @notice Returns whether an asset is whitelisted
    /// @param asset The asset address
    /// @return Whether the asset is whitelisted
    function assetStatus(address asset) external view returns (bool);

    /// @notice Returns the vault address associated with a strategy
    /// @param strategy The strategy address
    /// @return The associated vault address
    function getStrategyVault(address strategy) external view returns (address);

    /// @notice Returns a paginated list of strategy addresses
    /// @param start The start index
    /// @param end The end index
    /// @return Array of strategy addresses within the specified range
    function getStrategiesPaginated(uint256 start, uint256 end) external view returns (address[] memory);

    /// @notice Returns the total number of strategies created
    /// @return The total count of strategies
    function getStrategiesCount() external view returns (uint256);
}

/// @notice Parameters for creating a fixed term loan with an associated vault
struct FixedTermFactoryParams {
    /// @notice The asset token address for the strategy
    address asset;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice Whether shares are transferable
    bool sharesTransferable;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface IFixedTermFactory is IStrategyFactoryBase {
    /// @notice Emitted when a new fixed term loan is created
    /// @param proxy The address of the created loan proxy contract
    /// @param vault The address of the associated vault contract
    /// @param manager The investment manager address
    event FixedTermCreated(address indexed proxy, address indexed vault, address indexed manager);

    /// @notice Creates a new fixed term loan with an associated vault
    /// @param params The parameters for creating a fixed term loan with an associated vault
    function createFixedTermLoan(FixedTermFactoryParams memory params) external returns (address, address);
}

/// @notice Parameters for creating a fixed term loan with an associated vault and rewards distributor
struct FixedTermMMFactoryParams {
    /// @notice The asset token address for the loan
    address asset;
    /// @notice The native token address for the loan
    address native;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The price oracle address for the loan
    address priceOracle;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice The rewards type for the loan
    RewardsType rewardsType;
    /// @notice The timelock for root acceptence in merkle distributor
    uint256 rootTimelock;
    /// @notice Whether shares are transferable
    bool sharesTransferable;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface IFixedTermMMFactory is IStrategyFactoryBase {
    /// @notice Emitted when a new fixed term loan is created
    /// @param proxy The address of the created loan proxy contract
    /// @param vault The address of the associated vault contract
    /// @param rewards The address of the associated rewards distributor contract
    /// @param manager The investment manager address
    /// @param admin The admin address
    event FixedTermMMCreated(
        address indexed proxy, address indexed vault, address rewards, address indexed manager, address admin
    );

    /// @notice Creates a new fixed term loan with an associated vault
    /// @param params The parameters for creating a fixed term loan with an associated vault and rewards distributor
    function createFixedTermLoanMM(FixedTermMMFactoryParams memory params) external returns (address, address);
}

/// @notice Parameters for creating an open term loan with an associated vault
struct OpenTermFactoryParams {
    /// @notice The asset token address for the strategy
    address asset;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice Whether shares are transferable
    bool sharesTransferable;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface IOpenTermFactory is IStrategyFactoryBase {
    /// @notice Emitted when a new open term loan is created
    /// @param proxy The address of the created loan proxy contract
    /// @param vault The address of the associated vault contract
    /// @param manager The investment manager address
    event OpenTermCreated(address indexed proxy, address indexed vault, address indexed manager);

    /// @notice Creates a new open term loan with an associated vault
    /// @param params The parameters for creating an open term loan with an associated vault
    function createOpenTermLoan(OpenTermFactoryParams memory params) external returns (address, address);
}

/// @notice Parameters for creating a yield loan with an associated vault
struct YieldFactoryParams {
    /// @notice The asset token address for the strategy
    address asset;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice Whether shares are transferable
    bool sharesTransferable;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface IYieldStrategyFactory is IStrategyFactoryBase {
    /// @notice Emitted when a new yield loan is created
    /// @param proxy The address of the created loan proxy contract
    /// @param vault The address of the associated vault contract
    /// @param manager The investment manager address
    event YieldStrategyCreated(address indexed proxy, address indexed vault, address indexed manager);

    /// @notice Creates a new yield loan with an associated vault
    /// @param params The parameters for creating a yield loan with an associated vault
    function createYieldStrategy(YieldFactoryParams memory params) external returns (address, address);
}

/// @notice Parameters for creating a collateral fixed term loan with an associated vault
struct CollateralFixedTermFactoryParams {
    /// @notice The collateral asset token address
    address asset;
    /// @notice The loan token address distributed to LPs
    address loanToken;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface ICollateralFixedTermFactory is IStrategyFactoryBase, ILoanEscrowDeployer {
    /// @notice Emitted when a new collateral fixed term loan is created
    /// @param proxy The address of the created strategy proxy contract
    /// @param vault The address of the associated vault contract
    /// @param escrow The address of the associated loan escrow contract
    event CollateralFixedTermCreated(address indexed proxy, address indexed vault, address escrow);

    /// @notice Creates a new collateral fixed term loan with an associated vault and escrow
    /// @param params The parameters for creating the loan
    /// @return proxy The deployed strategy proxy address
    /// @return vault The deployed vault address
    /// @return escrow The deployed escrow address
    function createCollateralFixedTerm(CollateralFixedTermFactoryParams memory params)
        external
        returns (address proxy, address vault, address escrow);
}

src/modules/LoanEscrow.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import "../constants/Errors.sol";

import {ILoanEscrow, IEscrowStrategy} from "../interfaces/ILoanEscrow.sol";
import {IRecoverable} from "../interfaces/IRecoverable.sol";
import {IAccess, PermissionLevel} from "../interfaces/IAccess.sol";

import {IAccountableStrategy, Loan, LoanState} from "../interfaces/IAccountableStrategy.sol";

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";

/// @title LoanEscrow
/// @custom:security-contact [email protected]
/// @notice LoanEscrow is a module that enables a collateral based fixed term loan to issue loans in loanToken against collateral shares
contract LoanEscrow is ILoanEscrow, Initializable, UUPSUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable {
    using Math for uint256;
    using SafeERC20 for IERC20;

    uint256 private constant PRECISION = 1e36;

    uint256 public constant RECLAIM_GRACE_PERIOD = 30 days;

    uint256 public constant UPGRADE_TIMELOCK = 2 days;

    /// @dev Transient storage slot for share transfer flag
    bytes32 private constant _SHARE_TRANSFERS_ALLOWED_SLOT = keccak256("LoanEscrow.shareTransfersAllowed");

    /// @notice Loan asset distributed to LPs
    address public loanToken;

    /// @notice Vault share token used as collateral
    address public share;

    /// @notice Governing strategy for state gating
    address public strategy;

    /// @notice Scales with PRECISION
    uint256 public accLoanPerShare;

    /// @notice Whether the single funding round has completed
    bool public override funded;

    /// @notice Shares locked across all LPs
    uint256 public totalSharesHeld;

    /// @notice Loan tokens reserved for LP claims
    uint256 private _reservedLoanToken;

    /// @notice Reclaim grace period for LPs to reclaim shares after loan repayment
    uint256 public reclaimGracePeriod;

    /// @notice Timestamp when the loan was repaid, used to calculate reclaim grace period
    uint256 public repaidAt;

    /// @notice Last seen accumulator per account
    mapping(address => uint256) public userIndex;

    /// @notice Cumulative loan-token borrowed
    mapping(address => uint256) public loanClaimed;

    /// @notice Shares locked as collateral
    mapping(address => uint256) public sharesHeld;

    /// @notice Pending unclaimed loan tokens saved from transfers or deposits
    mapping(address => uint256) private _pendingLoan;

    /// @notice Tracks whether an account has ever claimed from the escrow
    mapping(address => bool) private _everClaimed;

    address private _pendingImplementation;

    uint256 private _upgradeReadyAt;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(address loanToken_, address share_, address strategy_) external initializer {
        __UUPSUpgradeable_init();
        __ReentrancyGuard_init();
        __Pausable_init();

        if (strategy_ == address(0)) revert ZeroAddress();
        if (loanToken_ == address(0)) revert ZeroAddress();
        if (share_ == address(0)) revert ZeroAddress();

        loanToken = loanToken_;
        share = share_;
        strategy = strategy_;
        reclaimGracePeriod = RECLAIM_GRACE_PERIOD;
    }

    function _manager() public view returns (address) {
        return IEscrowStrategy(strategy).investmentManager();
    }

    modifier onlyManager() {
        if (msg.sender != _manager()) revert Unauthorized();
        _;
    }

    modifier onlyStrategy() {
        if (msg.sender != strategy) revert Unauthorized();
        _;
    }

    modifier onlyStrategyOrManager() {
        if (msg.sender != strategy && msg.sender != _manager()) revert Unauthorized();
        _;
    }

    modifier allowShareTransfer() {
        bytes32 slot = _SHARE_TRANSFERS_ALLOWED_SLOT;
        assembly {
            tstore(slot, 1)
        }
        _;
        assembly {
            tstore(slot, 0)
        }
    }

    /// @inheritdoc ILoanEscrow
    function fund(uint256 amount) external override nonReentrant onlyStrategyOrManager {
        if (amount == 0) revert InsufficientAmount();

        _requireOngoing();

        uint256 supply = IERC20(share).totalSupply();
        if (supply == 0) revert InsufficientShares();

        funded = true;

        accLoanPerShare += Math.mulDiv(amount, PRECISION, supply);
        _reservedLoanToken += amount;

        IERC20(loanToken).safeTransferFrom(msg.sender, address(this), amount);

        emit Funded(amount, accLoanPerShare);
    }

    /// @inheritdoc ILoanEscrow
    function claim() external override nonReentrant whenNotPaused allowShareTransfer returns (uint256 amount) {
        _requireOngoing();
        _requireWhitelistIfConfigured(msg.sender);

        uint256 walletShares = IERC20(share).balanceOf(msg.sender);
        amount = _settle(msg.sender, walletShares);
        amount += _pendingLoan[msg.sender];

        if (walletShares == 0 && sharesHeld[msg.sender] == 0) revert InsufficientShares();
        if (amount == 0) return 0;

        _pendingLoan[msg.sender] = 0;

        loanClaimed[msg.sender] += amount;
        _everClaimed[msg.sender] = true;
        _reservedLoanToken -= amount;

        if (walletShares > 0) {
            sharesHeld[msg.sender] += walletShares;
            totalSharesHeld += walletShares;
            IERC20(share).safeTransferFrom(msg.sender, address(this), walletShares);
        }

        IERC20(loanToken).safeTransfer(msg.sender, amount);

        emit Claimed(msg.sender, amount, walletShares);
    }

    /// @inheritdoc ILoanEscrow
    function repay(uint256 amount) external override nonReentrant returns (uint256 shareAmount) {
        _requireRepaymentOpen();

        uint256 newlyPending = _settle(msg.sender);
        if (newlyPending > 0) _pendingLoan[msg.sender] += newlyPending;

        uint256 outstanding = loanClaimed[msg.sender];

        if (outstanding == 0) {
            if (_everClaimed[msg.sender]) revert AlreadyRepaid();
            revert NothingToRepay();
        }
        if (amount == 0) revert InsufficientAmount();
        if (amount > outstanding) revert ExceedsOutstanding();

        shareAmount = sharesHeld[msg.sender].mulDiv(amount, outstanding);

        loanClaimed[msg.sender] -= amount;
        sharesHeld[msg.sender] -= shareAmount;
        totalSharesHeld -= shareAmount;

        IERC20(loanToken).safeTransferFrom(msg.sender, address(this), amount);
        IERC20(share).safeTransfer(msg.sender, shareAmount);

        emit Repaid(msg.sender, amount, shareAmount);
    }

    /// @inheritdoc ILoanEscrow
    function settleAccount(address account) external override onlyStrategy {
        uint256 amount = _settle(account);
        if (amount > 0) _pendingLoan[account] += amount;
    }

    /// @inheritdoc IRecoverable
    function recoverTokens(address token, address to, uint256 amount) external override onlyManager {
        if (amount == 0) revert ZeroValue();
        if (to == address(0)) revert ZeroAddress();

        uint256 reserved;
        if (token == share) reserved = totalSharesHeld;
        else if (token == loanToken) reserved = _reservedLoanToken;

        uint256 balance = IERC20(token).balanceOf(address(this));
        if (balance <= reserved || (amount + reserved) > balance) {
            revert InsufficientAmount();
        }

        IERC20(token).safeTransfer(to, amount);

        emit TokensRecovered(token, to, amount);
    }

    /// @notice Sets the grace period for share reclaiming after loan repayment
    function setReclaimGracePeriod(uint256 period) external onlyManager {
        if (period < RECLAIM_GRACE_PERIOD) revert InvalidGracePeriod();
        reclaimGracePeriod = period;
        emit ReclaimGracePeriodSet(period);
    }

    /// @inheritdoc ILoanEscrow
    function notifyRepaid() external onlyStrategy {
        if (repaidAt != 0) revert AlreadyNotified();
        repaidAt = block.timestamp;
        uint256 reservedCleared = _reservedLoanToken;
        _reservedLoanToken = 0;
        emit RepaidNotified(block.timestamp, reservedCleared);
    }

    /// @inheritdoc ILoanEscrow
    function reclaimShares(address account) external nonReentrant onlyStrategyOrManager {
        address[] memory accounts = new address[](1);
        accounts[0] = account;
        _reclaimSharesInBulk(accounts);
    }

    /// @notice Reclaims shares from multiple accounts in a single operation
    function reclaimSharesInBulk(address[] calldata accounts) external nonReentrant onlyStrategyOrManager {
        _reclaimSharesInBulk(accounts);
    }

    function _reclaimSharesInBulk(address[] memory accounts) private {
        if (repaidAt == 0) revert LoanNotRepaid();
        if (block.timestamp <= repaidAt + reclaimGracePeriod) revert GracePeriodNotExpired();

        uint256 totalShares;
        for (uint256 i; i < accounts.length; ++i) {
            uint256 shareAmount = sharesHeld[accounts[i]];
            if (shareAmount == 0) continue;

            uint256 claimed = loanClaimed[accounts[i]];
            uint256 pendingAmount = _pendingLoan[accounts[i]];

            sharesHeld[accounts[i]] = 0;
            loanClaimed[accounts[i]] = 0;
            _pendingLoan[accounts[i]] = 0;
            _everClaimed[accounts[i]] = false;
            totalShares += shareAmount;

            emit SharesReclaimed(accounts[i], shareAmount, claimed, pendingAmount);
        }

        if (totalShares == 0) revert NothingToReclaim();
        totalSharesHeld -= totalShares;

        IERC20(share).safeTransfer(_manager(), totalShares);
    }

    /// @inheritdoc ILoanEscrow
    function seize() external override onlyStrategy returns (uint256 sharesSeized) {
        sharesSeized = totalSharesHeld;
        uint256 reservedCleared = _reservedLoanToken;
        totalSharesHeld = 0;
        _reservedLoanToken = 0;
        emit Seized(sharesSeized, reservedCleared);
    }

    /// @inheritdoc ILoanEscrow
    function pending(address account) external view override returns (uint256) {
        if (!_isLoanOngoing()) return 0;
        return Math.mulDiv(_entitled(account), accLoanPerShare - userIndex[account], PRECISION) + _pendingLoan[account];
    }

    /// @inheritdoc ILoanEscrow
    function entitled(address account) external view override returns (uint256) {
        return _entitled(account);
    }

    /// @inheritdoc ILoanEscrow
    function shareTransfersAllowed() external view returns (bool allowed) {
        bytes32 slot = _SHARE_TRANSFERS_ALLOWED_SLOT;
        assembly {
            allowed := tload(slot)
        }
    }

    /// @inheritdoc ILoanEscrow
    function isClaimAllowed() public view returns (bool) {
        return _isLoanOngoing();
    }

    function pendingLoan(address account) external view returns (uint256) {
        if (!isClaimAllowed()) return 0;
        return _pendingLoan[account];
    }

    /// @notice Proposes an implementation upgrade, starting the upgrade timelock
    /// @param newImplementation The implementation to upgrade to once the timelock elapses
    function proposeUpgrade(address newImplementation) external onlyManager {
        if (newImplementation == address(0)) revert ZeroAddress();
        if (_pendingImplementation == newImplementation) revert InvalidValue();

        _pendingImplementation = newImplementation;
        _upgradeReadyAt = block.timestamp + UPGRADE_TIMELOCK;

        emit UpgradeProposed(newImplementation, _upgradeReadyAt);
    }

    /// @notice Cancels a pending implementation upgrade
    function cancelUpgrade() external onlyManager {
        address pendingImpl = _pendingImplementation;
        if (pendingImpl == address(0)) revert InvalidState();

        delete _pendingImplementation;
        delete _upgradeReadyAt;

        emit UpgradeCancelled(pendingImpl);
    }

    /// @notice Returns the pending upgrade implementation and the timestamp it can be executed
    function pendingUpgrade() external view returns (address implementation, uint256 readyAt) {
        return (_pendingImplementation, _upgradeReadyAt);
    }

    /// @dev Authorizes the upgrade of the implementation, enforcing the upgrade timelock
    function _authorizeUpgrade(address newImplementation) internal override onlyManager {
        if (_upgradeReadyAt == 0 || block.timestamp < _upgradeReadyAt) revert TimelockNotExpired();
        if (newImplementation != _pendingImplementation) revert InvalidValue();

        delete _pendingImplementation;
        delete _upgradeReadyAt;
    }

    /// @notice Pauses the escrow, blocking new claims
    function pause() external onlyManager {
        _pause();
    }

    /// @notice Unpauses the escrow, allowing claims again
    function unpause() external onlyManager {
        _unpause();
    }

    function _requireOngoing() private view {
        if (!_isLoanOngoing()) revert LoanNotOngoing();
    }

    function _requireRepaymentOpen() private view {
        LoanState state_ = IAccountableStrategy(strategy).loanState();
        if (state_ == LoanState.Repaid) return;
        if (state_ != LoanState.OngoingLocked && state_ != LoanState.OngoingDynamic) revert RepayNotAllowed();

        Loan memory loan_ = IAccountableStrategy(strategy).loan();
        if (loan_.startTime == 0 || loan_.duration == 0 || block.timestamp < loan_.startTime + loan_.duration) {
            revert RepayNotAllowed();
        }
    }

    function _isLoanOngoing() internal view returns (bool) {
        LoanState state_ = IAccountableStrategy(strategy).loanState();
        return state_ == LoanState.OngoingLocked || state_ == LoanState.OngoingDynamic;
    }

    function _settle(address account) internal returns (uint256 amount) {
        return _settle(account, IERC20(share).balanceOf(account));
    }

    function _settle(address account, uint256 walletShares) internal returns (uint256 amount) {
        uint256 entitledAmount = walletShares + sharesHeld[account];
        amount = Math.mulDiv(entitledAmount, accLoanPerShare - userIndex[account], PRECISION);
        userIndex[account] = accLoanPerShare;
    }

    function _entitled(address account) private view returns (uint256) {
        return IERC20(share).balanceOf(account) + sharesHeld[account];
    }

    /// @inheritdoc ILoanEscrow
    function repaid(address account) external view override returns (bool) {
        return _everClaimed[account] && loanClaimed[account] == 0 && sharesHeld[account] == 0;
    }

    /// @dev Enforces whitelist access only when vault permission level is Whitelist
    function _requireWhitelistIfConfigured(address account) private view {
        PermissionLevel level;
        try IAccess(share).permissionLevel() returns (PermissionLevel permission) {
            level = permission;
        } catch {
            return;
        }
        if (level != PermissionLevel.Whitelist) return;

        bool isAllowed;
        try IAccess(share).allowed(account) returns (bool allowed_) {
            isAllowed = allowed_;
        } catch {
            isAllowed = false;
        }
        if (!isAllowed) revert Unauthorized();
    }
}

src/strategies/AccountableCollateralFixedTerm.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import "../constants/Errors.sol";

import {IFeeManager} from "../interfaces/IFeeManager.sol";
import {ILoanEscrow} from "../interfaces/ILoanEscrow.sol";
import {ILoanEscrowDeployer} from "../interfaces/ILoanEscrowDeployer.sol";
import {IAccountableVault} from "../interfaces/IAccountableAsyncVault.sol";
import {
    IAccountableCollateralFixedTerm,
    CollateralFixedTermInitParams
} from "../interfaces/IAccountableCollateralFixedTerm.sol";
import {
    IAccountableStrategy,
    IStrategyVaultHooks,
    IFeeManagerHooks,
    IAccountableLoan,
    LoanState,
    LoanTerms
} from "../interfaces/IAccountableStrategy.sol";
import {AccountableStrategy} from "../strategies/AccountableStrategy.sol";
import {CollateralFixedTermStorage} from "../strategies/storage/CollateralFixedTermStorage.sol";

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";

/// @title AccountableCollateralFixedTerm
/// @notice Implementation of a fixed term loan with collateral and without interest
/// @dev Implements IAccountableCollateralFixedTerm interface and extends AccountableStrategy for managing loan lifecycle and payments
/// @custom:security-contact [email protected]
contract AccountableCollateralFixedTerm is
    UUPSUpgradeable,
    ReentrancyGuardUpgradeable,
    AccountableStrategy,
    CollateralFixedTermStorage
{
    using Math for uint256;
    using SafeERC20 for IERC20;

    /// @notice Time that must elapse between proposing and executing an implementation upgrade
    uint256 public constant UPGRADE_TIMELOCK = 2 days;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    // ========================================================================== //
    //                          Initialization                                    //
    // ========================================================================== //

    function initialize(CollateralFixedTermInitParams memory params) external initializer {
        __Pausable_init();
        __UUPSUpgradeable_init();
        __ReentrancyGuard_init();

        if (params.asset == address(0)) revert ZeroAddress();
        if (params.loanToken == address(0)) revert ZeroAddress();
        if (params.globals == address(0)) revert ZeroAddress();
        if (params.feeManager == address(0)) revert ZeroAddress();
        if (params.investmentManager == address(0)) revert ZeroAddress();

        asset = params.asset;
        globals = params.globals;
        feeManager = params.feeManager;
        loanState = LoanState.Initialized;
        investmentManager = params.investmentManager;
        managerFeeRecipient = params.investmentManager;

        _makeVault(IERC20(params.asset), true, params.permissionLevel, params.name, params.symbol);

        if (params.loanToken == vault) revert InvalidLoanToken();
        if (params.loanToken == params.asset) revert InvalidLoanToken();

        escrow = ILoanEscrowDeployer(msg.sender).createLoanEscrow(params.loanToken, vault);

        IERC20(params.asset).forceApprove(vault, type(uint256).max);

        emit EscrowSet(escrow);
    }

    // ========================================================================== //
    //                          Loan Terms Management                             //
    // ========================================================================== //

    /// @inheritdoc IAccountableLoan
    function setTerms(LoanTerms memory terms) public onlyManager {
        _requireLoanTermsNotSet();

        if (borrower == address(0)) revert ZeroAddress();

        // Collateral fixed-term carries no interest
        terms.interestRate = 0;
        terms.lateInterestPenalty = 0;

        _requireIntervalDurationPair(terms.duration, terms.interestInterval);

        _setTerms(terms);

        loanState = LoanState.TermsSet;
        _loan.termsSetTime = block.timestamp;

        _cachedMgmtFeeRate = IFeeManager(feeManager).managementFee(address(this));

        emit LoanTermsSet(terms.minCapacity, terms.maxCapacity, 0, 0, terms.interestInterval, terms.duration);
    }

    /// @inheritdoc IAccountableLoan
    /// @dev Only capacity and action-period fields can be updated, rate/duration/interval are immutable
    function updateTerms(LoanTerms memory terms) external onlyManager {
        _requireLoanTermsSet();

        if (terms.maxCapacity < _loan.maxCapacity) revert CapacityTooLow();
        if (terms.acceptGracePeriod > _loan.acceptGracePeriod) revert AcceptGracePeriodTooLong();
        if (terms.minRedeem > _loan.minRedeem) revert MinRedeemTooHigh();
        if (terms.depositPeriod > _loan.depositPeriod) revert DepositPeriodTooLong();

        _loan.maxCapacity = terms.maxCapacity;
        _loan.minCapacity = terms.minCapacity;
        _loan.minRedeem = terms.minRedeem;
        _loan.minDeposit = terms.minDeposit;

        _loan.depositPeriod = terms.depositPeriod;
        _loan.acceptGracePeriod = terms.acceptGracePeriod;

        _loan.termsUpdateTime = block.timestamp;

        emit LoanTermsSet(terms.minCapacity, terms.maxCapacity, 0, 0, _loan.interestInterval, _loan.duration);
    }

    function reject() external whenNotPaused {
        _requireLoanTermsSet();
        _requireLoanNotOngoing();

        uint256 depositDeadline = _loan.termsSetTime + _loan.depositPeriod;
        uint256 acceptanceDeadline = depositDeadline + _loan.acceptGracePeriod;

        if (block.timestamp <= acceptanceDeadline) revert LoanTermsNotMet();

        loanState = LoanState.Rejected;

        emit LoanRejected();
    }

    /// @inheritdoc IAccountableLoan
    /// @dev Only allowed in OngoingDynamic
    function borrow(uint256) external pure {
        revert NotSupportedByStrategy();
    }

    /// @inheritdoc IAccountableLoan
    function repay(uint256) external nonReentrant onlyBorrower whenNotPaused {
        _requireLoanMatured();
        _requireLoanOngoing();

        uint256 amount = _loan.outstandingPrincipal;
        _loan.outstandingPrincipal = 0;

        loanState = LoanState.Repaid;

        _transferFrom(borrower, address(this), amount);
        IAccountableVault(vault).lockAssets(amount, address(this));
        ILoanEscrow(escrow).notifyRepaid();

        emit LoanRepaid(amount);
    }

    function acceptLoanLocked() external nonReentrant onlyBorrower whenNotPaused {
        _acceptLoan(LoanState.OngoingLocked);
    }

    function acceptLoanDynamic() external pure {
        revert NotSupportedByStrategy();
    }

    /// @inheritdoc IAccountableCollateralFixedTerm
    function setEscrow(address escrow_) external override onlyManager {
        if (escrow != address(0)) revert EscrowAlreadySet();

        escrow = escrow_;
        emit EscrowSet(escrow);
    }

    function defaultLoan() external override onlySafetyModuleOrManager {
        _requireLoanOngoing();

        // Prevent resetting the timer if default is already pending
        if (_defaultValidAt != 0) revert DefaultAlreadyPending();

        _defaultValidAt = block.timestamp + DAYS_1_SECONDS;

        emit LoanDefaultInitiated();
    }

    /// @dev Checkpoints the last ongoing management fees before entering default.
    function acceptDefault() public override(AccountableStrategy, IAccountableStrategy) nonReentrant {
        super.acceptDefault();

        uint256 seizedShares = ILoanEscrow(escrow).seize();
        if (seizedShares > 0) {
            IAccountableVault(vault).burnShares(seizedShares, escrow);
        }
    }

    function coverDefault(uint256 assets) external override nonReentrant onlySafetyModuleOrManager {
        _requireLoanInDefault();

        loanState = LoanState.InDefaultClaims;

        if (assets > 0) {
            IAccountableVault(vault).lockAssets(assets, msg.sender);
        }

        emit DefaultCovered(safetyModule, msg.sender, assets);
    }

    function prepay() external pure override {
        revert NotSupportedByStrategy();
    }

    function pay(uint256) external pure override {
        revert NoPaymentDue();
    }

    function claimInterest() external pure override returns (uint256) {
        return 0;
    }

    /// @notice Proposes an implementation upgrade, starting the upgrade timelock
    /// @param newImplementation The implementation to upgrade to once the timelock elapses
    function proposeUpgrade(address newImplementation) external onlyManagerOrSecurityAdmin {
        if (newImplementation == address(0)) revert ZeroAddress();
        if (_pendingImplementation == newImplementation) revert InvalidValue();

        _pendingImplementation = newImplementation;
        _upgradeReadyAt = block.timestamp + UPGRADE_TIMELOCK;

        emit UpgradeProposed(newImplementation, _upgradeReadyAt);
    }

    /// @notice Cancels a pending implementation upgrade
    function cancelUpgrade() external onlyManagerOrSecurityAdmin {
        address pending = _pendingImplementation;
        if (pending == address(0)) revert InvalidState();

        delete _pendingImplementation;
        delete _upgradeReadyAt;

        emit UpgradeCancelled(pending);
    }

    /// @notice Returns the pending upgrade implementation and the timestamp it can be executed
    function pendingUpgrade() external view returns (address implementation, uint256 readyAt) {
        return (_pendingImplementation, _upgradeReadyAt);
    }

    /// @dev Authorizes the upgrade of the implementation, enforcing the upgrade timelock
    function _authorizeUpgrade(address newImplementation) internal override onlyManagerOrSecurityAdmin {
        if (_upgradeReadyAt == 0 || block.timestamp < _upgradeReadyAt) revert TimelockNotExpired();
        if (newImplementation != _pendingImplementation) revert InvalidValue();

        delete _pendingImplementation;
        delete _upgradeReadyAt;
    }

    // ========================================================================== //
    //                          Hook Overrides                                    //
    // ========================================================================== //

    /// @dev Overridden deposit hook with extra validation logic and balances update
    function onDeposit(address share, uint256 assets, address receiver, address)
        public
        override(AccountableStrategy, IStrategyVaultHooks)
        nonReentrant
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        if (receiver == escrow) revert SharesNotTransferable();

        _requireCanRequestDeposit();
        _requireMinDepositAmount(assets);
        _requireBelowMaxCapacity(assets);

        _loan.drawableFunds += assets;
        _settleAccount(receiver);

        price = _sharePrice(share);
    }

    /// @dev Overridden transfer hook with extra validation logic and balances update
    function onTransfer(address, address from, address to, uint256)
        public
        override(AccountableStrategy, IStrategyVaultHooks)
        nonReentrant
        onlyVault
        whenNotPaused
    {
        if (to == escrow && !ILoanEscrow(escrow).shareTransfersAllowed()) revert SharesNotTransferable();

        if (
            (loanState == LoanState.OngoingLocked || loanState == LoanState.OngoingDynamic) && from != escrow
                && to != escrow
        ) {
            revert SharesNotTransferable();
        }

        if (from != escrow) _settleAccount(from);
        if (to != escrow) _settleAccount(to);
    }

    /// @dev Overridden mint hook with extra validation logic and balances update
    function onMint(address share, uint256 shares, address receiver, address)
        public
        override(AccountableStrategy, IStrategyVaultHooks)
        nonReentrant
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        if (receiver == escrow) revert SharesNotTransferable();

        _requireCanRequestDeposit();

        price = _sharePrice(share);
        uint256 assets = shares.mulDiv(price, PRECISION, Math.Rounding.Ceil);

        _requireMinDepositAmount(assets);
        _requireBelowMaxCapacity(assets);

        _loan.drawableFunds += assets;
        _settleAccount(receiver);
    }

    /// @dev Overridden onRequestRedeem hook
    function onRequestRedeem(address share, uint256 shares, address, address owner)
        public
        override(AccountableStrategy, IStrategyVaultHooks)
        nonReentrant
        onlyVault
        whenNotPaused
        returns (bool canFulfill, uint256 price)
    {
        _requireCanRequestRedeem();

        if (_loan.minRedeem > shares) revert InsufficientShares();
        uint256 remaining = IERC20(share).balanceOf(owner) - shares;
        if (remaining > 0 && remaining < _loan.minRedeem) revert InsufficientShares();

        canFulfill = true;

        price = _sharePrice(share);
    }

    /// @inheritdoc IAccountableStrategy
    function setDVNPublisher(address) external pure {
        revert NotSupportedByStrategy();
    }

    /// @inheritdoc IAccountableStrategy
    function publishRate(uint256, uint256) external pure {
        revert NotSupportedByStrategy();
    }

    /// @dev Max deposit is remaining capacity
    function maxDeposit(address, address)
        public
        view
        override(AccountableStrategy, IStrategyVaultHooks)
        returns (uint256 maxAssets)
    {
        if (paused()) return 0;
        if (loanState != LoanState.TermsSet) return 0;
        if (block.timestamp > _loan.termsSetTime + _loan.depositPeriod) return 0;
        maxAssets = _maxDeposit();
    }

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

    /// @inheritdoc IAccountableLoan
    function timeDelinquent() external pure returns (uint256) {
        return 0;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
        return interfaceId == type(IAccountableLoan).interfaceId
            || interfaceId == type(IAccountableStrategy).interfaceId
            || interfaceId == type(IAccountableCollateralFixedTerm).interfaceId
            || interfaceId == type(IERC165).interfaceId;
    }

    /// @inheritdoc IAccountableStrategy
    function setPenaltiesEnabled(bool) external pure override(AccountableStrategy, IAccountableStrategy) {
        revert NotSupportedByStrategy();
    }

    // ========================================================================== //
    //                          Internal Helper Functions                         //
    // ========================================================================== //

    /// @dev Share price: 1:1 during deposit period or after rejection, vault ratio otherwise
    function _sharePrice(address) internal view override returns (uint256) {
        LoanState loanState_ = loanState;

        if (loanState_ == LoanState.Initialized || loanState_ == LoanState.TermsSet) {
            return PRECISION;
        }

        if (
            loanState_ == LoanState.Repaid || loanState_ == LoanState.Rejected
                || loanState_ == LoanState.InDefaultClaims
        ) {
            return IAccountableVault(vault).assetShareRatio();
        }

        uint256 aum = _loan.drawableFunds + _loan.outstandingPrincipal;
        uint256 supply = IERC20(vault).totalSupply();
        if (supply == 0) return PRECISION;
        return aum.mulDiv(PRECISION, supply);
    }

    function _accruedAssets(address) internal view virtual override returns (uint256) {
        return 0;
    }

    function _maxDeposit() private view returns (uint256) {
        return _loan.maxCapacity - _loan.outstandingPrincipal - _loan.drawableFunds;
    }

    /// @dev Wrapper function for IERC20 safeTransferFrom
    function _transferFrom(address from, address to, uint256 amount) private {
        IERC20(asset).safeTransferFrom(from, to, amount);
    }

    /// @dev Accepts the loan, starts the clock and releases all drawable funds if any
    function _acceptLoan(LoanState state) private {
        _requireLoanTermsSet();
        _requireLoanNotOngoing();

        if (block.timestamp < _loan.termsSetTime + _loan.depositPeriod) revert LoanTermsNotMet();
        if (!_minCapFilled()) revert LoanTermsNotMet();

        loanState = state;
        _loan.startTime = block.timestamp;

        uint256 grossAssets = _borrowable(msg.sender);

        uint256 feeAssets = _collectFee(grossAssets);

        uint256 borrowerAssets = grossAssets - feeAssets;
        if (borrowerAssets > 0) _updateAndRelease(borrowerAssets);

        emit LoanAccepted();
    }

    /// @dev Collects the upfront management fee at loan acceptance
    function _collectFee(uint256 principal) private returns (uint256 feeAssets) {
        IFeeManager fm = IFeeManager(feeManager);
        uint256 mgmtFeeRate = _cachedMgmtFeeRate;
        uint256 managerSplit = fm.managerSplit(address(this), false);

        feeAssets = principal.mulDiv(mgmtFeeRate * _loan.duration, BASIS_POINTS * DAYS_365_SECONDS);
        if (feeAssets >= principal) revert InvalidManagementFee();

        uint256 managerAssets = feeAssets.mulDiv(managerSplit, BASIS_POINTS);
        uint256 protocolAssets = feeAssets - managerAssets;

        _loan.drawableFunds -= feeAssets;

        if (managerAssets > 0) {
            IAccountableVault(vault).releaseAssets(managerAssets, managerFeeRecipient);
        }

        if (protocolAssets > 0) {
            address treasury = fm.treasury();
            IAccountableVault(vault).releaseAssets(protocolAssets, treasury);
        }

        emit UpfrontFeeCollected(managerAssets, protocolAssets, feeAssets);
    }

    /// @dev Returns whether the min cap has been filled
    function _minCapFilled() internal view returns (bool) {
        return (_loan.outstandingPrincipal + _loan.drawableFunds) >= _loan.minCapacity;
    }

    /// @dev Drawable funds not yet released to the borrower
    function _borrowable(address) internal view returns (uint256) {
        return _loan.drawableFunds;
    }

    function _updateAndRelease(uint256 assets) private {
        _loan.drawableFunds -= assets;
        _loan.outstandingPrincipal += assets;

        IAccountableVault(vault).releaseAssets(assets, msg.sender);
    }

    /// @dev Settle an account's escrow index (called on deposit, mint, transfer)
    function _settleAccount(address user) internal {
        ILoanEscrow(escrow).settleAccount(user);
    }

    function _requireIntervalDurationPair(uint256 duration, uint256 interestInterval) private pure {
        if (interestInterval == 0) revert InvalidIntervalLength();
        if (duration < interestInterval) revert InvalidIntervalLength();
        if (duration % interestInterval != 0) revert InvalidIntervalDurationPair();
    }

    function _requireLoanMatured() internal view {
        if (block.timestamp < _loan.startTime + _loan.duration) revert LoanNotMatured();
    }

    /// @dev Checks that deposits are allowed
    function _requireCanRequestDeposit() internal view {
        if (loanState != LoanState.TermsSet || block.timestamp > _loan.termsSetTime + _loan.depositPeriod) {
            revert DepositNotAllowed();
        }
    }

    /// @dev Checks that the deposit amount is below the max capacity
    function _requireBelowMaxCapacity(uint256 assets) internal view {
        if (assets > _maxDeposit()) revert ExceedsMaxDeposit();
    }

    /// @dev Checks that redeem requests are allowed
    ///      It allows redemption requests in the following states:
    ///      [Repaid] || [Rejected] || [InDefaultClaims]
    function _requireCanRequestRedeem() internal view {
        if (loanState != LoanState.Repaid && loanState != LoanState.Rejected && loanState != LoanState.InDefaultClaims)
        {
            revert RedeemNotAllowed();
        }
    }
}

src/strategies/AccountableStrategy.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

import "../constants/Errors.sol";

import {IAccess, PermissionLevel} from "../interfaces/IAccess.sol";
import {IAsyncVaultFactory} from "../interfaces/IAsyncVaultFactory.sol";
import {IGlobalRegistry} from "../interfaces/IGlobalRegistry.sol";
import {IAccountableVault} from "../interfaces/IAccountableAsyncVault.sol";
import {
    IAccountableStrategy,
    IStrategyVaultHooks,
    IFeeManagerHooks,
    LoanState,
    LoanTerms,
    DVNProof,
    Loan
} from "../interfaces/IAccountableStrategy.sol";

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {StrategyStorage} from "./storage/StrategyStorage.sol";

/// @title AccountableStrategy
/// @notice Abstract contract that implements the IAccountableStrategy interface
/// @dev It holds the state of an accountable strategy and implements the IAccountableStrategy interface
/// @custom:security-contact [email protected]
abstract contract AccountableStrategy is PausableUpgradeable, StrategyStorage {
    // ========================================================================== //
    //                              Constants                                     //
    // ========================================================================== //

    /// @dev precision for calculations
    uint256 public constant PRECISION = 1e36;
    /// @dev 1e6 basis points representing 100%
    uint256 public constant BASIS_POINTS = 1e6;
    /// @dev seconds in a days
    uint256 public constant DAYS_1_SECONDS = 1 days;
    /// @dev seconds in a year considered 365 days
    uint256 public constant DAYS_365_SECONDS = 365 days;

    // ========================================================================== //
    //                              Modifiers                                     //
    // ========================================================================== //

    /// @notice modifier to check if caller is the borrower
    modifier onlyBorrower() {
        if (msg.sender != borrower) revert Unauthorized();
        _;
    }

    /// @notice modifier to check if caller is the investment manager
    modifier onlyManager() {
        if (msg.sender != investmentManager) revert Unauthorized();
        _;
    }

    /// @notice modifier to check if caller is the operations admin
    modifier onlyOperationsAdmin() {
        if (!operationsAdminEnabled) revert Unauthorized();
        if (msg.sender != IGlobalRegistry(globals).operationsAdmin()) revert Unauthorized();
        _;
    }

    /// @notice modifier to check if caller is the safety module or the manager
    modifier onlySafetyModuleOrManager() {
        if (safetyModule != address(0)) {
            revert_AtLeastOne(safetyModule, investmentManager);
        } else {
            if (msg.sender != investmentManager) revert Unauthorized();
        }
        _;
    }

    /// @notice modifier to check if caller is the manager or the security admin (if enabled)
    modifier onlyManagerOrSecurityAdmin() {
        if (securityAdminEnabled) {
            revert_AtLeastOne(IGlobalRegistry(globals).securityAdmin(), investmentManager);
        } else {
            if (msg.sender != investmentManager) revert Unauthorized();
        }
        _;
    }

    /// @notice modifier to check if caller is the manager or the operations admin (if enabled)
    modifier onlyManagerOrOperationsAdmin() {
        if (operationsAdminEnabled) {
            revert_AtLeastOne(IGlobalRegistry(globals).operationsAdmin(), investmentManager);
        } else {
            if (msg.sender != investmentManager) revert Unauthorized();
        }
        _;
    }

    /// @notice modifier to check if caller is the proof signer
    modifier onlyProofSigner() {
        if (msg.sender != proofSigner) revert Unauthorized();
        _;
    }

    /// @notice modifier to check if caller is the vault
    modifier onlyVault() {
        if (msg.sender != vault) revert Unauthorized();
        _;
    }

    /// @dev Reverts if the caller is not one of the two addresses
    function revert_AtLeastOne(address a, address b) internal view {
        if (msg.sender != a && msg.sender != b) revert Unauthorized();
    }

    // ========================================================================== //
    //                          Pausable Functions                                //
    // ========================================================================== //

    /// @dev Pauses the contract
    function pause() public onlyManagerOrSecurityAdmin {
        if (msg.sender == IGlobalRegistry(globals).securityAdmin()) {
            _pausedByAdmin = true;
        }
        _pause();
    }

    /// @dev Unpauses the contract and checks whether msg.sender is admin when loan was paused by admin
    function unpause() public onlyManagerOrSecurityAdmin {
        if (_pausedByAdmin && msg.sender != IGlobalRegistry(globals).securityAdmin()) {
            revert Unauthorized();
        }
        _pausedByAdmin = false;
        _unpause();
    }

    // ========================================================================== //
    //                          Configuration Functions                           //
    // ========================================================================== //

    /// @inheritdoc IAccountableStrategy
    function setPendingBorrower(address newBorrower) external virtual onlyManager {
        if (newBorrower == address(0)) revert ZeroAddress();
        pendingBorrower = newBorrower;

        emit PendingBorrowerSet(newBorrower);
    }

    /// @inheritdoc IAccountableStrategy
    function acceptBorrowerRole() external virtual {
        if (msg.sender != pendingBorrower) revert InvalidPendingBorrower();
        emit BorrowerChanged(borrower, msg.sender);
        borrower = msg.sender;
        pendingBorrower = address(0);
    }

    /// @inheritdoc IAccountableStrategy
    function setInvestmentManager(address investmentManager_) external virtual onlyManager {
        if (investmentManager_ == address(0)) revert ZeroAddress();
        investmentManager = investmentManager_;

        emit InvestmentManagerSet(investmentManager_);
    }

    /// @inheritdoc IAccountableStrategy
    function setAuthSigner(address authSigner_) external onlyManager {
        IAccess(vault).setSigner(authSigner_);
    }

    /// @inheritdoc IAccountableStrategy
    function setLenders(address[] calldata lenders, bool[] calldata allowed) external onlyManager {
        IAccess(vault).setAllowed(lenders, allowed);
    }

    /// @inheritdoc IAccountableStrategy
    function setProofSigner(address proofSigner_) external virtual onlyManager {
        if (proofSigner_ == address(0)) revert ZeroAddress();
        proofSigner = proofSigner_;

        emit ProofSignerSet(proofSigner_);
    }

    /// @inheritdoc IAccountableStrategy
    function setManagerFeeRecipient(address managerFeeRecipient_) external virtual onlyManager {
        if (managerFeeRecipient_ == address(0)) revert ZeroAddress();
        managerFeeRecipient = managerFeeRecipient_;

        emit ManagerFeeRecipientSet(managerFeeRecipient_);
    }

    /// @inheritdoc IAccountableStrategy
    function publishDVNProof(DVNProof memory proof) external virtual onlyProofSigner {
        _dvnProof = proof;

        emit DVNProofPublished(proof.root, proof.signature, proof.messageHash);
    }

    /// @inheritdoc IAccountableStrategy
    function acceptDefault() public virtual {
        if (block.timestamp < _defaultValidAt || _defaultValidAt == 0) revert TimelockNotExpired();
        _requireLoanOngoing(); // a repaid loan is no longer default-eligible
        loanState = LoanState.InDefault;

        emit LoanDefaulted(_loan.outstandingPrincipal, IAccountableVault(vault).totalAssets());
    }

    /// @inheritdoc IAccountableStrategy
    function rejectDefault() external onlyManager {
        _defaultValidAt = 0;

        emit LoanDefaultRejected();
    }

    /// @inheritdoc IAccountableStrategy
    function setPenaltiesEnabled(bool enabled) external virtual onlyManager {
        penaltiesEnabled = enabled;

        emit PenaltiesEnabledSet(enabled);
    }

    /// @inheritdoc IAccountableStrategy
    function setSecurityAdminEnabled(bool enabled) external virtual onlyManager {
        securityAdminEnabled = enabled;

        emit SecurityAdminEnabledSet(enabled);
    }

    /// @inheritdoc IAccountableStrategy
    function setOperationsAdminEnabled(bool enabled) external virtual onlyManager {
        operationsAdminEnabled = enabled;

        emit OperationsAdminEnabledSet(enabled);
    }

    /// @inheritdoc IAccountableStrategy
    function setSharesTransferable(bool transferable) external virtual onlyManager {
        IAccountableVault(vault).setSharesTransferable(transferable);
    }

    /// @inheritdoc IAccountableStrategy
    function setReserveThreshold(uint256 threshold) external virtual onlyManager {
        if (threshold > BASIS_POINTS) revert ThresholdTooHigh();
        _loan.reserveThreshold = threshold;

        emit ReserveThresholdSet(threshold);
    }

    /// @inheritdoc IAccountableStrategy
    function setSafetyModule(address safetyModule_) external virtual onlyManager {
        if (safetyModule_ == address(0)) revert ZeroAddress();
        safetyModule = safetyModule_;

        emit SafetyModuleSet(safetyModule_);
    }

    /// @inheritdoc IAccountableStrategy
    function setRewardsDistributor(address rewards_) external virtual onlyManager {
        if (rewards_ == address(0)) revert ZeroAddress();
        rewards = rewards_;

        emit RewardsDistributorSet(rewards_);
    }

    /// @inheritdoc IAccountableStrategy
    function setPriceOracle(address priceOracle_) external virtual onlyManager {
        _requireLoanNotOngoing();

        if (priceOracle_ == address(0)) revert ZeroAddress();
        priceOracle = priceOracle_;

        emit PriceOracleSet(priceOracle_);
    }

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

    /// @inheritdoc IAccountableStrategy
    function loan() external view returns (Loan memory) {
        return _loan;
    }

    /// @inheritdoc IAccountableStrategy
    function dvnProof() external view returns (DVNProof memory) {
        return _dvnProof;
    }

    // ========================================================================== //
    //                          Strategy Vault Hooks                              //
    // ========================================================================== //

    /// @inheritdoc IStrategyVaultHooks
    function onRequestDeposit(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (bool canFulfill, uint256 price)
    {
        return (false, _sharePrice(share));
    }

    /// @inheritdoc IStrategyVaultHooks
    function onRequestRedeem(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (bool canFulfill, uint256 price)
    {
        return (false, _sharePrice(share));
    }

    /// @inheritdoc IStrategyVaultHooks
    function onCancelDepositRequest(address, address) public virtual onlyVault whenNotPaused returns (bool canCancel) {
        return true;
    }

    /// @inheritdoc IStrategyVaultHooks
    function onCancelRedeemRequest(address, address) public virtual onlyVault whenNotPaused returns (bool canCancel) {
        return true;
    }

    /// @inheritdoc IStrategyVaultHooks
    function onDeposit(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        price = _sharePrice(share);
    }

    /// @inheritdoc IStrategyVaultHooks
    function onMint(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        price = _sharePrice(share);
    }

    /// @inheritdoc IStrategyVaultHooks
    function onRedeem(address, uint256, address, address) public virtual onlyVault whenNotPaused {}

    /// @inheritdoc IStrategyVaultHooks
    function onWithdraw(address, uint256, address, address) public virtual onlyVault whenNotPaused {}

    /// @inheritdoc IStrategyVaultHooks
    function onTransfer(address, address, address, uint256) public virtual onlyVault whenNotPaused {}

    /// @inheritdoc IStrategyVaultHooks
    function authOperator(address operator) external virtual {
        if (msg.sender != vault) revert Unauthorized();
        if (operator != investmentManager && operator != borrower) revert Unauthorized();
    }

    /// @inheritdoc IStrategyVaultHooks
    function sharePrice(address share) external view virtual returns (uint256 price) {
        return _sharePrice(share);
    }

    /// @dev Computes the share price. To be overridden by the derived strategy
    function _sharePrice(address share) internal view virtual returns (uint256 price);

    /// @inheritdoc IStrategyVaultHooks
    function accruedAssets(address share) external view virtual returns (uint256 assets) {
        assets = _accruedAssets(share);
    }

    /// @dev Computes the accrued assets. To be overridden by the derived strategy
    function _accruedAssets(address share) internal view virtual returns (uint256 assets);

    /// @inheritdoc IStrategyVaultHooks
    function maxDeposit(address, address) public view virtual returns (uint256 maxAssets) {
        return type(uint256).max;
    }

    /// @inheritdoc IStrategyVaultHooks
    function maxRedeem(address, address) public view virtual returns (uint256 maxShares) {
        return type(uint256).max;
    }

    // ========================================================================== //
    //                          Fee Manager Hooks                                 //
    // ========================================================================== //

    /// @inheritdoc IFeeManagerHooks
    function onFeeStructureChange() public virtual whenNotPaused {
        if (msg.sender != feeManager) revert Unauthorized();
    }

    /// @inheritdoc IAccountableStrategy
    function version() external view virtual returns (uint256) {
        return 2;
    }

    // ========================================================================== //
    //                          Internal Helper Functions                         //
    // ========================================================================== //

    /// @dev Calls the factory to create a new async redeem vault
    function _makeVault(
        IERC20 asset_,
        bool sharesTransferable_,
        PermissionLevel permissionLevel_,
        string memory name_,
        string memory symbol_
    ) internal {
        vault = IAsyncVaultFactory(IGlobalRegistry(globals).vaultFactory()).createAsyncRedeemVault(
            asset_, address(this), sharesTransferable_, permissionLevel_, name_, symbol_, PRECISION
        );
    }

    /// @dev Sets the loan terms and initializes the loan state
    function _setTerms(LoanTerms memory terms) internal {
        _loan = Loan({
            lateInterestGracePeriod: terms.lateInterestGracePeriod == 0 ? 2 days : terms.lateInterestGracePeriod,
            acceptGracePeriod: terms.acceptGracePeriod == 0 ? 2 days : terms.acceptGracePeriod,
            depositPeriod: terms.depositPeriod,
            withdrawalPeriod: terms.withdrawalPeriod,
            lateInterestPenalty: terms.lateInterestPenalty,
            interestInterval: terms.interestInterval,
            interestRate: terms.interestRate,
            minDeposit: terms.minDeposit,
            minRedeem: terms.minRedeem,
            maxCapacity: terms.maxCapacity,
            minCapacity: terms.minCapacity,
            duration: terms.duration,
            reserveThreshold: 0,
            outstandingPrincipal: 0,
            outstandingInterest: 0,
            claimableInterest: 0,
            drawableFunds: 0,
            termsSetTime: 0,
            termsUpdateTime: 0,
            startTime: 0
        });
    }

    /// @dev Checks that the loan terms have been set
    function _requireLoanTermsSet() internal view {
        if (loanState != LoanState.TermsSet) revert LoanTermsNotSet();
    }

    /// @dev Checks that the loan terms have not been set
    function _requireLoanTermsNotSet() internal view {
        if (loanState != LoanState.Initialized) revert LoanTermsAlreadySet();
    }

    /// @dev Checks that the loan is not ongoing
    function _requireLoanNotOngoing() internal view {
        if (loanState == LoanState.OngoingLocked || loanState == LoanState.OngoingDynamic) revert LoanOngoing();
    }

    /// @dev Checks that the loan is ongoing
    function _requireLoanOngoing() internal view {
        if (loanState != LoanState.OngoingLocked && loanState != LoanState.OngoingDynamic) revert LoanNotOngoing();
    }

    /// @dev Checks that the loan is in default
    function _requireLoanInDefault() internal view {
        if (loanState != LoanState.InDefault) revert LoanNotInDefault();
    }

    /// @dev Checks that the deposit amount is greater than the minimum deposit amount
    function _requireMinDepositAmount(uint256 amount) internal view {
        if (amount < _loan.minDeposit) revert InsufficientAmount();
    }
}

src/strategies/storage/CollateralFixedTermStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import {IAccountableCollateralFixedTerm} from "../../interfaces/IAccountableCollateralFixedTerm.sol";

/// @title CollateralFixedTermStorage
/// @notice Storage layout for AccountableCollateralFixedTerm with upgrade safety gap
/// @dev Centralizes storage to avoid collisions and simplify upgradeable contract development
///      All storage variables MUST be declared here

abstract contract CollateralFixedTermStorage is IAccountableCollateralFixedTerm {
    /// @notice Address of base token
    address public asset;

    /// @notice Address of the escrow
    address public escrow;

    /// @notice The implementation pending upgrade, set by proposeUpgrade
    address internal _pendingImplementation;

    /// @notice The timestamp after which the pending upgrade can be executed
    uint256 internal _upgradeReadyAt;

    /// @notice Management fee rate cached at terms set time
    uint256 internal _cachedMgmtFeeRate;

    /// @dev Gap for future storage variables in AccountableCollateralFixedTerm
    /// @dev Reserves 50 slots for future additions to AccountableCollateralFixedTerm
    uint256[50] private __gap;
}

src/strategies/storage/StrategyStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import {IAccountableStrategy, Loan, DVNProof, LoanState} from "../../interfaces/IAccountableStrategy.sol";

/// @title StrategyStorage
/// @notice Storage layout for AccountableStrategy with upgrade safety gap
/// @dev Centralizes storage to avoid collisions and simplify upgradeable contract development
///      All storage variables MUST be declared here
abstract contract StrategyStorage is IAccountableStrategy {
    /// @dev whether paused by admin
    bool internal _pausedByAdmin;

    /// @dev loan terms and state
    Loan internal _loan;

    /// @dev DVN proof
    DVNProof internal _dvnProof;

    /// @dev timestamp when the default is valid
    uint256 internal _defaultValidAt;

    /// @dev whether penalties are enabled
    bool public penaltiesEnabled;

    /// @dev whether security admin is enabled
    bool public securityAdminEnabled;

    /// @dev whether operations admin is enabled
    bool public operationsAdminEnabled;

    /// @notice loan borrower
    address public borrower;

    /// @notice pending loan borrower
    address public pendingBorrower;

    /// @dev loan state
    LoanState public loanState;

    /// @notice address of global registry
    address public globals;

    /// @notice address of fee manager
    address public feeManager;

    /// @notice address of safety module
    address public safetyModule;

    /// @notice address of proof signer
    /// @dev This is the public key of the DVN proof signer
    ///      It can be used to verify the published DVN proofs
    address public proofSigner;

    /// @notice address of vault
    address public vault;

    /// @notice address of investment manager
    address public investmentManager;

    /// @notice address of rewards distributor
    address public rewards;

    /// @notice address of price oracle
    address public priceOracle;

    /// @notice address of DVN publisher
    address public dvnPublisher;

    /// @notice address of manager fee recipient
    address public managerFeeRecipient;

    /// @dev Gap for future storage variables in base contract
    /// @dev Reserves 50 slots for future additions to AccountableStrategy
    uint256[48] private __gap;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "murky/=lib/murky/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
    "safe-smart-account/=lib/safe-smart-account/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.