MON Price: $0.017712 (-7.26%)

Contract

0x78f9486C71371bB5af50cBCdf4BACDC298eC8A97

Overview

MON Balance

Monad Chain LogoMonad Chain LogoMonad Chain Logo0 MON

MON Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Accrue Interest494973642026-01-18 10:36:197 days ago1768732579IN
0x78f9486C...298eC8A97
0 MON0.01800657102.103
Accrue Interest486642282026-01-14 13:30:1011 days ago1768397410IN
0x78f9486C...298eC8A97
0 MON0.01798841102
Accrue Interest479859272026-01-11 9:57:3114 days ago1768125451IN
0x78f9486C...298eC8A97
0 MON0.01198314101.94
Accrue Interest466825782026-01-05 8:35:2320 days ago1767602123IN
0x78f9486C...298eC8A97
0 MON0.01198518101.94
Accrue Interest465232822026-01-04 14:51:3721 days ago1767538297IN
0x78f9486C...298eC8A97
0 MON0.01198518101.94
Accrue Interest452070272025-12-29 12:20:4927 days ago1767010849IN
0x78f9486C...298eC8A97
0 MON0.01198314101.94
Process Availabl...450235962025-12-28 15:54:1628 days ago1766937256IN
0x78f9486C...298eC8A97
0 MON0.2113331284.65437838
Accrue Interest433286672025-12-20 18:42:1536 days ago1766256135IN
0x78f9486C...298eC8A97
0 MON0.0119902102
Process Availabl...433286662025-12-20 18:42:1536 days ago1766256135IN
0x78f9486C...298eC8A97
0 MON0.01131486102
Process Availabl...433257212025-12-20 18:22:3436 days ago1766254954IN
0x78f9486C...298eC8A97
0 MON0.051102
Accrue Interest433257202025-12-20 18:22:3336 days ago1766254953IN
0x78f9486C...298eC8A97
0 MON0.051102
Accrue Interest433254622025-12-20 18:20:5036 days ago1766254850IN
0x78f9486C...298eC8A97
0 MON0.051102
Process Availabl...422806012025-12-15 21:58:1840 days ago1765835898IN
0x78f9486C...298eC8A97
0 MON0.0138415102
Process Availabl...422804932025-12-15 21:57:3440 days ago1765835854IN
0x78f9486C...298eC8A97
0 MON0.02765444102
Process Availabl...422766072025-12-15 21:31:3441 days ago1765834294IN
0x78f9486C...298eC8A97
0 MON0.09780433102

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
377175262025-11-24 15:57:3662 days ago1763999856  Contract Creation0 MON
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0xD0943c76...58Dd01Ef3
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
ERC1967Proxy

Compiler Version
v0.8.27+commit.40a35a09

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion, MIT license

Contract Source Code (Solidity Standard Json-Input format)

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

pragma solidity ^0.8.20;

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

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

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

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

import {IAccountableStrategy} from "../interfaces/IAccountableStrategy.sol";
import {OpenTermInitParams} from "../interfaces/IAccountableOpenTerm.sol";

import {FailedDeployment} from "../constants/Errors.sol";
import {StrategyFactoryBase} from "./StrategyFactoryBase.sol";
import {AccountableOpenTerm} from "../strategies/AccountableOpenTerm.sol";
import {IOpenTermFactory, OpenTermFactoryParams} from "../interfaces/IStrategyFactory.sol";

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

/// @title OpenTermFactory
/// @notice Factory contract for creating and managing open term loans
contract OpenTermFactory is IOpenTermFactory, StrategyFactoryBase {
    /// @notice Initializes the factory with a globals address
    /// @param globals_ The initial globals address
    constructor(address globals_, address owner_) StrategyFactoryBase(globals_, owner_) {}

    /// @inheritdoc IOpenTermFactory
    function createOpenTermLoan(OpenTermFactoryParams memory params)
        external
        whenNotPaused
        onlyVerified
        onlyWhitelistedAsset(params.asset)
        returns (address strategyProxy, address vault)
    {
        bytes memory strategyInitData = abi.encode(
            strategyImplementation,
            abi.encodeCall(
                AccountableOpenTerm.initialize,
                (
                    OpenTermInitParams({
                        asset: params.asset,
                        globals: globals,
                        feeManager: feeManager,
                        investmentManager: params.investmentManager,
                        permissionLevel: params.permissionLevel,
                        sharesTransferable: params.sharesTransferable,
                        name: params.name,
                        symbol: params.symbol
                    })
                )
            )
        );
        bytes memory strategyProxyBytecode = abi.encodePacked(type(ERC1967Proxy).creationCode, strategyInitData);
        strategyProxy = Create2.deploy(0, params.salt, strategyProxyBytecode);
        if (strategyProxy == address(0)) revert FailedDeployment(ZERO_LOAN_PROXY_ADDRESS);

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

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

        emit OpenTermCreated(strategyProxy, vault, params.investmentManager);
    }
}

File 3 of 52 : 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);
}

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

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

/// @notice Struct for withdrawal batches
struct WithdrawalBatch {
    /// @notice The expiry time of the withdrawal batch
    uint256 expiry;
    /// @notice The start time of the withdrawal batch
    uint256 startTime;
    /// @notice The total shares of the withdrawal batch
    uint256 totalShares;
}

/// @notice Parameters for initializing the AccountableOpenTerm contract
struct OpenTermInitParams {
    /// @notice The asset of the loan
    address asset;
    /// @notice The global registry address
    address globals;
    /// @notice The fee manager of the loan
    address feeManager;
    /// @notice The investment manager of the loan
    address investmentManager;
    /// @notice The permission level of the loan
    PermissionLevel permissionLevel;
    /// @notice Whether the shares are transferable
    bool sharesTransferable;
    /// @notice The name of the share token
    string name;
    /// @notice The symbol of the share token
    string symbol;
}

/// @notice Interface for the AccountableOpenTerm contract
interface IAccountableOpenTerm is IAccountableLoan, IUpdateLateStatus {
    /// @notice Event emitted when the terms are accepted
    event TermsAccepted();

    /// @notice Event emitted when the terms are rejected
    event TermsRejected();

    /// @notice Event emitted when the interest rate is proposed
    event InterestRateProposed(uint256 interestRate);

    /// @notice Event emitted when the interest rate is approved
    event InterestRateApproved(uint256 interestRate);

    /// @notice Event emitted when the delinquency status changes
    /// @param isDelinquent Whether the loan is currently delinquent
    /// @param timestamp The timestamp of the delinquency status change
    event DelinquencyStatusChanged(bool isDelinquent, uint256 timestamp);

    /// @notice Accepts the terms of the loan
    function acceptTerms() external;

    /// @notice Rejects the new terms of the loan
    function rejectTerms() external;

    /// @notice Sets a proposer as approved or not
    /// @param proposer The interest rate proposer
    /// @param approved Whether the proposer is approved
    function setProposer(address proposer, bool approved) external;

    /// @notice Proposes a new interest rate for the loan
    /// @param interestRate The new pending interest rate
    /// @dev Proposal made by a borrower and pending approval
    function proposeInterestRate(uint256 interestRate) external;

    /// @notice Accepts the interest rate change of the loan
    /// @dev Only operational roles should have this authorization
    function approveInterestRateChange() external;

    /// @notice Manual interest accrual
    /// @return newScaleFactor The new scale factor
    function accrueInterest() external returns (uint256 newScaleFactor);

    /// @notice Processes available withdrawals
    /// @return usedAssets The number of assets used to process the withdrawals
    function processAvailableWithdrawals() external returns (uint256 usedAssets);

    /// @notice The withdrawal batches
    /// @param id Withdrawal batch id
    /// @return withdrawalBatch The withdrawal batch
    function withdrawalBatches(uint256 id) external view returns (WithdrawalBatch memory);

    /// @notice The new pending loan terms
    /// @return The loan terms
    function pendingTerms() external view returns (LoanTerms memory);

    /// @notice The current withdrawal batch
    /// @return The current withdrawal batch
    function currentBatch() external view returns (uint256);

    /// @notice The pending withdrawal batch
    /// @return The pending withdrawal batch
    function pendingBatch() external view returns (uint256);

    /// @notice The interest accrual factor
    /// @return The last valid scaleFactor recorded
    /// @dev This value can be stale and not reflect the current interest accrual
    function scaleFactor() external view returns (uint256);

    /// @notice Last repayment time
    /// @return The timestamp of the last repayment
    function lastPaidTime() external view returns (uint256);

    /// @notice The proposed interest rate
    function pendingInterestRate() external view returns (uint256);

    /// @notice The delinquency start time
    function delinquencyStartTime() external view returns (uint256);
}

File 5 of 52 : 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();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 7 of 52 : AccountableOpenTerm.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

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

import {IFeeManager} from "../interfaces/IFeeManager.sol";
import {IAccountableVault} from "../interfaces/IAccountableAsyncVault.sol";
import {IAccountableWithdrawalQueue} from "../interfaces/IAccountableWithdrawalQueue.sol";
import {IAccountableOpenTerm, OpenTermInitParams, WithdrawalBatch} from "../interfaces/IAccountableOpenTerm.sol";

import {
    IAccountableStrategy,
    IStrategyVaultHooks,
    IFeeManagerHooks,
    IAccountableLoan,
    LoanState,
    LoanTerms
} from "../interfaces/IAccountableStrategy.sol";

import {AccountableStrategy} from "../strategies/AccountableStrategy.sol";
import {OpenTermStorage} from "../strategies/storage/OpenTermStorage.sol";

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

/// @title AccountableOpenTerm
/// @notice Implementation of an open term loan
/// @dev Implements IAccountableOpenTerm interface and extends AccountableStrategy for managing loan lifecycle and payments
/// @custom:security-contact [email protected]
contract AccountableOpenTerm is UUPSUpgradeable, AccountableStrategy, OpenTermStorage {
    using Math for uint256;
    using SafeERC20 for IERC20;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    // ========================================================================== //
    //                          Initialization                                    //
    // ========================================================================== //

    function initialize(OpenTermInitParams memory params) external initializer {
        __Pausable_init();
        __UUPSUpgradeable_init();

        if (params.asset == address(0)) revert ZeroAddress();
        if (params.globals == address(0)) revert ZeroAddress();
        if (params.feeManager == address(0)) revert ZeroAddress();
        if (params.investmentManager == address(0)) revert ZeroAddress();

        asset = params.asset;
        globals = params.globals;
        feeManager = params.feeManager;
        loanState = LoanState.Initialized;
        investmentManager = params.investmentManager;

        penaltiesEnabled = true;

        _makeVault(IERC20(params.asset), params.sharesTransferable, params.permissionLevel, params.name, params.symbol);

        IERC20(params.asset).approve(vault, type(uint256).max);
        IERC20(params.asset).approve(params.feeManager, type(uint256).max);
    }

    // ========================================================================== //
    //                          Loan Terms Management                             //
    // ========================================================================== //

    /// @inheritdoc IAccountableLoan
    function setTerms(LoanTerms memory terms) public onlyManager {
        _requireLoanTermsNotSet();

        if (borrower == address(0)) revert ZeroAddress();
        if (terms.interestInterval == 0) revert InvalidIntervalLength();
        if (terms.withdrawalPeriod >= terms.interestInterval) revert InvalidWithdrawalPeriod();

        terms.duration = 0;
        _setTerms(terms);

        _scaleFactor = PRECISION;
        _scaleFactorNet = PRECISION;

        loanState = LoanState.TermsSet;
        _loan.termsSetTime = block.timestamp;

        emit LoanTermsSet(
            terms.minCapacity,
            terms.maxCapacity,
            terms.interestRate,
            terms.lateInterestPenalty,
            terms.interestInterval,
            terms.duration
        );
    }

    /// @inheritdoc IAccountableLoan
    function updateTerms(LoanTerms memory terms) external onlyManager {
        _requireLoanOngoing();

        _accrueInterest();

        _pendingTerms = terms;

        emit LoanTermsSet(
            terms.minCapacity,
            terms.maxCapacity,
            terms.interestRate,
            terms.lateInterestPenalty,
            terms.interestInterval,
            terms.duration
        );
    }

    /// @inheritdoc IAccountableOpenTerm
    function acceptTerms() external onlyBorrower whenNotPaused {
        if (loanState == LoanState.TermsSet) {
            loanState = LoanState.OngoingDynamic;

            _accruedAt = block.timestamp + _loan.depositPeriod;
            _loan.startTime = block.timestamp;
            _lastPaidTime = block.timestamp;

            _updateInterestParams();

            emit TermsAccepted();
            return;
        }

        _accrueInterest();
        _processAvailableWithdrawals();

        LoanTerms memory terms = _pendingTerms;
        delete _pendingTerms;

        uint256 currentMaxCap = _loan.maxCapacity;
        if (currentMaxCap > terms.maxCapacity) {
            uint256 diff = currentMaxCap - terms.maxCapacity;
            if (diff > maxDeposit(address(0), address(0))) revert CapacityTooLow();
        }
        if (terms.interestInterval == 0) revert InvalidIntervalLength();
        if (terms.withdrawalPeriod >= terms.interestInterval) revert InvalidWithdrawalPeriod();

        _loan.minDeposit = terms.minDeposit;
        _loan.minRedeem = terms.minRedeem;
        _loan.maxCapacity = terms.maxCapacity;

        _loan.interestRate = terms.interestRate;
        _loan.interestInterval = terms.interestInterval;
        _loan.lateInterestPenalty = terms.lateInterestPenalty;

        _loan.withdrawalPeriod = terms.withdrawalPeriod;
        _loan.lateInterestGracePeriod = terms.lateInterestGracePeriod;

        _loan.termsUpdateTime = block.timestamp;

        _updateInterestParams();

        emit TermsAccepted();
    }

    /// @inheritdoc IAccountableOpenTerm
    function rejectTerms() external onlyBorrower whenNotPaused {
        if (loanState == LoanState.TermsSet) {
            delete _loan;

            loanState = LoanState.Initialized;

            emit TermsRejected();
            return;
        }

        delete _pendingTerms;

        emit TermsRejected();
    }

    /// @inheritdoc IAccountableStrategy
    function setReserveThreshold(uint256 threshold)
        external
        override(AccountableStrategy, IAccountableStrategy)
        onlyManager
    {
        if (threshold > BASIS_POINTS) revert ThresholdTooHigh();
        _loan.reserveThreshold = threshold;

        _updateDelinquentStatus();

        emit ReserveThresholdSet(threshold);
    }

    /// @inheritdoc IAccountableOpenTerm
    function setProposer(address proposer, bool approved) external onlyManager {
        _proposers[proposer] = approved;
    }

    /// @inheritdoc IAccountableOpenTerm
    function proposeInterestRate(uint256 interestRate) external {
        if (msg.sender != borrower && !_proposers[msg.sender]) revert Unauthorized();

        pendingInterestRate = interestRate;

        emit InterestRateProposed(interestRate);
    }

    /// @inheritdoc IAccountableOpenTerm
    function approveInterestRateChange() external onlyManager {
        uint256 pendingRate_ = pendingInterestRate;

        _accrueInterest();

        _loan.interestRate = pendingRate_;
        delete pendingInterestRate;

        _updateInterestParams();

        emit InterestRateApproved(pendingRate_);
    }

    // ========================================================================== //
    //                          Loan Lifecycle Functions                          //
    // ========================================================================== //

    /// @inheritdoc IAccountableLoan
    /// @dev This should be callable when paused
    ///      It is safer to pause and then default to first prevent other operations
    function defaultLoan() external onlySafetyModuleOrManager {
        _requireLoanOngoing();

        _defaultValidAt = block.timestamp + 1 days;

        emit LoanDefaultInitiated();
    }

    /// @inheritdoc IAccountableLoan
    /// @dev This should be callable when paused
    ///      Default coverage should be possible at all times if loan is in default
    function coverDefault(uint256 assets) external onlySafetyModuleOrManager {
        _requireLoanInDefault();

        loanState = LoanState.InDefaultClaims;

        IAccountableVault(vault).lockAssets(assets, msg.sender);

        _updateDelinquentStatus();

        emit DefaultCovered(safetyModule, msg.sender, assets);
    }

    /// @inheritdoc IAccountableLoan
    function borrow(uint256 assets) external onlyBorrower whenNotPaused {
        _requireLoanOngoing();

        _accrueInterest();

        uint256 borrowable = _borrowable(msg.sender);
        uint256 maxBorrowable = Math.min(borrowable, assets);

        if (maxBorrowable == 0) revert InsufficientAmount();

        /// In the open term loan, outstanding principal is tracked in debt share units
        _loan.outstandingPrincipal += maxBorrowable.mulDiv(PRECISION, _scaleFactor, Math.Rounding.Ceil);

        IAccountableVault(vault).releaseAssets(maxBorrowable, msg.sender);

        _updateDelinquentStatus();

        emit Borrowed(msg.sender, maxBorrowable);
    }

    /// @inheritdoc IAccountableLoan
    function repay(uint256 assets) external onlyBorrower whenNotPaused {
        _requireLoanOngoing();

        if (assets == 0) revert InsufficientAmount();

        _accrueInterest();

        address asset_ = asset;
        address vault_ = vault;
        uint256 scaleFactor_ = _scaleFactor;
        uint256 scaleFactorNet_ = _scaleFactorNet;

        uint256 principalShares = _loan.outstandingPrincipal;
        uint256 principalAssets = principalShares.mulDiv(scaleFactor_, PRECISION, Math.Rounding.Ceil);

        IFeeManager fm = IFeeManager(feeManager);
        uint256 establishmentFee = _prorataFee(principalAssets, fm.establishmentFee(address(this)));
        if (establishmentFee > assets) revert InsufficientAmount();

        uint256 repaymentPrincipal = Math.min(assets - establishmentFee, principalAssets);
        IERC20(asset_).safeTransferFrom(msg.sender, address(this), repaymentPrincipal + establishmentFee);

        uint256 maxShares = repaymentPrincipal.mulDiv(PRECISION, scaleFactor_);
        uint256 performanceFee = maxShares.mulDiv(scaleFactor_ - scaleFactorNet_, PRECISION);

        _lastPaidTime = block.timestamp;
        fm.collect(asset_, performanceFee, establishmentFee);

        IAccountableVault(vault_).lockAssets(repaymentPrincipal - performanceFee, address(this));
        _processAvailableWithdrawals();

        _loan.outstandingPrincipal -= repaymentPrincipal.mulDiv(PRECISION, scaleFactor_, Math.Rounding.Floor);

        if (_loan.outstandingPrincipal == 0) {
            loanState = LoanState.Repaid;
            _updateDelinquentStatus();
        } else {
            _updateDelinquentStatus();
        }

        emit LoanRepaid(repaymentPrincipal + establishmentFee);
    }

    /// @inheritdoc IAccountableLoan
    function prepay() external pure {
        revert NotSupportedByStrategy();
    }

    /// @inheritdoc IAccountableLoan
    function pay(uint256) external pure {
        revert NotSupportedByStrategy();
    }

    // ========================================================================== //
    //                          Hook Overrides                                    //
    // ========================================================================== //

    /// @dev Overriden deposit hook with extra validation logic and balances update
    function onDeposit(address share, uint256 assets, address, address)
        public
        override(AccountableStrategy, IStrategyVaultHooks)
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        _requireCanDeposit();
        _requireMinDepositAmount(assets);

        _accrueInterest();

        _requireBelowMaxCapacity(assets);

        price = _sharePrice(share);

        _updateDelinquentStatus();
    }

    /// @dev Overriden mint hook with extra validation logic and balances update
    function onMint(address share, uint256 shares, address, address)
        public
        override(AccountableStrategy, IStrategyVaultHooks)
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        _requireCanDeposit();

        _accrueInterest();

        price = _sharePrice(share);
        uint256 assets = shares.mulDiv(price, PRECISION, Math.Rounding.Ceil);

        _requireMinDepositAmount(assets);
        _requireBelowMaxCapacity(assets);

        _updateDelinquentStatus();
    }

    /// @dev Overriden onRequestRedeem hook for allocating a redemption request
    function onRequestRedeem(address share, uint256 shares, address, address)
        public
        override(AccountableStrategy, IStrategyVaultHooks)
        onlyVault
        whenNotPaused
        returns (bool canFulfill, uint256 price)
    {
        if (shares < _loan.minRedeem) revert InsufficientShares();

        _accrueInterest();

        price = _sharePrice(share);

        uint256 assets = shares.mulDiv(price, PRECISION);

        if (_isInstantRedeem()) {
            canFulfill = true;
        } else {
            uint256 availableLiquidity = _getAvailableLiquidity();
            if (availableLiquidity >= assets) {
                canFulfill = true;
            } else if (_loan.withdrawalPeriod != 0) {
                _createOrAddWithdrawalBatch(shares);
                canFulfill = false;
            }
        }

        _updateDelinquentStatus();
    }

    function onFeeStructureChange() public override(AccountableStrategy, IFeeManagerHooks) {
        super.onFeeStructureChange();

        if (_loan.startTime != 0) {
            _accrueInterest();
            _updateInterestParams();
        }
    }

    /// @dev Overriden maxDeposit hook
    function maxDeposit(address, address)
        public
        view
        override(AccountableStrategy, IStrategyVaultHooks)
        returns (uint256 maxAssets)
    {
        uint256 maxCapacity_ = _loan.maxCapacity;
        uint256 totalAssets = IAccountableVault(vault).totalAssets();
        uint256 principalAssets = _loan.outstandingPrincipal.mulDiv(_scaleFactor, PRECISION, Math.Rounding.Ceil);
        uint256 capMinusDebt = maxCapacity_ > principalAssets ? maxCapacity_ - principalAssets : 0;
        maxAssets = totalAssets >= capMinusDebt ? 0 : capMinusDebt - totalAssets;
    }

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

    /// @dev Updates the late status of the loan
    function updateLateStatus() external {
        _requireLoanOngoing();

        _accrueInterest();
        _updateDelinquentStatus();
    }

    /// @inheritdoc IAccountableOpenTerm
    function accrueInterest() external returns (uint256 newScaleFactor) {
        _accrueInterest();

        newScaleFactor = _scaleFactor;
    }

    /// @inheritdoc IAccountableOpenTerm
    function processAvailableWithdrawals() external whenNotPaused returns (uint256 usedAssets) {
        usedAssets = _processAvailableWithdrawals();
    }

    /// @inheritdoc IAccountableOpenTerm
    function scaleFactor() external view returns (uint256) {
        return _scaleFactor;
    }

    /// @inheritdoc IAccountableOpenTerm
    function lastPaidTime() external view returns (uint256) {
        return _lastPaidTime;
    }

    /// @inheritdoc IAccountableLoan
    function timeDelinquent() external view returns (uint256) {
        uint256 delinquencyStartTime_ = delinquencyStartTime;
        return delinquencyStartTime_ > 0 ? block.timestamp - delinquencyStartTime_ : 0;
    }

    /// @inheritdoc IAccountableOpenTerm
    function pendingTerms() external view returns (LoanTerms memory) {
        return _pendingTerms;
    }

    /// @inheritdoc IAccountableOpenTerm
    function withdrawalBatches(uint256 id) external view returns (WithdrawalBatch memory) {
        return _withdrawalBatches[id];
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
        return interfaceId == type(IAccountableLoan).interfaceId
            || interfaceId == type(IAccountableStrategy).interfaceId
            || interfaceId == type(IAccountableOpenTerm).interfaceId || interfaceId == type(IERC165).interfaceId;
    }

    // ========================================================================== //
    //                          Internal Helper Functions                         //
    // ========================================================================== //

    /// @notice Calculate establishment fee prorated by time elapsed
    function _prorataFee(uint256 principal, uint256 fee) internal view returns (uint256) {
        if (fee == 0) return 0;

        uint256 timeDelta = block.timestamp - _lastPaidTime;
        if (timeDelta == 0) return 0;

        return Math.mulDiv(principal * fee, timeDelta, DAYS_365_SECONDS * BASIS_POINTS, Math.Rounding.Ceil);
    }

    /// @dev Returns whether the loan is delinquent based on reserves available
    function _isDelinquent() public view returns (bool) {
        address vault_ = vault;
        uint256 totalAssets = IAccountableVault(vault_).totalAssets();
        uint256 requiredLiquidity = _calculateRequiredLiquidity(vault_);

        return totalAssets < requiredLiquidity;
    }

    /// @notice Accrues interest based time delta since last accrual
    function _accrueInterest() internal {
        uint256 accruedAt_ = _accruedAt;
        if (block.timestamp < accruedAt_) return;

        uint256 timeDelta = block.timestamp - accruedAt_;
        if (timeDelta == 0) return;

        uint256 delinquencyFee = _penaltyFee(timeDelta);

        uint256 baseInterest = _linearInterest(_loan.interestRate, timeDelta);
        uint256 baseNetInterest = _linearInterest(_netInterestRate, timeDelta);

        _scaleFactor += baseInterest + delinquencyFee;
        _scaleFactorNet += baseNetInterest + delinquencyFee;

        _accruedAt = block.timestamp;
    }

    /// @notice Calculates the max borrowable amount based on the current liquidity
    function _borrowable(address) private view returns (uint256) {
        address vault_ = vault;
        uint256 requiredReserves = _calculateRequiredLiquidity(vault_);
        uint256 totalAssets = IAccountableVault(vault_).totalAssets();

        return totalAssets > requiredReserves ? totalAssets - requiredReserves : 0;
    }

    /// @notice Automatically process pending withdrawals when liquidity becomes available
    function _processAvailableWithdrawals() internal returns (uint256 usedAssets) {
        address vault_ = vault;
        uint256 liquidity = _getAvailableLiquidityForProcessing(vault_);
        if (liquidity == 0) return 0;

        IAccountableWithdrawalQueue q = IAccountableWithdrawalQueue(vault_);

        if (_loan.withdrawalPeriod == 0) {
            (uint256 maxShares,) = q.previewRequiredShares(liquidity);
            if (maxShares == 0) return 0;

            usedAssets = q.processUpToShares(maxShares);
            return usedAssets;
        }

        while (pendingBatch <= currentBatch && liquidity > 0) {
            WithdrawalBatch memory batch = _withdrawalBatches[pendingBatch];
            if (block.timestamp < batch.expiry) break;

            (uint256 maxShares,) = q.previewRequiredShares(liquidity);

            if (maxShares == 0) {
                if (batch.totalShares > 0) {
                    _withdrawalBatches[pendingBatch++].totalShares = 0;
                    continue;
                }
                break;
            }

            uint256 sharesToProcess = maxShares > batch.totalShares ? batch.totalShares : maxShares;

            uint256 processedAssets = q.processUpToShares(sharesToProcess);
            liquidity -= processedAssets;
            usedAssets += processedAssets;

            if (sharesToProcess >= batch.totalShares) {
                _withdrawalBatches[pendingBatch++].totalShares = 0;
            } else {
                _withdrawalBatches[pendingBatch].totalShares -= sharesToProcess;
                break;
            }
        }
    }

    /// @dev Calculates the delinquency fee for the given time delta
    function _penaltyFee(uint256 timeDelta) internal view returns (uint256) {
        if (!penaltiesEnabled) return 0;

        uint256 delinquencyStart_ = delinquencyStartTime;
        uint256 lateInterestPenalty_ = _loan.lateInterestPenalty;

        if (delinquencyStart_ == 0 || lateInterestPenalty_ == 0) return 0;

        uint256 gracePeriod = _loan.lateInterestGracePeriod;
        uint256 delinquencyTime = block.timestamp - delinquencyStart_;
        if (delinquencyTime <= gracePeriod) return 0;

        uint256 penaltyTime = Math.min(delinquencyTime - gracePeriod, timeDelta);
        return lateInterestPenalty_.mulDiv(penaltyTime * PRECISION, DAYS_1_SECONDS * BASIS_POINTS);
    }

    /// @notice Calculate linear interest for the given time delta and annualized rate
    function _linearInterest(uint256 interestRate, uint256 timeDelta) internal pure returns (uint256) {
        return interestRate.mulDiv(timeDelta * PRECISION, DAYS_365_SECONDS * BASIS_POINTS);
    }

    /// @dev Updates the late status of the loan payments
    function _updateDelinquentStatus() internal {
        bool wasDelinquent = delinquencyStartTime > 0;
        bool isCurrentlyDelinquent = _isDelinquent();

        if (isCurrentlyDelinquent && !wasDelinquent) {
            delinquencyStartTime = block.timestamp;

            emit DelinquencyStatusChanged(true, block.timestamp);
        } else if (!isCurrentlyDelinquent && wasDelinquent) {
            delinquencyStartTime = 0;

            emit DelinquencyStatusChanged(false, block.timestamp);
        }
    }

    /// @dev Creates or adds a withdrawal batch
    function _createOrAddWithdrawalBatch(uint256 shares) internal {
        uint256 startTime = _loan.startTime;
        uint256 period = _loan.withdrawalPeriod;
        uint256 interval = _loan.interestInterval;

        if (period == 0) return;

        // Bounds: [batchStart, batchStart + period]
        uint256 currInterval = ((block.timestamp - startTime) / interval);
        uint256 currBatchStartTime = startTime + (currInterval * interval);

        WithdrawalBatch memory batch = _withdrawalBatches[currentBatch];

        // Can add to existing batch
        if (block.timestamp <= batch.expiry) {
            _withdrawalBatches[currentBatch].totalShares += shares;
            return;
        }
        // No active batch - create new batch
        if (block.timestamp <= currBatchStartTime + period) {
            if (batch.expiry == 0) {
                _withdrawalBatches[currentBatch] =
                    WithdrawalBatch(currBatchStartTime + period, currBatchStartTime, shares);
            } else {
                _withdrawalBatches[++currentBatch] =
                    WithdrawalBatch(currBatchStartTime + period, currBatchStartTime, shares);
            }
            return;
        }

        // Otherwise advance and create the future batch
        uint256 targetStartTime = currBatchStartTime + interval;
        _withdrawalBatches[++currentBatch] = WithdrawalBatch(targetStartTime + period, targetStartTime, shares);
    }

    /// @dev Returns the required reserves accounting for the queued/processed withdrawals
    function _calculateRequiredLiquidity(address vault_) internal view returns (uint256) {
        uint256 totalShares = IAccountableVault(vault_).totalSupply();
        uint256 queuedShares = IAccountableWithdrawalQueue(vault_).totalQueuedShares();

        uint256 scaleFactor_ = _scaleFactor;

        uint256 debtShares = totalShares - queuedShares;
        uint256 debtValue = debtShares.mulDiv(scaleFactor_, PRECISION);

        uint256 baseReserves = debtValue.mulDiv(_loan.reserveThreshold, BASIS_POINTS);

        uint256 queuedWithdrawalValue = queuedShares.mulDiv(scaleFactor_, PRECISION);
        uint256 processedWithdrawals = IAccountableWithdrawalQueue(vault_).reservedLiquidity();

        return baseReserves + queuedWithdrawalValue + processedWithdrawals;
    }

    /// @dev Returns the available liquidity after accounting for the required reserves
    function _getAvailableLiquidity() internal view returns (uint256) {
        address vault_ = vault;
        uint256 totalAssets = IAccountableVault(vault_).totalAssets();
        uint256 queuedShares = IAccountableWithdrawalQueue(vault_).totalQueuedShares();
        uint256 processedWithdrawals = IAccountableWithdrawalQueue(vault_).reservedLiquidity();
        uint256 requiredReserves = queuedShares.mulDiv(_scaleFactor, PRECISION) + processedWithdrawals;

        return totalAssets > requiredReserves ? totalAssets - requiredReserves : 0;
    }

    /// @dev Returns the available liquidity for processing
    function _getAvailableLiquidityForProcessing(address vault_) internal view returns (uint256) {
        uint256 totalAssets = IAccountableVault(vault_).totalAssets();
        uint256 reservedLiquidity = IAccountableWithdrawalQueue(vault_).reservedLiquidity();

        return totalAssets > reservedLiquidity ? totalAssets - reservedLiquidity : 0;
    }

    /// @dev Updates the interest parameters based on the current fee structure
    function _updateInterestParams() internal {
        uint256 feeFactor = BASIS_POINTS - IFeeManager(feeManager).performanceFee(address(this));
        _netInterestRate = _loan.interestRate.mulDiv(feeFactor, BASIS_POINTS);
    }

    /// @dev Returns the share price at current moment, using the _scaleFactorNet for virtual interest accrual
    ///      Share price required to use decimals precision stored as PRECION in the vault
    /// @return The share price
    function _sharePrice(address) internal view override returns (uint256) {
        if (_isInDepositPeriod()) {
            return PRECISION;
        }

        if (loanState == LoanState.Repaid || loanState == LoanState.InDefaultClaims) {
            return IAccountableVault(vault).assetShareRatio();
        }

        return _scaleFactorNet;
    }

    /// @dev Returns the total amount of reserved accrued assets
    function _accruedAssets(address) internal pure override returns (uint256) {
        return 0;
    }

    /// @dev Checks if the current timestamp is within the deposit period
    function _isInDepositPeriod() internal view returns (bool) {
        return block.timestamp <= _loan.startTime + _loan.depositPeriod;
    }

    /// @dev Checks whether the loan accepts instant redeem/withdrawal
    function _isInstantRedeem() internal view returns (bool) {
        return loanState == LoanState.Repaid || loanState == LoanState.InDefaultClaims;
    }

    /// @dev Checks that deposits are allowed
    function _requireCanDeposit() internal view {
        if (loanState != LoanState.OngoingDynamic) revert DepositNotAllowed();
    }

    /// @dev Checks that the deposit amount is below the max capacity
    function _requireBelowMaxCapacity(uint256 assets) internal view {
        if (assets > maxDeposit(address(0), address(0))) revert ExceedsMaxDeposit();
    }

    /// @dev Hook for UUPS upgradeable contract
    function _authorizeUpgrade(address newImplementation) internal override onlyManagerOrSecurityAdmin {}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /// @notice Returns the vault address associated with a strategy
    /// @param strategy The strategy address
    /// @return The associated vault address
    function getStrategyVault(address strategy) external view returns (address);

    /// @notice Returns a paginated list of strategy addresses
    /// @param start The start index
    /// @param end The end index
    /// @return Array of strategy addresses within the specified range
    function getStrategiesPaginated(uint256 start, uint256 end) external view returns (address[] memory);

    /// @notice Returns the total number of strategies created
    /// @return The total count of strategies
    function getStrategiesCount() external view returns (uint256);
}

/// @notice Parameters for creating a fixed term loan with an associated vault
struct FixedTermFactoryParams {
    /// @notice The asset token address for the strategy
    address asset;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice Whether shares are transferable
    bool sharesTransferable;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface IFixedTermFactory is IStrategyFactoryBase {
    /// @notice Emitted when a new fixed term loan is created
    /// @param proxy The address of the created loan proxy contract
    /// @param vault The address of the associated vault contract
    /// @param manager The investment manager address
    event FixedTermCreated(address indexed proxy, address indexed vault, address indexed manager);

    /// @notice Creates a new fixed term loan with an associated vault
    /// @param params The parameters for creating a fixed term loan with an associated vault
    function createFixedTermLoan(FixedTermFactoryParams memory params) external returns (address, address);
}

/// @notice Parameters for creating a fixed term loan with an associated vault and rewards distributor
struct FixedTermMMFactoryParams {
    /// @notice The asset token address for the loan
    address asset;
    /// @notice The native token address for the loan
    address native;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The price oracle address for the loan
    address priceOracle;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice The rewards type for the loan
    RewardsType rewardsType;
    /// @notice The timelock for root acceptence in merkle distributor
    uint256 rootTimelock;
    /// @notice Whether shares are transferable
    bool sharesTransferable;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface IFixedTermMMFactory is IStrategyFactoryBase {
    /// @notice Emitted when a new fixed term loan is created
    /// @param proxy The address of the created loan proxy contract
    /// @param vault The address of the associated vault contract
    /// @param rewards The address of the associated rewards distributor contract
    /// @param manager The investment manager address
    /// @param admin The admin address
    event FixedTermMMCreated(
        address indexed proxy, address indexed vault, address rewards, address indexed manager, address admin
    );

    /// @notice Creates a new fixed term loan with an associated vault
    /// @param params The parameters for creating a fixed term loan with an associated vault and rewards distributor
    function createFixedTermLoanMM(FixedTermMMFactoryParams memory params) external returns (address, address);
}

/// @notice Parameters for creating an open term loan with an associated vault
struct OpenTermFactoryParams {
    /// @notice The asset token address for the strategy
    address asset;
    /// @notice The investment manager address
    address investmentManager;
    /// @notice The permission level for the loan
    PermissionLevel permissionLevel;
    /// @notice Whether shares are transferable
    bool sharesTransferable;
    /// @notice The symbol for the vault's shares token
    string symbol;
    /// @notice The name for the vault's shares token
    string name;
    /// @notice The salt used for deterministic address generation
    bytes32 salt;
}

interface IOpenTermFactory is IStrategyFactoryBase {
    /// @notice Emitted when a new open term loan is created
    /// @param proxy The address of the created loan proxy contract
    /// @param vault The address of the associated vault contract
    /// @param manager The investment manager address
    event OpenTermCreated(address indexed proxy, address indexed vault, address indexed manager);

    /// @notice Creates a new open term loan with an associated vault
    /// @param params The parameters for creating an open term loan with an associated vault
    function createOpenTermLoan(OpenTermFactoryParams memory params) external returns (address, address);
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /// @notice Collects establishment fees
    /// @param asset The address of the asset
    /// @param amount The amount of establishment fees
    function collectEstablishmentFee(address asset, uint256 amount) external;

    /// @notice Collects performance fees
    /// @param asset The address of the asset
    /// @param amount The amount of performance fees
    function collectPerformanceFee(address asset, uint256 amount) external;

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

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

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

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

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

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

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

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

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

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

    /// @notice Returns the manager split
    /// @param strategy The address of the strategy
    /// @return The manager split
    function managerSplit(address strategy) external view returns (uint256);

    /// @notice Returns the protocol split
    /// @param strategy The address of the strategy
    /// @return The protocol split
    function protocolSplit(address strategy) external view returns (uint256);

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

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

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

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

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

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

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

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

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

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

File 18 of 52 : AccountableStrategy.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

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

import {RewardsType} from "../interfaces/IRewards.sol";
import {IAccess, PermissionLevel} from "../interfaces/IAccess.sol";
import {IRewardsFactory} from "../interfaces/IRewardsFactory.sol";
import {IAsyncVaultFactory} from "../interfaces/IAsyncVaultFactory.sol";
import {IGlobalRegistry} from "../interfaces/IGlobalRegistry.sol";
import {IAccountableVault} from "../interfaces/IAccountableAsyncVault.sol";
import {
    IAccountableStrategy,
    IStrategyVaultHooks,
    IFeeManagerHooks,
    LoanState,
    LoanTerms,
    DVNProof,
    Loan
} from "../interfaces/IAccountableStrategy.sol";

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {StrategyStorage} from "./storage/StrategyStorage.sol";

/// @title AccountableStrategy
/// @notice Abstract contract that implements the IAccountableStrategy interface
/// @dev It holds the state of an accountable strategy and implements the IAccountableStrategy interface
/// @custom:security-contact [email protected]
abstract contract AccountableStrategy is PausableUpgradeable, StrategyStorage {
    // ========================================================================== //
    //                              Constants                                     //
    // ========================================================================== //

    /// @dev precision for calculations
    uint256 public constant PRECISION = 1e36;
    /// @dev 1e6 basis points representing 100%
    uint256 public constant BASIS_POINTS = 1e6;
    /// @dev seconds in a day
    uint256 public constant DAYS_1_SECONDS = 1 days;
    /// @dev seconds in a year considered 365 days
    uint256 public constant DAYS_365_SECONDS = 365 days;

    // ========================================================================== //
    //                              Modifiers                                     //
    // ========================================================================== //

    /// @notice modifier to check if caller is the borrower
    modifier onlyBorrower() {
        if (msg.sender != borrower) revert Unauthorized();
        _;
    }

    /// @notice modifier to check if caller is the investment manager
    modifier onlyManager() {
        if (msg.sender != investmentManager) revert Unauthorized();
        _;
    }

    /// @notice modifier to check if caller is the safety module or the manager
    modifier onlySafetyModuleOrManager() {
        if (safetyModule != address(0)) {
            revert_AtLeastOne(safetyModule, investmentManager);
        } else {
            if (msg.sender != investmentManager) revert Unauthorized();
        }
        _;
    }

    /// @notice modifier to check if caller is the manager or the security admin (if enabled)
    modifier onlyManagerOrSecurityAdmin() {
        if (securityAdminEnabled) {
            revert_AtLeastOne(IGlobalRegistry(globals).securityAdmin(), investmentManager);
        } else {
            if (msg.sender != investmentManager) revert Unauthorized();
        }
        _;
    }

    /// @notice modifier to check if caller is the manager or the operations admin (if enabled)
    modifier onlyManagerOrOperationsAdmin() {
        if (operationsAdminEnabled) {
            revert_AtLeastOne(IGlobalRegistry(globals).operationsAdmin(), investmentManager);
        } else {
            if (msg.sender != investmentManager) revert Unauthorized();
        }
        _;
    }

    /// @notice modifier to check if caller is the proof signer
    modifier onlyProofSigner() {
        if (msg.sender != proofSigner) revert Unauthorized();
        _;
    }

    /// @notice modifier to check if caller is the vault
    modifier onlyVault() {
        if (msg.sender != vault) revert Unauthorized();
        _;
    }

    /// @dev Reverts if the caller is not one of the two addresses
    function revert_AtLeastOne(address a, address b) internal view {
        if (msg.sender != a && msg.sender != b) revert Unauthorized();
    }

    // ========================================================================== //
    //                          Pausable Functions                                //
    // ========================================================================== //

    /// @dev Pauses the contract
    function pause() public onlyManagerOrSecurityAdmin {
        if (msg.sender == IGlobalRegistry(globals).securityAdmin()) {
            _pausedByAdmin = true;
        }
        _pause();
    }

    /// @dev Unpauses the contract and checks whether msg.sender is admin when loan was paused by admin
    function unpause() public onlyManagerOrSecurityAdmin {
        if (_pausedByAdmin && msg.sender != IGlobalRegistry(globals).securityAdmin()) {
            revert Unauthorized();
        }
        _pausedByAdmin = false;
        _unpause();
    }

    // ========================================================================== //
    //                          Configuration Functions                           //
    // ========================================================================== //

    /// @inheritdoc IAccountableStrategy
    function setPendingBorrower(address newBorrower) external virtual onlyManager {
        if (newBorrower == address(0)) revert ZeroAddress();
        pendingBorrower = newBorrower;

        emit PendingBorrowerSet(newBorrower);
    }

    /// @inheritdoc IAccountableStrategy
    function acceptBorrowerRole() external virtual {
        if (msg.sender != pendingBorrower) revert InvalidPendingBorrower();

        address oldBorrower = borrower;
        borrower = msg.sender;
        pendingBorrower = address(0);

        emit BorrowerChanged(oldBorrower, msg.sender);
    }

    /// @inheritdoc IAccountableStrategy
    function setInvestmentManager(address investmentManager_) external virtual onlyManager {
        if (investmentManager_ == address(0)) revert ZeroAddress();
        investmentManager = investmentManager_;

        emit InvestmentManagerSet(investmentManager_);
    }

    /// @inheritdoc IAccountableStrategy
    function setAuthSigner(address authSigner_) external onlyManager {
        IAccess(vault).setSigner(authSigner_);
    }

    /// @inheritdoc IAccountableStrategy
    function setLenders(address[] calldata lenders, bool[] calldata allowed) external onlyManager {
        IAccess(vault).setAllowed(lenders, allowed);
    }

    /// @inheritdoc IAccountableStrategy
    function setProofSigner(address proofSigner_) external virtual onlyManager {
        if (proofSigner_ == address(0)) revert ZeroAddress();
        proofSigner = proofSigner_;

        emit ProofSignerSet(proofSigner_);
    }

    /// @inheritdoc IAccountableStrategy
    function publishDVNProof(DVNProof memory proof) external virtual onlyProofSigner {
        _dvnProof = proof;

        emit DVNProofPublished(proof.root, proof.signature, proof.messageHash);
    }

    /// @inheritdoc IAccountableStrategy
    function acceptDefault() external {
        if (block.timestamp < _defaultValidAt || _defaultValidAt == 0) revert TimelockNotExpired();

        loanState = LoanState.InDefault;

        emit LoanDefaulted(_loan.outstandingPrincipal, IAccountableVault(vault).totalAssets());
    }

    /// @inheritdoc IAccountableStrategy
    function rejectDefault() external onlyManager {
        _defaultValidAt = 0;

        emit LoanDefaultRejected();
    }

    /// @inheritdoc IAccountableStrategy
    function setPenaltiesEnabled(bool enabled) external virtual onlyManager {
        penaltiesEnabled = enabled;

        emit PenaltiesEnabledSet(enabled);
    }

    /// @inheritdoc IAccountableStrategy
    function setSecurityAdminEnabled(bool enabled) external virtual onlyManager {
        securityAdminEnabled = enabled;

        emit SecurityAdminEnabledSet(enabled);
    }

    /// @inheritdoc IAccountableStrategy
    function setOperationsAdminEnabled(bool enabled) external virtual onlyManager {
        operationsAdminEnabled = enabled;

        emit OperationsAdminEnabledSet(enabled);
    }

    /// @inheritdoc IAccountableStrategy
    function setSharesTransferable(bool transferable) external virtual onlyManager {
        IAccountableVault(vault).setSharesTransferable(transferable);
    }

    /// @inheritdoc IAccountableStrategy
    function setReserveThreshold(uint256 threshold) external virtual onlyManager {
        if (threshold > BASIS_POINTS) revert ThresholdTooHigh();
        _loan.reserveThreshold = threshold;

        emit ReserveThresholdSet(threshold);
    }

    /// @inheritdoc IAccountableStrategy
    function setSafetyModule(address safetyModule_) external virtual onlyManager {
        if (safetyModule_ == address(0)) revert ZeroAddress();
        safetyModule = safetyModule_;

        emit SafetyModuleSet(safetyModule_);
    }

    /// @inheritdoc IAccountableStrategy
    function setRewardsDistributor(address rewards_) external virtual onlyManager {
        if (rewards_ == address(0)) revert ZeroAddress();
        rewards = rewards_;

        emit RewardsDistributorSet(rewards_);
    }

    /// @inheritdoc IAccountableStrategy
    function setPriceOracle(address priceOracle_) external virtual onlyManager {
        _requireLoanNotOngoing();

        if (priceOracle_ == address(0)) revert ZeroAddress();
        priceOracle = priceOracle_;

        emit PriceOracleSet(priceOracle_);
    }

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

    /// @inheritdoc IAccountableStrategy
    function loan() external view returns (Loan memory) {
        return _loan;
    }

    /// @inheritdoc IAccountableStrategy
    function dvnProof() external view returns (DVNProof memory) {
        return _dvnProof;
    }

    // ========================================================================== //
    //                          Strategy Vault Hooks                              //
    // ========================================================================== //

    /// @inheritdoc IStrategyVaultHooks
    function onRequestDeposit(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (bool canFulfill, uint256 price)
    {
        return (false, _sharePrice(share));
    }

    /// @inheritdoc IStrategyVaultHooks
    function onRequestRedeem(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (bool canFulfill, uint256 price)
    {
        return (false, _sharePrice(share));
    }

    /// @inheritdoc IStrategyVaultHooks
    function onCancelDepositRequest(address, address) public virtual onlyVault whenNotPaused returns (bool canCancel) {
        return true;
    }

    /// @inheritdoc IStrategyVaultHooks
    function onCancelRedeemRequest(address, address) public virtual onlyVault whenNotPaused returns (bool canCancel) {
        return true;
    }

    /// @inheritdoc IStrategyVaultHooks
    function onDeposit(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        price = _sharePrice(share);
    }

    /// @inheritdoc IStrategyVaultHooks
    function onMint(address share, uint256, address, address)
        public
        virtual
        onlyVault
        whenNotPaused
        returns (uint256 price)
    {
        price = _sharePrice(share);
    }

    /// @inheritdoc IStrategyVaultHooks
    function onRedeem(address, uint256, address, address) public virtual onlyVault whenNotPaused {}

    /// @inheritdoc IStrategyVaultHooks
    function onWithdraw(address, uint256, address, address) public virtual onlyVault whenNotPaused {}

    /// @inheritdoc IStrategyVaultHooks
    function onTransfer(address, address, address, uint256) public virtual onlyVault whenNotPaused {}

    /// @inheritdoc IStrategyVaultHooks
    function authOperator(address operator) external virtual {
        if (msg.sender != vault) revert Unauthorized();
        if (operator != investmentManager && operator != borrower) revert Unauthorized();
    }

    /// @inheritdoc IStrategyVaultHooks
    function sharePrice(address share) external view virtual returns (uint256 price) {
        return _sharePrice(share);
    }

    /// @dev Computes the share price. To be overridden by the derived strategy
    function _sharePrice(address share) internal view virtual returns (uint256 price);

    /// @inheritdoc IStrategyVaultHooks
    function accruedAssets(address share) external view virtual returns (uint256 assets) {
        assets = _accruedAssets(share);
    }

    /// @dev Computes the accrued assets. To be overridden by the derived strategy
    function _accruedAssets(address share) internal view virtual returns (uint256 assets);

    /// @inheritdoc IStrategyVaultHooks
    function maxDeposit(address, address) public view virtual returns (uint256 maxAssets) {
        return type(uint256).max;
    }

    /// @inheritdoc IStrategyVaultHooks
    function maxRedeem(address, address) public view virtual returns (uint256 maxShares) {
        return type(uint256).max;
    }

    // ========================================================================== //
    //                          Fee Manager Hooks                                 //
    // ========================================================================== //

    /// @inheritdoc IFeeManagerHooks
    function onFeeStructureChange() public virtual whenNotPaused {
        if (msg.sender != feeManager) revert Unauthorized();
    }

    /// @inheritdoc IAccountableStrategy
    function version() external view virtual returns (uint256) {
        return 1;
    }

    // ========================================================================== //
    //                          Internal Helper Functions                         //
    // ========================================================================== //

    /// @dev Calls the factory to create a new async redeem vault
    function _makeVault(
        IERC20 asset_,
        bool sharesTransferable_,
        PermissionLevel permissionLevel_,
        string memory name_,
        string memory symbol_
    ) internal {
        vault = IAsyncVaultFactory(IGlobalRegistry(globals).vaultFactory()).createAsyncRedeemVault(
            asset_, address(this), sharesTransferable_, permissionLevel_, name_, symbol_, PRECISION
        );
    }

    /// @dev Sets the loan terms and initializes the loan state
    function _setTerms(LoanTerms memory terms) internal {
        _loan = Loan({
            lateInterestGracePeriod: terms.lateInterestGracePeriod == 0 ? 2 days : terms.lateInterestGracePeriod,
            acceptGracePeriod: terms.acceptGracePeriod == 0 ? 2 days : terms.acceptGracePeriod,
            depositPeriod: terms.depositPeriod,
            withdrawalPeriod: terms.withdrawalPeriod,
            lateInterestPenalty: terms.lateInterestPenalty,
            interestInterval: terms.interestInterval,
            interestRate: terms.interestRate,
            minDeposit: terms.minDeposit,
            minRedeem: terms.minRedeem,
            maxCapacity: terms.maxCapacity,
            minCapacity: terms.minCapacity,
            duration: terms.duration,
            reserveThreshold: 0,
            outstandingPrincipal: 0,
            outstandingInterest: 0,
            claimableInterest: 0,
            drawableFunds: 0,
            termsSetTime: 0,
            termsUpdateTime: 0,
            startTime: 0
        });
    }

    /// @dev Checks that the loan terms have been set
    function _requireLoanTermsSet() internal view {
        if (loanState != LoanState.TermsSet) revert LoanTermsNotSet();
    }

    /// @dev Checks that the loan terms have not been set
    function _requireLoanTermsNotSet() internal view {
        if (loanState != LoanState.Initialized) revert LoanTermsAlreadySet();
    }

    /// @dev Checks that the loan is not ongoing
    function _requireLoanNotOngoing() internal view {
        if (loanState == LoanState.OngoingLocked || loanState == LoanState.OngoingDynamic) revert LoanOngoing();
    }

    /// @dev Checks that the loan is ongoing
    function _requireLoanOngoing() internal view {
        if (loanState != LoanState.OngoingLocked && loanState != LoanState.OngoingDynamic) revert LoanNotOngoing();
    }

    /// @dev Checks that the loan is in default
    function _requireLoanInDefault() internal view {
        if (loanState != LoanState.InDefault) revert LoanNotInDefault();
    }

    /// @dev Checks that the deposit amount is greater than the minimum deposit amount
    function _requireMinDepositAmount(uint256 amount) internal view {
        if (amount < _loan.minDeposit) revert InsufficientAmount();
    }
}

File 19 of 52 : OpenTermStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import {LoanTerms} from "../../interfaces/IAccountableStrategy.sol";
import {IAccountableOpenTerm, WithdrawalBatch} from "../../interfaces/IAccountableOpenTerm.sol";

/// @title OpenTermStorage
/// @notice Storage layout for AccountableOpenTerm with upgrade safety gap
/// @dev Centralizes storage to avoid collisions and simplify upgradeable contract development
///      All storage variables MUST be declared here
abstract contract OpenTermStorage is IAccountableOpenTerm {
    /// @notice Scale factor of all interest accrual
    uint256 internal _scaleFactor;

    /// @notice Scale factor of interest accrual excluding performance fee
    uint256 internal _scaleFactorNet;

    /// @notice Interest rate excluding performance fee rate
    uint256 internal _netInterestRate;

    /// @notice Last interest accrual timestamp
    uint256 internal _accruedAt;

    /// @notice Last interest payment timestamp
    uint256 internal _lastPaidTime;

    /// @dev Pending terms update
    LoanTerms internal _pendingTerms;

    /// @dev Approved interest rate proposers
    mapping(address proposer => bool approved) internal _proposers;

    /// @dev Withdrawal batches
    mapping(uint256 id => WithdrawalBatch batch) internal _withdrawalBatches;

    /// @notice address of base token
    address public asset;

    /// @dev Current withdrawal batch
    uint256 public currentBatch;

    /// @dev Pending withdrawal batch
    uint256 public pendingBatch;

    /// @dev Time when delinquency started
    uint256 public delinquencyStartTime;

    /// @dev Pending interest rate
    uint256 public pendingInterestRate;

    /// @dev Gap for future storage variables in AccountableOpenTerm
    /// @dev Reserves 50 slots for future additions to AccountableOpenTerm
    uint256[50] private __gap;
}

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

interface IRewardsDistributorStrategy is IRewardsDistributorBase {}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// @title IRewardsFactory
/// @notice Interface for creating rewards distributors
interface IRewardsFactory {
    /// @notice Emitted when a new rewards distributor is created
    /// @param rewards The address of the created rewards distributor
    event RewardsDistributorCreated(address indexed rewards);

    /// @notice Creates a new rewards distributor
    /// @param owner The owner of the rewards distributor
    /// @param strategy The strategy that will use the rewards distributor
    /// @param timelock The timelock for root acceptence in merkle distributor
    /// @param rewardsType The type of rewards distributor to create
    /// @return The address of the created rewards distributor
    function createRewardsDistributor(address owner, address strategy, uint256 timelock, RewardsType rewardsType)
        external
        returns (address);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 38 of 52 : StrategyStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

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

/// @title StrategyStorage
/// @notice Storage layout for AccountableStrategy with upgrade safety gap
/// @dev Centralizes storage to avoid collisions and simplify upgradeable contract development
///      All storage variables MUST be declared here
abstract contract StrategyStorage is IAccountableStrategy {
    /// @dev whether paused by admin
    bool internal _pausedByAdmin;

    /// @dev loan terms and state
    Loan internal _loan;

    /// @dev DVN proof
    DVNProof internal _dvnProof;

    /// @dev timestamp when the default is valid
    uint256 internal _defaultValidAt;

    /// @dev whether penalties are enabled
    bool public penaltiesEnabled;

    /// @dev whether security admin is enabled
    bool public securityAdminEnabled;

    /// @dev whether operations admin is enabled
    bool public operationsAdminEnabled;

    /// @notice loan borrower
    address public borrower;

    /// @notice pending loan borrower
    address public pendingBorrower;

    /// @dev loan state
    LoanState public loanState;

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

    /// @notice address of fee manager
    address public feeManager;

    /// @notice address of safety module
    address public safetyModule;

    /// @notice address of proof signer
    /// @dev This is the public key of the DVN proof signer
    ///      It can be used to verify the published DVN proofs
    address public proofSigner;

    /// @notice address of vault
    address public vault;

    /// @notice address of investment manager
    address public investmentManager;

    /// @notice address of rewards distributor
    address public rewards;

    /// @notice address of price oracle
    address public priceOracle;

    /// @dev Gap for future storage variables in base contract
    /// @dev Reserves 50 slots for future additions to AccountableStrategy
    uint256[50] private __gap;
}

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

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

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

// 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
        }
    }
}

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

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

File 47 of 52 : 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
        );
}

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

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

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

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

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

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

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

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

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

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

Settings
{
  "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/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"stateMutability":"payable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"stateMutability":"payable","type":"fallback"}]

0x608060405261029d8038038061001481610168565b92833981016040828203126101645781516001600160a01b03811692909190838303610164576020810151906001600160401b03821161016457019281601f8501121561016457835161006e610069826101a1565b610168565b9481865260208601936020838301011161016457815f926020809301865e86010152823b15610152577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a282511561013a575f8091610122945190845af43d15610132573d91610113610069846101a1565b9283523d5f602085013e6101bc565b505b6040516082908161021b8239f35b6060916101bc565b50505034156101245763b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b5f80fd5b6040519190601f01601f191682016001600160401b0381118382101761018d57604052565b634e487b7160e01b5f52604160045260245ffd5b6001600160401b03811161018d57601f01601f191660200190565b906101e057508051156101d157805190602001fd5b630a12f52160e11b5f5260045ffd5b81511580610211575b6101f1575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156101e956fe60806040527f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545f9081906001600160a01b0316368280378136915af43d5f803e156048573d5ff35b3d5ffdfea26469706673582212205930e04847f25c502725e018fc0b653d314783132e602028ab11856fcfa5b9fb64736f6c634300081b003300000000000000000000000059b0b84371bb3261fad538c512efffc414cc1725000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000001a4883b755a0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000754704bc059f8c67012fed69bc8a327a5aafb603000000000000000000000000f786154e56e5c88ce984800dea71b48ea4ffabfe0000000000000000000000004de9b4d7b70d1680cd8e3a2c60717cbbe60149910000000000000000000000006c14a43ab9ab10fea793acc2d2627390dc404d94000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000174173696120437265646974205969656c64205661756c74000000000000000000000000000000000000000000000000000000000000000000000000000000000473624d550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Deployed Bytecode

0x60806040527f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545f9081906001600160a01b0316368280378136915af43d5f803e156048573d5ff35b3d5ffdfea26469706673582212205930e04847f25c502725e018fc0b653d314783132e602028ab11856fcfa5b9fb64736f6c634300081b0033

Deployed Bytecode Sourcemap

599:1116:10:-:0;;;1327:66:11;;-1:-1:-1;;;;;;;;;1327:66:11;1019:819:12;-1:-1:-1;;1019:819:12;;;;;;;-1:-1:-1;1019:819:12;;;;;;-1:-1:-1;1019:819:12;;;-1:-1:-1;1019:819:12

Swarm Source

ipfs://5930e04847f25c502725e018fc0b653d314783132e602028ab11856fcfa5b9fb

Block Transaction Gas Used Reward
view all blocks produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.