Skip to content
Verified contractPartialGPL-2.0-or-later

FeeWrapperDeployer

Address0xc02e946a2ab8a8b633f8d86f287fabcfd33ca119
Balance

0 ETH

 

Transactions

11

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 100,000 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,741,238
Creation transaction
0x4440389086…921f9a1e32

lib/morpho-snippets/src/vault-v2/FeeWrapperDeployer.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2026 Morpho Association
pragma solidity ^0.8.0;

import {IVaultV2Factory} from "../../lib/vault-v2/src/interfaces/IVaultV2Factory.sol";
import {IVaultV2} from "../../lib/vault-v2/src/interfaces/IVaultV2.sol";
import {
    IMorphoVaultV1AdapterFactory
} from "../../lib/vault-v2/src/adapters/interfaces/IMorphoVaultV1AdapterFactory.sol";
import {MAX_MAX_RATE, MAX_FORCE_DEALLOCATE_PENALTY, WAD} from "../../lib/vault-v2/src/libraries/ConstantsLib.sol";

/// @title FeeWrapperDeployer
/// @notice Deploys and configures a VaultV2 "fee wrapper" on top of an existing Morpho Vault V2 child vault.
///
/// ============================================================================================
///  HOW TO DEPLOY A FEE WRAPPER  ->  USE THE SCRIPT, NOT THIS CONTRACT DIRECTLY
/// ============================================================================================
///
///   Deploy through the Foundry script:  script/DeployFeeWrapper.s.sol
///
///       forge script script/DeployFeeWrapper.s.sol:DeployFeeWrapper --rpc-url <rpc> --broadcast
///
///   Do NOT call createFeeWrapper ad hoc from another contract or from unpinned tooling.
///   The fee wrapper's deterministic (CREATE2) address is bound to the caller (msg.sender), so it
///   is only meaningful relative to the account that created it. The script pins that account,
///   logs the resulting address, and verifies on-chain provenance so deployments stay reproducible
///   and cannot be front-run/squatted.
///
///   ->  Read the sections below IN FULL before deploying. In particular:
///         - "Deterministic Address & Front-Running Protection" (why the script is mandatory)
///         - "Roles & Responsibilities"                          (owner MUST be a safe multisig)
///         - "What is FIXED at deployment"                       (irreversible choices)
///
/// ============================================================================================
///
/// A fee wrapper is a VaultV2 that wraps a single child vault via a fixed MorphoVaultV1Adapter.
/// Users deposit into the fee wrapper, which routes funds to the child vault. The wrapper owner
/// charges performance and/or management fees on the yield.
///
/// IMPORTANT: The child vault MUST be a Morpho Vault V2. Do not deploy fee wrappers on Morpho Vault V1 instances.
/// The adapter name "MorphoVaultV1Adapter" is a legacy naming artifact; the adapter is ERC4626-compatible,
/// but V2 is the only audited and recommended configuration.
///
/// ---- What is FIXED at deployment (cannot be changed after) ----
///
///   - addAdapter:     ABDICATED (the single adapter pointing to the child vault is permanent)
///   - removeAdapter:  ABDICATED (the adapter cannot be removed)
///
/// ---- What is set to RECOMMENDED DEFAULTS ----
///
///   - Absolute cap:              type(uint128).max (no restriction)
///   - Relative cap:              WAD / 100% (all funds can flow to the child vault)
///   - Max rate:                  MAX_MAX_RATE / 200% APR (does not artificially cap child vault returns)
///   - Force deallocate penalty:  MAX_FORCE_DEALLOCATE_PENALTY / 2% (disincentivizes forceAllocate spam)
///   - Liquidity adapter:         The MorphoVaultV1Adapter with empty data
///   - Allocator:                 The owner
///   - Sentinel:                  The owner
///   - Curator:                   The owner
///
/// ---- What is CONFIGURABLE by the deployer ----
///
///   - owner:                     The final owner of the fee wrapper (MUST be a safe wallet, e.g. multisig)
///   - name / symbol:             The ERC20 name and symbol of the fee wrapper token
///   - performanceFee:            Performance fee (in WAD, max 50%). Set to 0 to skip.
///   - managementFee:             Management fee (in WAD per second, max ~5% APR). Set to 0 to skip.
///   - feeRecipient:              The address receiving both performance and management fees
///   - abdicateNonCriticalGates:  If true, permanently abdicates 3 gate setters (receiveShares, sendShares,
///                                receiveAssets) to guarantee non-custodial operation. The sendAssets gate is
///                                not abdicated because it is non-critical (cannot lock user funds).
///                                See "Gates & Non-Custodiality" below.
///
/// ---- Gates & Non-Custodiality ----
///
///   By default, all four gates are set to address(0) (disabled / permissionless).
///   This means anyone can deposit, withdraw, and transfer freely.
///
///   For NON-CUSTODIAL guarantees: set abdicateNonCriticalGates = true.
///   This permanently locks the three critical gates to address(0), ensuring no one can ever
///   restrict deposits, withdrawals, or transfers. This is the recommended setup for DeFi-native
///   deployments where trustless access matters.
///
///   For COMPLIANCE use cases (e.g. KYC/AML allowlists, Fireblocks, institutional mandates):
///   leave abdicateNonCriticalGates = false. The owner/curator retains the ability to set gates
///   later via the timelock mechanism. Be aware this makes the vault partially custodial.
///
/// ---- Roles & Responsibilities ----
///
///   Owner:     Full control. Sets curator, sentinels, name/symbol. Must be a secure wallet.
///              The owner carries real operational responsibility. Do NOT use a personal hot wallet.
///   Curator:   Same as owner. Sets fees, gates, caps, allocators, timelocks, adapter registry.
///   Allocator: Same as owner. Rebalances liquidity, sets liquidity adapter and max rate.
///   Sentinel:  Same as owner (or a dedicated monitoring bot). Emergency fund recovery: if the
///              child vault is compromised, the sentinel can set caps to zero and deallocate
///              funds back to idle. Do NOT skip this role.
///
/// ---- Auth Model Recap ----
///
///   Owner functions (no timelock):  setOwner, setCurator, setIsSentinel, setName, setSymbol
///   Curator functions (timelocked): addAdapter, removeAdapter, abdicate, setIsAllocator,
///                                   set*Gate, increaseAbsoluteCap, increaseRelativeCap,
///                                   setPerformanceFee, setManagementFee, set*FeeRecipient,
///                                   setForceDeallocatePenalty, increaseTimelock, decreaseTimelock,
///                                   setAdapterRegistry
///   Allocator functions (no timelock): allocate, deallocate, setLiquidityAdapterAndData, setMaxRate
///
///   At vault creation, all timelocks are 0. This allows the deployer to submit + execute
///   curator functions atomically in the same transaction.
///
/// ---- Deterministic Address & Front-Running Protection ----
///
///   The wrapper vault is created via CREATE2, so its address is deterministic. A naive
///   implementation that forwarded the raw `config.salt` to the factory would be vulnerable to
///   address squatting: the factory computes the address from (factory, salt, initCodeHash), and
///   because this deployer is always the initial owner, the initCodeHash is identical for every
///   caller. A mempool observer could copy a pending `salt`, substitute their own `owner` and a
///   malicious (same-asset) `childVault`, front-run the victim, and occupy the victim's
///   pre-computed address with an attacker-controlled, fund-draining configuration.
///
///   To make squatting impossible, the CREATE2 salt actually used is NOT `config.salt` directly.
///   It is an "effective salt" derived from the authenticated deployment parameters:
///
///       effectiveSalt = keccak256(abi.encode(msg.sender, owner, childVault, salt))
///
///   Consequences:
///     - The deployed address is a pure function of (deployer EOA, owner, childVault, salt).
///     - A front-runner necessarily has a different `msg.sender`, so they land on a DIFFERENT
///       address and can never occupy the address a victim pre-computed. Substituting `owner` or
///       `childVault` likewise yields a different address.
///     - The deployment address is therefore bound to the trusted configuration. Anyone can
///       reproduce it off-chain (or on-chain via `feeWrapperSalt`) knowing only the intended
///       deployer address and the config.
///
///   IMPORTANT: This contract is a low-level building block. The sanctioned way to deploy a fee
///   wrapper is through the `script/DeployFeeWrapper.s.sol` Foundry script, which pins the
///   broadcaster (the salt-binding `msg.sender`), logs the resulting deterministic address, and
///   keeps deployments reproducible. Do not call `createFeeWrapper` ad hoc from other contracts
///   or from unpinned tooling: the address is only meaningful relative to the caller that created
///   it, and off-script calls make provenance and address prediction harder to reason about.
contract FeeWrapperDeployer {
    /// @notice Emitted once a fee wrapper has been fully deployed and handed over to its owner.
    /// @param vault The deterministic address of the deployed fee wrapper VaultV2.
    /// @param caller The address that called createFeeWrapper (part of the CREATE2 salt).
    /// @param owner The final owner the wrapper was handed over to (part of the CREATE2 salt).
    /// @param childVault The wrapped child vault (part of the CREATE2 salt).
    /// @param userSalt The user-supplied salt entropy (config.salt).
    event FeeWrapperCreated(
        address indexed vault, address indexed caller, address indexed owner, address childVault, bytes32 userSalt
    );

    /// @notice Computes the CREATE2 salt that {createFeeWrapper} will use for a given caller and
    /// configuration. Use this to pre-compute or verify a fee wrapper's deterministic address
    /// off-chain: the wrapper is deployed by `morphoVaultV2Factory` at
    /// CREATE2(factory, feeWrapperSalt(...), keccak256(VaultV2 initCode ++ abi.encode(this, asset))).
    /// @param caller The address that will call {createFeeWrapper} (i.e. the deploy tx sender).
    /// @param owner The final owner from the config.
    /// @param childVault The child vault from the config.
    /// @param userSalt The user-supplied salt from the config.
    /// @return The effective CREATE2 salt, bound to the caller and the trusted parameters.
    function feeWrapperSalt(address caller, address owner, address childVault, bytes32 userSalt)
        public
        pure
        returns (bytes32)
    {
        return keccak256(abi.encode(caller, owner, childVault, userSalt));
    }

    /// @notice Configuration for a fee wrapper deployment.
    struct FeeWrapperConfig {
        // ---- Required ----
        address owner; // Final owner. MUST be a safe wallet (multisig, institutional, etc.).
        bytes32 salt; // User entropy for deterministic deployment. The effective CREATE2 salt is
        // keccak256(abi.encode(msg.sender, owner, childVault, salt)); see feeWrapperSalt.
        address childVault; // The underlying Morpho Vault V2 to wrap. MUST be a V2 vault.
        // ---- Token metadata ----
        string name; // ERC20 name for the fee wrapper token. Can be empty (settable later by owner).
        string symbol; // ERC20 symbol for the fee wrapper token. Can be empty (settable later by owner).
        // ---- Fees (optional, can be configured later by curator) ----
        uint256 performanceFee; // Performance fee in WAD (e.g. 0.1e18 = 10%). Set to 0 to skip.
        uint256 managementFee; // Management fee in WAD/second (e.g. ~1.585e9 for ~5% APR). Set to 0 to skip.
        address feeRecipient; // Address receiving fees. Required if either fee > 0.
        // ---- Non-custodiality option ----
        bool abdicateNonCriticalGates; // If true, abdicate 3 gate setters for non-custodial guarantees.
    }

    /// @notice Deploys and fully configures a fee wrapper VaultV2.
    /// @param morphoVaultV2Factory The VaultV2Factory address.
    /// @param morphoVaultV1AdapterFactory The MorphoVaultV1AdapterFactory address.
    /// @param config The fee wrapper configuration.
    /// @return vault The address of the deployed fee wrapper vault.
    function createFeeWrapper(
        address morphoVaultV2Factory,
        address morphoVaultV1AdapterFactory,
        FeeWrapperConfig calldata config
    ) external returns (address vault) {
        // =====================================================================
        //  PHASE 1: VAULT CREATION
        //  The deployer contract becomes temporary owner so it can configure
        //  everything atomically. Ownership is transferred at the very end.
        // =====================================================================

        // Verify the child vault is a Morpho Vault V2 created by the canonical factory.
        // This prevents wrapping V1 vaults or arbitrary ERC4626 contracts, which are
        // outside the audited configuration.
        require(
            IVaultV2Factory(morphoVaultV2Factory).isVaultV2(config.childVault),
            "FeeWrapperDeployer: child vault must be a Morpho Vault V2"
        );

        // Bind the CREATE2 salt to the caller AND the trusted parameters (owner, childVault).
        // This is what makes address squatting / front-running impossible: an attacker copying
        // config.salt from the mempool necessarily has a different msg.sender (and/or substitutes
        // owner/childVault), so they land on a different address and can never occupy the address a
        // victim pre-computed. See feeWrapperSalt and the contract-level NatSpec.
        bytes32 effectiveSalt = feeWrapperSalt(msg.sender, config.owner, config.childVault, config.salt);

        // Create the wrapper vault. The deployer is the initial owner.
        vault = IVaultV2Factory(morphoVaultV2Factory)
            .createVaultV2(
                address(this), // temporary owner = this deployer
                IVaultV2(config.childVault).asset(), // same asset as child vault
                effectiveSalt
            );

        // Make the deployer the curator so it can submit + execute timelocked functions.
        // (setCurator is an owner function, no timelock needed.)
        IVaultV2(vault).setCurator(address(this));

        // =====================================================================
        //  PHASE 2: ADAPTER SETUP (curator functions: submit + execute)
        //  Create the adapter, add it, then permanently lock the adapter config
        //  by abdicating addAdapter and removeAdapter.
        // =====================================================================

        // Create the MorphoVaultV1Adapter pointing to the child vault.
        // Despite the "V1" naming, this adapter is ERC4626-compatible and works with V2 child vaults.
        address adapter = IMorphoVaultV1AdapterFactory(morphoVaultV1AdapterFactory)
            .createMorphoVaultV1Adapter(vault, config.childVault);

        // The adapter's id data, used for cap configuration.
        // This matches the adapterId computed inside the MorphoVaultV1Adapter constructor:
        //   adapterId = keccak256(abi.encode("this", address(this)))
        bytes memory adapterIdData = abi.encode("this", adapter);

        // Add the adapter to the vault (timelocked, but timelock is 0 at creation).
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.addAdapter, (adapter)));
        IVaultV2(vault).addAdapter(adapter);

        // Permanently abdicate addAdapter: no new adapters can ever be added.
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.abdicate, (IVaultV2.addAdapter.selector)));
        IVaultV2(vault).abdicate(IVaultV2.addAdapter.selector);

        // Permanently abdicate removeAdapter: the existing adapter can never be removed.
        // Together with addAdapter abdication, this guarantees the fee wrapper will always
        // point to the same child vault.
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.abdicate, (IVaultV2.removeAdapter.selector)));
        IVaultV2(vault).abdicate(IVaultV2.removeAdapter.selector);

        // =====================================================================
        //  PHASE 3: ALLOCATOR SETUP (curator functions: submit + execute)
        //  The deployer needs to be an allocator to call setLiquidityAdapterAndData
        //  and setMaxRate in Phase 5. The final owner also becomes an allocator.
        // =====================================================================

        // Make the deployer a temporary allocator (needed for Phase 5).
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.setIsAllocator, (address(this), true)));
        IVaultV2(vault).setIsAllocator(address(this), true);

        // Make the final owner an allocator (permanent).
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.setIsAllocator, (config.owner, true)));
        IVaultV2(vault).setIsAllocator(config.owner, true);

        // =====================================================================
        //  PHASE 4: CAPS CONFIGURATION (curator functions: submit + execute)
        //  Set caps to maximum so the fee wrapper imposes no additional restriction
        //  beyond what the child vault itself enforces.
        // =====================================================================

        // Absolute cap = type(uint128).max: no limit on how many assets can be allocated.
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.increaseAbsoluteCap, (adapterIdData, type(uint128).max)));
        IVaultV2(vault).increaseAbsoluteCap(adapterIdData, type(uint128).max);

        // Relative cap = WAD (100%): all assets can flow to the child vault.
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.increaseRelativeCap, (adapterIdData, WAD)));
        IVaultV2(vault).increaseRelativeCap(adapterIdData, WAD);

        // =====================================================================
        //  PHASE 5: ALLOCATOR CONFIGURATION (allocator functions, no timelock)
        //  These require isAllocator[msg.sender], which we set in Phase 3.
        // =====================================================================

        // Set the liquidity adapter so deposits/withdrawals are automatically routed
        // through the adapter to the child vault. Empty data (hex"") because the
        // MorphoVaultV1Adapter expects zero-length data.
        IVaultV2(vault).setLiquidityAdapterAndData(adapter, hex"");

        // Set max rate to 200% APR. This avoids artificially capping returns from the
        // child vault. The max rate limits how fast the share price can increase per
        // second, protecting against donation-based manipulation.
        IVaultV2(vault).setMaxRate(MAX_MAX_RATE);

        // =====================================================================
        //  PHASE 6: PENALTY CONFIGURATION (curator function: submit + execute)
        //  Set the forceAllocate penalty to 2% (MAX_FORCE_DEALLOCATE_PENALTY).
        //  This disincentivizes forceAllocate spam: an attacker loses 2% each time
        //  they call forceDeallocate, making it economically irrational.
        // =====================================================================

        IVaultV2(vault)
            .submit(abi.encodeCall(IVaultV2.setForceDeallocatePenalty, (adapter, MAX_FORCE_DEALLOCATE_PENALTY)));
        IVaultV2(vault).setForceDeallocatePenalty(adapter, MAX_FORCE_DEALLOCATE_PENALTY);

        // =====================================================================
        //  PHASE 7: OPTIONAL FEES (curator functions: submit + execute)
        //  Fee recipients must be set BEFORE fees, because the vault enforces:
        //    fee != 0 => recipient != address(0)
        //  If fees are 0, this phase is skipped entirely.
        // =====================================================================

        if (config.performanceFee > 0) {
            // Set recipient first (fee is still 0, so the recipient invariant is satisfied).
            IVaultV2(vault).submit(abi.encodeCall(IVaultV2.setPerformanceFeeRecipient, (config.feeRecipient)));
            IVaultV2(vault).setPerformanceFeeRecipient(config.feeRecipient);

            // Now set the fee (recipient is already set).
            IVaultV2(vault).submit(abi.encodeCall(IVaultV2.setPerformanceFee, (config.performanceFee)));
            IVaultV2(vault).setPerformanceFee(config.performanceFee);
        }

        if (config.managementFee > 0) {
            // Set recipient first.
            IVaultV2(vault).submit(abi.encodeCall(IVaultV2.setManagementFeeRecipient, (config.feeRecipient)));
            IVaultV2(vault).setManagementFeeRecipient(config.feeRecipient);

            // Now set the fee.
            IVaultV2(vault).submit(abi.encodeCall(IVaultV2.setManagementFee, (config.managementFee)));
            IVaultV2(vault).setManagementFee(config.managementFee);
        }

        // =====================================================================
        //  PHASE 8: OPTIONAL NON-CUSTODIAL GATES (curator functions: submit + execute)
        //
        //  By default, all gates are address(0) (permissionless). Abdicating the gate
        //  setters permanently locks them to address(0), guaranteeing that no one can
        //  ever restrict deposits, withdrawals, or transfers.
        //
        //  Three gates are abdicated (the "critical" ones that can lock user funds):
        //    - setReceiveSharesGate:  controls who can receive shares (deposit/transfer)
        //    - setSendSharesGate:     controls who can send shares (withdraw/transfer)
        //    - setReceiveAssetsGate:  controls who can receive assets (withdraw)
        //
        //  The fourth gate (setSendAssetsGate) is NOT abdicated because it is non-critical:
        //  it can only restrict who deposits, but cannot lock existing user funds.
        //
        //  If you need compliance gates (KYC/AML), leave abdicateNonCriticalGates = false
        //  and configure gates later via the curator + timelock mechanism.
        // =====================================================================

        if (config.abdicateNonCriticalGates) {
            IVaultV2(vault).submit(abi.encodeCall(IVaultV2.abdicate, (IVaultV2.setReceiveSharesGate.selector)));
            IVaultV2(vault).abdicate(IVaultV2.setReceiveSharesGate.selector);

            IVaultV2(vault).submit(abi.encodeCall(IVaultV2.abdicate, (IVaultV2.setSendSharesGate.selector)));
            IVaultV2(vault).abdicate(IVaultV2.setSendSharesGate.selector);

            IVaultV2(vault).submit(abi.encodeCall(IVaultV2.abdicate, (IVaultV2.setReceiveAssetsGate.selector)));
            IVaultV2(vault).abdicate(IVaultV2.setReceiveAssetsGate.selector);
        }

        // =====================================================================
        //  PHASE 9: TOKEN METADATA (owner functions, no timelock)
        // =====================================================================

        if (bytes(config.name).length > 0) {
            IVaultV2(vault).setName(config.name);
        }
        if (bytes(config.symbol).length > 0) {
            IVaultV2(vault).setSymbol(config.symbol);
        }

        // =====================================================================
        //  PHASE 10: OWNERSHIP TRANSFER
        //  Remove the deployer's temporary privileges and hand everything over
        //  to the final owner.
        //
        //  Order matters here:
        //    1. Remove deployer as allocator (curator function, deployer is still curator)
        //    2. Set sentinel for owner (owner function, deployer is still owner)
        //    3. Transfer curator to owner (owner function, deployer is still owner)
        //    4. Transfer ownership to owner (owner function, MUST BE LAST)
        //
        //  After step 4, the deployer has zero privileges on the vault.
        // =====================================================================

        // 1. Remove the deployer as allocator (curator function: submit + execute).
        IVaultV2(vault).submit(abi.encodeCall(IVaultV2.setIsAllocator, (address(this), false)));
        IVaultV2(vault).setIsAllocator(address(this), false);

        // 2. Set the owner as sentinel.
        //    The sentinel can deallocate funds in emergencies (e.g. child vault compromised).
        //    This is a critical safety role. Do NOT skip.
        IVaultV2(vault).setIsSentinel(config.owner, true);

        // 3. Transfer curator role to the final owner.
        IVaultV2(vault).setCurator(config.owner);

        // 4. Transfer ownership. THIS MUST BE THE LAST CALL.
        //    After this, the deployer contract has no privileges on the vault.
        IVaultV2(vault).setOwner(config.owner);

        emit FeeWrapperCreated(vault, msg.sender, config.owner, config.childVault, config.salt);
    }
}

lib/morpho-snippets/lib/vault-v2/src/adapters/interfaces/IMorphoVaultV1AdapterFactory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;

interface IMorphoVaultV1AdapterFactory {
    /* EVENTS */

    event CreateMorphoVaultV1Adapter(
        address indexed parentVault, address indexed morphoVaultV1, address indexed morphoVaultV1Adapter
    );

    /* FUNCTIONS */

    function morphoVaultV1Adapter(address parentVault, address morphoVaultV1) external view returns (address);
    function isMorphoVaultV1Adapter(address account) external view returns (bool);
    function createMorphoVaultV1Adapter(address parentVault, address morphoVaultV1)
        external
        returns (address morphoVaultV1Adapter);
}

lib/morpho-snippets/lib/vault-v2/src/interfaces/IERC20.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;

interface IERC20 {
    function decimals() external view returns (uint8);
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 shares) external returns (bool success);
    function transferFrom(address from, address to, uint256 shares) external returns (bool success);
    function approve(address spender, uint256 shares) external returns (bool success);
    function allowance(address owner, address spender) external view returns (uint256);
}

lib/morpho-snippets/lib/vault-v2/src/interfaces/IERC2612.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;

interface IERC2612 {
    function permit(address owner, address spender, uint256 shares, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;
    function nonces(address owner) external view returns (uint256);
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/morpho-snippets/lib/vault-v2/src/interfaces/IERC4626.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;

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

interface IERC4626 is IERC20 {
    function asset() external view returns (address);
    function totalAssets() external view returns (uint256);
    function convertToAssets(uint256 shares) external view returns (uint256 assets);
    function convertToShares(uint256 assets) external view returns (uint256 shares);
    function deposit(uint256 assets, address onBehalf) external returns (uint256 shares);
    function mint(uint256 shares, address onBehalf) external returns (uint256 assets);
    function withdraw(uint256 assets, address receiver, address onBehalf) external returns (uint256 shares);
    function redeem(uint256 shares, address receiver, address onBehalf) external returns (uint256 assets);
    function previewDeposit(uint256 assets) external view returns (uint256 shares);
    function previewMint(uint256 shares) external view returns (uint256 assets);
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);
    function previewRedeem(uint256 shares) external view returns (uint256 assets);
    function maxDeposit(address onBehalf) external view returns (uint256 assets);
    function maxMint(address onBehalf) external view returns (uint256 shares);
    function maxWithdraw(address onBehalf) external view returns (uint256 assets);
    function maxRedeem(address onBehalf) external view returns (uint256 shares);
}

lib/morpho-snippets/lib/vault-v2/src/interfaces/IVaultV2.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;

import {IERC4626} from "./IERC4626.sol";
import {IERC2612} from "./IERC2612.sol";

struct Caps {
    uint256 allocation;
    uint128 absoluteCap;
    uint128 relativeCap;
}

interface IVaultV2 is IERC4626, IERC2612 {
    // State variables
    function virtualShares() external view returns (uint256);
    function owner() external view returns (address);
    function curator() external view returns (address);
    function receiveSharesGate() external view returns (address);
    function sendSharesGate() external view returns (address);
    function receiveAssetsGate() external view returns (address);
    function sendAssetsGate() external view returns (address);
    function adapterRegistry() external view returns (address);
    function isSentinel(address account) external view returns (bool);
    function isAllocator(address account) external view returns (bool);
    function firstTotalAssets() external view returns (uint256);
    function _totalAssets() external view returns (uint128);
    function lastUpdate() external view returns (uint64);
    function maxRate() external view returns (uint64);
    function adapters(uint256 index) external view returns (address);
    function adaptersLength() external view returns (uint256);
    function isAdapter(address account) external view returns (bool);
    function allocation(bytes32 id) external view returns (uint256);
    function absoluteCap(bytes32 id) external view returns (uint256);
    function relativeCap(bytes32 id) external view returns (uint256);
    function forceDeallocatePenalty(address adapter) external view returns (uint256);
    function liquidityAdapter() external view returns (address);
    function liquidityData() external view returns (bytes memory);
    function timelock(bytes4 selector) external view returns (uint256);
    function abdicated(bytes4 selector) external view returns (bool);
    function executableAt(bytes memory data) external view returns (uint256);
    function performanceFee() external view returns (uint96);
    function performanceFeeRecipient() external view returns (address);
    function managementFee() external view returns (uint96);
    function managementFeeRecipient() external view returns (address);

    // Gating
    function canSendShares(address account) external view returns (bool);
    function canReceiveShares(address account) external view returns (bool);
    function canSendAssets(address account) external view returns (bool);
    function canReceiveAssets(address account) external view returns (bool);

    // Multicall
    function multicall(bytes[] memory data) external;

    // Owner functions
    function setOwner(address newOwner) external;
    function setCurator(address newCurator) external;
    function setIsSentinel(address account, bool isSentinel) external;
    function setName(string memory newName) external;
    function setSymbol(string memory newSymbol) external;

    // Timelocks for curator functions
    function submit(bytes memory data) external;
    function revoke(bytes memory data) external;

    // Curator functions
    function setIsAllocator(address account, bool newIsAllocator) external;
    function setReceiveSharesGate(address newReceiveSharesGate) external;
    function setSendSharesGate(address newSendSharesGate) external;
    function setReceiveAssetsGate(address newReceiveAssetsGate) external;
    function setSendAssetsGate(address newSendAssetsGate) external;
    function setAdapterRegistry(address newAdapterRegistry) external;
    function addAdapter(address account) external;
    function removeAdapter(address account) external;
    function increaseTimelock(bytes4 selector, uint256 newDuration) external;
    function decreaseTimelock(bytes4 selector, uint256 newDuration) external;
    function abdicate(bytes4 selector) external;
    function setPerformanceFee(uint256 newPerformanceFee) external;
    function setManagementFee(uint256 newManagementFee) external;
    function setPerformanceFeeRecipient(address newPerformanceFeeRecipient) external;
    function setManagementFeeRecipient(address newManagementFeeRecipient) external;
    function increaseAbsoluteCap(bytes memory idData, uint256 newAbsoluteCap) external;
    function decreaseAbsoluteCap(bytes memory idData, uint256 newAbsoluteCap) external;
    function increaseRelativeCap(bytes memory idData, uint256 newRelativeCap) external;
    function decreaseRelativeCap(bytes memory idData, uint256 newRelativeCap) external;
    function setMaxRate(uint256 newMaxRate) external;
    function setForceDeallocatePenalty(address adapter, uint256 newForceDeallocatePenalty) external;

    // Allocator functions
    function allocate(address adapter, bytes memory data, uint256 assets) external;
    function deallocate(address adapter, bytes memory data, uint256 assets) external;
    function setLiquidityAdapterAndData(address newLiquidityAdapter, bytes memory newLiquidityData) external;

    // Exchange rate
    function accrueInterest() external;
    function accrueInterestView()
        external
        view
        returns (uint256 newTotalAssets, uint256 performanceFeeShares, uint256 managementFeeShares);

    // Force deallocate
    function forceDeallocate(address adapter, bytes memory data, uint256 assets, address onBehalf)
        external
        returns (uint256 penaltyShares);
}

lib/morpho-snippets/lib/vault-v2/src/interfaces/IVaultV2Factory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;

interface IVaultV2Factory {
    /* EVENTS */

    event CreateVaultV2(address indexed owner, address indexed asset, bytes32 salt, address indexed newVaultV2);

    /* FUNCTIONS */

    function isVaultV2(address account) external view returns (bool);
    function vaultV2(address owner, address asset, bytes32 salt) external view returns (address);
    function createVaultV2(address owner, address asset, bytes32 salt) external returns (address newVaultV2);
}

lib/morpho-snippets/lib/vault-v2/src/libraries/ConstantsLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity ^0.8.0;

uint256 constant WAD = 1e18;
bytes32 constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
bytes32 constant PERMIT_TYPEHASH =
    keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
uint256 constant MAX_MAX_RATE = 200e16 / uint256(365 days); // 200% APR
uint256 constant MAX_PERFORMANCE_FEE = 0.5e18; // 50%
uint256 constant MAX_MANAGEMENT_FEE = 0.05e18 / uint256(365 days); // 5%
uint256 constant MAX_FORCE_DEALLOCATE_PENALTY = 0.02e18; // 2%
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 100000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts-v4/contracts/",
    "@aave-v3-core/=lib/aave-v3-core/contracts/",
    "@aave-vault/=lib/Aave-Vault/src/",
    "forge-std/=lib/forge-std/src/",
    "@morpho-snippets/=lib/morpho-snippets/src/",
    "@aave-v3-periphery/=lib/Aave-Vault/lib/aave-v3-periphery/contracts/",
    "@openzeppelin-upgradeable/=lib/Aave-Vault/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin-v5/=lib/Aave-Vault/lib/openzeppelin-contracts-v5.3.0/contracts/",
    "@pcaversaccio/createx/=lib/Aave-Vault/lib/createx/src/",
    "Aave-Vault/=lib/Aave-Vault/",
    "aave-v3-core/=lib/aave-v3-core/",
    "aave-v3-periphery/=lib/Aave-Vault/lib/aave-v3-periphery/contracts/",
    "createx/=lib/Aave-Vault/lib/createx/src/",
    "ds-test/=lib/morpho-snippets/lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/Aave-Vault/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/morpho-snippets/lib/vault-v2/lib/morpho-blue/lib/halmos-cheatcodes/src/",
    "metamorpho-v1.1/=lib/morpho-snippets/lib/vault-v2/lib/metamorpho-v1.1/",
    "metamorpho/=lib/morpho-snippets/lib/metamorpho/",
    "morpho-blue-irm/=lib/morpho-snippets/lib/vault-v2/lib/morpho-blue-irm/",
    "morpho-blue/=lib/morpho-snippets/lib/morpho-blue/",
    "morpho-snippets/=lib/morpho-snippets/",
    "openzeppelin-contracts-upgradeable/=lib/Aave-Vault/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts-v4/=lib/openzeppelin-contracts-v4/",
    "openzeppelin-contracts/=lib/morpho-snippets/lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts-v4/contracts/",
    "solady/=lib/Aave-Vault/lib/createx/lib/solady/",
    "solmate/=lib/morpho-snippets/lib/solmate/src/",
    "vault-v2/=lib/morpho-snippets/lib/vault-v2/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.