Skip to content
Verified contractExactGPL-2.0-or-later

AccountableAsyncRedeemVault

Address0xeaba08b4d40f2ae0449f694a3db48a817dce6c71
Balance

0 ETH

 

Transactions

32

 

Compiler

solc 0.8.27

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,378,148
Creation transaction
0xeac5a2f15a…1a0ad82d08
Main copy (most transactions)
0xa73424f1…d4af25d9

32 files

src/vault/AccountableAsyncRedeemVault.sol

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

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

import {IStrategyVaultHooks, IUpdateLateStatus} from "../interfaces/IAccountableStrategy.sol";
import {PermissionLevel} from "../interfaces/IAccess.sol";

import {
    IAccountableAsyncRedeemVault,
    IControllerOperator,
    IAsyncRedeem,
    IAsyncCancelRedeem,
    IAccountableVault,
    VaultState
} from "../interfaces/IAccountableAsyncVault.sol";

import {IAccountableWithdrawalQueue} from "../interfaces/IAccountableWithdrawalQueue.sol";

import {AccountableVault} from "./AccountableVault.sol";
import {AccountableWithdrawalQueue} from "./queue/AccountableWithdrawalQueue.sol";

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
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";

/// @title AccountableAsyncRedeemVault
/// @notice An ERC4626-compatible vault with ERC7540 asynchronous redemptions
/// @dev Implements IAccountableAsyncRedeemVault interface for async operations and access control
/// @custom:security-contact [email protected]
contract AccountableAsyncRedeemVault is IAccountableAsyncRedeemVault, AccountableWithdrawalQueue, AccountableVault {
    using Math for uint256;

    uint128 private constant INSTANT_REQUEST_ID = 0;

    /// @notice AccountableAsyncVault constructor
    /// @param asset_ The underlying asset token for the vault
    /// @param strategy_ The loan manager contract address
    /// @param sharesTransferable_ Whether shares are transferable
    /// @param name_ The name of the vault issued share token
    /// @param symbol_ The symbol of the vault issued share token
    constructor(
        IERC20 asset_,
        address strategy_,
        bool sharesTransferable_,
        PermissionLevel permissionLevel_,
        string memory name_,
        string memory symbol_,
        uint256 precision_
    ) AccountableWithdrawalQueue(precision_) AccountableVault(asset_, permissionLevel_) ERC20(name_, symbol_) {
        if (strategy_ == address(0)) revert ZeroAddress();

        strategy = IStrategyVaultHooks(strategy_);
        transferableShares = sharesTransferable_;
        precision = precision_;
    }

    /// @inheritdoc IAccountableVault
    function deposit(uint256 assets, address receiver, address controller)
        public
        onlyAuth(receiver, controller)
        returns (uint256 shares)
    {
        _checkMinAmount(assets);
        _checkController(controller);

        uint256 price = strategy.onDeposit(address(this), assets, receiver, controller);
        shares = _convertToShares(assets, price, Math.Rounding.Floor);

        _mint(receiver, shares);
        _deposit(controller, assets);

        emit Deposit(controller, receiver, assets, shares);
    }

    /// @inheritdoc IERC4626
    function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {
        shares = deposit(assets, receiver, msg.sender);
    }

    /// @inheritdoc IAccountableVault
    function mint(uint256 shares, address receiver, address controller)
        public
        onlyAuth(receiver, controller)
        returns (uint256 assets)
    {
        _checkMinAmount(shares);
        _checkController(controller);

        uint256 price = strategy.onMint(address(this), shares, receiver, controller);
        assets = _convertToAssets(shares, price, Math.Rounding.Ceil);

        _mint(receiver, shares);
        _deposit(controller, assets);

        emit Deposit(controller, receiver, assets, shares);
    }

    /// @inheritdoc IERC4626
    function mint(uint256 shares, address receiver) public override returns (uint256 assets) {
        assets = mint(shares, receiver, msg.sender);
    }

    /// @inheritdoc IAsyncRedeem
    function requestRedeem(uint256 shares, address controller, address owner)
        public
        onlyAuth(owner, controller)
        returns (uint256 requestId)
    {
        _checkOperator(owner);
        _checkController(controller);
        _checkMinAmount(shares);
        _checkShares(owner, shares);

        VaultState storage state = _vaultStates[controller];

        state.pendingRedeemRequest += shares;

        (bool canFulfill, uint256 price) = strategy.onRequestRedeem(address(this), shares, controller, owner);
        if (canFulfill) {
            requestId = INSTANT_REQUEST_ID;
            _fulfillRedeemRequest(INSTANT_REQUEST_ID, controller, shares, price);
        } else {
            requestId = _push(controller, shares);
        }

        _transfer(owner, address(this), shares);

        /// @dev RequestId is non-zero if in queue, 0 otherwise (instant fulfill)
        emit RedeemRequest(controller, owner, requestId, msg.sender, shares);
    }

    /// @inheritdoc IAsyncRedeem
    function pendingRedeemRequest(uint256, address controller) public view returns (uint256 pendingShares) {
        pendingShares = _vaultStates[controller].pendingRedeemRequest;
    }

    /// @inheritdoc IAsyncRedeem
    function claimableRedeemRequest(uint256, address controller) public view returns (uint256 claimableShares) {
        claimableShares = maxRedeem(controller);
    }

    /// @inheritdoc IERC4626
    function redeem(uint256 shares, address receiver, address controller)
        public
        onlyAuth(receiver, controller)
        returns (uint256 assets)
    {
        _checkMinAmount(shares);
        _checkController(controller);
        if (shares > maxRedeem(controller)) revert ExceedsMaxRedeem();

        VaultState storage state = _vaultStates[controller];
        uint256 redeemPrice = state.redeemPrice;
        assets = _convertToAssets(shares, redeemPrice, Math.Rounding.Floor);
        uint256 assetsUp = _convertToAssets(shares, redeemPrice, Math.Rounding.Ceil);

        strategy.onRedeem(address(this), shares, receiver, controller);

        _updateReservedLiquidity(assets);
        _updateRedeemState(state, assets, assetsUp, shares, shares);

        _burn(address(this), shares);
        _withdraw(receiver, assets);

        emit Withdraw(msg.sender, receiver, controller, assets, shares);
    }

    /// @inheritdoc IERC4626
    function withdraw(uint256 assets, address receiver, address controller)
        public
        onlyAuth(receiver, controller)
        returns (uint256 shares)
    {
        _checkMinAmount(assets);
        _checkController(controller);
        if (assets > maxWithdraw(controller)) revert ExceedsMaxRedeem();

        VaultState storage state = _vaultStates[controller];
        uint256 withdrawPrice = state.withdrawPrice;
        shares = _convertToShares(assets, withdrawPrice, Math.Rounding.Floor);
        uint256 sharesUp = _convertToShares(assets, withdrawPrice, Math.Rounding.Ceil);

        strategy.onWithdraw(address(this), assets, receiver, controller);

        _updateReservedLiquidity(assets);
        _updateRedeemState(state, assets, assets, shares, sharesUp);

        _burn(address(this), shares);
        _withdraw(receiver, assets);

        emit Withdraw(msg.sender, receiver, controller, assets, shares);
    }

    function _updateRedeemState(
        VaultState storage state,
        uint256 assets,
        uint256 assetsUp,
        uint256 shares,
        uint256 sharesUp
    ) private {
        uint256 maxWithdraw_ = state.maxWithdraw;
        uint256 redeemShares_ = state.redeemShares;

        if (assets > maxWithdraw_) revert ExceedsRedeemLimit();
        state.maxWithdraw = maxWithdraw_ > assetsUp ? maxWithdraw_ - assetsUp : 0;

        if (shares > redeemShares_) revert ExceedsRedeemLimit();
        state.redeemShares = redeemShares_ > sharesUp ? redeemShares_ - sharesUp : 0;
        if (state.maxWithdraw == 0) state.redeemShares = 0;
        if (state.redeemShares == 0) state.maxWithdraw = 0;
    }

    /// @inheritdoc IAsyncCancelRedeem
    function cancelRedeemRequest(address controller, address receiver) public onlyAuth(receiver, controller) {
        _checkController(controller);
        VaultState storage state = _vaultStates[controller];
        if (state.pendingRedeemRequest == 0) revert NoPendingRedeemRequest();

        bool canCancel = strategy.onCancelRedeemRequest(address(this), controller);
        if (!canCancel) revert CancelRedeemRequestFailed();

        uint256 requestId = _requestIds[controller];
        uint256 pendingShares = state.pendingRedeemRequest;

        state.pendingRedeemRequest = 0;

        _transfer(address(this), receiver, pendingShares);
        _reduce(controller, pendingShares);

        try IUpdateLateStatus(address(strategy)).updateLateStatus() {} catch {}

        emit CancelRedeemRequest(controller, receiver, requestId, msg.sender);
    }

    // ========================================================================== //
    //                             Queue operations                               //
    // ========================================================================== //

    /// @inheritdoc IAccountableWithdrawalQueue
    function fulfillRedeemRequest(address controller, uint256 shares) public onlyStrategy {
        _fulfillRedeemRequest(_requestIds[controller], controller, shares, sharePrice());
        _reduce(controller, shares);
    }

    /// @inheritdoc IAccountableWithdrawalQueue
    function processUpToShares(uint256 maxShares) public onlyStrategy returns (uint256 assetsUsed) {
        assetsUsed = _processUpToShares(maxShares, _liquidity(), sharePrice());
    }

    /// @inheritdoc IAccountableWithdrawalQueue
    function processUpToRequestId(uint256 maxRequestId)
        public
        onlyStrategy
        returns (uint256 processedShares, uint256 assetsUsed)
    {
        (processedShares, assetsUsed) = _processUpToRequestId(maxRequestId, _liquidity(), sharePrice());
    }

    /// @inheritdoc IAccountableWithdrawalQueue
    function previewRequiredShares(uint256 maxAssets)
        public
        view
        returns (uint256 processedShares, uint256 assetsUsed)
    {
        (processedShares, assetsUsed) = _previewRequiredShares(maxAssets, sharePrice());
    }

    /// @inheritdoc IAccountableWithdrawalQueue
    function previewMaxRequestId(uint256 maxAssets) public view returns (uint256 maxRequestId, uint256 assetsUsed) {
        (maxRequestId, assetsUsed) = _previewMaxRequestId(maxAssets, sharePrice());
    }

    /// @dev Computes free liquidity excluding accrued locked assets and reserved queue liquidity
    function _liquidity() internal view returns (uint256) {
        uint256 excludedAssets = strategy.accruedAssets(address(this)) + reservedLiquidity;
        return totalAssets() > excludedAssets ? totalAssets() - excludedAssets : 0;
    }

    /// @dev Fulfills a redeem request
    function _fulfillRedeemRequest(uint128 requestId, address controller, uint256 shares, uint256 price)
        internal
        override
    {
        VaultState storage state = _vaultStates[controller];
        uint256 pendingRedeemRequest_ = state.pendingRedeemRequest;

        if (pendingRedeemRequest_ == 0) revert NoRedeemRequest();
        if (pendingRedeemRequest_ < shares) revert InsufficientAmount();

        uint256 assets = _convertToAssets(shares, price, Math.Rounding.Floor);
        if (assets > _liquidity()) revert InsufficientLiquidity();

        reservedLiquidity += assets;
        state.maxWithdraw += assets;
        state.redeemShares += shares;
        state.pendingRedeemRequest -= shares;

        state.redeemPrice = state.maxWithdraw.mulDiv(precision, state.redeemShares);
        state.withdrawPrice = state.maxWithdraw.mulDiv(precision, state.redeemShares, Math.Rounding.Ceil);

        /// @dev RequestId is non-zero if in queue, 0 otherwise (instant fulfill)
        emit RedeemClaimable(controller, requestId, assets, shares);
    }

    /// @inheritdoc IERC4626
    function maxDeposit(address controller) public view override returns (uint256 maxAssets) {
        maxAssets = strategy.maxDeposit(address(this), controller);
    }

    /// @inheritdoc IERC4626
    function maxMint(address controller) public view override returns (uint256 maxShares) {
        maxShares = _convertToShares(maxDeposit(controller), sharePrice(), Math.Rounding.Floor);
    }

    /// @inheritdoc IERC4626
    function maxRedeem(address controller) public view override returns (uint256 maxShares) {
        VaultState storage state = _vaultStates[controller];
        maxShares = state.redeemShares;
        if (maxShares == 0) return 0;
    }

    /// @inheritdoc IERC4626
    function maxWithdraw(address controller) public view override returns (uint256 maxAssets) {
        VaultState storage state = _vaultStates[controller];
        maxAssets = state.maxWithdraw;
        if (state.redeemShares == 0) return 0;
    }

    /// @inheritdoc IERC4626
    /// @notice Preview deposit works for sync deposit vaults
    function previewDeposit(uint256 assets) public view returns (uint256 shares) {
        shares = _convertToShares(assets, sharePrice(), Math.Rounding.Floor);
    }

    /// @inheritdoc IERC4626
    /// @notice Preview mint works for sync deposit vaults
    function previewMint(uint256 shares) public view returns (uint256 assets) {
        assets = _convertToAssets(shares, sharePrice(), Math.Rounding.Ceil);
    }

    /// @inheritdoc IERC4626
    /// @notice Preview functions are not supported for async vaults
    function previewRedeem(uint256) public pure returns (uint256) {
        revert();
    }

    /// @inheritdoc IERC4626
    /// @notice Preview functions are not supported for async vaults
    function previewWithdraw(uint256) public pure returns (uint256) {
        revert();
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public pure override returns (bool) {
        return interfaceId == type(IAccountableAsyncRedeemVault).interfaceId || interfaceId == type(IERC165).interfaceId
            || interfaceId == type(IAsyncRedeem).interfaceId || interfaceId == type(IAsyncCancelRedeem).interfaceId
            || interfaceId == type(IAccountableVault).interfaceId || interfaceId == type(IERC4626).interfaceId
            || interfaceId == type(IControllerOperator).interfaceId || interfaceId == type(IERC20).interfaceId
            || interfaceId == type(IAccountableWithdrawalQueue).interfaceId
            || interfaceId == type(IERC20Metadata).interfaceId;
    }
}

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-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

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

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     * ```
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

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

import {IAccess, PermissionLevel} from "../interfaces/IAccess.sol";

import {Whitelistable} from "./Whitelistable.sol";
import {Authorizable} from "./Authorizable.sol";

/// @title AccessBase - A base contract for access control extending Whitelistable and Authorizable
/// @notice This contract is used to gate access to callable/interactable contracts
/// @dev See IAccess for detailed interface documentation
/// @custom:security-contact [email protected]
abstract contract AccessBase is IAccess, Whitelistable, Authorizable {
    /// @inheritdoc IAccess
    PermissionLevel public permissionLevel;

    /// @notice Constructor
    /// @param permissionLevel_ The permission level for the contract
    constructor(PermissionLevel permissionLevel_) {
        permissionLevel = permissionLevel_;
    }

    function _isVerified(address account, bytes calldata msgData) internal returns (bool) {
        PermissionLevel _permission = permissionLevel;

        if (_permission == PermissionLevel.KYC) return _verify(account, msgData);

        if (_permission == PermissionLevel.Whitelist) return allowed[account];

        return true;
    }

    function _areVerified(address[] memory accounts, bytes calldata msgData) internal returns (bool) {
        PermissionLevel _permission = permissionLevel;

        if (_permission == PermissionLevel.KYC) return _verifyMany(accounts, msgData);

        if (_permission == PermissionLevel.Whitelist) return allowedMany(accounts);

        return true;
    }
}

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

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

import {IWhitelistable} from "../interfaces/IAccess.sol";

import {ArrayLengthMismatch} from "../constants/Errors.sol";

/// @title Whitelistable - A contract that allows whitelisting of accounts
/// @notice This contract is used to allow/disallow account access
/// @dev See IWhitelistable for detailed interface documentation
/// @custom:security-contact [email protected]
abstract contract Whitelistable is IWhitelistable {
    /// @notice Mapping to track the allowed status of accounts
    /// @dev Maps an account address to its allowed status
    mapping(address account => bool allowed) public allowed;

    /// @inheritdoc IWhitelistable
    function setAllowed(address[] calldata accounts, bool[] calldata statuses) public virtual {
        if (accounts.length != statuses.length) revert ArrayLengthMismatch();

        for (uint256 i = 0; i < accounts.length;) {
            allowed[accounts[i]] = statuses[i];
            emit AllowedSet(accounts[i], statuses[i]);
            unchecked {
                ++i;
            }
        }
    }

    function allowedMany(address[] memory accounts) public view returns (bool) {
        for (uint256 i = 0; i < accounts.length;) {
            if (!allowed[accounts[i]]) return false;
            unchecked {
                ++i;
            }
        }
        return true;
    }
}

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

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

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

/// @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 Error thrown when no cancel redeem request exists
error NoCancelRedeemRequest();

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

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

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

/// @notice Error thrown when no queue requests exist
error NoQueueRequests();

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

// ========================================================================== //
//                             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 loan is not in default
error LoanNotInDefault();

/// @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 repayment terms are not met
error LoanCannotBeRepaid();

/// @notice Error thrown when interest is already claimed
error InterestAlreadyClaimed();

/// @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 vault manager permissions
error InvalidVaultManager();

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

// ========================================================================== //
//                            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 operation is requested with zero amount
error ZeroAmount();

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

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

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

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

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

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

// ========================================================================== //
//                            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();

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/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 proof is published
    event DVNProofPublished(bytes32 indexed root, bytes32 indexed signature, bytes32 indexed messageHash);

    /// @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 Publish a new DVN proof
    /// @param proof Latest DVN proof data
    function publishDVNProof(DVNProof memory proof) 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 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 establishmentFee The establishment fee amount paid
    /// @param paymentInterval The interval of the payment
    event InterestPaid(
        address indexed borrower,
        uint256 totalAmount,
        uint256 interestPenalty,
        uint256 performanceFee,
        uint256 establishmentFee,
        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/IAccountableWithdrawalQueue.sol

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

/// @notice Struct tracking a withdrawal request
struct WithdrawalRequest {
    /// @notice The number of shares requested
    uint256 shares;
    /// @notice The controller of the request
    address controller;
}

/// @notice Struct tracking the withdrawal queue
struct WithdrawalQueue {
    /// @notice The next request ID to be processed
    uint128 nextRequestId;
    /// @notice The last request ID to be processed
    uint128 lastRequestId;
    /// @notice The mapping of request IDs to withdrawal requests
    mapping(uint128 requestId => WithdrawalRequest request) requests;
}

/// @notice Interface for the withdrawal queue
interface IAccountableWithdrawalQueue {
    /// @notice Fulfill a redeem request
    /// @param controller The controller of the request
    /// @param shares The number of shares to fulfill
    function fulfillRedeemRequest(address controller, uint256 shares) external;

    /// @notice Process up to `maxShares` shares
    /// @param maxShares The maximum number of shares to process
    /// @return assetsUsed The number of assets used to process the shares
    function processUpToShares(uint256 maxShares) external returns (uint256 assetsUsed);

    /// @notice Process up to `maxRequestId` request
    /// @param maxRequestId The last request ID to process
    /// @return processedShares The number of shares that were processed
    /// @return assetsUsed The number of assets used to process the shares
    function processUpToRequestId(uint256 maxRequestId)
        external
        returns (uint256 processedShares, uint256 assetsUsed);

    /// @notice Preview required shares that can be processed with `maxAssets`
    /// @param maxAssets The maximum number of assets to be matched with `maxAssets`
    /// @return processedShares The number of shares that can be processed with the assets
    /// @return assetsUsed The number of assets used to process the shares
    function previewRequiredShares(uint256 maxAssets)
        external
        view
        returns (uint256 processedShares, uint256 assetsUsed);

    /// @notice Preview the last request ID that can be processed with `maxAssets`
    /// @param maxAssets The maximum number of assets to be matched with `maxAssets`
    /// @return maxRequestId The last request ID that can be processed with the assets
    /// @return assetsUsed The number of assets used to process the shares
    function previewMaxRequestId(uint256 maxAssets) external view returns (uint256 maxRequestId, uint256 assetsUsed);

    /// @notice Get the total number of shares queued
    /// @return totalQueuedShares The total number of shares queued
    function totalQueuedShares() external view returns (uint256 totalQueuedShares);

    /// @notice Get the reserved liquidity
    /// @return reservedLiquidity The reserved liquidity
    function reservedLiquidity() external view returns (uint256 reservedLiquidity);

    /// @notice Get the withdrawal queue indices
    /// @return nextRequestId The next request ID to be processed
    /// @return lastRequestId The last request ID to be processed
    function queue() external view returns (uint128 nextRequestId, uint128 lastRequestId);

    /// @notice Get the withdrawal request for a controller
    /// @param controller The controller of the request
    /// @return request The withdrawal request
    function withdrawalRequest(address controller) external view returns (WithdrawalRequest memory request);

    /// @notice Get the withdrawal requests
    /// @param start The start index of the queue
    /// @param end The end index of the queue
    /// @return requests The withdrawal requests
    function withdrawalRequests(uint128 start, uint128 end)
        external
        view
        returns (WithdrawalRequest[] memory requests);
}

src/vault/AccountableVault.sol

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

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

import {IStrategyVaultHooks} from "../interfaces/IAccountableStrategy.sol";
import {IAuthorizable, IWhitelistable, PermissionLevel} from "../interfaces/IAccess.sol";
import {IAccountableVault, IControllerOperator, VaultState} from "../interfaces/IAccountableAsyncVault.sol";

import {AccessBase} from "../access/AccessBase.sol";
import {Authorizable} from "../access/Authorizable.sol";
import {Whitelistable} from "../access/Whitelistable.sol";

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

/// @title AccountableVault
/// @notice Base contract for Accountable async vaults
/// @custom:security-contact [email protected]
abstract contract AccountableVault is IAccountableVault, ERC20, AccessBase {
    using Math for uint256;
    using SafeERC20 for IERC20;

    /// @notice Underlying asset
    IERC20 internal immutable _asset;

    /// @notice Decimals of the underlying asset
    uint8 internal immutable _underlyingDecimals;

    /// @notice Total assets in the vault
    uint256 internal _totalAssets;

    /// @notice Mapping of vault states by controller
    mapping(address controller => VaultState state) internal _vaultStates;

    /// @notice Minimum amount in wei to prevent dust attacks
    uint256 public constant MIN_AMOUNT_WEI = 10_000;

    /// @notice The loan manager contract that handles deposit/redeem requests
    IStrategyVaultHooks public strategy;

    /// @notice Precision for share calculations
    uint256 public precision;

    /// @notice Mapping of owner addresses to their approved operators
    mapping(address => mapping(address => bool)) public isOperator;

    /// @notice Whether the vault is transferable
    bool public transferableShares;

    /// @notice Ensures only the loan manager can call certain functions
    modifier onlyStrategy() {
        if (msg.sender != address(strategy)) {
            revert Unauthorized();
        }
        _;
    }

    /// @notice Ensures only authorized accounts can call certain functions
    modifier onlyAuth(address receiverOwner, address controller) {
        if (receiverOwner == controller) {
            if (!_isVerified(controller, msg.data)) revert Unauthorized();
        } else {
            address[] memory accounts = new address[](2);
            accounts[0] = receiverOwner;
            accounts[1] = controller;

            if (!_areVerified(accounts, msg.data)) revert Unauthorized();
        }
        _;
    }

    constructor(IERC20 asset_, PermissionLevel permissionLevel_) AccessBase(permissionLevel_) {
        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
        _underlyingDecimals = success ? assetDecimals : 18;
        _asset = asset_;
    }

    /// @dev Try to get the decimals of the underlying asset
    function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {
        (bool success, bytes memory encodedDecimals) =
            address(asset_).staticcall(abi.encodeCall(IERC20Metadata.decimals, ()));

        if (success && encodedDecimals.length >= 32) {
            uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
            if (returnedDecimals <= type(uint8).max) {
                return (true, uint8(returnedDecimals));
            }
        }
        return (false, 0);
    }

    /// @inheritdoc IControllerOperator
    function setOperator(address operator, bool approved) public returns (bool) {
        if (msg.sender == operator) {
            revert InvalidOperator();
        }
        isOperator[msg.sender][operator] = approved;
        emit OperatorSet(msg.sender, operator, approved);
        return true;
    }

    /// @inheritdoc IERC20Metadata
    function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
        return _underlyingDecimals;
    }

    /// @inheritdoc IERC4626
    function asset() public view virtual returns (address) {
        return address(_asset);
    }

    /// @inheritdoc IERC4626
    function totalAssets() public view returns (uint256) {
        return _totalAssets;
    }

    /// @inheritdoc IERC20
    function transfer(address to, uint256 amount) public virtual override(ERC20, IERC20) returns (bool) {
        _checkTransfer(amount, msg.sender, to);
        strategy.onTransfer(address(this), msg.sender, to, amount);
        return super.transfer(to, amount);
    }

    /// @inheritdoc IERC20
    function transferFrom(address from, address to, uint256 amount)
        public
        virtual
        override(ERC20, IERC20)
        returns (bool)
    {
        _checkTransfer(amount, from, to);
        strategy.onTransfer(address(this), from, to, amount);
        return super.transferFrom(from, to, amount);
    }

    /// @dev Checks transfer restrictions before executing the underlying transfer
    function _checkTransfer(uint256, address, address to) private {
        if (!transferableShares) revert SharesNotTransferable();
        if (!_isVerified(to, msg.data)) revert Unauthorized();
    }

    /// @inheritdoc IERC4626
    function convertToShares(uint256 assets) public view returns (uint256) {
        return _convertToShares(assets, sharePrice(), Math.Rounding.Floor);
    }

    /// @inheritdoc IERC4626
    function convertToAssets(uint256 shares) public view returns (uint256) {
        return _convertToAssets(shares, sharePrice(), Math.Rounding.Floor);
    }

    /// @inheritdoc IAccountableVault
    function assetShareRatio() public view returns (uint256) {
        uint256 shares = totalSupply();
        uint256 reserved = IStrategyVaultHooks(strategy).accruedAssets(address(this));
        return shares == 0 ? precision : (totalAssets() - reserved).mulDiv(precision, shares, Math.Rounding.Floor);
    }

    /// @dev Computes the assets based on shares and price
    function _convertToAssets(uint256 shares, uint256 price, Math.Rounding rounding)
        internal
        view
        virtual
        returns (uint256 assets)
    {
        assets = shares.mulDiv(price, precision, rounding);
    }

    /// @dev Computes the shares based on assets and price
    function _convertToShares(uint256 assets, uint256 price, Math.Rounding rounding)
        internal
        view
        virtual
        returns (uint256 shares)
    {
        shares = assets.mulDiv(precision, price, rounding);
    }

    /// @inheritdoc IAccountableVault
    function sharePrice() public view returns (uint256) {
        return strategy.sharePrice(address(this));
    }

    /// @inheritdoc IAccountableVault
    function share() public view returns (address) {
        return address(this);
    }

    /// @inheritdoc IAccountableVault
    function getState(address controller) public view returns (VaultState memory) {
        return _vaultStates[controller];
    }

    /// @inheritdoc IAccountableVault
    function lockAssets(uint256 assets, address sender) public onlyStrategy {
        _deposit(sender, assets);
        emit LockAssets(sender, assets);
    }

    /// @inheritdoc IAccountableVault
    function releaseAssets(uint256 assets, address receiver) public onlyStrategy {
        _withdraw(receiver, assets);
        emit ReleaseAssets(receiver, assets);
    }

    /// @inheritdoc IAccountableVault
    function mintShares(uint256 shares, address receiver) public onlyStrategy {
        _mint(receiver, shares);
    }

    /// @inheritdoc IAccountableVault
    function burnShares(uint256 shares, address sender) public onlyStrategy {
        _burn(sender, shares);
    }

    /// @inheritdoc IAccountableVault
    function forceTransferShares(address from, address to, uint256 shares) public onlyStrategy {
        strategy.onTransfer(address(this), from, to, shares);
        _transfer(from, to, shares);
    }

    /// @inheritdoc IAccountableVault
    function setSharesTransferable(bool sharesTransferable_) public onlyStrategy {
        bool oldStatus = transferableShares;
        transferableShares = sharesTransferable_;
        emit SharesTransferableSet(oldStatus, sharesTransferable_);
    }

    /// @inheritdoc IAuthorizable
    function setSigner(address signer_) public override(IAuthorizable, Authorizable) onlyStrategy {
        if (permissionLevel != PermissionLevel.KYC) revert PermissionLevelMismatch();
        super.setSigner(signer_);
    }

    /// @inheritdoc IWhitelistable
    function setAllowed(address[] calldata accounts, bool[] calldata statuses)
        public
        override(IWhitelistable, Whitelistable)
        onlyStrategy
    {
        if (permissionLevel != PermissionLevel.Whitelist) revert PermissionLevelMismatch();
        super.setAllowed(accounts, statuses);
    }

    /// @dev Deposit assets into the vault and increment total assets
    function _deposit(address caller, uint256 assets) internal virtual {
        _totalAssets += assets;
        _asset.safeTransferFrom(caller, address(this), assets);
    }

    /// @dev Withdraw assets from the vault and decrement total assets
    function _withdraw(address receiver, uint256 assets) internal virtual {
        _totalAssets -= assets;
        _asset.safeTransfer(receiver, assets);
    }

    /// @dev Checks if the caller is an approved operator for the owner
    /// @param owner The owner address to check against
    function _checkOperator(address owner) internal view {
        if (owner != msg.sender && !isOperator[owner][msg.sender]) {
            revert InvalidOperator();
        }
    }

    /// @dev Checks if the caller is an approved operator for the controller
    /// @param controller The controller address to check against
    function _checkController(address controller) internal view {
        if (controller != msg.sender && !isOperator[controller][msg.sender]) {
            revert InvalidController();
        }
    }

    /// @dev Checks if the owner has sufficient shares
    /// @param owner The owner address to check
    /// @param shares The amount of shares to check for
    function _checkShares(address owner, uint256 shares) internal view {
        if (balanceOf(owner) < shares || shares == 0) {
            revert InsufficientShares();
        }
    }

    /// @dev Checks if the amount is greater than the minimum amount
    function _checkMinAmount(uint256 amount) internal pure {
        if (amount < MIN_AMOUNT_WEI) revert InsufficientAmount();
    }
}

src/vault/queue/AccountableWithdrawalQueue.sol

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

import {InsufficientShares, InvalidRange, OutOfBounds, NoQueueRequest} from "../../constants/Errors.sol";

import {
    IAccountableWithdrawalQueue,
    WithdrawalRequest,
    WithdrawalQueue
} from "../../interfaces/IAccountableWithdrawalQueue.sol";

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

/// @title AccountableWithdrawalQueue
/// @notice A contract that manages the withdrawal queue
/// @custom:security-contact [email protected]
abstract contract AccountableWithdrawalQueue is IAccountableWithdrawalQueue {
    using Math for uint256;

    /// @notice Price precision
    uint256 internal _precision;

    /// @notice Withdrawal queue
    WithdrawalQueue internal _queue;

    /// @notice Mapping of controller to request ID
    mapping(address controller => uint128 requestId) internal _requestIds;

    /// @inheritdoc IAccountableWithdrawalQueue
    uint256 public totalQueuedShares;

    /// @inheritdoc IAccountableWithdrawalQueue
    /// @dev The reserved liquidity is the amount of assets that are reserved for withdrawals
    /// @dev Has to be excluded from total liquidity calculations to avoid double counting
    uint256 public reservedLiquidity;

    constructor(uint256 precision_) {
        _precision = precision_;

        _queue.nextRequestId = 1;
    }

    /// @inheritdoc IAccountableWithdrawalQueue
    function queue() external view returns (uint128 nextRequestId, uint128 lastRequestId) {
        (nextRequestId, lastRequestId) = (_queue.nextRequestId, _queue.lastRequestId);
    }

    /// @inheritdoc IAccountableWithdrawalQueue
    function withdrawalRequest(address controller) external view returns (WithdrawalRequest memory request) {
        request = _queue.requests[_requestIds[controller]];
    }

    /// @inheritdoc IAccountableWithdrawalQueue
    function withdrawalRequests(uint128 start, uint128 end)
        external
        view
        returns (WithdrawalRequest[] memory requests)
    {
        if (start == 0 || start > end) revert InvalidRange();
        if (end > _queue.lastRequestId) revert OutOfBounds();

        uint128 len = end - start + 1;
        requests = new WithdrawalRequest[](len);

        for (uint128 i = 0; i < len;) {
            requests[i] = _queue.requests[start + i];
            unchecked {
                ++i;
            }
        }
    }

    /// @dev Pushes a new withdrawal request to the queue
    function _push(address controller, uint256 shares) internal returns (uint128 requestId) {
        uint128 requestId_ = _requestIds[controller];
        if (requestId_ == 0) {
            requestId = ++_queue.lastRequestId;

            _requestIds[controller] = requestId;
            _queue.requests[requestId] = WithdrawalRequest(shares, controller);
        } else {
            requestId = requestId_;
            _queue.requests[requestId_].shares += shares;
        }

        totalQueuedShares += shares;
    }

    /// @dev Reduces or removes the shares of a withdrawal request
    function _reduce(address controller, uint256 shares) internal returns (uint256 remainingShares) {
        uint128 requestId = _requestIds[controller];
        if (requestId == 0) revert NoQueueRequest();

        uint256 currentShares = _queue.requests[requestId].shares;
        if (shares > currentShares || currentShares == 0) revert InsufficientShares();

        remainingShares = currentShares - shares;
        totalQueuedShares -= shares;

        if (remainingShares == 0) {
            _delete(controller, requestId);
        } else {
            _queue.requests[requestId].shares = remainingShares;
        }
    }

    /// @dev Deletes a withdrawal request and its controller from the queue
    function _delete(address controller, uint128 requestId) private {
        delete _queue.requests[requestId];
        delete _requestIds[controller];
    }

    /// @dev Processes up to the given number of shares
    function _processUpToShares(uint256 maxShares, uint256 liquidity, uint256 currentPrice)
        internal
        returns (uint256 assetsUsed)
    {
        if (maxShares == 0 || totalQueuedShares == 0) return 0;

        uint256 precision_ = _precision;
        uint128 nextRequestId = _queue.nextRequestId;
        uint128 lastRequestId = _queue.lastRequestId;

        while (maxShares > 0 && nextRequestId <= lastRequestId) {
            WithdrawalRequest memory request_ = _queue.requests[nextRequestId];

            (uint256 shares_, uint256 assets_, bool processed_) =
                _processRequest(request_, liquidity, maxShares, currentPrice, precision_);

            if (shares_ == 0) {
                if (processed_) {
                    ++nextRequestId;
                    continue;
                }
                break;
            }

            _fulfillRedeemRequest(nextRequestId, request_.controller, shares_, currentPrice);

            assetsUsed += assets_;
            liquidity -= assets_;
            maxShares -= shares_;

            if (!processed_) break;

            ++nextRequestId;
        }

        _queue.nextRequestId = nextRequestId;
    }

    /// @dev Processes requests up to the given request ID
    function _processUpToRequestId(uint256 maxRequestId, uint256 liquidity, uint256 currentPrice)
        internal
        returns (uint256 processedShares, uint256 assetsUsed)
    {
        uint256 maxShares_ = totalQueuedShares;
        if (maxRequestId == 0 || maxShares_ == 0) return (0, 0);

        uint256 precision_ = _precision;
        uint128 nextRequestId = _queue.nextRequestId;
        uint128 lastRequestId = _queue.lastRequestId;

        uint256 cappedMaxRequestId = maxRequestId > lastRequestId ? lastRequestId : maxRequestId;

        while (nextRequestId <= cappedMaxRequestId) {
            WithdrawalRequest memory request_ = _queue.requests[nextRequestId];
            (uint256 shares_, uint256 assets_, bool processed_) =
                _processRequest(request_, liquidity, maxShares_, currentPrice, precision_);

            if (shares_ == 0) {
                if (processed_) {
                    ++nextRequestId;
                    continue;
                }
                break;
            }

            _fulfillRedeemRequest(nextRequestId, request_.controller, shares_, currentPrice);

            processedShares += shares_;
            assetsUsed += assets_;
            liquidity -= assets_;

            if (!processed_) break;

            ++nextRequestId;
        }

        _queue.nextRequestId = nextRequestId;
    }

    /// @dev Processes a withdrawal request updating all relevant state
    function _processRequest(
        WithdrawalRequest memory request,
        uint256 liquidity,
        uint256 maxShares,
        uint256 currentPrice,
        uint256 precision
    ) internal returns (uint256 processedShares, uint256 assetsUsed, bool processed) {
        if (request.controller == address(0)) return (0, 0, true);

        uint256 liquidShares = liquidity.mulDiv(precision, currentPrice);
        uint256 sharesToProcess = _min3(request.shares, liquidShares, maxShares);

        if (sharesToProcess == 0) return (0, 0, false);

        processedShares = sharesToProcess;
        assetsUsed = sharesToProcess.mulDiv(currentPrice, precision);

        processed = (sharesToProcess == request.shares);

        _reduce(request.controller, processedShares);
    }

    /// @dev Returns the number of shares that can be processed with the given assets
    function _previewRequiredShares(uint256 maxAssets, uint256 currentPrice)
        internal
        view
        returns (uint256 processedShares, uint256 assetsUsed)
    {
        uint256 precision_ = _precision;
        uint128 nextRequestId = _queue.nextRequestId;
        uint128 lastRequestId = _queue.lastRequestId;

        uint256 remainingShares = totalQueuedShares;

        while (maxAssets > 0 && remainingShares > 0 && nextRequestId <= lastRequestId) {
            WithdrawalRequest memory request_ = _queue.requests[nextRequestId];
            uint256 requestAssets = request_.shares.mulDiv(currentPrice, precision_);

            if (requestAssets > maxAssets) {
                uint256 maxAvailable = Math.min(maxAssets, requestAssets);
                uint256 maxShares = maxAvailable.mulDiv(precision_, currentPrice);

                if (maxShares > 0) {
                    processedShares += maxShares;
                    assetsUsed += maxShares.mulDiv(currentPrice, precision_);
                }
                break;
            }

            processedShares += request_.shares;
            remainingShares -= request_.shares;

            assetsUsed += requestAssets;
            maxAssets -= requestAssets;

            ++nextRequestId;
        }
    }

    /// @dev Returns the maximum request ID that can be processed with the given assets
    function _previewMaxRequestId(uint256 maxAssets, uint256 currentPrice)
        internal
        view
        returns (uint256 maxRequestId, uint256 assetsUsed)
    {
        uint256 precision_ = _precision;
        uint128 nextRequestId_ = _queue.nextRequestId;
        uint128 lastRequestId_ = _queue.lastRequestId;

        uint256 remainingShares = totalQueuedShares;

        while (maxAssets > 0 && remainingShares > 0 && nextRequestId_ <= lastRequestId_) {
            WithdrawalRequest memory request_ = _queue.requests[nextRequestId_];
            uint256 requestAssets = request_.shares.mulDiv(currentPrice, precision_);

            if (requestAssets > maxAssets) {
                uint256 maxAvailable = Math.min(maxAssets, requestAssets);
                uint256 maxShares = maxAvailable.mulDiv(precision_, currentPrice);

                if (maxShares > 0) {
                    maxRequestId = nextRequestId_;
                    assetsUsed += maxShares.mulDiv(currentPrice, precision_);
                }
                break;
            }

            assetsUsed += requestAssets;
            maxAssets -= requestAssets;

            remainingShares -= request_.shares;

            maxRequestId = nextRequestId_++;
        }
    }

    /// @dev Updates the reserved liquidity, to be triggered on withdraw/redeem
    function _updateReservedLiquidity(uint256 assets) internal {
        reservedLiquidity = assets < reservedLiquidity ? reservedLiquidity - assets : 0;
    }

    /// @dev Returns the minimum of three values
    function _min3(uint256 a, uint256 b, uint256 c) internal pure returns (uint256 result) {
        assembly {
            result := a
            if lt(b, result) { result := b }
            if lt(c, result) { result := c }
        }
    }

    /// @dev Hook function to trigger state updates when a request is processed
    function _fulfillRedeemRequest(uint128 requestId, address controller, uint256 shares, uint256 price)
        internal
        virtual;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "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/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.