ETH Price: $2,737.74 (-1.01%)

Contract

0x3D4d196Ab4a32Dee3f653fd58e9aB491584E3f0a

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

> 10 Internal Transactions found.

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
169920022025-11-21 14:20:1330 hrs ago1763734813
0x3D4d196A...1584E3f0a
0 ETH
169920022025-11-21 14:20:1330 hrs ago1763734813
0x3D4d196A...1584E3f0a
0 ETH
169920022025-11-21 14:20:1330 hrs ago1763734813
0x3D4d196A...1584E3f0a
0 ETH
169896262025-11-21 13:40:3731 hrs ago1763732437
0x3D4d196A...1584E3f0a
0 ETH
169896262025-11-21 13:40:3731 hrs ago1763732437
0x3D4d196A...1584E3f0a
0 ETH
169896262025-11-21 13:40:3731 hrs ago1763732437
0x3D4d196A...1584E3f0a
0 ETH
169822762025-11-21 11:38:0733 hrs ago1763725087
0x3D4d196A...1584E3f0a
0 ETH
169822762025-11-21 11:38:0733 hrs ago1763725087
0x3D4d196A...1584E3f0a
0 ETH
169822762025-11-21 11:38:0733 hrs ago1763725087
0x3D4d196A...1584E3f0a
0 ETH
169822542025-11-21 11:37:4533 hrs ago1763725065
0x3D4d196A...1584E3f0a
0 ETH
169822542025-11-21 11:37:4533 hrs ago1763725065
0x3D4d196A...1584E3f0a
0 ETH
169822542025-11-21 11:37:4533 hrs ago1763725065
0x3D4d196A...1584E3f0a
0 ETH
169815002025-11-21 11:25:1133 hrs ago1763724311
0x3D4d196A...1584E3f0a
0 ETH
169815002025-11-21 11:25:1133 hrs ago1763724311
0x3D4d196A...1584E3f0a
0 ETH
169815002025-11-21 11:25:1133 hrs ago1763724311
0x3D4d196A...1584E3f0a
0 ETH
169814592025-11-21 11:24:3033 hrs ago1763724270
0x3D4d196A...1584E3f0a
0 ETH
169814592025-11-21 11:24:3033 hrs ago1763724270
0x3D4d196A...1584E3f0a
0 ETH
169814592025-11-21 11:24:3033 hrs ago1763724270
0x3D4d196A...1584E3f0a
0 ETH
169677732025-11-21 7:36:2437 hrs ago1763710584
0x3D4d196A...1584E3f0a
0 ETH
169677732025-11-21 7:36:2437 hrs ago1763710584
0x3D4d196A...1584E3f0a
0 ETH
169677732025-11-21 7:36:2437 hrs ago1763710584
0x3D4d196A...1584E3f0a
0 ETH
169674812025-11-21 7:31:3237 hrs ago1763710292
0x3D4d196A...1584E3f0a
0 ETH
169674812025-11-21 7:31:3237 hrs ago1763710292
0x3D4d196A...1584E3f0a
0 ETH
169674812025-11-21 7:31:3237 hrs ago1763710292
0x3D4d196A...1584E3f0a
0 ETH
169629342025-11-21 6:15:4538 hrs ago1763705745
0x3D4d196A...1584E3f0a
0 ETH
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MorphoSupplyStrategy

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 50 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { IBaseStrategy } from "../../../interfaces/optimizer/IBaseStrategy.sol";
import { IMorphoSupplyStrategy } from "../../../interfaces/optimizer/strategies/IMorphoSupplyStrategy.sol";

import { BaseStrategy } from "../BaseStrategy.sol";
import { BaseMorphoUtils } from "../../positions/base/BorrowLending/Morpho/BaseMorphoUtils.sol";
import { VersionedVaultUtils } from "../../positions/base/VersionedVaultUtils.sol";

import { Constants } from "../../../optimizer/utils/Constants.sol";
import { ZeroAddress } from "../../../utils/Helpers.sol";

contract MorphoSupplyStrategy is VersionedVaultUtils, BaseMorphoUtils, BaseStrategy, IMorphoSupplyStrategy {
    bytes32 private constant STRATEGY_STORAGE_SLOT = keccak256("MorphoSupplyStrategy.storage")
        & ~bytes32(uint256(0xff));

    constructor(
        address optimizerVault,
        address positionManager,
        MorphoStrategyConfig memory strategyConfig
    )
        BaseStrategy(optimizerVault)
        Ownable(msg.sender)
    {
        if (positionManager == address(0)) revert ZeroAddress();
        _initVersionedVaultStrategyStorage(positionManager);
        _setMorphoCommonsStorage(strategyConfig);
    }

    // To be called via delegate
    function processHook(
        address strategy,
        uint32 transactionType,
        bytes calldata cmd
    )
        external
        override
        onlyDelegateCall(strategy)
        onlyEpochProcessingDelegate
    {
        IMorphoSupplyStrategy conn = IMorphoSupplyStrategy(strategy);
        IBaseStrategy baseStrategy = IBaseStrategy(strategy);
        BaseStrategyStorage memory cfg = baseStrategy.getBaseStrategyConfig();

        _checkVersionAndSetConfig(conn);

        if (transactionType == Constants.MORPHO_SUPPLY_TRANSACTION_CODE_SUPPLY) {
            uint256 assetsToSupply = _decodeCmdForSupply(cmd);
            _supply(cfg.optimizerVault, assetsToSupply);
        } else if (transactionType == Constants.MORPHO_SUPPLY_TRANSACTION_CODE_WITHDRAW) {
            uint256 assetsToWithdraw = _decodeCmdForWithdraw(cmd);
            _withdrawKATFromSupply(cfg.optimizerVault, assetsToWithdraw);
        } else if (transactionType == Constants.MORPHO_SUPPLY_TRANSACTION_CODE_MAX_WITHDRAWABLE) {
            uint256 maxWithdrawable = _withdrawableSupplyBalance(cfg.optimizerVault);
            _withdrawKATFromSupply(cfg.optimizerVault, maxWithdrawable);
        } else if (transactionType == Constants.MORPHO_SUPPLY_TRANSACTION_CODE_WITHDRAW_ALL) {
            _withdrawAllKATFromSupply(cfg.optimizerVault);
        } else if (transactionType == Constants.MORPHO_SUPPLY_TRANSACTION_CODE_FINALIZE) {
            uint256 assetsToWithdraw = _decodeCmdForWithdraw(cmd);
            _reserveKATForWithdrawalEntryPoint(conn, assetsToWithdraw);
        } else if (transactionType == Constants.MORPHO_SUPPLY_TRANSACTION_CODE_RESET) {
            _resetReservedKATForWithdrawalEntryPoint(conn);
        } else {
            revert InvalidTransactionType(transactionType);
        }
    }

    function finalizeHook(
        address strategy,
        uint32 transactionType,
        bytes calldata /*cmd*/
    )
        external
        view
        override
    {
        if (transactionType != Constants.MORPHO_SUPPLY_TRANSACTION_CODE_FINALIZE) {
            revert InvalidTransactionType(transactionType);
        }

        IMorphoSupplyStrategy conn = IMorphoSupplyStrategy(strategy);
        if (conn.getKATReservedForWithdrawal() != 0) revert UnclaimedKATForWithdrawal();
    }

    function claimWithdrawalHook(
        uint256, /*totalSharesForWithdrawal*/
        uint256 /*totalAssetsForWithdrawalInWithdrawalToken*/
    )
        external
        pure
        override
    {
        revert NotWithdrawableByUser();
    }

    function addKATReservedForWithdrawal(uint256 kATReservedForWithdrawal)
        external
        override
        onlyOptimizerVault
        onlyEpochProcessing
    {
        _getStorage().kATReservedForWithdrawal += kATReservedForWithdrawal;
    }

    function resetKATReservedForWithdrawal() external override onlyOptimizerVault onlyEpochProcessing {
        _getStorage().kATReservedForWithdrawal = 0;
    }

    function getStrategyConfig() external view override returns (MorphoSupplyStrategyVersionedConfig memory) {
        MorphoStrategyConfig memory morphoStrategyConfig = _getMorphoCommonsConfig();
        VaultStrategyStorage memory vaultStrategyConfig = _getVaultStrategyStorage();

        return MorphoSupplyStrategyVersionedConfig({
            morphoStrategyConfig: morphoStrategyConfig, vaultStrategyConfig: vaultStrategyConfig
        });
    }

    function _supply(address optimizerVault, uint256 assetsToSupply) internal {
        _supplyLoanToken(optimizerVault, assetsToSupply);
        emit KATSupplied(assetsToSupply);
    }

    function _withdrawKATFromSupply(address optimizerVault, uint256 assetsToWithdraw) internal {
        _withdrawLoanToken(optimizerVault, assetsToWithdraw);
        emit KATWithdrawnFromSupply(assetsToWithdraw);
    }

    function _withdrawAllKATFromSupply(address optimizerVault) internal {
        (uint256 katWithdrawn,) = _withdrawAllLoanToken(optimizerVault);
        emit KATWithdrawnFromSupply(katWithdrawn);
    }

    function _resetReservedKATForWithdrawalEntryPoint(IMorphoSupplyStrategy conn) internal {
        conn.resetKATReservedForWithdrawal();
        emit KATResetReservedForWithdrawal();
    }

    function _reserveKATForWithdrawalEntryPoint(IMorphoSupplyStrategy conn, uint256 kATReservedForWithdrawal) internal {
        conn.addKATReservedForWithdrawal(kATReservedForWithdrawal);
        emit KATReservedForWithdrawal(kATReservedForWithdrawal);
    }

    function _checkVersionAndSetConfig(IMorphoSupplyStrategy conn) internal {
        uint256 strategyVersion = conn.version();
        if (strategyVersion == _version()) {
            return;
        }

        MorphoSupplyStrategyVersionedConfig memory config = conn.getStrategyConfig();
        _setMorphoCommonsStorage(config.morphoStrategyConfig);
        _setVaultStrategyStorage(config.vaultStrategyConfig);

        emit StrategyVersionUpdated(address(this), address(conn), strategyVersion);
    }

    // Token whitelisted to be deposited in the strategy
    function token() external pure override returns (address) {
        revert NoPrimaryDepositToken();
    }

    // Whether user can directly deposits token linked to this strategy
    function isDepositEnabled() external pure override returns (bool) {
        return false;
    }

    // Returns balance for vault accounted by the strategy in terms of underlying token
    function balance() external view override returns (uint256, bool) {
        BaseStrategyStorage storage s = _getBaseStrategyStorage();
        uint256 supplyBalance = _supplyBalance(s.optimizerVault);

        return (supplyBalance, false);
    }

    function version() external view returns (uint256) {
        return _version();
    }

    function getKATReservedForWithdrawal() external view override returns (uint256) {
        return _getStorage().kATReservedForWithdrawal;
    }

    // How much supply balance is available to be withdrawn
    function withdrawableSupplyBalance() external view override returns (uint256) {
        BaseStrategyStorage storage s = _getBaseStrategyStorage();
        return _withdrawableSupplyBalance(s.optimizerVault);
    }

    function encodeCallDataForSupply(uint256 assetsToSupply) external pure returns (bytes memory) {
        return abi.encode(assetsToSupply);
    }

    function encodeCallDataToWithdraw(uint256 assetsToWithdraw) external pure returns (bytes memory) {
        return abi.encode(assetsToWithdraw);
    }

    function _decodeCmdForSupply(bytes calldata cmd) internal pure returns (uint256) {
        return abi.decode(cmd, (uint256));
    }

    function _decodeCmdForWithdraw(bytes calldata cmd) internal pure returns (uint256) {
        return abi.decode(cmd, (uint256));
    }

    function _version() internal view returns (uint256) {
        return _getVaultStrategyStorage().version;
    }

    function _getStorage() internal pure returns (MorphoSupplyStrategyStorage storage s) {
        bytes32 slot = STRATEGY_STORAGE_SLOT;
        assembly {
            s.slot := slot
        }
    }
}

// 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-3.0
pragma solidity 0.8.28;

interface IBaseStrategy {
    struct BaseStrategyStorage {
        address optimizerVault;
    }

    // To be called via delegate
    function processHook(address strategy, uint32 transactionType, bytes calldata cmd) external;

    // To be called via delegate
    function finalizeHook(address strategy, uint32 transactionType, bytes calldata cmd) external;

    // To be called directly. How much asset to be deducted from reserve when claiming withdrawal
    function claimWithdrawalHook(
        uint256 totalSharesForWithdrawal,
        uint256 totalAssetsForWithdrawalInWithdrawalToken
    )
        external;

    function getBaseStrategyConfig() external view returns (BaseStrategyStorage memory);

    // Returns balance for vault accounted by the strategy in terms of underlying token
    function balance() external view returns (uint256, bool);

    // Token whitelisted to be deposited in the strategy
    function token() external view returns (address);

    // Whether user can directly deposits token linked to this strategy
    function isDepositEnabled() external view returns (bool);
}

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

import { IMorphoCommons } from "../../positions/BorrowLending/IMorphoCommons.sol";
import { IVersionedVaultUtils } from "../../positions/IVaultStrategy.sol";

interface IMorphoSupplyStrategy {
    struct MorphoSupplyStrategyStorage {
        uint256 kATReservedForWithdrawal;
    }

    struct MorphoSupplyStrategyVersionedConfig {
        IMorphoCommons.MorphoStrategyConfig morphoStrategyConfig;
        IVersionedVaultUtils.VaultStrategyStorage vaultStrategyConfig;
    }

    struct StrategyConfig {
        bytes32 marketID;
    }

    error UnclaimedKATForWithdrawal();

    event KATSupplied(uint256 kATSupplied);
    event KATWithdrawnFromSupply(uint256 kATWithdrawnFromSupply);
    event KATReservedForWithdrawal(uint256 kATReservedForWithdrawal);
    event KATResetReservedForWithdrawal();
    event StrategyVersionUpdated(address source, address strategy, uint256 strategyVersion);

    function addKATReservedForWithdrawal(uint256 kATReservedForWithdrawal) external;
    function resetKATReservedForWithdrawal() external;

    function getKATReservedForWithdrawal() external view returns (uint256);
    function withdrawableSupplyBalance() external view returns (uint256);
    function getStrategyConfig() external view returns (MorphoSupplyStrategyVersionedConfig memory);
    function version() external view returns (uint256);
}

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

import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";

import { IRagaEpochVault } from "../../interfaces/IRagaEpochVault.sol";
import { IBaseStrategy } from "../../interfaces/optimizer/IBaseStrategy.sol";
import { IOptimizerVault } from "../../interfaces/optimizer/IOptimizerVault.sol";

import { RagaEpochVaultStorageLibrary } from "../../libraries/RagaEpochVaultStorageLibrary.sol";
import { PermissionDenied, ZeroAddress } from "../../utils/Helpers.sol";

abstract contract BaseStrategy is IBaseStrategy {
    bytes32 private constant BASE_STRATEGY_STORAGE_SLOT = keccak256("BaseStrategy.storage") & ~bytes32(uint256(0xff));

    error NoPrimaryDepositToken();
    error NotWithdrawableByUser();
    error InvalidTransactionType(uint32 transactionType);

    modifier onlyOptimizerVault() {
        BaseStrategyStorage storage s = _getBaseStrategyStorage();
        if (msg.sender != s.optimizerVault) revert PermissionDenied();
        _;
    }

    modifier onlyExecutor() {
        BaseStrategyStorage storage s = _getBaseStrategyStorage();
        if (msg.sender != IRagaEpochVault(s.optimizerVault).getExecutor()) revert PermissionDenied();
        _;
    }

    modifier onlyDelegateCall(address strategy) {
        BaseStrategyStorage memory s = IBaseStrategy(strategy).getBaseStrategyConfig();
        if (address(this) != s.optimizerVault) revert PermissionDenied();
        _;
    }

    modifier onlyEpochProcessingDelegate() {
        require(_isEpochProccessingDelegate(), IRagaEpochVault.NoEpochProcessing());
        _;
    }

    modifier onlyEpochProcessing() {
        BaseStrategyStorage storage s = _getBaseStrategyStorage();
        IRagaEpochVault epochVault = IRagaEpochVault(s.optimizerVault);
        require(_isEpochProcessing(epochVault), IRagaEpochVault.NoEpochProcessing());
        _;
    }

    constructor(address optimizerVault) {
        if (optimizerVault == address(0)) revert ZeroAddress();
        BaseStrategyStorage storage s = _getBaseStrategyStorage();
        s.optimizerVault = optimizerVault;
    }

    function getBaseStrategyConfig() external pure override returns (BaseStrategyStorage memory) {
        return _getBaseStrategyStorage();
    }

    function _isEpochProcessing(IRagaEpochVault epochVault) internal view returns (bool) {
        uint32 currentEpoch = epochVault.getCurrentEpoch();
        if (currentEpoch == 0) return false;
        IRagaEpochVault.EpochData memory epochData = epochVault.getEpochData(currentEpoch - 1);
        return epochData.status == IRagaEpochVault.EpochStatus.PROCESSING;
    }

    function _isEpochProccessingDelegate() internal view returns (bool) {
        RagaEpochVaultStorageLibrary.RagaEpochVaultStorage storage s = RagaEpochVaultStorageLibrary._getStorage();
        uint32 currentEpoch = RagaEpochVaultStorageLibrary._getCurrentEpoch(s);
        if (currentEpoch == 0) return false;
        IRagaEpochVault.EpochData storage epochData = RagaEpochVaultStorageLibrary._getEpochData(s, currentEpoch - 1);
        return epochData.status == IRagaEpochVault.EpochStatus.PROCESSING;
    }

    function _getBaseStrategyStorage() internal pure returns (BaseStrategyStorage storage s) {
        bytes32 slot = BASE_STRATEGY_STORAGE_SLOT;
        assembly {
            s.slot := slot
        }
    }
}

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

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

import { IOracle } from "@morpho-blue/src/interfaces/IOracle.sol";
import { IMorpho, MarketParams, Id } from "@morpho-blue/src/interfaces/IMorpho.sol";

import { MorphoLib } from "@morpho-blue/src/libraries/periphery/MorphoLib.sol";
import { SharesMathLib } from "@morpho-blue/src/libraries/SharesMathLib.sol";
import { MarketParamsLib } from "@morpho-blue/src/libraries/MarketParamsLib.sol";
import { MorphoBalancesLib } from "@morpho-blue/src/libraries/periphery/MorphoBalancesLib.sol";

import { ORACLE_PRICE_SCALE } from "@morpho-blue/src/libraries/ConstantsLib.sol";

import { IPriceFeed } from "../../../../../interfaces/shared/IPriceFeed.sol";

import { Constants } from "../../../../../positions/Constants.sol";
import { BaseMorphoCommons } from "./BaseMorphoCommons.sol";

/// @dev Utility functions to be used by Ajna Borrow Lending strategy and Spectra Looping
abstract contract BaseMorphoUtils is BaseMorphoCommons {
    using SharesMathLib for uint256;
    using MorphoLib for IMorpho;
    using MorphoBalancesLib for IMorpho;

    using MarketParamsLib for MarketParams;

    function _supplyLoanToken(
        address user,
        uint256 amount
    )
        internal
        returns (uint256 assetsSupplied, uint256 sharesReceived)
    {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
        BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();

        IMorpho morpho = s.morpho;
        IERC20 borrowToken = IERC20(b.borrowToken);
        MarketParams memory params = s.marketParams;

        SafeERC20.forceApprove(borrowToken, address(morpho), amount);
        (assetsSupplied, sharesReceived) = morpho.supply(params, amount, 0, user, hex"");
    }

    /// @notice Withdraws a specified amount of loan tokens from the user's supply position
    /// @dev use max amount if user wants to withdraw all shares
    function _withdrawLoanToken(
        address user,
        uint256 amount
    )
        internal
        returns (uint256 assetsWithdrawn, uint256 sharesBurned)
    {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        morpho.accrueInterest(params);

        uint256 maxAmount = _supplyBalance(user);
        if (amount > maxAmount) {
            (assetsWithdrawn, sharesBurned) = _withdrawAllLoanToken(user);
            return (assetsWithdrawn, sharesBurned);
        }

        (assetsWithdrawn, sharesBurned) = s.morpho.withdraw(params, amount, 0, user, user);
    }

    function _withdrawAllLoanToken(address user) internal returns (uint256 assetsWithdrawn, uint256 sharesBurned) {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        uint256 allShares = morpho.supplyShares(params.id(), user);
        (assetsWithdrawn, sharesBurned) = morpho.withdraw(params, 0, allShares, user, user);
    }

    /**
     * @dev To be used via inheritence
     */
    function _drawDebt(
        address user,
        uint256 collateralToAdd,
        uint256 debtToBorrow
    )
        internal
        override
        returns (uint256, uint256)
    {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
        BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();

        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        if (collateralToAdd > 0) {
            ERC20 collateralToken = ERC20(b.collateralToken);
            SafeERC20.forceApprove(collateralToken, address(morpho), collateralToAdd);
            morpho.supplyCollateral(params, collateralToAdd, user, hex"");
        }

        uint256 debtBorrowed = 0;
        if (debtToBorrow > 0) {
            (debtBorrowed,) = morpho.borrow(params, debtToBorrow, 0, user, user);
        }

        return (collateralToAdd, debtBorrowed);
    }

    /**
     * @dev To be used via inheritence
     */
    function _repayDebt(
        address user,
        uint256 collateralToPull,
        uint256 debtToRepay,
        address repayRecipent
    )
        internal
        override
        returns (uint256, uint256)
    {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
        BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();

        MorphoRepayParams memory repayParams =
            MorphoRepayParams({ morpho: s.morpho, marketParams: s.marketParams, borrowToken: b.borrowToken });

        repayParams.morpho.accrueInterest(repayParams.marketParams);

        uint256 debtRepaid = 0;
        if (debtToRepay > 0) {
            uint256 assetsMax = repayParams.morpho.expectedBorrowAssets(repayParams.marketParams, user);

            if (debtToRepay >= assetsMax) {
                debtRepaid = _repayAll(user, debtToRepay, repayRecipent);
            } else {
                SafeERC20.forceApprove(IERC20(repayParams.borrowToken), address(repayParams.morpho), debtToRepay);
                (debtRepaid,) = repayParams.morpho.repay(repayParams.marketParams, debtToRepay, 0, user, hex"");
            }
        }

        if (collateralToPull > 0) {
            repayParams.morpho.withdrawCollateral(repayParams.marketParams, collateralToPull, user, user);
        }

        return (collateralToPull, debtRepaid);
    }

    /// @dev it is recommended to use borrow shares in cases where complete debt is to be paid
    function _repayAll(
        address user,
        uint256 amount,
        address repayRecipent
    )
        internal
        override
        returns (uint256 assetRepaid)
    {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
        BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();

        IERC20 borrowToken = IERC20(b.borrowToken);

        SafeERC20.forceApprove(borrowToken, address(s.morpho), amount);

        // Get Total borrow shares for user
        uint256 shares = s.morpho.borrowShares(s.marketParams.id(), user);

        (assetRepaid,) = s.morpho.repay(s.marketParams, 0, shares, user, hex"");
        SafeERC20.forceApprove(borrowToken, address(s.morpho), 0);

        if (amount > assetRepaid) {
            SafeERC20.safeTransfer(borrowToken, repayRecipent, amount - assetRepaid);
        }
    }

    function _onFlashLoan(uint256 assets, bytes memory data) internal override {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
        BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();

        IMorpho morpho = s.morpho;
        address borrowToken = b.borrowToken;

        morpho.flashLoan(borrowToken, assets, data);
    }

    // get balance of borrowed token (with interest) (in borrowed Token)
    function borrowBalance(address user) public view override returns (uint256) {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();

        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        uint256 accuredBorrow = morpho.expectedBorrowAssets(params, user);
        return accuredBorrow;
    }

    function _supplyBalance(address user) internal view returns (uint256) {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();

        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        return morpho.expectedSupplyAssets(params, user);
    }

    function _withdrawableSupplyBalance(address user) internal view returns (uint256) {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();

        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        uint256 totalBorrow = morpho.totalBorrowAssets(params.id());
        uint256 totalSupply = morpho.totalSupplyAssets(params.id());
        uint256 supplyBalance = morpho.expectedSupplyAssets(params, user);

        uint256 withdrawableSupply = totalSupply - totalBorrow;

        return Math.min(withdrawableSupply, supplyBalance);
    }

    // get balance of collateral token (in collateral Token)
    function collateralBalance(address user) public view override returns (uint256) {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();

        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        return morpho.collateral(params.id(), user);
    }

    function _riskInternal(address user, uint256 baseValue) internal view override returns (uint256) {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();

        IMorpho morpho = s.morpho;
        MarketParams memory params = s.marketParams;

        uint256 collateralPrice = IOracle(params.oracle).price();
        uint256 collateral = morpho.collateral(params.id(), user);

        uint256 borrowed = morpho.expectedBorrowAssets(params, user);

        uint256 maxBorrowUncapped = Math.mulDiv(collateral, collateralPrice, ORACLE_PRICE_SCALE);
        uint256 maxBorrow = Math.mulDiv(maxBorrowUncapped, params.lltv, Constants.WAD);

        return Math.mulDiv(borrowed, baseValue, maxBorrow);
    }

    /// @dev calculate TP -> borrow / collateral * 1.04
    function _previewRiskInternal(
        uint256 baseValue,
        uint256 totalCollateral,
        uint256 totalBorrow
    )
        internal
        view
        override
        returns (uint256)
    {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();

        MarketParams memory params = s.marketParams;
        IOracle oracle = IOracle(params.oracle);
        uint256 collateralPrice = oracle.price();

        uint256 maxBorrowUncapped = Math.mulDiv(totalCollateral, collateralPrice, ORACLE_PRICE_SCALE);
        uint256 maxBorrow = Math.mulDiv(maxBorrowUncapped, params.lltv, Constants.WAD);

        return Math.mulDiv(totalBorrow, baseValue, maxBorrow);
    }

    /// @return updatedBorrowAmount = borrowAmount + originationFee
    function _previewBorrow(uint256 borrowAmount) internal pure override returns (uint256) {
        return borrowAmount;
    }

    function _balanceInCollateralToken(address user) internal view override returns (uint256) {
        BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();

        IPriceFeed priceFeed = b.priceFeed;
        address collateralToken = b.collateralToken;
        address borrowToken = b.borrowToken;

        uint256 cBalance = collateralBalance(user);
        uint256 bBalance = borrowBalance(user);

        uint256 bBalanceInCollateralToken = priceFeed.convertTokenBalance(borrowToken, collateralToken, bBalance);

        return cBalance > bBalanceInCollateralToken ? cBalance - bBalanceInCollateralToken : 0;
    }
}

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

import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { IVersionedVaultUtils } from "../../../interfaces/positions/IVaultStrategy.sol";

import { PermissionDenied, ZeroAddress } from "../../../utils/Helpers.sol";

/// @notice Stores version, deep copy and auto increment logic for the strategy
abstract contract VersionedVaultUtils is IVersionedVaultUtils, Ownable {
    event PositionManagerUpdated(address sender, address newPositionManager, uint256 newVersion);

    bytes32 constant VAULT_STRATEGY_STORAGE_POSITION = keccak256("vault.strategy.storage") & ~bytes32(uint256(0xff));
    bytes32 constant CALLER_INFO_STORAGE_POSITION = keccak256("caller.info.storage") & ~bytes32(uint256(0xff));

    modifier onlyPositionManager() {
        if (msg.sender != _getVaultStrategyStorage().positionManager) revert PermissionDenied();
        _;
    }

    modifier onlyDelegate() {
        if (address(this) == _getCallerInfoStorage().self) revert PermissionDenied();
        _;
    }

    function getConfig() external view returns (VaultStrategyStorage memory) {
        VaultStrategyStorage memory config = _getVaultStrategyStorage();
        return config;
    }

    function updatePositionManager(address newPositionManager) external onlyOwner {
        if (newPositionManager == address(0)) revert ZeroAddress();

        VaultStrategyStorage storage s = _getVaultStrategyStorage();
        s.positionManager = newPositionManager;
        s.version += 1;

        emit PositionManagerUpdated(msg.sender, newPositionManager, s.version);
    }

    function _initVersionedVaultStrategyStorage(address positionManager) internal {
        if (positionManager == address(0)) revert ZeroAddress();

        VaultStrategyStorage storage s = _getVaultStrategyStorage();
        CallerInfoStorage storage c = _getCallerInfoStorage();

        s.version = 1;
        s.positionManager = positionManager;

        c.self = address(this);
    }

    function _setVaultStrategyStorage(VaultStrategyStorage memory config) internal {
        VaultStrategyStorage storage s = _getVaultStrategyStorage();
        s.version = config.version;
        s.positionManager = config.positionManager;
    }

    function _getVaultStrategyStorage() internal pure returns (VaultStrategyStorage storage s) {
        bytes32 slot = VAULT_STRATEGY_STORAGE_POSITION;
        assembly {
            s.slot := slot
        }
    }

    function _getCallerInfoStorage() internal pure returns (CallerInfoStorage storage s) {
        bytes32 slot = CALLER_INFO_STORAGE_POSITION;
        assembly {
            s.slot := slot
        }
    }
}

File 8 of 50 : Constants.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;

library Constants {
    uint256 constant WAD = 1e18;

    uint32 constant FEE_TYPE_DEPOSIT = 1;
    uint32 constant FEE_TYPE_WITHDRAWAL = 2;
    uint32 constant FEE_TYPE_MANAGEMENT = 3;
    uint32 constant FEE_TYPE_PERFORMANCE = 4;

    uint32 constant MORPHO_SUPPLY_TRANSACTION_CODE_SUPPLY = 1001;
    uint32 constant MORPHO_SUPPLY_TRANSACTION_CODE_WITHDRAW = 1002;
    uint32 constant MORPHO_SUPPLY_TRANSACTION_CODE_MAX_WITHDRAWABLE = 1003;
    uint32 constant MORPHO_SUPPLY_TRANSACTION_CODE_WITHDRAW_ALL = 1004;
    uint32 constant MORPHO_SUPPLY_TRANSACTION_CODE_RESET = 1005;
    uint32 constant MORPHO_SUPPLY_TRANASCTION_CODE_RESERVE_FOR_WITHDRAWAL = 1006;
    uint32 constant MORPHO_SUPPLY_TRANSACTION_CODE_FINALIZE = 1007;

    uint32 constant AVKAT_TRANSACTION_CODE_DEPOSIT = 2001;
    uint32 constant AVKAT_TRANSACTION_CODE_RESERVE_FOR_WITHDRAWAL = 2002;
    uint32 constant AVKAT_TRANSACTION_CODE_FINALIZE = 2003;

    uint32 constant KAT_TRANSACTION_CODE_RESERVE_FOR_WITHDRAWAL = 3001;
    uint32 constant KAT_TRANSACTION_CODE_RESET = 3002;
    uint32 constant KAT_TRANSACTION_CODE_FINALIZE = 3003;

    uint32 constant MORPHO_LOOPING_TRANSACTION_CODE_OPEN_POSITION = 4001;
    uint32 constant MORPHO_LOOPING_TRANSACTION_CODE_DEPOSIT_POSITION = 4002;
    uint32 constant MORPHO_LOOPING_TRANSACTION_CODE_WITHDRAW_POSITION = 4003;
    uint32 constant MORPHO_LOOPING_TRANSACTION_CODE_WITHDRAW_ALL_POSITION = 4004;
    uint32 constant MORPHO_LOOPING_TRANSACTION_CODE_RESERVE_FOR_WITHDRAWAL = 4005;
    uint32 constant MORPHO_LOOPING_TRANSACTION_CODE_RESET = 4006;
    uint32 constant MORPHO_LOOPING_TRANSACTION_CODE_FINALIZE = 4007;
}

File 9 of 50 : Helpers.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

// common errors
error IncorrectTypeID(uint256 _typeId, address _sender);
error NegativePriceError();
error PriceStaleError();
error CallFailed();
error NotDepositContract(address _address);
error NotExecutor(address _address);
error NotStrategyContract(address _address);
error IncorrectTokenAddress(address _tokenAddress);
error IncorrectValue();
error IncorrectMessageAddress(address _sender);
error ZeroAddress();
error ZeroAmount();
error ZeroValue();
error MinimumDustAmountError();
error NonPayableFunction();
error DivideByZeroError();
error PermissionDenied();
error InvalidLendingThreshold();

error NotImplemented();

// common events

//deposit events

//deposit

// 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: GPL-3.0
pragma solidity 0.8.28;

import { IMorpho, MarketParams } from "@morpho-blue/src/interfaces/IMorpho.sol";

import { IVersionedVaultUtils } from "../IVaultStrategy.sol";
import { IBorrowLendingUtils } from "./IBorrowLendingUtils.sol";

interface IMorphoCommons {
    struct MorphoCommonsStorage {
        MarketParams marketParams;
        IMorpho morpho;
    }

    struct MorphoStrategyConfig {
        MorphoCommonsStorage morphoCommons;
        address priceFeed;
    }

    struct MorphoRepayParams {
        IMorpho morpho;
        MarketParams marketParams;
        address borrowToken;
    }
}

interface IMorphoConfigFetcher {
    struct MorphoStrategyVersionedConfig {
        IMorphoCommons.MorphoStrategyConfig morphoStrategyConfig;
        IVersionedVaultUtils.VaultStrategyStorage vaultStrategyConfig;
    }

    function getMorphoCommonsConfig() external view returns (MorphoStrategyVersionedConfig memory);
}

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

import { IStrategyManager } from "./IStrategyManager.sol";
import { IVaultManager } from "./IVaultManager.sol";

interface IVaultStrategy {
    // errors
    error InvalidToken(address token);
    error InvalidUserConfig();
    error StrategyLoopingNotEnabled();
    error InvalidTransactionCode(uint256 code);

    // read-only functions
    function version() external view returns (uint256);

    function risk(address user, uint256 baseValue) external view returns (uint256);

    function balance(address user) external view returns (uint256);
    function balanceInUSD(address user) external view returns (uint256);
    function balanceInDepositToken(address user) external view returns (uint256);
    function balanceInWithdrawalToken(address user) external view returns (uint256);

    function validatePreDeposit(
        address user,
        uint64 transactionCode,
        address _tokenAddress,
        uint256 _value,
        IStrategyManager.StrategyConfig calldata strategyConfig,
        IVaultManager.VaultStrategyConfig calldata userConfig,
        bytes calldata _extras
    )
        external
        view;

    // write-only functions

    /// @dev This call will always be delegated
    /// @notice Called by vault to copy the strategy config to vault storage slot
    function setConfig(address strategy) external;

    // @dev this call will always be delegated
    function deposit(
        address user,
        uint64 transactionCode,
        address _tokenAddress,
        uint256 _value,
        IStrategyManager.StrategyConfig calldata strategyConfig,
        IVaultManager.VaultStrategyConfig calldata userConfig,
        bytes calldata _extras
    )
        external
        payable;

    // @dev this call will always be delegated
    function withdraw(
        address user,
        uint64 transactionCode,
        address _tokenAddress,
        uint256 _value,
        IStrategyManager.StrategyConfig calldata strategyConfig,
        IVaultManager.VaultStrategyConfig calldata userConfig,
        bytes calldata _extras
    )
        external
        payable;
}

interface IVersionedVaultUtils {
    struct VaultStrategyStorage {
        uint256 version;
        address positionManager;
    }

    struct CallerInfoStorage {
        address self;
    }

    function getConfig() external view returns (VaultStrategyStorage memory);
}

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface of the ERC-4626 "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 redemption 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: GPL-3.0
pragma solidity 0.8.28;

interface IRagaEpochVault {
    // Enums
    enum EpochStatus {
        ACTIVE,
        PROCESSING,
        FINALIZED
    }

    // Structs
    struct EpochData {
        uint32 epoch;
        uint48 startTime;
        uint48 endTime;
        // Updated whenever a deposit is made
        uint256 assetsDeposited;
        uint256 sharesMinted;
        // Updated whenever epoch is finalized and withdrawals are processed
        // Asset in terms of withdrawal token
        uint256 assetsWithdrawnInWithdrawalToken;
        // Updated on withdrawal request
        uint256 sharesBurned;
        EpochStatus status;
    }

    struct WithdrawalRequest {
        uint256 shares;
        uint32 epoch;
    }

    // Errors
    error NoEpochProcessing();
    error EpochNotFinalized();
    error EpochNotProcessing();
    error PreviousEpochNotFinalized();

    // Events
    event WithdrawalRequested(address indexed user, uint256 shares, uint256 epoch);
    event WithdrawalClaimed(
        address indexed user, address withdrawalToken, uint256 shares, uint256 assetsInWithdrawalToken
    );

    event EpochStarted(uint256 indexed epoch, uint256 startTime);
    event EpochProcessing(uint256 indexed epoch, uint256 startTime, uint256 endTime, bytes executionData);

    event EpochFinalized(
        uint256 indexed epoch,
        uint256 sharesMinted,
        uint256 assetDeposited,
        uint256 sharesBurned,
        uint256 assetsWithdrawnInWithdrawalToken
    );

    // read-only functions
    function getExecutor() external view returns (address);
    function getCurrentEpoch() external view returns (uint32);
    function getEpochData(uint32 epoch) external view returns (EpochData memory);
    function getWithdrawalToken() external view returns (address);
}

File 15 of 50 : IOptimizerVault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;

interface IOptimizerVault {
    // errors
    error NegativeBalance();

    // structs

    // transactionType: Code to be defined in separately
    struct StrategyExecutionCallData {
        address strategy;
        uint32 transactionType;
        bytes cmd;
    }

    // events
    event DepositToken(address user, address token, uint256 assets, uint256 shares);
    event ClaimWithdrawalHookCalled(
        address strategy, uint256 totalSharesForWithdrawal, uint256 totalAssetsForWithdrawalInWithdrawalToken
    );
    event StrategyProcessHookCalled(address strategy, uint32 transactionType);
    event StrategyFinalizeHookCalled(address strategy, uint32 transactionType);

    event FeeTransferred(address sender, address receiver, address token, uint256 fee);
}

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

import { IRagaEpochVault } from "../interfaces/IRagaEpochVault.sol";
import { WithrawalQueueLibrary } from "./WithrawalQueueLibrary.sol";

library RagaEpochVaultStorageLibrary {
    using WithrawalQueueLibrary for WithrawalQueueLibrary.WithdrawalQueue;

    bytes32 internal constant STORAGE_SLOT = keccak256("raga.epoch.vault.storage") & ~bytes32(uint256(0xff));

    struct RagaEpochVaultStorage {
        address executor;
        uint32 currentEpoch;
        // Token in which user will receive the withdrawal funds
        address withdrawalToken;
        mapping(uint32 => IRagaEpochVault.EpochData) epochs;
        mapping(address => WithrawalQueueLibrary.WithdrawalQueue) userWithdrawalQueue;
        // Shares scheduled for withdrawal, yet to be processed and claimed by the user
        uint256 scheduledWithdrawalShares;
        uint256 totalAssetsReservedForWithdrawalInWithdrawalToken;
    }

    function _getStorage() internal pure returns (RagaEpochVaultStorage storage ds) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            ds.slot := slot
        }
    }

    function _initStorage(RagaEpochVaultStorage storage ds, address withdrawalToken, address executor) internal {
        ds.withdrawalToken = withdrawalToken;
        ds.executor = executor;
    }

    function _updateEpochDepositInfo(RagaEpochVaultStorage storage ds, uint256 shares, uint256 assets) internal {
        uint32 epoch = ds.currentEpoch;
        IRagaEpochVault.EpochData storage epochData = ds.epochs[epoch];

        epochData.sharesMinted += shares;
        epochData.assetsDeposited += assets;
    }

    function _updateEpochWithdrawalInfo(RagaEpochVaultStorage storage ds, uint32 epoch, uint256 assets) internal {
        IRagaEpochVault.EpochData storage epochData = ds.epochs[epoch];
        if (epochData.status != IRagaEpochVault.EpochStatus.PROCESSING) {
            revert IRagaEpochVault.EpochNotProcessing();
        }

        epochData.assetsWithdrawnInWithdrawalToken += assets;
    }

    function _initializeFirstEpoch(RagaEpochVaultStorage storage ds) internal {
        ds.currentEpoch = 0;

        ds.epochs[0] = IRagaEpochVault.EpochData({
            epoch: 0,
            startTime: uint48(block.timestamp),
            endTime: 0,
            status: IRagaEpochVault.EpochStatus.ACTIVE,
            assetsDeposited: 0,
            assetsWithdrawnInWithdrawalToken: 0,
            sharesMinted: 0,
            sharesBurned: 0
        });
    }

    /**
     * @dev Increments the current epoch and creates a new epoch data entry.
     * @param ds The storage pointer to the RagaEpochVaultStorage struct.
     */
    function _incrementEpoch(RagaEpochVaultStorage storage ds)
        internal
        returns (uint32 newEpoch, uint32 processingEpoch)
    {
        if (ds.currentEpoch > 0) {
            uint32 previousEpoch = ds.currentEpoch - 1;
            if (ds.epochs[previousEpoch].status != IRagaEpochVault.EpochStatus.FINALIZED) {
                revert IRagaEpochVault.PreviousEpochNotFinalized();
            }
        }

        uint48 currentTs = uint48(block.timestamp);

        // Close the current epoch
        ds.epochs[ds.currentEpoch].endTime = currentTs;
        ds.epochs[ds.currentEpoch].status = IRagaEpochVault.EpochStatus.PROCESSING;
        processingEpoch = ds.currentEpoch;

        // Start a new epoch with relevant details
        ds.currentEpoch++;
        ds.epochs[ds.currentEpoch] = IRagaEpochVault.EpochData({
            epoch: ds.currentEpoch,
            startTime: currentTs,
            endTime: 0,
            status: IRagaEpochVault.EpochStatus.ACTIVE,
            assetsDeposited: 0,
            assetsWithdrawnInWithdrawalToken: 0,
            sharesMinted: 0,
            sharesBurned: 0
        });

        newEpoch = ds.currentEpoch;
    }

    function _finalizeEpoch(RagaEpochVaultStorage storage ds, uint32 epoch) internal {
        IRagaEpochVault.EpochData storage proccessingEpoch = ds.epochs[epoch];
        if (proccessingEpoch.status != IRagaEpochVault.EpochStatus.PROCESSING) {
            revert IRagaEpochVault.EpochNotProcessing();
        }

        // Update the status and assets for epoch finalized
        proccessingEpoch.status = IRagaEpochVault.EpochStatus.FINALIZED;

        // Remove the shares burned from the scheduled withdrawal shares as they have been processed
        ds.scheduledWithdrawalShares -= proccessingEpoch.sharesBurned;
    }

    function _createWithdrawalRequest(RagaEpochVaultStorage storage ds, address user, uint256 shares) internal {
        WithrawalQueueLibrary.WithdrawalQueue storage queue = ds.userWithdrawalQueue[user];

        ds.scheduledWithdrawalShares += shares;
        ds.epochs[ds.currentEpoch].sharesBurned += shares;

        if (queue._isEmpty()) {
            queue._enqueue(IRagaEpochVault.WithdrawalRequest({ shares: shares, epoch: ds.currentEpoch }));
            return;
        }

        IRagaEpochVault.WithdrawalRequest storage latestRequest = queue._backMut();
        if (latestRequest.epoch == ds.currentEpoch) {
            latestRequest.shares += shares;
            return;
        }

        queue._enqueue(IRagaEpochVault.WithdrawalRequest({ shares: shares, epoch: ds.currentEpoch }));
    }

    /**
     * @notice Clears the withdrawal queue for a user from all claimable requests
     * @dev Effect step which clears all the claimable requests from the withdrawal queue
     * @param ds The storage pointer to the RagaEpochVaultStorage struct.
     * @param user The address of the user whose withdrawal queue is to be cleared.
     */
    function _aggregateAndClearClaimableWithdrawalRequests(
        RagaEpochVaultStorage storage ds,
        address user
    )
        internal
        returns (uint256 totalShares, uint256 totalAssetsInWithdrawalToken)
    {
        WithrawalQueueLibrary.WithdrawalQueue storage queue = ds.userWithdrawalQueue[user];

        while (!queue._isEmpty()) {
            uint128 idx = queue._head();
            IRagaEpochVault.WithdrawalRequest memory request = queue._peek(idx);

            // Check
            if (ds.epochs[request.epoch].status != IRagaEpochVault.EpochStatus.FINALIZED) {
                break;
            }

            // Effect
            totalShares += request.shares;
            totalAssetsInWithdrawalToken += _calculateAssets(ds, request.epoch, request.shares);

            // Interaction
            queue._dequeueFront();
        }
    }

    function _getCurrentEpoch(RagaEpochVaultStorage storage ds) internal view returns (uint32) {
        return ds.currentEpoch;
    }

    function _getEpochData(
        RagaEpochVaultStorage storage ds,
        uint32 epoch
    )
        internal
        view
        returns (IRagaEpochVault.EpochData storage)
    {
        return ds.epochs[epoch];
    }

    function _getProcessingEpochData(RagaEpochVaultStorage storage ds)
        internal
        view
        returns (IRagaEpochVault.EpochData storage)
    {
        uint32 currentEpoch = _getCurrentEpoch(ds);
        if (currentEpoch == 0) revert IRagaEpochVault.NoEpochProcessing();

        IRagaEpochVault.EpochData storage epochData = _getEpochData(ds, currentEpoch - 1);
        if (epochData.status != IRagaEpochVault.EpochStatus.PROCESSING) revert IRagaEpochVault.NoEpochProcessing();

        return epochData;
    }

    function _aggregateClaimableRequests(
        RagaEpochVaultStorage storage ds,
        address user
    )
        internal
        view
        returns (uint256 totalShares, uint256 totalAssetsInWithdrawalToken)
    {
        WithrawalQueueLibrary.WithdrawalQueue storage queue = ds.userWithdrawalQueue[user];

        for (uint128 i = queue._head(); i < queue._tail(); i++) {
            IRagaEpochVault.WithdrawalRequest memory request = queue._peek(i);

            if (ds.epochs[request.epoch].status != IRagaEpochVault.EpochStatus.FINALIZED) {
                break;
            }

            totalShares += request.shares;
            totalAssetsInWithdrawalToken += _calculateAssets(ds, request.epoch, request.shares);
        }
    }

    function _calculateAssets(
        RagaEpochVaultStorage storage ds,
        uint32 epoch,
        uint256 shares
    )
        internal
        view
        returns (uint256)
    {
        IRagaEpochVault.EpochData storage epochData = ds.epochs[epoch];
        if (epochData.status != IRagaEpochVault.EpochStatus.FINALIZED) revert IRagaEpochVault.EpochNotFinalized();

        if (epochData.sharesBurned == 0) return 0;

        return shares * epochData.assetsWithdrawnInWithdrawalToken / epochData.sharesBurned;
    }

    function _getWithdrawalToken(RagaEpochVaultStorage storage ds) internal view returns (address) {
        return ds.withdrawalToken;
    }

    function _getExecutor(RagaEpochVaultStorage storage ds) internal view returns (address) {
        return ds.executor;
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

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

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

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

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

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

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

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

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

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

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

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

        emit Transfer(from, to, value);
    }

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

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

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

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

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

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

File 20 of 50 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(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.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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 {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 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 low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

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

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, 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 ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

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

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            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⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

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

File 21 of 50 : IOracle.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title IOracle
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface that oracles used by Morpho must implement.
/// @dev It is the user's responsibility to select markets with safe oracles.
interface IOracle {
    /// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.
    /// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in
    /// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals`
    /// decimals of precision.
    function price() external view returns (uint256);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

type Id is bytes32;

struct MarketParams {
    address loanToken;
    address collateralToken;
    address oracle;
    address irm;
    uint256 lltv;
}

/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
    uint256 supplyShares;
    uint128 borrowShares;
    uint128 collateral;
}

/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
    uint128 totalSupplyAssets;
    uint128 totalSupplyShares;
    uint128 totalBorrowAssets;
    uint128 totalBorrowShares;
    uint128 lastUpdate;
    uint128 fee;
}

struct Authorization {
    address authorizer;
    address authorized;
    bool isAuthorized;
    uint256 nonce;
    uint256 deadline;
}

struct Signature {
    uint8 v;
    bytes32 r;
    bytes32 s;
}

/// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoBase {
    /// @notice The EIP-712 domain separator.
    /// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on chains sharing the
    /// same chain id and on forks because the domain separator would be the same.
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice The owner of the contract.
    /// @dev It has the power to change the owner.
    /// @dev It has the power to set fees on markets and set the fee recipient.
    /// @dev It has the power to enable but not disable IRMs and LLTVs.
    function owner() external view returns (address);

    /// @notice The fee recipient of all markets.
    /// @dev The recipient receives the fees of a given market through a supply position on that market.
    function feeRecipient() external view returns (address);

    /// @notice Whether the `irm` is enabled.
    function isIrmEnabled(address irm) external view returns (bool);

    /// @notice Whether the `lltv` is enabled.
    function isLltvEnabled(uint256 lltv) external view returns (bool);

    /// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
    /// @dev Anyone is authorized to modify their own positions, regardless of this variable.
    function isAuthorized(address authorizer, address authorized) external view returns (bool);

    /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
    function nonce(address authorizer) external view returns (uint256);

    /// @notice Sets `newOwner` as `owner` of the contract.
    /// @dev Warning: No two-step transfer ownership.
    /// @dev Warning: The owner can be set to the zero address.
    function setOwner(address newOwner) external;

    /// @notice Enables `irm` as a possible IRM for market creation.
    /// @dev Warning: It is not possible to disable an IRM.
    function enableIrm(address irm) external;

    /// @notice Enables `lltv` as a possible LLTV for market creation.
    /// @dev Warning: It is not possible to disable a LLTV.
    function enableLltv(uint256 lltv) external;

    /// @notice Sets the `newFee` for the given market `marketParams`.
    /// @param newFee The new fee, scaled by WAD.
    /// @dev Warning: The recipient can be the zero address.
    function setFee(MarketParams memory marketParams, uint256 newFee) external;

    /// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
    /// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
    /// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
    /// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
    function setFeeRecipient(address newFeeRecipient) external;

    /// @notice Creates the market `marketParams`.
    /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
    /// Morpho behaves as expected:
    /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
    /// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
    /// burn functions are not supported.
    /// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
    /// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
    /// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
    /// - The IRM should not re-enter Morpho.
    /// - The oracle should return a price with the correct scaling.
    /// - The oracle price should not be able to change instantly such that the new price is less than the old price
    /// multiplied by LLTV*LIF. In particular, if the loan asset is a vault that can receive donations, the oracle
    /// should not price its shares using the AUM.
    /// @dev Here is a list of assumptions on the market's dependencies which, if broken, could break Morpho's liveness
    /// properties (funds could get stuck):
    /// - The token should not revert on `transfer` and `transferFrom` if balances and approvals are right.
    /// - The amount of assets supplied and borrowed should not be too high (max ~1e32), otherwise the number of shares
    /// might not fit within 128 bits.
    /// - The IRM should not revert on `borrowRate`.
    /// - The IRM should not return a very high borrow rate (otherwise the computation of `interest` in
    /// `_accrueInterest` can overflow).
    /// - The oracle should not revert `price`.
    /// - The oracle should not return a very high price (otherwise the computation of `maxBorrow` in `_isHealthy` or of
    /// `assetsRepaid` in `liquidate` can overflow).
    /// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
    /// the point where `totalBorrowShares` is very large and borrowing overflows.
    function createMarket(MarketParams memory marketParams) external;

    /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoSupply` function with the given `data`.
    /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
    /// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
    /// amount of shares is given for full compatibility and precision.
    /// @dev Supplying a large amount can revert for overflow.
    /// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
    /// Consider using the `assets` parameter to avoid this.
    /// @param marketParams The market to supply assets to.
    /// @param assets The amount of assets to supply.
    /// @param shares The amount of shares to mint.
    /// @param onBehalf The address that will own the increased supply position.
    /// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
    /// @return assetsSupplied The amount of assets supplied.
    /// @return sharesSupplied The amount of shares minted.
    function supply(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);

    /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
    /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
    /// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
    /// conversion roundings between shares and assets.
    /// @param marketParams The market to withdraw assets from.
    /// @param assets The amount of assets to withdraw.
    /// @param shares The amount of shares to burn.
    /// @param onBehalf The address of the owner of the supply position.
    /// @param receiver The address that will receive the withdrawn assets.
    /// @return assetsWithdrawn The amount of assets withdrawn.
    /// @return sharesWithdrawn The amount of shares burned.
    function withdraw(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);

    /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
    /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
    /// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
    /// given for full compatibility and precision.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Borrowing a large amount can revert for overflow.
    /// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
    /// Consider using the `assets` parameter to avoid this.
    /// @param marketParams The market to borrow assets from.
    /// @param assets The amount of assets to borrow.
    /// @param shares The amount of shares to mint.
    /// @param onBehalf The address that will own the increased borrow position.
    /// @param receiver The address that will receive the borrowed assets.
    /// @return assetsBorrowed The amount of assets borrowed.
    /// @return sharesBorrowed The amount of shares minted.
    function borrow(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);

    /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoRepay` function with the given `data`.
    /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
    /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
    /// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
    /// roundings between shares and assets.
    /// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
    /// @param marketParams The market to repay assets to.
    /// @param assets The amount of assets to repay.
    /// @param shares The amount of shares to burn.
    /// @param onBehalf The address of the owner of the debt position.
    /// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
    /// @return assetsRepaid The amount of assets repaid.
    /// @return sharesRepaid The amount of shares burned.
    function repay(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);

    /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoSupplyCollateral` function with the given `data`.
    /// @dev Interest are not accrued since it's not required and it saves gas.
    /// @dev Supplying a large amount can revert for overflow.
    /// @param marketParams The market to supply collateral to.
    /// @param assets The amount of collateral to supply.
    /// @param onBehalf The address that will own the increased collateral position.
    /// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
    function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
        external;

    /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
    /// @param marketParams The market to withdraw collateral from.
    /// @param assets The amount of collateral to withdraw.
    /// @param onBehalf The address of the owner of the collateral position.
    /// @param receiver The address that will receive the collateral assets.
    function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
        external;

    /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
    /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
    /// `onMorphoLiquidate` function with the given `data`.
    /// @dev Either `seizedAssets` or `repaidShares` should be zero.
    /// @dev Seizing more than the collateral balance will underflow and revert without any error message.
    /// @dev Repaying more than the borrow balance will underflow and revert without any error message.
    /// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
    /// @param marketParams The market of the position.
    /// @param borrower The owner of the position.
    /// @param seizedAssets The amount of collateral to seize.
    /// @param repaidShares The amount of shares to repay.
    /// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
    /// @return The amount of assets seized.
    /// @return The amount of assets repaid.
    function liquidate(
        MarketParams memory marketParams,
        address borrower,
        uint256 seizedAssets,
        uint256 repaidShares,
        bytes memory data
    ) external returns (uint256, uint256);

    /// @notice Executes a flash loan.
    /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
    /// markets combined, plus donations).
    /// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
    /// - `flashFee` is zero.
    /// - `maxFlashLoan` is the token's balance of this contract.
    /// - The receiver of `assets` is the caller.
    /// @param token The token to flash loan.
    /// @param assets The amount of assets to flash loan.
    /// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
    function flashLoan(address token, uint256 assets, bytes calldata data) external;

    /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
    /// @param authorized The authorized address.
    /// @param newIsAuthorized The new authorization status.
    function setAuthorization(address authorized, bool newIsAuthorized) external;

    /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
    /// @dev Warning: Reverts if the signature has already been submitted.
    /// @dev The signature is malleable, but it has no impact on the security here.
    /// @dev The nonce is passed as argument to be able to revert with a different error message.
    /// @param authorization The `Authorization` struct.
    /// @param signature The signature.
    function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;

    /// @notice Accrues interest for the given market `marketParams`.
    function accrueInterest(MarketParams memory marketParams) external;

    /// @notice Returns the data stored on the different `slots`.
    function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
}

/// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoStaticTyping is IMorphoBase {
    /// @notice The state of the position of `user` on the market corresponding to `id`.
    /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
    /// accrual.
    function position(Id id, address user)
        external
        view
        returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);

    /// @notice The state of the market corresponding to `id`.
    /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
    /// accrual.
    function market(Id id)
        external
        view
        returns (
            uint128 totalSupplyAssets,
            uint128 totalSupplyShares,
            uint128 totalBorrowAssets,
            uint128 totalBorrowShares,
            uint128 lastUpdate,
            uint128 fee
        );

    /// @notice The market params corresponding to `id`.
    /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
    /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
    function idToMarketParams(Id id)
        external
        view
        returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
}

/// @title IMorpho
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
interface IMorpho is IMorphoBase {
    /// @notice The state of the position of `user` on the market corresponding to `id`.
    /// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
    /// accrual.
    function position(Id id, address user) external view returns (Position memory p);

    /// @notice The state of the market corresponding to `id`.
    /// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
    /// interest accrual.
    function market(Id id) external view returns (Market memory m);

    /// @notice The market params corresponding to `id`.
    /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
    /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
    function idToMarketParams(Id id) external view returns (MarketParams memory);
}

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

import {IMorpho, Id} from "../../interfaces/IMorpho.sol";
import {MorphoStorageLib} from "./MorphoStorageLib.sol";

/// @title MorphoLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Helper library to access Morpho storage variables.
/// @dev Warning: Supply and borrow getters may return outdated values that do not include accrued interest.
library MorphoLib {
    function supplyShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.positionSupplySharesSlot(id, user));
        return uint256(morpho.extSloads(slot)[0]);
    }

    function borrowShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function collateral(IMorpho morpho, Id id, address user) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function totalSupplyAssets(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function totalSupplyShares(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function totalBorrowAssets(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function totalBorrowShares(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function lastUpdate(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function fee(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function _array(bytes32 x) private pure returns (bytes32[] memory) {
        bytes32[] memory res = new bytes32[](1);
        res[0] = x;
        return res;
    }
}

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

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

/// @title SharesMathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Shares management library.
/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
library SharesMathLib {
    using MathLib for uint256;

    /// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
    /// high precision computations.
    /// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
    /// stays low enough not to inflate these assets to a significant value.
    /// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
    uint256 internal constant VIRTUAL_SHARES = 1e6;

    /// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
    /// empty.
    uint256 internal constant VIRTUAL_ASSETS = 1;

    /// @dev Calculates the value of `assets` quoted in shares, rounding down.
    function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
    }

    /// @dev Calculates the value of `shares` quoted in assets, rounding down.
    function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
    }

    /// @dev Calculates the value of `assets` quoted in shares, rounding up.
    function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
    }

    /// @dev Calculates the value of `shares` quoted in assets, rounding up.
    function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
    }
}

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

import {Id, MarketParams} from "../interfaces/IMorpho.sol";

/// @title MarketParamsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to convert a market to its id.
library MarketParamsLib {
    /// @notice The length of the data used to compute the id of a market.
    /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
    uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;

    /// @notice Returns the id of the market `marketParams`.
    function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
        assembly ("memory-safe") {
            marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
        }
    }
}

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

import {Id, MarketParams, Market, IMorpho} from "../../interfaces/IMorpho.sol";
import {IIrm} from "../../interfaces/IIrm.sol";

import {MathLib} from "../MathLib.sol";
import {UtilsLib} from "../UtilsLib.sol";
import {MorphoLib} from "./MorphoLib.sol";
import {SharesMathLib} from "../SharesMathLib.sol";
import {MarketParamsLib} from "../MarketParamsLib.sol";

/// @title MorphoBalancesLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Helper library exposing getters with the expected value after interest accrual.
/// @dev This library is not used in Morpho itself and is intended to be used by integrators.
/// @dev The getter to retrieve the expected total borrow shares is not exposed because interest accrual does not apply
/// to it. The value can be queried directly on Morpho using `totalBorrowShares`.
library MorphoBalancesLib {
    using MathLib for uint256;
    using MathLib for uint128;
    using UtilsLib for uint256;
    using MorphoLib for IMorpho;
    using SharesMathLib for uint256;
    using MarketParamsLib for MarketParams;

    /// @notice Returns the expected market balances of a market after having accrued interest.
    /// @return The expected total supply assets.
    /// @return The expected total supply shares.
    /// @return The expected total borrow assets.
    /// @return The expected total borrow shares.
    function expectedMarketBalances(IMorpho morpho, MarketParams memory marketParams)
        internal
        view
        returns (uint256, uint256, uint256, uint256)
    {
        Id id = marketParams.id();
        Market memory market = morpho.market(id);

        uint256 elapsed = block.timestamp - market.lastUpdate;

        // Skipped if elapsed == 0 or totalBorrowAssets == 0 because interest would be null, or if irm == address(0).
        if (elapsed != 0 && market.totalBorrowAssets != 0 && marketParams.irm != address(0)) {
            uint256 borrowRate = IIrm(marketParams.irm).borrowRateView(marketParams, market);
            uint256 interest = market.totalBorrowAssets.wMulDown(borrowRate.wTaylorCompounded(elapsed));
            market.totalBorrowAssets += interest.toUint128();
            market.totalSupplyAssets += interest.toUint128();

            if (market.fee != 0) {
                uint256 feeAmount = interest.wMulDown(market.fee);
                // The fee amount is subtracted from the total supply in this calculation to compensate for the fact
                // that total supply is already updated.
                uint256 feeShares =
                    feeAmount.toSharesDown(market.totalSupplyAssets - feeAmount, market.totalSupplyShares);
                market.totalSupplyShares += feeShares.toUint128();
            }
        }

        return (market.totalSupplyAssets, market.totalSupplyShares, market.totalBorrowAssets, market.totalBorrowShares);
    }

    /// @notice Returns the expected total supply assets of a market after having accrued interest.
    function expectedTotalSupplyAssets(IMorpho morpho, MarketParams memory marketParams)
        internal
        view
        returns (uint256 totalSupplyAssets)
    {
        (totalSupplyAssets,,,) = expectedMarketBalances(morpho, marketParams);
    }

    /// @notice Returns the expected total borrow assets of a market after having accrued interest.
    function expectedTotalBorrowAssets(IMorpho morpho, MarketParams memory marketParams)
        internal
        view
        returns (uint256 totalBorrowAssets)
    {
        (,, totalBorrowAssets,) = expectedMarketBalances(morpho, marketParams);
    }

    /// @notice Returns the expected total supply shares of a market after having accrued interest.
    function expectedTotalSupplyShares(IMorpho morpho, MarketParams memory marketParams)
        internal
        view
        returns (uint256 totalSupplyShares)
    {
        (, totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);
    }

    /// @notice Returns the expected supply assets balance of `user` on a market after having accrued interest.
    /// @dev Warning: Wrong for `feeRecipient` because their supply shares increase is not taken into account.
    function expectedSupplyAssets(IMorpho morpho, MarketParams memory marketParams, address user)
        internal
        view
        returns (uint256)
    {
        Id id = marketParams.id();
        uint256 supplyShares = morpho.supplyShares(id, user);
        (uint256 totalSupplyAssets, uint256 totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);

        return supplyShares.toAssetsDown(totalSupplyAssets, totalSupplyShares);
    }

    /// @notice Returns the expected borrow assets balance of `user` on a market after having accrued interest.
    /// @dev Warning: The expected balance is rounded up, so it may be greater than the market's expected total borrow
    /// assets.
    function expectedBorrowAssets(IMorpho morpho, MarketParams memory marketParams, address user)
        internal
        view
        returns (uint256)
    {
        Id id = marketParams.id();
        uint256 borrowShares = morpho.borrowShares(id, user);
        (,, uint256 totalBorrowAssets, uint256 totalBorrowShares) = expectedMarketBalances(morpho, marketParams);

        return borrowShares.toAssetsUp(totalBorrowAssets, totalBorrowShares);
    }
}

File 27 of 50 : ConstantsLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @dev The maximum fee a market can have (25%).
uint256 constant MAX_FEE = 0.25e18;

/// @dev Oracle price scale.
uint256 constant ORACLE_PRICE_SCALE = 1e36;

/// @dev Liquidation cursor.
uint256 constant LIQUIDATION_CURSOR = 0.3e18;

/// @dev Max liquidation incentive factor.
uint256 constant MAX_LIQUIDATION_INCENTIVE_FACTOR = 1.15e18;

/// @dev The EIP-712 typeHash for EIP712Domain.
bytes32 constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");

/// @dev The EIP-712 typeHash for Authorization.
bytes32 constant AUTHORIZATION_TYPEHASH =
    keccak256("Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)");

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

abstract contract IPriceFeed {
    error TokenPairMissing();

    // Gets token price in USD (WAD)
    function _getTokenBalanceInUSD(address src, uint256 value) internal view virtual returns (uint256);

    // Converts token src to token dst
    function _convertTokenBalance(address src, address dst, uint256 value) internal view virtual returns (uint256) {
        if (src == dst || value == 0) return value;
        revert TokenPairMissing();
    }

    function getTokenBalanceInUSD(address src, uint256 value) external view returns (uint256) {
        return _getTokenBalanceInUSD(src, value);
    }

    // Converts token src to token dst
    function convertTokenBalance(address src, address dst, uint256 value) external view returns (uint256) {
        return _convertTokenBalance(src, dst, value);
    }
}

File 29 of 50 : Constants.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;

library Constants {
    uint64 internal constant TRANSACTION_CODE_STANDARD_DEPOSIT = 1001; // Deposit for Permissionless Strategy
    uint64 internal constant TRANSACTION_CODE_LEVERAGED_DEPOSIT = 1002; // Deposit for Looping Borrow-Lending Strategy
    uint64 internal constant TRANSACTION_CODE_REPAY = 1003; // Deposit for Borrow-Lending Repay Strategy
    uint64 internal constant TRANSACTION_CODE_INITIAL_DEPOSIT = 1004; // Deposit at time of initial position creation

    uint64 internal constant TRANSACTION_CODE_STANDARD_WITHDRAW = 2001; // Withdrawal for Permissionless Strategy
    uint64 internal constant TRANSACTION_CODE_WITHDRAW_ALL = 2010; // Withdrawal all the assets (used to close
    // positions)
    uint64 internal constant TRANSACTION_CODE_WITHDRAW_BORROW = 2002; // Withdrawal for Borrow Lending Borrowed Token

    // Deposit user's asset in flash loan callback
    uint64 internal constant TRANSACTION_CODE_FLASH_LOAN_DEPOSIT = 3001;
    // Withdraw user's asset in flash loan callback
    uint64 internal constant TRANSACTION_CODE_FLASH_LOAN_WITHDRAW = 3002;
    // Withdraw All user's asset in flash loan callback
    uint64 internal constant TRANSACTION_CODE_FLASH_LOAN_WITHDRAW_ALL = 3003;

    uint256 constant DOLLAR_BALANCE_PRECISION = 18;
    uint256 constant WEI_DECIMALS = 18;
    uint256 constant WAD = 1e18;
}

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

import { IMorpho, MarketParams } from "@morpho-blue/src/interfaces/IMorpho.sol";

import { IPriceFeed } from "../../../../../interfaces/shared/IPriceFeed.sol";
import { IMorphoCommons } from "../../../../../interfaces/positions/BorrowLending/IMorphoCommons.sol";
import { IFlashLoanUtils } from "../../../../../interfaces/positions/BorrowLending/IFlashLoanUtils.sol";

import { ZeroAddress } from "../../../../../utils/Helpers.sol";

abstract contract BaseMorphoCommons is IMorphoCommons, IFlashLoanUtils {
    error PreviewRiskExceeded();

    bytes32 constant MORPHO_STORAGE_POSITION = keccak256("morpho.commons.storage") & ~bytes32(uint256(0xff));

    function _getMorphoCommonsConfig() internal view virtual returns (MorphoStrategyConfig memory) {
        MorphoCommonsStorage memory morphoCommons = _getMorphoCommonsStorage();
        address priceFeed = address(_getBorrowLendingStorage().priceFeed);

        return MorphoStrategyConfig({ morphoCommons: morphoCommons, priceFeed: priceFeed });
    }

    function _setMorphoCommonsStorage(MorphoStrategyConfig memory config) internal virtual {
        MorphoCommonsStorage storage s = _getMorphoCommonsStorage();

        if (address(config.morphoCommons.morpho) == address(0)) revert ZeroAddress();
        if (config.priceFeed == address(0)) revert ZeroAddress();

        s.marketParams = config.morphoCommons.marketParams;
        s.morpho = config.morphoCommons.morpho;

        _setBorrowLendingStorage(
            BorrowLendingUtilStorage({
                borrowToken: config.morphoCommons.marketParams.loanToken,
                collateralToken: config.morphoCommons.marketParams.collateralToken,
                priceFeed: IPriceFeed(config.priceFeed)
            })
        );
    }

    function _getMorphoCommonsStorage() internal pure virtual returns (MorphoCommonsStorage storage s) {
        bytes32 slot = MORPHO_STORAGE_POSITION;
        assembly {
            s.slot := slot
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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 Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @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
     * {Errors.FailedCall} 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 Errors.InsufficientBalance(address(this).balance, value);
        }
        (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 {Errors.FailedCall}) 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 {Errors.FailedCall} 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 {Errors.FailedCall}.
     */
    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
            assembly ("memory-safe") {
                revert(add(returndata, 0x20), mload(returndata))
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

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

import { IPriceFeed } from "../../shared/IPriceFeed.sol";
import { ZeroAddress } from "../../../utils/Helpers.sol";

/// @dev Borrow Lending Utils
abstract contract IBorrowLendingUtils {
    bytes32 constant BORROW_LENDING_UTILS_STORAGE_POSITION =
        keccak256("borrow.lending.utils.storage") & ~bytes32(uint256(0xff));

    struct BorrowLendingUtilStorage {
        address borrowToken;
        address collateralToken;
        IPriceFeed priceFeed;
    }

    function _riskInternal(address user, uint256 baseValue) internal view virtual returns (uint256);

    /// @dev calculate TP -> borrow / collateral * 1.04
    function _previewRiskInternal(
        uint256 baseValue,
        uint256 totalCollateral,
        uint256 totalBorrow
    )
        internal
        view
        virtual
        returns (uint256);

    // get balance of borrowed token (with interest) (in borrowed Token)
    function borrowBalance(address user) public view virtual returns (uint256);

    // get balance of collateral token (in collateral Token)
    function collateralBalance(address user) public view virtual returns (uint256);

    /// @return updatedBorrowAmount = borrowAmount + fee
    function _previewBorrow(uint256 borrowAmount) internal view virtual returns (uint256);

    /// @notice Returns balance in terms of collateral token (collateral - debt)
    function _balanceInCollateralToken(address user) internal view virtual returns (uint256);

    /**
     * @dev Use this function to add collateral or borrow amount
     *     @return collateralAdded - Collateral Added to Borrow Lending Pool
     *     @return amountBorrowed - Amount borrowed, this could be greater than debtToBorrow if fee is part of borrow
     */
    function _drawDebt(
        address user,
        uint256 collateralToAdd,
        uint256 debtToBorrow
    )
        internal
        virtual
        returns (uint256, uint256);

    /**
     * @dev Use this function to repay debt or pull out collateral post repayment
     *     @param repayReceipent - Repay remaining amount unpaid back to repayer
     *     @return collateralToPull - Collateral pulled out of Borrow Lending
     *     @return debtRepaid - Debt repaid (could be less than debtToRepay if remaining debt is less than amount
     * provided)
     */
    function _repayDebt(
        address user,
        uint256 collateralToPull,
        uint256 debtToRepay,
        address repayReceipent
    )
        internal
        virtual
        returns (uint256, uint256);

    function _setBorrowLendingStorage(BorrowLendingUtilStorage memory config) internal virtual {
        BorrowLendingUtilStorage storage s = _getBorrowLendingStorage();

        if (config.borrowToken == address(0)) revert ZeroAddress();
        if (config.collateralToken == address(0)) revert ZeroAddress();
        if (address(config.priceFeed) == address(0)) revert ZeroAddress();

        s.borrowToken = config.borrowToken;
        s.collateralToken = config.collateralToken;
        s.priceFeed = config.priceFeed;
    }

    function _getBorrowLendingStorage() internal pure virtual returns (BorrowLendingUtilStorage storage s) {
        bytes32 slot = BORROW_LENDING_UTILS_STORAGE_POSITION;
        assembly {
            s.slot := slot
        }
    }
}

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

interface IStrategyManager {
    struct StrategyConfig {
        address underlying;
        address primaryDepositToken; // useful in case of swapping token to primary token for deposits
        address primaryWithdrawalToken; // useful in case of swapping token to primary token for withdrawals
        bool depositEnabled;
        bool loopingEnabled;
    }

    // event
    event StrategyAdded(
        address strategyAddress,
        address primaryDepositToken,
        address primaryWithdrawalToken,
        address underlying,
        bool loopingEnabled
    );
    event StrategyRemoved(address strategyAddress);

    event StrategyDepositFlagUpdated(address strategyAddress, bool flag);
    event StrategyTransactionCodeUpdated(address strategyAddress, uint64 transactionCode, bool flag);
    event StrategyTokenWhitelistingUpdated(address strategyAddress, address tokenAddress, uint64 purpose, bool flag);

    // error
    error InvalidStrategy();
    error StrategyAlreadyExist(address strategy);
    error StrategyDoesNotExist(address strategy);
    error StrategyTokenNotWhitelisted(address strategy, address token, uint64 purpose);

    // read-only function
    function isDepositEnabled(address strategyAddress) external view returns (bool);
    function getStrategyConfig(address strategyAddress) external view returns (StrategyConfig memory);
    function assertStrategyExists(address strategyAddress) external view;
    function isTransactionCodeWhitelisted(address strategyAddress, uint64 transactionCode) external view returns (bool);
    function assertStrategyTokenWhitelisted(
        address strategyAddress,
        address tokenAddress,
        uint64 purpose
    )
        external
        view;

    // write-only functions
    function addStrategy(
        address strategyAddress,
        address primaryDepositToken,
        address primaryWithdrawalToken,
        address underlying,
        bool loopingEnabled
    )
        external;
    function removeStrategy(address strategyAddress) external;
    function upsertDepositEnabled(address strategyAddress, bool flag) external;
    function upsertTransactionCode(address strategyAddress, uint64 transactionCode, bool flag) external;
    function updateTokenWhitelisting(address strategyAddress, address tokenAddress, uint64 purpose, bool flag) external;
}

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

interface IVaultManager {
    struct VaultStrategyConfig {
        address user;
        address strategy;
        uint64 iteration;
        uint256 lendingThreshold;
        bool depositEnabled;
    }

    // event
    event VaultGlobalDepositFlagUpdated(address sender, bool flag);
    event VaultDepositFlagUpdated(address vault, address sender, bool flag);

    event VaultRegistered(address user, address vault, address strategy, uint256 lendingThreshold, uint64 iteration);

    event VaultRegistryUpdated(address sender, address vaultRegistry);
    event PositionManagerUpdated(address sender, address positionManager);
    event MorphoBlueCallerUpdated(address sender, address morphoBlueCaller);

    // errors
    error InvalidStrategyMapping();
    error VaultNotRegistered();

    // read-only functions
    function assertValidStrategy(address vault, address strategy) external view;
    function getStrategyManager() external view returns (address);
    function getPositionManager() external view returns (address);
    function getVaultStrategyConfig(address vault) external view returns (VaultStrategyConfig memory);
    function getDepositEnabled(address vault) external view returns (bool);
    function getMorphoBlueCaller() external view returns (address);

    // write-only functions
    function upsertGlobalDepositFlag(bool flag) external;
    function registerVault(
        address user,
        address vault,
        address strategy,
        uint256 lendingThreshold,
        uint64 iteration
    )
        external;
    function upsertDepositEnabled(address vault, bool flag) external;
}

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 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-3.0
pragma solidity 0.8.28;

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

library WithrawalQueueLibrary {
    struct WithdrawalQueue {
        uint128 head;
        uint128 tail;
        mapping(uint128 => IRagaEpochVault.WithdrawalRequest) requestMap;
    }

    function _head(WithdrawalQueue storage queue) internal view returns (uint128) {
        return queue.head;
    }

    function _tail(WithdrawalQueue storage queue) internal view returns (uint128) {
        return queue.tail;
    }

    function _length(WithdrawalQueue storage queue) internal view returns (uint128) {
        return queue.tail - queue.head;
    }

    function _isEmpty(WithdrawalQueue storage queue) internal view returns (bool) {
        return queue.tail == queue.head;
    }

    function _enqueue(WithdrawalQueue storage queue, IRagaEpochVault.WithdrawalRequest memory request) internal {
        uint128 idx = queue.tail;
        queue.requestMap[idx] = request;
        unchecked {
            queue.tail = idx + 1;
        }
    }

    function _dequeueFront(WithdrawalQueue storage queue) internal returns (IRagaEpochVault.WithdrawalRequest memory) {
        require(queue.tail > queue.head, "Queue: empty");

        uint128 idx = queue.head;
        IRagaEpochVault.WithdrawalRequest memory request = queue.requestMap[idx];

        delete queue.requestMap[idx];
        unchecked {
            queue.head = idx + 1;
        }

        return request;
    }

    function _dequeueBack(WithdrawalQueue storage queue) internal returns (IRagaEpochVault.WithdrawalRequest memory) {
        require(queue.tail > queue.head, "Queue: empty");

        uint128 idx = queue.tail - 1;
        IRagaEpochVault.WithdrawalRequest memory request = queue.requestMap[idx];

        delete queue.requestMap[idx];
        unchecked {
            queue.tail = idx;
        }

        return request;
    }

    /**
     * @notice Returns a mutable reference to the last element in the queue.
     */
    function _backMut(WithdrawalQueue storage queue) internal view returns (IRagaEpochVault.WithdrawalRequest storage) {
        require(queue.tail > queue.head, "Queue: empty");
        uint128 idx = queue.tail - 1;
        return queue.requestMap[idx];
    }

    function _peek(
        WithdrawalQueue storage queue,
        uint128 idx
    )
        internal
        view
        returns (IRagaEpochVault.WithdrawalRequest memory)
    {
        require(idx >= queue.head && idx < queue.tail, "Queue: index out of bounds");
        return queue.requestMap[idx];
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

File 40 of 50 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

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

import {Id} from "../../interfaces/IMorpho.sol";

/// @title MorphoStorageLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Helper library exposing getters to access Morpho storage variables' slot.
/// @dev This library is not used in Morpho itself and is intended to be used by integrators.
library MorphoStorageLib {
    /* SLOTS */

    uint256 internal constant OWNER_SLOT = 0;
    uint256 internal constant FEE_RECIPIENT_SLOT = 1;
    uint256 internal constant POSITION_SLOT = 2;
    uint256 internal constant MARKET_SLOT = 3;
    uint256 internal constant IS_IRM_ENABLED_SLOT = 4;
    uint256 internal constant IS_LLTV_ENABLED_SLOT = 5;
    uint256 internal constant IS_AUTHORIZED_SLOT = 6;
    uint256 internal constant NONCE_SLOT = 7;
    uint256 internal constant ID_TO_MARKET_PARAMS_SLOT = 8;

    /* SLOT OFFSETS */

    uint256 internal constant LOAN_TOKEN_OFFSET = 0;
    uint256 internal constant COLLATERAL_TOKEN_OFFSET = 1;
    uint256 internal constant ORACLE_OFFSET = 2;
    uint256 internal constant IRM_OFFSET = 3;
    uint256 internal constant LLTV_OFFSET = 4;

    uint256 internal constant SUPPLY_SHARES_OFFSET = 0;
    uint256 internal constant BORROW_SHARES_AND_COLLATERAL_OFFSET = 1;

    uint256 internal constant TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET = 0;
    uint256 internal constant TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET = 1;
    uint256 internal constant LAST_UPDATE_AND_FEE_OFFSET = 2;

    /* GETTERS */

    function ownerSlot() internal pure returns (bytes32) {
        return bytes32(OWNER_SLOT);
    }

    function feeRecipientSlot() internal pure returns (bytes32) {
        return bytes32(FEE_RECIPIENT_SLOT);
    }

    function positionSupplySharesSlot(Id id, address user) internal pure returns (bytes32) {
        return bytes32(
            uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT))))) + SUPPLY_SHARES_OFFSET
        );
    }

    function positionBorrowSharesAndCollateralSlot(Id id, address user) internal pure returns (bytes32) {
        return bytes32(
            uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT)))))
                + BORROW_SHARES_AND_COLLATERAL_OFFSET
        );
    }

    function marketTotalSupplyAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET);
    }

    function marketTotalBorrowAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET);
    }

    function marketLastUpdateAndFeeSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + LAST_UPDATE_AND_FEE_OFFSET);
    }

    function isIrmEnabledSlot(address irm) internal pure returns (bytes32) {
        return keccak256(abi.encode(irm, IS_IRM_ENABLED_SLOT));
    }

    function isLltvEnabledSlot(uint256 lltv) internal pure returns (bytes32) {
        return keccak256(abi.encode(lltv, IS_LLTV_ENABLED_SLOT));
    }

    function isAuthorizedSlot(address authorizer, address authorizee) internal pure returns (bytes32) {
        return keccak256(abi.encode(authorizee, keccak256(abi.encode(authorizer, IS_AUTHORIZED_SLOT))));
    }

    function nonceSlot(address authorizer) internal pure returns (bytes32) {
        return keccak256(abi.encode(authorizer, NONCE_SLOT));
    }

    function idToLoanTokenSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LOAN_TOKEN_OFFSET);
    }

    function idToCollateralTokenSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + COLLATERAL_TOKEN_OFFSET);
    }

    function idToOracleSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + ORACLE_OFFSET);
    }

    function idToIrmSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + IRM_OFFSET);
    }

    function idToLltvSlot(Id id) internal pure returns (bytes32) {
        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LLTV_OFFSET);
    }
}

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

uint256 constant WAD = 1e18;

/// @title MathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to manage fixed-point arithmetic.
library MathLib {
    /// @dev Returns (`x` * `y`) / `WAD` rounded down.
    function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD);
    }

    /// @dev Returns (`x` * `WAD`) / `y` rounded down.
    function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y);
    }

    /// @dev Returns (`x` * `WAD`) / `y` rounded up.
    function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y);
    }

    /// @dev Returns (`x` * `y`) / `d` rounded down.
    function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
        return (x * y) / d;
    }

    /// @dev Returns (`x` * `y`) / `d` rounded up.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
        return (x * y + (d - 1)) / d;
    }

    /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
    /// continuous compound interest rate.
    function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
        uint256 firstTerm = x * n;
        uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
        uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);

        return firstTerm + secondTerm + thirdTerm;
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {MarketParams, Market} from "./IMorpho.sol";

/// @title IIrm
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.
interface IIrm {
    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.
    /// @dev Assumes that `market` corresponds to `marketParams`.
    function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);

    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any
    /// storage.
    /// @dev Assumes that `market` corresponds to `marketParams`.
    function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
}

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

import {ErrorsLib} from "../libraries/ErrorsLib.sol";

/// @title UtilsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library exposing helpers.
/// @dev Inspired by https://github.com/morpho-org/morpho-utils.
library UtilsLib {
    /// @dev Returns true if there is exactly one zero among `x` and `y`.
    function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {
        assembly {
            z := xor(iszero(x), iszero(y))
        }
    }

    /// @dev Returns the min of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns `x` safely cast to uint128.
    function toUint128(uint256 x) internal pure returns (uint128) {
        require(x <= type(uint128).max, ErrorsLib.MAX_UINT128_EXCEEDED);
        return uint128(x);
    }

    /// @dev Returns max(0, x - y).
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }
}

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

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

/// @dev Flash Loan Utility
abstract contract IFlashLoanUtils is IBorrowLendingUtils {
    function _onFlashLoan(uint256 assets, bytes memory data) internal virtual;

    /// @dev Use this function to payback complete borrowed amount
    function _repayAll(address user, uint256 amount, address repayRecipent) internal virtual returns (uint256);
}

File 46 of 50 : Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

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

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

File 47 of 50 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

File 48 of 50 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

File 49 of 50 : ErrorsLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @title ErrorsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library exposing error messages.
library ErrorsLib {
    /// @notice Thrown when the caller is not the owner.
    string internal constant NOT_OWNER = "not owner";

    /// @notice Thrown when the LLTV to enable exceeds the maximum LLTV.
    string internal constant MAX_LLTV_EXCEEDED = "max LLTV exceeded";

    /// @notice Thrown when the fee to set exceeds the maximum fee.
    string internal constant MAX_FEE_EXCEEDED = "max fee exceeded";

    /// @notice Thrown when the value is already set.
    string internal constant ALREADY_SET = "already set";

    /// @notice Thrown when the IRM is not enabled at market creation.
    string internal constant IRM_NOT_ENABLED = "IRM not enabled";

    /// @notice Thrown when the LLTV is not enabled at market creation.
    string internal constant LLTV_NOT_ENABLED = "LLTV not enabled";

    /// @notice Thrown when the market is already created.
    string internal constant MARKET_ALREADY_CREATED = "market already created";

    /// @notice Thrown when a token to transfer doesn't have code.
    string internal constant NO_CODE = "no code";

    /// @notice Thrown when the market is not created.
    string internal constant MARKET_NOT_CREATED = "market not created";

    /// @notice Thrown when not exactly one of the input amount is zero.
    string internal constant INCONSISTENT_INPUT = "inconsistent input";

    /// @notice Thrown when zero assets is passed as input.
    string internal constant ZERO_ASSETS = "zero assets";

    /// @notice Thrown when a zero address is passed as input.
    string internal constant ZERO_ADDRESS = "zero address";

    /// @notice Thrown when the caller is not authorized to conduct an action.
    string internal constant UNAUTHORIZED = "unauthorized";

    /// @notice Thrown when the collateral is insufficient to `borrow` or `withdrawCollateral`.
    string internal constant INSUFFICIENT_COLLATERAL = "insufficient collateral";

    /// @notice Thrown when the liquidity is insufficient to `withdraw` or `borrow`.
    string internal constant INSUFFICIENT_LIQUIDITY = "insufficient liquidity";

    /// @notice Thrown when the position to liquidate is healthy.
    string internal constant HEALTHY_POSITION = "position is healthy";

    /// @notice Thrown when the authorization signature is invalid.
    string internal constant INVALID_SIGNATURE = "invalid signature";

    /// @notice Thrown when the authorization signature is expired.
    string internal constant SIGNATURE_EXPIRED = "signature expired";

    /// @notice Thrown when the nonce is invalid.
    string internal constant INVALID_NONCE = "invalid nonce";

    /// @notice Thrown when a token transfer reverted.
    string internal constant TRANSFER_REVERTED = "transfer reverted";

    /// @notice Thrown when a token transfer returned false.
    string internal constant TRANSFER_RETURNED_FALSE = "transfer returned false";

    /// @notice Thrown when a token transferFrom reverted.
    string internal constant TRANSFER_FROM_REVERTED = "transferFrom reverted";

    /// @notice Thrown when a token transferFrom returned false
    string internal constant TRANSFER_FROM_RETURNED_FALSE = "transferFrom returned false";

    /// @notice Thrown when the maximum uint128 is exceeded.
    string internal constant MAX_UINT128_EXCEEDED = "max uint128 exceeded";
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@spectra-core/src/=lib/spectra-core/src/",
    "@pythnetwork/pyth-sdk-solidity/=node_modules/@pythnetwork/pyth-sdk-solidity/",
    "hardhat/=node_modules/hardhat/",
    "@morpho-blue/=lib/morpho-blue/",
    "ds-test/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "morpho-blue/=lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin-erc20-basic/=lib/spectra-core/lib/openzeppelin-contracts/contracts/token/ERC20/",
    "openzeppelin-erc20-extensions/=lib/spectra-core/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/",
    "openzeppelin-erc20/=lib/spectra-core/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "openzeppelin-math/=lib/spectra-core/lib/openzeppelin-contracts/contracts/utils/math/",
    "openzeppelin-proxy/=lib/spectra-core/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/",
    "openzeppelin-utils/=lib/spectra-core/lib/openzeppelin-contracts/contracts/utils/",
    "solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
    "spectra-core/=lib/spectra-core/",
    "v3-core/=lib/v3-core/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 50
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"optimizerVault","type":"address"},{"internalType":"address","name":"positionManager","type":"address"},{"components":[{"components":[{"components":[{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"address","name":"irm","type":"address"},{"internalType":"uint256","name":"lltv","type":"uint256"}],"internalType":"struct MarketParams","name":"marketParams","type":"tuple"},{"internalType":"contract IMorpho","name":"morpho","type":"address"}],"internalType":"struct IMorphoCommons.MorphoCommonsStorage","name":"morphoCommons","type":"tuple"},{"internalType":"address","name":"priceFeed","type":"address"}],"internalType":"struct IMorphoCommons.MorphoStrategyConfig","name":"strategyConfig","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint32","name":"transactionType","type":"uint32"}],"name":"InvalidTransactionType","type":"error"},{"inputs":[],"name":"NoEpochProcessing","type":"error"},{"inputs":[],"name":"NoPrimaryDepositToken","type":"error"},{"inputs":[],"name":"NotWithdrawableByUser","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PermissionDenied","type":"error"},{"inputs":[],"name":"PreviewRiskExceeded","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"UnclaimedKATForWithdrawal","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"kATReservedForWithdrawal","type":"uint256"}],"name":"KATReservedForWithdrawal","type":"event"},{"anonymous":false,"inputs":[],"name":"KATResetReservedForWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"kATSupplied","type":"uint256"}],"name":"KATSupplied","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"kATWithdrawnFromSupply","type":"uint256"}],"name":"KATWithdrawnFromSupply","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"newPositionManager","type":"address"},{"indexed":false,"internalType":"uint256","name":"newVersion","type":"uint256"}],"name":"PositionManagerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"source","type":"address"},{"indexed":false,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"uint256","name":"strategyVersion","type":"uint256"}],"name":"StrategyVersionUpdated","type":"event"},{"inputs":[{"internalType":"uint256","name":"kATReservedForWithdrawal","type":"uint256"}],"name":"addKATReservedForWithdrawal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"balance","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"borrowBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"claimWithdrawalHook","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"collateralBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assetsToSupply","type":"uint256"}],"name":"encodeCallDataForSupply","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"assetsToWithdraw","type":"uint256"}],"name":"encodeCallDataToWithdraw","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint32","name":"transactionType","type":"uint32"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"finalizeHook","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getBaseStrategyConfig","outputs":[{"components":[{"internalType":"address","name":"optimizerVault","type":"address"}],"internalType":"struct IBaseStrategy.BaseStrategyStorage","name":"","type":"tuple"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getConfig","outputs":[{"components":[{"internalType":"uint256","name":"version","type":"uint256"},{"internalType":"address","name":"positionManager","type":"address"}],"internalType":"struct IVersionedVaultUtils.VaultStrategyStorage","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getKATReservedForWithdrawal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getStrategyConfig","outputs":[{"components":[{"components":[{"components":[{"components":[{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"address","name":"irm","type":"address"},{"internalType":"uint256","name":"lltv","type":"uint256"}],"internalType":"struct MarketParams","name":"marketParams","type":"tuple"},{"internalType":"contract IMorpho","name":"morpho","type":"address"}],"internalType":"struct IMorphoCommons.MorphoCommonsStorage","name":"morphoCommons","type":"tuple"},{"internalType":"address","name":"priceFeed","type":"address"}],"internalType":"struct IMorphoCommons.MorphoStrategyConfig","name":"morphoStrategyConfig","type":"tuple"},{"components":[{"internalType":"uint256","name":"version","type":"uint256"},{"internalType":"address","name":"positionManager","type":"address"}],"internalType":"struct IVersionedVaultUtils.VaultStrategyStorage","name":"vaultStrategyConfig","type":"tuple"}],"internalType":"struct IMorphoSupplyStrategy.MorphoSupplyStrategyVersionedConfig","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isDepositEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint32","name":"transactionType","type":"uint32"},{"internalType":"bytes","name":"cmd","type":"bytes"}],"name":"processHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resetKATReservedForWithdrawal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newPositionManager","type":"address"}],"name":"updatePositionManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"withdrawableSupplyBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

608060405234801561000f575f5ffd5b506040516130d33803806130d383398101604081905261002e916104a5565b82338061005457604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b61005d816100fb565b506001600160a01b0381166100855760405163d92e233d60e01b815260040160405180910390fd5b5f7feae00031c28a6f170099d0b3cb74122be9df00baf3745c5b377a885957a7070080546001600160a01b0319166001600160a01b039384161790555082166100e15760405163d92e233d60e01b815260040160405180910390fd5b6100ea8261014a565b6100f3816101ff565b5050506105a3565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b0381166101715760405163d92e233d60e01b815260040160405180910390fd5b60017ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae00557ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae0180546001600160a01b03929092166001600160a01b03199283161790557f77dfe5000ebf9e003c57377ca58618c48c4cbb3e849c5aac4b8be634c98fc800805490911630179055565b8051602001517ffa8cd390214ee76f5bb8c7ea1b63ea1107ccbd7e4761fc37eee7155261967100906001600160a01b031661024d5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b03166102785760405163d92e233d60e01b815260040160405180910390fd5b81518051805183546001600160a01b03199081166001600160a01b0392831617855560208084015160018701805484169185169190911790556040808501516002880180548516918616919091179055606080860151600389018054861691871691909117905560809095015160048801559481015160058701805490931690841617909155835192830184528551515182168352855151810151821683820152850151169181019190915261032d90610331565b5050565b80517fa2cb2ed7d820b5d5e467fcfe3a5dc1cfa81ba017c457bb1d2da9519a43ed1f00906001600160a01b031661037b5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b03166103a65760405163d92e233d60e01b815260040160405180910390fd5b60408201516001600160a01b03166103d15760405163d92e233d60e01b815260040160405180910390fd5b815181546001600160a01b03199081166001600160a01b0392831617835560208401516001840180548316918416919091179055604090930151600290920180549093169116179055565b6001600160a01b0381168114610430575f5ffd5b50565b805161043e8161041c565b919050565b604080519081016001600160401b038111828210171561047157634e487b7160e01b5f52604160045260245ffd5b60405290565b60405160a081016001600160401b038111828210171561047157634e487b7160e01b5f52604160045260245ffd5b5f5f5f8385036101208112156104b9575f5ffd5b84516104c48161041c565b60208601519094506104d58161041c565b9250603f190160e08112156104e8575f5ffd5b6104f0610443565b60c08212156104fd575f5ffd5b610505610443565b60a0831215610512575f5ffd5b61051a610477565b9250604087015161052a8161041c565b8352606087015161053a8161041c565b6020840152608087015161054d8161041c565b604084015260a08701516105608161041c565b606084015260c0870151608084015282815261057e60e08801610433565b602082015281526105926101008701610433565b602082015280925050509250925092565b612b23806105b05f395ff3fe608060405234801561000f575f5ffd5b506004361061011f575f3560e01c80638da5cb5b116100a55780638da5cb5b146101dd5780639f24da04146101f6578063a1bf2840146101fe578063ade84ff814610211578063b69ef8a814610226578063bae7a34614610243578063c3f909d414610256578063dadc63731461026b578063f2fde38b14610273578063faa6441b14610286578063fc0c546a146102a6575f5ffd5b80634892379914610123578063490272321461013e5780634a867833146101535780634d73e9ba1461016657806353836e8a1461017957806354fd4d501461018c5780635656fc78146101945780636881d8cb146101a2578063715018a6146101b55780638342695f146101bd578063891a491d146101bd575b5f5ffd5b61012b6102ae565b6040519081526020015b60405180910390f35b61015161014c366004612204565b6102bd565b005b610151610161366004612240565b610353565b61012b6101743660046122cc565b610411565b6101516101873660046122ee565b610484565b61012b61049d565b6040515f8152602001610135565b6101516101b03660046122cc565b6104ab565b61015161055b565b6101d06101cb366004612204565b61056e565b604051610135919061233c565b5f546001600160a01b03165b604051610135919061234e565b61012b610599565b61012b61020c3660046122cc565b6105c0565b610219610645565b60405161013591906123b9565b61022e61069b565b60408051928352901515602083015201610135565b610151610251366004612240565b6106c9565b61025e6108f4565b6040516101359190612409565b610151610938565b6101516102813660046122cc565b6109ba565b61028e6109f7565b60405190516001600160a01b03168152602001610135565b6101e9610a2a565b5f6102b7610a44565b54919050565b5f6102c6610a68565b80549091506001600160a01b031633146102f357604051630782484160e21b815260040160405180910390fd5b5f6102fc610a68565b80549091506001600160a01b031661031381610a8c565b6103305760405163a5030a3f60e01b815260040160405180910390fd5b83610339610a44565b80545f9061034890849061242b565b909155505050505050565b63ffffffff83166103ef146103885760405163d8d0a3fd60e01b815263ffffffff841660048201526024015b60405180910390fd5b5f849050806001600160a01b031663489237996040518163ffffffff1660e01b8152600401602060405180830381865afa1580156103c8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103ec919061243e565b1561040a5760405163b269083160e01b815260040160405180910390fd5b5050505050565b5f5f61041b610ba8565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f61047a838388610bcc565b9695505050505050565b604051633712d1c360e01b815260040160405180910390fd5b5f6104a6610c1e565b905090565b6104b3610c27565b6001600160a01b0381166104da5760405163d92e233d60e01b815260040160405180910390fd5b5f6104e3610c53565b600181810180546001600160a01b0319166001600160a01b03861617905581549192509082905f9061051690849061242b565b909155505080546040517fec07f803439eafbb5e1976432b2a5907b419652cd86b296cebe5a6725363beaa9161054f9133918691612455565b60405180910390a15050565b610563610c27565b61056c5f610c77565b565b60608160405160200161058391815260200190565b6040516020818303038152906040529050919050565b5f5f6105a3610a68565b80549091506105ba906001600160a01b0316610cc6565b91505090565b5f5f6105ca610ba8565b60058101546040805160a08101825283546001600160a01b039081168252600185015481166020830152600285015481169282019290925260038401548216606082015260048401546080820152929350169061063c61062b8260a0902090565b6001600160a01b0384169087610da0565b95945050505050565b61064d612179565b5f610656610e4c565b90505f610661610c53565b604080518082018252825481526001909201546001600160a01b031660208084019190915281518083019092529381529283015250919050565b5f5f5f6106a6610a68565b80549091505f906106bf906001600160a01b0316610ee7565b945f945092505050565b835f816001600160a01b031663faa6441b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610707573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061072b919061253a565b80519091506001600160a01b0316301461075857604051630782484160e21b815260040160405180910390fd5b610760610f4f565b61077d5760405163a5030a3f60e01b815260040160405180910390fd5b5f8690505f8790505f816001600160a01b031663faa6441b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107c2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e6919061253a565b90506107f183610fe1565b6103e81963ffffffff891601610821575f61080c8888611113565b905061081b825f015182611129565b506108e9565b6103e91963ffffffff89160161084b575f61083c8888611113565b905061081b825f015182611165565b6103ea1963ffffffff891601610868575f61083c825f0151610cc6565b6103eb1963ffffffff891601610888578051610883906111a1565b6108e9565b6103ee1963ffffffff8916016108af575f6108a38888611113565b905061081b84826111df565b6103ec1963ffffffff8916016108c85761088383611265565b60405163d8d0a3fd60e01b815263ffffffff8916600482015260240161037f565b505050505050505050565b604080518082019091525f80825260208201525f610910610c53565b60408051808201909152815481526001909101546001600160a01b0316602082015292915050565b5f610941610a68565b80549091506001600160a01b0316331461096e57604051630782484160e21b815260040160405180910390fd5b5f610977610a68565b80549091506001600160a01b031661098e81610a8c565b6109ab5760405163a5030a3f60e01b815260040160405180910390fd5b5f6109b4610a44565b55505050565b6109c2610c27565b6001600160a01b0381166109eb575f604051631e4fbdf760e01b815260040161037f919061234e565b6109f481610c77565b50565b60408051602081019091525f8152610a0d610a68565b604080516020810190915290546001600160a01b03168152919050565b5f604051631406371360e11b815260040160405180910390fd5b7f2d8acfb5c9f14854a8e698f0598e226c0fe355b78beac23b0b61404b66aab50090565b7feae00031c28a6f170099d0b3cb74122be9df00baf3745c5b377a885957a7070090565b5f5f826001600160a01b031663b97dd9e26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610aca573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610aee9190612585565b90508063ffffffff165f03610b0557505f92915050565b5f6001600160a01b03841663f2ae9d0b610b206001856125a0565b6040516001600160e01b031960e084901b16815263ffffffff91909116600482015260240161010060405180830381865afa158015610b61573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b8591906125df565b905060018160e001516002811115610b9f57610b9f612669565b14949350505050565b7ffa8cd390214ee76f5bb8c7ea1b63ea1107ccbd7e4761fc37eee715526196710090565b5f5f610bd98460a0902090565b90505f610bf06001600160a01b03871683866112de565b90505f5f610bfe888861138b565b9094509250610c1291508490508383611606565b98975050505050505050565b5f6102b7610c53565b5f546001600160a01b0316331461056c573360405163118cdaa760e01b815260040161037f919061234e565b7ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae0090565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f5f610cd0610ba8565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f610d42610d328360a0902090565b6001600160a01b03851690611632565b90505f610d63610d538460a0902090565b6001600160a01b038616906116dd565b90505f610d7a6001600160a01b038616858a6116eb565b90505f610d87848461267d565b9050610d938183611730565b9998505050505050505050565b5f5f610db4610daf858561173f565b6117a9565b90506080856001600160a01b0316637784c685836040518263ffffffff1660e01b8152600401610de49190612690565b5f60405180830381865afa158015610dfe573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610e2591908101906126d2565b5f81518110610e3657610e36612778565b6020026020010151901c5f1c9150509392505050565b610e546121af565b5f610e5d610ba8565b6040805160e08101825282546001600160a01b039081169282019283526001840154811660608301526002840154811660808301526003840154811660a0830152600484015460c083015291815260059092015416602082015290505f610ec26117f2565b60020154604080518082019091529283526001600160a01b0316602083015250919050565b5f5f610ef1610ba8565b60058101546040805160a08101825283546001600160a01b039081168252600185015481166020830152600285015481169282019290925260038401548216606082015260048401546080820152929350169061063c8282876116eb565b7f09232bebc33d8ffa7aaa574d9b368412805f314ca7c9b8bb526f2051d6c1960080545f9190600160a01b900463ffffffff16808303610f91575f9250505090565b5f610fbb83610fa16001856125a0565b63ffffffff165f9081526002919091016020526040902090565b90506001600582015460ff166002811115610fd857610fd8612669565b14935050505090565b5f816001600160a01b03166354fd4d506040518163ffffffff1660e01b8152600401602060405180830381865afa15801561101e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611042919061243e565b905061104c610c1e565b8103611056575050565b5f826001600160a01b031663ade84ff86040518163ffffffff1660e01b815260040161012060405180830381865afa158015611094573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110b891906127c4565b90506110c6815f0151611816565b6110d38160200151611932565b7f3e0c4d8090bb7b1dc2e1f7df18d2c95713b89c7d555ae0cce0a7c78b9b91934130848460405161110693929190612455565b60405180910390a1505050565b5f61112082840184612204565b90505b92915050565b611133828261196b565b50506040518181527f3c65efda24bfef7157933da31b229bcf504f71e7ea1a4541b1ae665aa7b3af4b9060200161054f565b61116f8282611a67565b50506040518181527f9bb59487a21f9cc98558951342e825928ccc88a08f7039230ebd3f2c1a7763019060200161054f565b5f6111ab82611bc8565b5090507f9bb59487a21f9cc98558951342e825928ccc88a08f7039230ebd3f2c1a7763018160405161054f91815260200190565b604051632481391960e11b8152600481018290526001600160a01b038316906349027232906024015f604051808303815f87803b15801561121e575f5ffd5b505af1158015611230573d5f5f3e3d5ffd5b505050507f8c040a06209fa803fbf0bc767aad7398e1199513a1090c16f1a75644dc8b9a068160405161054f91815260200190565b806001600160a01b031663dadc63736040518163ffffffff1660e01b81526004015f604051808303815f87803b15801561129d575f5ffd5b505af11580156112af573d5f5f3e3d5ffd5b50506040517ffa034736dced4633a6f51201dac757129f5bb9604967b83c3894968352a74ff492505f9150a150565b5f5f6112ed610daf858561173f565b604051637784c68560e01b81529091506001600160a01b03861690637784c6859061131c908490600401612690565b5f60405180830381865afa158015611336573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261135d91908101906126d2565b5f8151811061136e5761136e612778565b60200260200101515f1c6001600160801b03169150509392505050565b5f5f5f5f5f61139b8660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa1580156113e3573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061140791906128ca565b90505f81608001516001600160801b031642611423919061267d565b90508015801590611440575060408201516001600160801b031615155b8015611458575060608801516001600160a01b031615155b156115d2576060880151604051638c00bf6b60e01b81525f916001600160a01b031690638c00bf6b90611491908c908790600401612968565b602060405180830381865afa1580156114ac573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114d0919061243e565b90505f6114f46114e08385611cca565b60408601516001600160801b031690611d28565b90506114ff81611d3c565b8460400181815161151091906129d2565b6001600160801b031690525061152581611d3c565b845185906115349083906129d2565b6001600160801b0390811690915260a0860151161590506115cf575f6115708560a001516001600160801b031683611d2890919063ffffffff16565b90505f6115a482875f01516001600160801b031661158e919061267d565b60208801518491906001600160801b0316611d98565b90506115af81611d3c565b866020018181516115c091906129d2565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f61162a61161560018561242b565b611622620f42408561242b565b869190611dbc565b949350505050565b5f5f611640610daf84611de7565b604051637784c68560e01b81529091506001600160a01b03851690637784c6859061166f908490600401612690565b5f60405180830381865afa158015611689573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526116b091908101906126d2565b5f815181106116c1576116c1612778565b60200260200101515f1c6001600160801b031691505092915050565b5f5f611640610daf84611e29565b5f5f6116f88460a0902090565b90505f61170f6001600160a01b0387168386611e48565b90505f5f61171d888861138b565b509193509150610c129050838383611eec565b5f828218828410028218611120565b5f600182846002604051602001611760929190918252602082015260400190565b604051602081830303815290604052805190602001206040516020016117879291906129f1565b604051602081830303815290604052805190602001205f1c611120919061242b565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f815181106117e1576117e1612778565b602090810291909101015292915050565b7fa2cb2ed7d820b5d5e467fcfe3a5dc1cfa81ba017c457bb1d2da9519a43ed1f0090565b5f61181f610ba8565b8251602001519091506001600160a01b031661184e5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b03166118795760405163d92e233d60e01b815260040160405180910390fd5b81518051805183546001600160a01b03199081166001600160a01b0392831617855560208084015160018701805484169185169190911790556040808501516002880180548516918616919091179055606080860151600389018054861691871691909117905560809095015160048801559481015160058701805490931690841617909155835192830184528551515182168352855151810151821683820152850151169181019190915261192e90611f08565b5050565b5f61193b610c53565b82518155602090920151600190920180546001600160a01b0319166001600160a01b039093169290921790915550565b5f5f5f611976610ba8565b90505f6119816117f2565b600583015481546040805160a08101825286546001600160a01b039081168252600188015481166020830152600288015481169282019290925260038701548216606082015260048701546080820152939450918216929116906119e682848a611fdd565b60405163a99aad8960e01b81526001600160a01b0384169063a99aad8990611a189084908c905f908f90600401612a0a565b60408051808303815f875af1158015611a33573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a579190612a4b565b909a909950975050505050505050565b5f5f5f611a72610ba8565b60058101546040805160a08101825283546001600160a01b039081168252600185015481166020830152600285015481168284015260038501548116606083015260048086015460808401529251630a8e0d6f60e11b815294955090921692839163151c1ade91611ae591859101612a6d565b5f604051808303815f87803b158015611afc575f5ffd5b505af1158015611b0e573d5f5f3e3d5ffd5b505050505f611b1c88610ee7565b905080871115611b3e57611b2f88611bc8565b9096509450611bc19350505050565b6005840154604051635c2bea4960e01b81526001600160a01b0390911690635c2bea4990611b789085908b905f908e908190600401612a7b565b60408051808303815f875af1158015611b93573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bb79190612a4b565b9096509450505050505b9250929050565b5f5f5f611bd3610ba8565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f611c46611c358360a0902090565b6001600160a01b0385169089611e48565b604051635c2bea4960e01b81529091506001600160a01b03841690635c2bea4990611c7d9085905f9086908d908190600401612a7b565b60408051808303815f875af1158015611c98573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cbc9190612a4b565b909890975095505050505050565b5f80611cd68385612ab7565b90505f611cf68280611cf1670de0b6b3a76400006002612ab7565b6120a5565b90505f611d118284611cf1670de0b6b3a76400006003612ab7565b905080611d1e838561242b565b61047a919061242b565b5f6111208383670de0b6b3a76400006120a5565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b03831115611d915760405162461bcd60e51b815260040161037f919061233c565b5090919050565b5f61162a611da9620f42408461242b565b611db460018661242b565b8691906120a5565b5f81611dc960018261267d565b611dd38587612ab7565b611ddd919061242b565b61162a9190612ace565b5f6001826003604051602001611e07929190918252602082015260400190565b604051602081830303815290604052805190602001205f1c611123919061242b565b5f5f826003604051602001611e07929190918252602082015260400190565b5f5f611e57610daf85856120b1565b604051637784c68560e01b81529091506001600160a01b03861690637784c68590611e86908490600401612690565b5f60405180830381865afa158015611ea0573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611ec791908101906126d2565b5f81518110611ed857611ed8612778565b60200260200101515f1c9150509392505050565b5f61162a611efb60018561242b565b611db4620f42408561242b565b5f611f116117f2565b82519091506001600160a01b0316611f3c5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b0316611f675760405163d92e233d60e01b815260040160405180910390fd5b60408201516001600160a01b0316611f925760405163d92e233d60e01b815260040160405180910390fd5b815181546001600160a01b03199081166001600160a01b0392831617835560208401516001840180548316918416919091179055604090930151600290920180549093169116179055565b5f836001600160a01b031663095ea7b384846040516024016120009291906129f1565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050905061203984826120d1565b61209f5761209584856001600160a01b031663095ea7b3865f6040516024016120639291906129f1565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050612116565b61209f8482612116565b50505050565b5f81611ddd8486612ab7565b5f5f82846002604051602001611760929190918252602082015260400190565b5f5f5f5f60205f8651602088015f8a5af192503d91505f51905082801561047a57508115612102578060011461047a565b50505050506001600160a01b03163b151590565b5f5f60205f8451602086015f885af180612135576040513d5f823e3d81fd5b50505f513d9150811561214c578060011415612159565b6001600160a01b0384163b155b1561209f5783604051635274afe760e01b815260040161037f919061234e565b604051806040016040528061218c6121af565b81526020016121aa604080518082019091525f808252602082015290565b905290565b60405180604001604052806121c26121ce565b81525f60209091015290565b6040805160e0810182525f918101828152606082018390526080820183905260a0820183905260c08201929092529081906121c2565b5f60208284031215612214575f5ffd5b5035919050565b6001600160a01b03811681146109f4575f5ffd5b63ffffffff811681146109f4575f5ffd5b5f5f5f5f60608587031215612253575f5ffd5b843561225e8161221b565b9350602085013561226e8161222f565b925060408501356001600160401b03811115612288575f5ffd5b8501601f81018713612298575f5ffd5b80356001600160401b038111156122ad575f5ffd5b8760208284010111156122be575f5ffd5b949793965060200194505050565b5f602082840312156122dc575f5ffd5b81356122e78161221b565b9392505050565b5f5f604083850312156122ff575f5ffd5b50508035926020909101359150565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f611120602083018461230e565b6001600160a01b0391909116815260200190565b80516001600160a01b03908116835260208083015182169084015260408083015182169084015260608083015190911690830152608090810151910152565b805182526020908101516001600160a01b0316910152565b5f61012082019050825180516123d0848251612362565b6020908101516001600160a01b0390811660a08601529181015190911660c084015283015161240260e08401826123a1565b5092915050565b6040810161112382846123a1565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561112357611123612417565b5f6020828403121561244e575f5ffd5b5051919050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b5f52604160045260245ffd5b60405161010081016001600160401b03811182821017156124b0576124b0612479565b60405290565b604080519081016001600160401b03811182821017156124b0576124b0612479565b60405160a081016001600160401b03811182821017156124b0576124b0612479565b604051601f8201601f191681016001600160401b038111828210171561252257612522612479565b604052919050565b80516125358161221b565b919050565b5f602082840312801561254b575f5ffd5b50604051602081016001600160401b038111828210171561256e5761256e612479565b604052825161257c8161221b565b81529392505050565b5f60208284031215612595575f5ffd5b81516122e78161222f565b63ffffffff828116828216039081111561112357611123612417565b805165ffffffffffff81168114612535575f5ffd5b805160038110612535575f5ffd5b5f6101008284031280156125f1575f5ffd5b506125fa61248d565b82516126058161222f565b8152612613602084016125bc565b6020820152612624604084016125bc565b6040820152606083810151908201526080808401519082015260a0808401519082015260c0808401519082015261265d60e084016125d1565b60e08201529392505050565b634e487b7160e01b5f52602160045260245ffd5b8181038181111561112357611123612417565b602080825282518282018190525f918401906040840190835b818110156126c75783518352602093840193909201916001016126a9565b509095945050505050565b5f602082840312156126e2575f5ffd5b81516001600160401b038111156126f7575f5ffd5b8201601f81018413612707575f5ffd5b80516001600160401b0381111561272057612720612479565b8060051b612730602082016124fa565b9182526020818401810192908101908784111561274b575f5ffd5b6020850194505b8385101561276d578451825260209485019490910190612752565b979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f6040828403121561279c575f5ffd5b6127a46124b6565b8251815260208301519091506127b98161221b565b602082015292915050565b5f818303610120811280156127d7575f5ffd5b506127e06124b6565b60e08212156127ed575f5ffd5b6127f56124b6565b60c0831215612802575f5ffd5b61280a6124b6565b60a0841215612817575f5ffd5b61281f6124d8565b9350855161282c8161221b565b8452602086015161283c8161221b565b6020850152604086015161284f8161221b565b604085015260608601516128628161221b565b60608501526080868101519085015283815261288060a0870161252a565b6020820152815261289360c0860161252a565b602082015281526128a78560e0860161278c565b6020820152949350505050565b80516001600160801b0381168114612535575f5ffd5b5f60c08284031280156128db575f5ffd5b5060405160c081016001600160401b03811182821017156128fe576128fe612479565b60405261290a836128b4565b8152612918602084016128b4565b6020820152612929604084016128b4565b604082015261293a606084016128b4565b606082015261294b608084016128b4565b608082015261295c60a084016128b4565b60a08201529392505050565b61016081016129778285612362565b82516001600160801b0390811660a0848101919091526020850151821660c08501526040850151821660e085015260608501518216610100850152608085015182166101208501529093015190921661014090910152919050565b6001600160801b03818116838216019081111561112357611123612417565b6001600160a01b03929092168252602082015260400190565b612a148186612362565b60a081019390935260c08301919091526001600160a01b031660e082015261012061010082018190525f9082015261014001919050565b5f5f60408385031215612a5c575f5ffd5b505080516020909101519092909150565b60a081016111238284612362565b6101208101612a8a8288612362565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b808202811582820484141761112357611123612417565b5f82612ae857634e487b7160e01b5f52601260045260245ffd5b50049056fea2646970667358221220419c043e27721edea761b3fab72fcf010b626d1d1b5a2b1f751587f4ad4df09264736f6c634300081c0033000000000000000000000000c385fee416dcd3731aa3abdccd36dd57dca012230000000000000000000000005477b94198f12e4e5faab2c8d95b807c061797c5000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da0000000000000000000000001cb453f8d5565643fb20f5d005454db88dc088be0000000000000000000000004f708c0ae7ded3d74736594c2109c2e3c065b4280000000000000000000000000000000000000000000000000bef55718ad60000000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e

Deployed Bytecode

0x608060405234801561000f575f5ffd5b506004361061011f575f3560e01c80638da5cb5b116100a55780638da5cb5b146101dd5780639f24da04146101f6578063a1bf2840146101fe578063ade84ff814610211578063b69ef8a814610226578063bae7a34614610243578063c3f909d414610256578063dadc63731461026b578063f2fde38b14610273578063faa6441b14610286578063fc0c546a146102a6575f5ffd5b80634892379914610123578063490272321461013e5780634a867833146101535780634d73e9ba1461016657806353836e8a1461017957806354fd4d501461018c5780635656fc78146101945780636881d8cb146101a2578063715018a6146101b55780638342695f146101bd578063891a491d146101bd575b5f5ffd5b61012b6102ae565b6040519081526020015b60405180910390f35b61015161014c366004612204565b6102bd565b005b610151610161366004612240565b610353565b61012b6101743660046122cc565b610411565b6101516101873660046122ee565b610484565b61012b61049d565b6040515f8152602001610135565b6101516101b03660046122cc565b6104ab565b61015161055b565b6101d06101cb366004612204565b61056e565b604051610135919061233c565b5f546001600160a01b03165b604051610135919061234e565b61012b610599565b61012b61020c3660046122cc565b6105c0565b610219610645565b60405161013591906123b9565b61022e61069b565b60408051928352901515602083015201610135565b610151610251366004612240565b6106c9565b61025e6108f4565b6040516101359190612409565b610151610938565b6101516102813660046122cc565b6109ba565b61028e6109f7565b60405190516001600160a01b03168152602001610135565b6101e9610a2a565b5f6102b7610a44565b54919050565b5f6102c6610a68565b80549091506001600160a01b031633146102f357604051630782484160e21b815260040160405180910390fd5b5f6102fc610a68565b80549091506001600160a01b031661031381610a8c565b6103305760405163a5030a3f60e01b815260040160405180910390fd5b83610339610a44565b80545f9061034890849061242b565b909155505050505050565b63ffffffff83166103ef146103885760405163d8d0a3fd60e01b815263ffffffff841660048201526024015b60405180910390fd5b5f849050806001600160a01b031663489237996040518163ffffffff1660e01b8152600401602060405180830381865afa1580156103c8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103ec919061243e565b1561040a5760405163b269083160e01b815260040160405180910390fd5b5050505050565b5f5f61041b610ba8565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f61047a838388610bcc565b9695505050505050565b604051633712d1c360e01b815260040160405180910390fd5b5f6104a6610c1e565b905090565b6104b3610c27565b6001600160a01b0381166104da5760405163d92e233d60e01b815260040160405180910390fd5b5f6104e3610c53565b600181810180546001600160a01b0319166001600160a01b03861617905581549192509082905f9061051690849061242b565b909155505080546040517fec07f803439eafbb5e1976432b2a5907b419652cd86b296cebe5a6725363beaa9161054f9133918691612455565b60405180910390a15050565b610563610c27565b61056c5f610c77565b565b60608160405160200161058391815260200190565b6040516020818303038152906040529050919050565b5f5f6105a3610a68565b80549091506105ba906001600160a01b0316610cc6565b91505090565b5f5f6105ca610ba8565b60058101546040805160a08101825283546001600160a01b039081168252600185015481166020830152600285015481169282019290925260038401548216606082015260048401546080820152929350169061063c61062b8260a0902090565b6001600160a01b0384169087610da0565b95945050505050565b61064d612179565b5f610656610e4c565b90505f610661610c53565b604080518082018252825481526001909201546001600160a01b031660208084019190915281518083019092529381529283015250919050565b5f5f5f6106a6610a68565b80549091505f906106bf906001600160a01b0316610ee7565b945f945092505050565b835f816001600160a01b031663faa6441b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610707573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061072b919061253a565b80519091506001600160a01b0316301461075857604051630782484160e21b815260040160405180910390fd5b610760610f4f565b61077d5760405163a5030a3f60e01b815260040160405180910390fd5b5f8690505f8790505f816001600160a01b031663faa6441b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107c2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e6919061253a565b90506107f183610fe1565b6103e81963ffffffff891601610821575f61080c8888611113565b905061081b825f015182611129565b506108e9565b6103e91963ffffffff89160161084b575f61083c8888611113565b905061081b825f015182611165565b6103ea1963ffffffff891601610868575f61083c825f0151610cc6565b6103eb1963ffffffff891601610888578051610883906111a1565b6108e9565b6103ee1963ffffffff8916016108af575f6108a38888611113565b905061081b84826111df565b6103ec1963ffffffff8916016108c85761088383611265565b60405163d8d0a3fd60e01b815263ffffffff8916600482015260240161037f565b505050505050505050565b604080518082019091525f80825260208201525f610910610c53565b60408051808201909152815481526001909101546001600160a01b0316602082015292915050565b5f610941610a68565b80549091506001600160a01b0316331461096e57604051630782484160e21b815260040160405180910390fd5b5f610977610a68565b80549091506001600160a01b031661098e81610a8c565b6109ab5760405163a5030a3f60e01b815260040160405180910390fd5b5f6109b4610a44565b55505050565b6109c2610c27565b6001600160a01b0381166109eb575f604051631e4fbdf760e01b815260040161037f919061234e565b6109f481610c77565b50565b60408051602081019091525f8152610a0d610a68565b604080516020810190915290546001600160a01b03168152919050565b5f604051631406371360e11b815260040160405180910390fd5b7f2d8acfb5c9f14854a8e698f0598e226c0fe355b78beac23b0b61404b66aab50090565b7feae00031c28a6f170099d0b3cb74122be9df00baf3745c5b377a885957a7070090565b5f5f826001600160a01b031663b97dd9e26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610aca573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610aee9190612585565b90508063ffffffff165f03610b0557505f92915050565b5f6001600160a01b03841663f2ae9d0b610b206001856125a0565b6040516001600160e01b031960e084901b16815263ffffffff91909116600482015260240161010060405180830381865afa158015610b61573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b8591906125df565b905060018160e001516002811115610b9f57610b9f612669565b14949350505050565b7ffa8cd390214ee76f5bb8c7ea1b63ea1107ccbd7e4761fc37eee715526196710090565b5f5f610bd98460a0902090565b90505f610bf06001600160a01b03871683866112de565b90505f5f610bfe888861138b565b9094509250610c1291508490508383611606565b98975050505050505050565b5f6102b7610c53565b5f546001600160a01b0316331461056c573360405163118cdaa760e01b815260040161037f919061234e565b7ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae0090565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f5f610cd0610ba8565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f610d42610d328360a0902090565b6001600160a01b03851690611632565b90505f610d63610d538460a0902090565b6001600160a01b038616906116dd565b90505f610d7a6001600160a01b038616858a6116eb565b90505f610d87848461267d565b9050610d938183611730565b9998505050505050505050565b5f5f610db4610daf858561173f565b6117a9565b90506080856001600160a01b0316637784c685836040518263ffffffff1660e01b8152600401610de49190612690565b5f60405180830381865afa158015610dfe573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610e2591908101906126d2565b5f81518110610e3657610e36612778565b6020026020010151901c5f1c9150509392505050565b610e546121af565b5f610e5d610ba8565b6040805160e08101825282546001600160a01b039081169282019283526001840154811660608301526002840154811660808301526003840154811660a0830152600484015460c083015291815260059092015416602082015290505f610ec26117f2565b60020154604080518082019091529283526001600160a01b0316602083015250919050565b5f5f610ef1610ba8565b60058101546040805160a08101825283546001600160a01b039081168252600185015481166020830152600285015481169282019290925260038401548216606082015260048401546080820152929350169061063c8282876116eb565b7f09232bebc33d8ffa7aaa574d9b368412805f314ca7c9b8bb526f2051d6c1960080545f9190600160a01b900463ffffffff16808303610f91575f9250505090565b5f610fbb83610fa16001856125a0565b63ffffffff165f9081526002919091016020526040902090565b90506001600582015460ff166002811115610fd857610fd8612669565b14935050505090565b5f816001600160a01b03166354fd4d506040518163ffffffff1660e01b8152600401602060405180830381865afa15801561101e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611042919061243e565b905061104c610c1e565b8103611056575050565b5f826001600160a01b031663ade84ff86040518163ffffffff1660e01b815260040161012060405180830381865afa158015611094573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110b891906127c4565b90506110c6815f0151611816565b6110d38160200151611932565b7f3e0c4d8090bb7b1dc2e1f7df18d2c95713b89c7d555ae0cce0a7c78b9b91934130848460405161110693929190612455565b60405180910390a1505050565b5f61112082840184612204565b90505b92915050565b611133828261196b565b50506040518181527f3c65efda24bfef7157933da31b229bcf504f71e7ea1a4541b1ae665aa7b3af4b9060200161054f565b61116f8282611a67565b50506040518181527f9bb59487a21f9cc98558951342e825928ccc88a08f7039230ebd3f2c1a7763019060200161054f565b5f6111ab82611bc8565b5090507f9bb59487a21f9cc98558951342e825928ccc88a08f7039230ebd3f2c1a7763018160405161054f91815260200190565b604051632481391960e11b8152600481018290526001600160a01b038316906349027232906024015f604051808303815f87803b15801561121e575f5ffd5b505af1158015611230573d5f5f3e3d5ffd5b505050507f8c040a06209fa803fbf0bc767aad7398e1199513a1090c16f1a75644dc8b9a068160405161054f91815260200190565b806001600160a01b031663dadc63736040518163ffffffff1660e01b81526004015f604051808303815f87803b15801561129d575f5ffd5b505af11580156112af573d5f5f3e3d5ffd5b50506040517ffa034736dced4633a6f51201dac757129f5bb9604967b83c3894968352a74ff492505f9150a150565b5f5f6112ed610daf858561173f565b604051637784c68560e01b81529091506001600160a01b03861690637784c6859061131c908490600401612690565b5f60405180830381865afa158015611336573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261135d91908101906126d2565b5f8151811061136e5761136e612778565b60200260200101515f1c6001600160801b03169150509392505050565b5f5f5f5f5f61139b8660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa1580156113e3573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061140791906128ca565b90505f81608001516001600160801b031642611423919061267d565b90508015801590611440575060408201516001600160801b031615155b8015611458575060608801516001600160a01b031615155b156115d2576060880151604051638c00bf6b60e01b81525f916001600160a01b031690638c00bf6b90611491908c908790600401612968565b602060405180830381865afa1580156114ac573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114d0919061243e565b90505f6114f46114e08385611cca565b60408601516001600160801b031690611d28565b90506114ff81611d3c565b8460400181815161151091906129d2565b6001600160801b031690525061152581611d3c565b845185906115349083906129d2565b6001600160801b0390811690915260a0860151161590506115cf575f6115708560a001516001600160801b031683611d2890919063ffffffff16565b90505f6115a482875f01516001600160801b031661158e919061267d565b60208801518491906001600160801b0316611d98565b90506115af81611d3c565b866020018181516115c091906129d2565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f61162a61161560018561242b565b611622620f42408561242b565b869190611dbc565b949350505050565b5f5f611640610daf84611de7565b604051637784c68560e01b81529091506001600160a01b03851690637784c6859061166f908490600401612690565b5f60405180830381865afa158015611689573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526116b091908101906126d2565b5f815181106116c1576116c1612778565b60200260200101515f1c6001600160801b031691505092915050565b5f5f611640610daf84611e29565b5f5f6116f88460a0902090565b90505f61170f6001600160a01b0387168386611e48565b90505f5f61171d888861138b565b509193509150610c129050838383611eec565b5f828218828410028218611120565b5f600182846002604051602001611760929190918252602082015260400190565b604051602081830303815290604052805190602001206040516020016117879291906129f1565b604051602081830303815290604052805190602001205f1c611120919061242b565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f815181106117e1576117e1612778565b602090810291909101015292915050565b7fa2cb2ed7d820b5d5e467fcfe3a5dc1cfa81ba017c457bb1d2da9519a43ed1f0090565b5f61181f610ba8565b8251602001519091506001600160a01b031661184e5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b03166118795760405163d92e233d60e01b815260040160405180910390fd5b81518051805183546001600160a01b03199081166001600160a01b0392831617855560208084015160018701805484169185169190911790556040808501516002880180548516918616919091179055606080860151600389018054861691871691909117905560809095015160048801559481015160058701805490931690841617909155835192830184528551515182168352855151810151821683820152850151169181019190915261192e90611f08565b5050565b5f61193b610c53565b82518155602090920151600190920180546001600160a01b0319166001600160a01b039093169290921790915550565b5f5f5f611976610ba8565b90505f6119816117f2565b600583015481546040805160a08101825286546001600160a01b039081168252600188015481166020830152600288015481169282019290925260038701548216606082015260048701546080820152939450918216929116906119e682848a611fdd565b60405163a99aad8960e01b81526001600160a01b0384169063a99aad8990611a189084908c905f908f90600401612a0a565b60408051808303815f875af1158015611a33573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a579190612a4b565b909a909950975050505050505050565b5f5f5f611a72610ba8565b60058101546040805160a08101825283546001600160a01b039081168252600185015481166020830152600285015481168284015260038501548116606083015260048086015460808401529251630a8e0d6f60e11b815294955090921692839163151c1ade91611ae591859101612a6d565b5f604051808303815f87803b158015611afc575f5ffd5b505af1158015611b0e573d5f5f3e3d5ffd5b505050505f611b1c88610ee7565b905080871115611b3e57611b2f88611bc8565b9096509450611bc19350505050565b6005840154604051635c2bea4960e01b81526001600160a01b0390911690635c2bea4990611b789085908b905f908e908190600401612a7b565b60408051808303815f875af1158015611b93573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bb79190612a4b565b9096509450505050505b9250929050565b5f5f5f611bd3610ba8565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f611c46611c358360a0902090565b6001600160a01b0385169089611e48565b604051635c2bea4960e01b81529091506001600160a01b03841690635c2bea4990611c7d9085905f9086908d908190600401612a7b565b60408051808303815f875af1158015611c98573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cbc9190612a4b565b909890975095505050505050565b5f80611cd68385612ab7565b90505f611cf68280611cf1670de0b6b3a76400006002612ab7565b6120a5565b90505f611d118284611cf1670de0b6b3a76400006003612ab7565b905080611d1e838561242b565b61047a919061242b565b5f6111208383670de0b6b3a76400006120a5565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b03831115611d915760405162461bcd60e51b815260040161037f919061233c565b5090919050565b5f61162a611da9620f42408461242b565b611db460018661242b565b8691906120a5565b5f81611dc960018261267d565b611dd38587612ab7565b611ddd919061242b565b61162a9190612ace565b5f6001826003604051602001611e07929190918252602082015260400190565b604051602081830303815290604052805190602001205f1c611123919061242b565b5f5f826003604051602001611e07929190918252602082015260400190565b5f5f611e57610daf85856120b1565b604051637784c68560e01b81529091506001600160a01b03861690637784c68590611e86908490600401612690565b5f60405180830381865afa158015611ea0573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611ec791908101906126d2565b5f81518110611ed857611ed8612778565b60200260200101515f1c9150509392505050565b5f61162a611efb60018561242b565b611db4620f42408561242b565b5f611f116117f2565b82519091506001600160a01b0316611f3c5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b0316611f675760405163d92e233d60e01b815260040160405180910390fd5b60408201516001600160a01b0316611f925760405163d92e233d60e01b815260040160405180910390fd5b815181546001600160a01b03199081166001600160a01b0392831617835560208401516001840180548316918416919091179055604090930151600290920180549093169116179055565b5f836001600160a01b031663095ea7b384846040516024016120009291906129f1565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050905061203984826120d1565b61209f5761209584856001600160a01b031663095ea7b3865f6040516024016120639291906129f1565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050612116565b61209f8482612116565b50505050565b5f81611ddd8486612ab7565b5f5f82846002604051602001611760929190918252602082015260400190565b5f5f5f5f60205f8651602088015f8a5af192503d91505f51905082801561047a57508115612102578060011461047a565b50505050506001600160a01b03163b151590565b5f5f60205f8451602086015f885af180612135576040513d5f823e3d81fd5b50505f513d9150811561214c578060011415612159565b6001600160a01b0384163b155b1561209f5783604051635274afe760e01b815260040161037f919061234e565b604051806040016040528061218c6121af565b81526020016121aa604080518082019091525f808252602082015290565b905290565b60405180604001604052806121c26121ce565b81525f60209091015290565b6040805160e0810182525f918101828152606082018390526080820183905260a0820183905260c08201929092529081906121c2565b5f60208284031215612214575f5ffd5b5035919050565b6001600160a01b03811681146109f4575f5ffd5b63ffffffff811681146109f4575f5ffd5b5f5f5f5f60608587031215612253575f5ffd5b843561225e8161221b565b9350602085013561226e8161222f565b925060408501356001600160401b03811115612288575f5ffd5b8501601f81018713612298575f5ffd5b80356001600160401b038111156122ad575f5ffd5b8760208284010111156122be575f5ffd5b949793965060200194505050565b5f602082840312156122dc575f5ffd5b81356122e78161221b565b9392505050565b5f5f604083850312156122ff575f5ffd5b50508035926020909101359150565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f611120602083018461230e565b6001600160a01b0391909116815260200190565b80516001600160a01b03908116835260208083015182169084015260408083015182169084015260608083015190911690830152608090810151910152565b805182526020908101516001600160a01b0316910152565b5f61012082019050825180516123d0848251612362565b6020908101516001600160a01b0390811660a08601529181015190911660c084015283015161240260e08401826123a1565b5092915050565b6040810161112382846123a1565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561112357611123612417565b5f6020828403121561244e575f5ffd5b5051919050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b5f52604160045260245ffd5b60405161010081016001600160401b03811182821017156124b0576124b0612479565b60405290565b604080519081016001600160401b03811182821017156124b0576124b0612479565b60405160a081016001600160401b03811182821017156124b0576124b0612479565b604051601f8201601f191681016001600160401b038111828210171561252257612522612479565b604052919050565b80516125358161221b565b919050565b5f602082840312801561254b575f5ffd5b50604051602081016001600160401b038111828210171561256e5761256e612479565b604052825161257c8161221b565b81529392505050565b5f60208284031215612595575f5ffd5b81516122e78161222f565b63ffffffff828116828216039081111561112357611123612417565b805165ffffffffffff81168114612535575f5ffd5b805160038110612535575f5ffd5b5f6101008284031280156125f1575f5ffd5b506125fa61248d565b82516126058161222f565b8152612613602084016125bc565b6020820152612624604084016125bc565b6040820152606083810151908201526080808401519082015260a0808401519082015260c0808401519082015261265d60e084016125d1565b60e08201529392505050565b634e487b7160e01b5f52602160045260245ffd5b8181038181111561112357611123612417565b602080825282518282018190525f918401906040840190835b818110156126c75783518352602093840193909201916001016126a9565b509095945050505050565b5f602082840312156126e2575f5ffd5b81516001600160401b038111156126f7575f5ffd5b8201601f81018413612707575f5ffd5b80516001600160401b0381111561272057612720612479565b8060051b612730602082016124fa565b9182526020818401810192908101908784111561274b575f5ffd5b6020850194505b8385101561276d578451825260209485019490910190612752565b979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f6040828403121561279c575f5ffd5b6127a46124b6565b8251815260208301519091506127b98161221b565b602082015292915050565b5f818303610120811280156127d7575f5ffd5b506127e06124b6565b60e08212156127ed575f5ffd5b6127f56124b6565b60c0831215612802575f5ffd5b61280a6124b6565b60a0841215612817575f5ffd5b61281f6124d8565b9350855161282c8161221b565b8452602086015161283c8161221b565b6020850152604086015161284f8161221b565b604085015260608601516128628161221b565b60608501526080868101519085015283815261288060a0870161252a565b6020820152815261289360c0860161252a565b602082015281526128a78560e0860161278c565b6020820152949350505050565b80516001600160801b0381168114612535575f5ffd5b5f60c08284031280156128db575f5ffd5b5060405160c081016001600160401b03811182821017156128fe576128fe612479565b60405261290a836128b4565b8152612918602084016128b4565b6020820152612929604084016128b4565b604082015261293a606084016128b4565b606082015261294b608084016128b4565b608082015261295c60a084016128b4565b60a08201529392505050565b61016081016129778285612362565b82516001600160801b0390811660a0848101919091526020850151821660c08501526040850151821660e085015260608501518216610100850152608085015182166101208501529093015190921661014090910152919050565b6001600160801b03818116838216019081111561112357611123612417565b6001600160a01b03929092168252602082015260400190565b612a148186612362565b60a081019390935260c08301919091526001600160a01b031660e082015261012061010082018190525f9082015261014001919050565b5f5f60408385031215612a5c575f5ffd5b505080516020909101519092909150565b60a081016111238284612362565b6101208101612a8a8288612362565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b808202811582820484141761112357611123612417565b5f82612ae857634e487b7160e01b5f52601260045260245ffd5b50049056fea2646970667358221220419c043e27721edea761b3fab72fcf010b626d1d1b5a2b1f751587f4ad4df09264736f6c634300081c0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000c385fee416dcd3731aa3abdccd36dd57dca012230000000000000000000000005477b94198f12e4e5faab2c8d95b807c061797c5000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da0000000000000000000000001cb453f8d5565643fb20f5d005454db88dc088be0000000000000000000000004f708c0ae7ded3d74736594c2109c2e3c065b4280000000000000000000000000000000000000000000000000bef55718ad60000000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e

-----Decoded View---------------
Arg [0] : optimizerVault (address): 0xC385FeE416DCd3731Aa3aBDCCd36dd57dca01223
Arg [1] : positionManager (address): 0x5477B94198f12E4E5fAab2c8D95B807C061797C5
Arg [2] : strategyConfig (tuple):
Arg [1] : morphoCommons (tuple):
Arg [1] : marketParams (tuple):
Arg [1] : loanToken (address): 0xCD6863bB697d7CEE5b7Ed8deA7D803374F7e4Aa6
Arg [2] : collateralToken (address): 0x297612c171fc8ADce32ac333085a9Ee1F2BCC1Da
Arg [3] : oracle (address): 0x1cB453F8d5565643fb20F5d005454DB88dC088Be
Arg [4] : irm (address): 0x4F708C0ae7deD3d74736594C2109C2E3c065B428
Arg [5] : lltv (uint256): 860000000000000000

Arg [2] : morpho (address): 0xD50F2DffFd62f94Ee4AEd9ca05C61d0753268aBc

Arg [2] : priceFeed (address): 0xaB162c41Ad27DF8614eDd43F886857Bb2054C23e


-----Encoded View---------------
9 Constructor Arguments found :
Arg [0] : 000000000000000000000000c385fee416dcd3731aa3abdccd36dd57dca01223
Arg [1] : 0000000000000000000000005477b94198f12e4e5faab2c8d95b807c061797c5
Arg [2] : 000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6
Arg [3] : 000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da
Arg [4] : 0000000000000000000000001cb453f8d5565643fb20f5d005454db88dc088be
Arg [5] : 0000000000000000000000004f708c0ae7ded3d74736594c2109c2e3c065b428
Arg [6] : 0000000000000000000000000000000000000000000000000bef55718ad60000
Arg [7] : 000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc
Arg [8] : 000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

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.