Skip to content
Verified contractPartialApache-2.0

ForceRedeemMorphoVaultHook

Address0x798a8457ef2412d9304bfaf4e3a40206ed3bbe3f
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
License
Apache-2.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,391,015
Creation transaction
0x05a7ce7816…33e51109e2

src/hooks/vaults/metamorpho/ForceRedeemMorphoVaultHook.sol

// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;

// external
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { BytesLib } from "../../../vendor/BytesLib.sol";
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";

// Superform
import { BaseHook } from "../../BaseHook.sol";
import { HookSubTypes } from "../../../libraries/HookSubTypes.sol";
import { HookDataDecoder } from "../../../libraries/HookDataDecoder.sol";
import {
    ISuperHookResult,
    ISuperHookContextAware,
    ISuperHookInspector,
    ISuperHookInflowOutflow,
    ISuperHookOutflow
} from "../../../interfaces/ISuperHook.sol";
import { IMorphoVaultV2 } from "../../../vendor/morpho/IMorphoVaultV2.sol";
import { IMorphoMarketV1Adapter } from "../../../vendor/morpho/IMorphoMarketV1Adapter.sol";
import { IMorphoStaticTyping, MarketParams, Id } from "../../../vendor/morpho/IMorpho.sol";
import { MathLib } from "../../../vendor/morpho/MathLib.sol";

/// @title ForceRedeemMorphoVaultHook
/// @author Superform Labs
/// @notice OUTFLOW hook that exits an illiquid Morpho Vault V2 in one call: force-deallocates across the
///         vault's listed markets, cheapest-penalty-first, then withdraws the freed underlying.
/// @dev Third member of the family, replacing neither. `ForceDeallocateMorphoHook` takes one market;
///      `ForceDeallocateMorphoVaultHook` reads the whole list but stops at the vault's idle balance, and is
///      LIVE (mainnet 0x81fCC76adcE2180D43b375D6d065FE81bc15586e), which is why this is not a rename of it.
/// @dev data has the following structure
/// @notice         bytes32 yieldSourceOracleId = bytes32(BytesLib.slice(data, 0, 32), 0);
/// @notice         address yieldSource = BytesLib.toAddress(data, 32);
/// @notice         uint256 assets = BytesLib.toUint256(data, 52);
/// @notice         bool usePrevHookAmount = _decodeBool(data, 84);
/// @dev Those four lines ARE the OMS registry build path, not documentation. Renaming a field changes
///      what Superman can encode: `yieldSourceOracleId` must not match `^placeholder\d*$` (zero-filled),
///      and OMS asset identity reads the field named literally `yieldSource`.
/// @dev Deallocating without withdrawing is not an exit: the freed underlying lands in the VAULT'S own
///      balance, which `withdraw` pays to whoever burns shares next, while the penalty is already burned.
///      Hence one call, and the vault's idle ends where it started.
/// @dev `withdraw`, not `redeem` — the calldata amount is underlying. `receiver` and `onBehalf` are both
///      the account, so `msg.sender == onBehalf` and Vault V2's `exit` needs no share allowance.
/// @dev OUTFLOW/ERC4626 because it pays the account, so offset 0 must carry the chain's real oracle id;
///      a zero or unregistered id reverts `MANAGER_NOT_SET`. The deallocate siblings ignore that field.
/// @dev Do not place another exit on the same position after this hook; it has already withdrawn.
/// @dev Trusts Vault V2's reentrancy guards, adapter registry and 2% penalty ceiling. The adapter SET is
///      curator-controlled, which is why every adapter is identity-checked and gas-stipended.
contract ForceRedeemMorphoVaultHook is
    BaseHook,
    ISuperHookContextAware,
    ISuperHookInflowOutflow,
    ISuperHookOutflow
{
    using BytesLib for bytes;
    using HookDataDecoder for bytes;
    using MathLib for uint256;

    /*//////////////////////////////////////////////////////////////
                                ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice A cap of zero, or one above Morpho's own 2% ceiling, would be meaningless
    error INVALID_PENALTY_CAP();
    /// @notice The fill fell short AND an adapter was excluded for being over the cap
    /// @dev A diagnostic, not a gate: an over-cap adapter is skipped. This fires only when the cap is
    ///      the actual cause, turning an opaque "not enough liquidity" into something actionable.
    error PENALTY_ABOVE_CAP(uint256 penaltyWad, uint256 capWad);
    /// @notice The payload is not exactly the declared 85-byte layout
    error INVALID_DATA_LENGTH(uint256 given, uint256 expected);
    /// @notice The vault lists more markets than one transaction will walk
    error TOO_MANY_MARKETS(uint256 count, uint256 maxCount);
    /// @notice The vault registers more adapters than one transaction will probe
    error TOO_MANY_ADAPTERS(uint256 count, uint256 maxCount);
    /// @notice Every eligible market together cannot cover the request
    error SHORTFALL(uint256 available, uint256 requested);
    /// @notice The account cannot cover the penalty share burn the planned pulls would charge
    error INSUFFICIENT_SHARES(uint256 held, uint256 required);

    /*//////////////////////////////////////////////////////////////
                              CONSTANTS
    //////////////////////////////////////////////////////////////*/

    /// @notice Morpho Vault V2's own hard ceiling on `forceDeallocatePenalty`, in WAD (2%).
    /// @dev A compile-time constant in Morpho's non-upgradeable bytecode, so it cannot be raised. A cap
    ///      above it would never bind and is rejected in the constructor as a configuration error.
    uint256 public constant MORPHO_MAX_PENALTY_WAD = 0.02e18;

    /// @dev A DoS bound. `build` runs on chain inside the UserOp, so without it a curator could grow the
    ///      market list until every exit ran out of gas. Gauntlet WETH Prime listed 3 on 2026-11-10.
    uint256 public constant MAX_MARKETS = 32;

    /// @dev `MAX_MARKETS` does not bound this: shape-rejected adapters contribute zero markets, so a long
    ///      list of junk adapters would still be walked in full, each costing a cold read and a probe.
    uint256 public constant MAX_ADAPTERS = 32;

    /// @notice The single sized leg. `replaceCalldataAmounts` writes bytes 52..83 and nothing else.
    uint256 private constant AMOUNT_POSITION = 52;
    uint256 private constant USE_PREV_HOOK_AMOUNT_POSITION = 84;
    /// @notice Exact, not minimum: there is no adapter and no `adapterData` tail in this layout, so a
    ///         longer payload is a caller error rather than a trailing blob to forward.
    uint256 private constant DATA_LENGTH = 85;

    /// @dev Measured, and the SUM is what matters: 192 probes worst case, so 100_000 each exceeded the
    ///      16,777,216 (2^24) per-tx cap from EIP-7825. This is ~3x the heaviest honest probe
    ///      (`expectedSupplyAssets`, 22,663 gas cold on mainnet); both bounds are pinned by tests.
    uint256 private constant PROBE_GAS = 70_000;

    /*//////////////////////////////////////////////////////////////
                              IMMUTABLES
    //////////////////////////////////////////////////////////////*/

    /// @dev An immutable, not a calldata field: it keeps the 85-byte layout, lands in the CREATE2 address
    ///      so every leaf already commits to it, and cannot be set vacuously by whoever builds calldata.
    /// @dev Needed despite Morpho's own 2% ceiling, because the per-adapter rate is curator-settable and
    ///      read at execution time, while signed intents can land much later.
    uint256 public immutable MAX_PENALTY_WAD;

    /// @dev An immutable gate: `adapter.morpho()` comes from a curator-registered contract and was otherwise
    ///      the target of typed, un-stipended reads — able to revert `build`, burn gas or claim unlimited
    ///      capacity. It also keeps the per-market-id ledger key sound; ids collide across deployments.
    address public immutable MORPHO;

    /*//////////////////////////////////////////////////////////////
                               STRUCTS
    //////////////////////////////////////////////////////////////*/

    /// @notice What the adapter-level probe concluded about one entry in `vault.adapters`
    struct AdapterInfo {
        bool eligible;
        address adapter;
        address morpho;
        /// @dev `address(0)` means "this adapter pins no IRM" (the V1 shape), not "pins the zero IRM".
        address adaptiveCurveIrm;
        uint256 marketCount;
        uint256 penaltyWad;
    }

    /// @notice One (adapter, market) pair that survived every filter
    struct Candidate {
        address adapter;
        /// @dev Kept so the fill loop can net out liquidity already committed to the SAME market id by a
        ///      different adapter. See `_fill`.
        bytes32 marketId;
        uint256 penaltyWad;
        uint256 position;
        uint256 liquidity;
        /// @dev Carried rather than re-read, so the bytes handed to `forceDeallocate` cannot differ from
        ///      the params this pass filtered on.
        MarketParams params;
    }

    /// @notice One planned `forceDeallocate`
    struct Pull {
        address adapter;
        uint256 amount;
        MarketParams params;
    }

    /// @notice The outcome of the greedy fill
    struct Plan {
        Pull[] pulls;
        uint256 totalPenaltyAssets;
        /// @dev Count of pulls charging a NON-ZERO penalty. Drives the `+ n` rounding slack in the
        ///      solvency bound; a zero-penalty leg burns no shares and contributes no rounding.
        uint256 penalisedCount;
    }

    /*//////////////////////////////////////////////////////////////
                             CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    /// @param morpho_ The Morpho Blue singleton for this chain. Adapters pointing anywhere else are
    ///        skipped. Part of the CREATE2 address, so it cannot be repointed after deployment.
    /// @param maxPenaltyWad_ Ceiling in WAD. Must be non-zero and at most `MORPHO_MAX_PENALTY_WAD`; a cap
    ///        above Morpho's own ceiling could never bind.
    constructor(address morpho_, uint256 maxPenaltyWad_) BaseHook(HookType.OUTFLOW, HookSubTypes.ERC4626) {
        if (morpho_ == address(0)) revert ADDRESS_NOT_VALID();
        if (maxPenaltyWad_ == 0 || maxPenaltyWad_ > MORPHO_MAX_PENALTY_WAD) revert INVALID_PENALTY_CAP();
        MORPHO = morpho_;
        MAX_PENALTY_WAD = maxPenaltyWad_;
    }

    /// @notice Human-readable name for UI display
    function name() external pure override returns (string memory) {
        return "Force Redeem Morpho Vault";
    }

    /// @notice One-sentence description of what this hook does
    function description() external pure override returns (string memory) {
        return "Force deallocates across a Morpho Vault V2's markets and withdraws the assets";
    }

    /*//////////////////////////////////////////////////////////////
                                 VIEW METHODS
    //////////////////////////////////////////////////////////////*/

    /// @dev Everything lives in this one view because `BaseHook.build` offers no non-view phase: resolve,
    ///      count and bound, collect with capacities, order cheapest-first, fill, then prove solvency.
    function _buildHookExecutions(
        address prevHook,
        address account,
        bytes calldata data
    )
        internal
        view
        override
        returns (Execution[] memory executions)
    {
        (address vault, uint256 assets) = _resolveRequest(prevHook, account, data);

        AdapterInfo[] memory infos = _probeAdapters(vault);
        Candidate[] memory candidates = _collectCandidates(vault, infos);
        Plan memory plan = _fill(candidates, _sortOrder(candidates), assets, infos);

        _requireSolvent(vault, account, assets, plan);

        return _emit(vault, account, assets, plan.pulls);
    }

    /// @dev `!=`, not `<`: a longer payload has nowhere to go, so accepting it would ignore caller bytes.
    function _resolveRequest(
        address prevHook,
        address account,
        bytes calldata data
    )
        private
        view
        returns (address vault, uint256 assets)
    {
        if (data.length != DATA_LENGTH) revert INVALID_DATA_LENGTH(data.length, DATA_LENGTH);

        vault = data.extractYieldSource();
        if (vault == address(0)) revert ADDRESS_NOT_VALID();

        assets = data.toUint256(AMOUNT_POSITION);
        if (_decodeBool(data, USE_PREV_HOOK_AMOUNT_POSITION)) {
            if (prevHook == address(0)) revert ADDRESS_NOT_VALID();
            assets = ISuperHookResult(prevHook).getOutAmount(account);
        }
        if (assets == 0) revert AMOUNT_NOT_VALID();
    }

    /// @dev Counts only adapters surviving the adapter-level filter — a rejected one contributes zero,
    ///      because its `marketIds` are never read. Markets dropped later still count.
    function _probeAdapters(address vault) private view returns (AdapterInfo[] memory infos) {
        uint256 len = IMorphoVaultV2(vault).adaptersLength();
        if (len > MAX_ADAPTERS) revert TOO_MANY_ADAPTERS(len, MAX_ADAPTERS);
        infos = new AdapterInfo[](len);

        uint256 total;
        for (uint256 i; i < len; ++i) {
            infos[i] = _probeAdapter(vault, IMorphoVaultV2(vault).adapters(i));
            if (!infos[i].eligible) continue;
            total += infos[i].marketCount;
            // Stop walking the moment the ceiling is breached; the revert is the same either way, and
            // continuing would pay for probes whose results are about to be discarded.
            if (total > MAX_MARKETS) revert TOO_MANY_MARKETS(total, MAX_MARKETS);
        }
    }

    /// @dev Every read is a guarded `staticcall`, not `try/catch`: the adapter list is heterogeneous and a
    ///      `STATICCALL` to a codeless address succeeds with empty returndata. Ineligible means skipped.
    function _probeAdapter(address vault, address adapter) private view returns (AdapterInfo memory info) {
        info.adapter = adapter;

        (bool ok, bytes32 word) = _probe(adapter, abi.encodeCall(IMorphoMarketV1Adapter.parentVault, ()));
        if (!ok || address(uint160(uint256(word))) != vault) return info;

        // Equality with the immutable, NOT merely "is a contract". See `MORPHO`.
        (ok, word) = _probe(adapter, abi.encodeCall(IMorphoMarketV1Adapter.morpho, ()));
        if (!ok || address(uint160(uint256(word))) != MORPHO) return info;
        info.morpho = MORPHO;

        (ok, word) = _probe(adapter, abi.encodeCall(IMorphoMarketV1Adapter.marketIdsLength, ()));
        if (!ok) return info;
        info.marketCount = uint256(word);

        info.penaltyWad = IMorphoVaultV2(vault).forceDeallocatePenalty(adapter);
        if (info.penaltyWad > MAX_PENALTY_WAD) return info;

        // Absent on the V1 adapter shape; a failed read is "pins no IRM", which is the correct reading.
        (ok, word) = _probe(adapter, abi.encodeCall(IMorphoMarketV1Adapter.adaptiveCurveIrm, ()));
        if (ok) info.adaptiveCurveIrm = address(uint160(uint256(word)));

        info.eligible = true;
    }

    /// @notice Pass B: expand each eligible adapter's market list into scored candidates
    function _collectCandidates(
        address vault,
        AdapterInfo[] memory infos
    )
        private
        view
        returns (Candidate[] memory candidates)
    {
        address asset = IMorphoVaultV2(vault).asset();
        Candidate[] memory scratch = new Candidate[](MAX_MARKETS);
        uint256 found;

        // Adapter-major, market-minor. The fill sort is STABLE, so this order supplies the
        // "adapter index then market index ascending" tie-break for free.
        for (uint256 i; i < infos.length; ++i) {
            if (!infos[i].eligible) continue;
            for (uint256 j; j < infos[i].marketCount; ++j) {
                (bool ok, Candidate memory c) = _marketCapacity(infos[i], j, asset);
                if (ok && !_alreadyCollected(scratch, found, c.adapter, c.marketId)) scratch[found++] = c;
            }
        }

        candidates = new Candidate[](found);
        for (uint256 k; k < found; ++k) {
            candidates[k] = scratch[k];
        }
    }

    /// @dev Deduplication is correctness: `expectedSupplyAssets` returns one number per (adapter, market),
    ///      so a duplicate listing describes the same capacity. Left in, the plan pulls twice the position
    ///      and the second call reverts — the liquidity ledger does not catch it.
    function _alreadyCollected(
        Candidate[] memory collected,
        uint256 count,
        address adapter,
        bytes32 marketId
    )
        private
        pure
        returns (bool)
    {
        for (uint256 i; i < count; ++i) {
            if (collected[i].adapter == adapter && collected[i].marketId == marketId) return true;
        }
        return false;
    }

    /// @dev Both bounds are real: `expectedSupplyAssets` is the adapter's accrued position, which can
    ///      exceed what the market can pay; exceeding either reverts and takes the transaction with it.
    function _marketCapacity(
        AdapterInfo memory info,
        uint256 index,
        address asset
    )
        private
        view
        returns (bool ok, Candidate memory c)
    {
        bytes32 word;
        (ok, word) = _probe(info.adapter, abi.encodeCall(IMorphoMarketV1Adapter.marketIds, (index)));
        if (!ok) return (false, c);

        c.marketId = word;
        c.params = _marketParams(info.morpho, word);
        if (c.params.loanToken == address(0) || c.params.loanToken != asset) return (false, c);
        // The V2 adapter reverts `IrmMismatch` on a market outside its pinned IRM, which would revert the
        // whole fill, so such a market is dropped here rather than discovered at execution time.
        if (info.adaptiveCurveIrm != address(0) && c.params.irm != info.adaptiveCurveIrm) return (false, c);

        c.liquidity = _marketLiquidity(info.morpho, word);
        if (c.liquidity == 0) return (false, c);

        (ok, word) = _probe(info.adapter, abi.encodeCall(IMorphoMarketV1Adapter.expectedSupplyAssets, (c.marketId)));
        if (!ok) return (false, c);
        c.position = uint256(word);
        if (c.position == 0) return (false, c);

        c.adapter = info.adapter;
        c.penaltyWad = info.penaltyWad;
        ok = true;
    }

    /// @dev Raw, and exact: `supply - borrow` is invariant under accrual, since `_accrueInterest` adds the
    ///      same `interest` to both asset legs and pays the fee by minting shares. Morpho's own withdraw
    ///      guard is this same difference, which is why matching it exactly is admissible.
    function _marketLiquidity(address morpho, bytes32 marketId) private view returns (uint256) {
        (uint128 supplyAssets,, uint128 borrowAssets,,,) = IMorphoStaticTyping(morpho).market(Id.wrap(marketId));
        return supplyAssets > borrowAssets ? uint256(supplyAssets - borrowAssets) : 0;
    }

    /// @notice The market's parameters, or an all-zero struct when the id is unknown to Morpho
    function _marketParams(address morpho, bytes32 marketId) private view returns (MarketParams memory params) {
        (params.loanToken, params.collateralToken, params.oracle, params.irm, params.lltv) =
            IMorphoStaticTyping(morpho).idToMarketParams(Id.wrap(marketId));
    }

    /// @dev Indices, not structs. Stability is load-bearing: discovery is adapter-major/market-minor, so a
    ///      stable sort supplies the spec's final tie-break for free. Insertion sort because n <= 32.
    function _sortOrder(Candidate[] memory candidates) private pure returns (uint256[] memory order) {
        uint256 n = candidates.length;
        order = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            order[i] = i;
        }

        for (uint256 i = 1; i < n; ++i) {
            uint256 slot = order[i];
            uint256 j = i;
            while (j > 0 && _cheaperFirst(candidates[slot], candidates[order[j - 1]])) {
                order[j] = order[j - 1];
                --j;
            }
            order[j] = slot;
        }
    }

    /// @notice Strict ordering predicate: is `a` to be filled before `b`?
    /// @dev Must be STRICT. Returning true on a tie would make the insertion sort unstable and silently
    ///      break the discovery-order tie-break that `_sortOrder` relies on.
    function _cheaperFirst(Candidate memory a, Candidate memory b) private pure returns (bool) {
        if (a.penaltyWad != b.penaltyWad) return a.penaltyWad < b.penaltyWad;
        return _capacity(a) > _capacity(b);
    }

    /// @notice Capacity of one candidate before any liquidity has been committed elsewhere
    function _capacity(Candidate memory c) private pure returns (uint256) {
        return c.position < c.liquidity ? c.position : c.liquidity;
    }

    /// @dev The ledger is load-bearing: `min(position, liquidity)` is per (adapter, market) but liquidity
    ///      belongs to the MARKET, so two adapters sharing one could be sized past what it can pay and the
    ///      second call would revert. Markets are not emptied merely because they are listed.
    function _fill(
        Candidate[] memory candidates,
        uint256[] memory order,
        uint256 assets,
        AdapterInfo[] memory infos
    )
        private
        view
        returns (Plan memory plan)
    {
        Pull[] memory scratch = new Pull[](order.length);
        bytes32[] memory seenIds = new bytes32[](order.length);
        uint256[] memory committed = new uint256[](order.length);
        uint256 distinct;
        uint256 taken;
        uint256 remaining = assets;

        for (uint256 i; i < order.length && remaining != 0; ++i) {
            Candidate memory c = candidates[order[i]];
            uint256 slot = _ledgerSlot(seenIds, distinct, c.marketId);
            if (slot == distinct) {
                seenIds[slot] = c.marketId;
                ++distinct;
            }

            // Clamped rather than a bare subtraction. The `MORPHO` gate makes a cross-deployment id
            // collision impossible today, so this cannot currently go negative — but an underflow here
            // would surface as a bare `Panic(0x11)` that reverts the whole exit instead of skipping one
            // candidate, which is too sharp an edge to leave resting on an invariant proved elsewhere.
            uint256 free = c.liquidity > committed[slot] ? c.liquidity - committed[slot] : 0;
            uint256 capacity = c.position < free ? c.position : free;
            if (capacity == 0) continue;

            uint256 pull = remaining < capacity ? remaining : capacity;
            committed[slot] += pull;
            remaining -= pull;

            scratch[taken++] = Pull(c.adapter, pull, c.params);
            uint256 penalty = pull.mulDivUp(c.penaltyWad, 1e18);
            if (penalty != 0) {
                plan.totalPenaltyAssets += penalty;
                ++plan.penalisedCount;
            }
        }

        if (remaining != 0) _revertUnfillable(infos, assets, assets - remaining);

        plan.pulls = new Pull[](taken);
        for (uint256 k; k < taken; ++k) {
            plan.pulls[k] = scratch[k];
        }
    }

    /// @notice Index of `marketId` in the ledger, or `count` when it is not present yet
    function _ledgerSlot(bytes32[] memory ids, uint256 count, bytes32 marketId) private pure returns (uint256) {
        for (uint256 i; i < count; ++i) {
            if (ids[i] == marketId) return i;
        }
        return count;
    }

    /// @dev Reverts unconditionally; split out to stay inside the repo's `code-complexity` ceiling.
    /// @dev A non-zero rate on an ineligible adapter is exactly the "skipped for cost" signal, since
    ///      `_probeAdapter` leaves it zero when it rejected earlier on shape.
    function _revertUnfillable(AdapterInfo[] memory infos, uint256 assets, uint256 available) private view {
        uint256 worstSkipped;
        for (uint256 i; i < infos.length; ++i) {
            if (!infos[i].eligible && infos[i].penaltyWad > worstSkipped) worstSkipped = infos[i].penaltyWad;
        }
        if (worstSkipped > MAX_PENALTY_WAD) revert PENALTY_ABOVE_CAP(worstSkipped, MAX_PENALTY_WAD);
        revert SHORTFALL(available, assets);
    }

    /// @notice Refuse the plan unless the account's claim covers the WHOLE exit, assets plus penalty.
    /// @dev Bounding the penalty alone let a leaf burn up to the cap of the vault's entire reachable
    ///      liquidity, not of this account's exit. Conservative by up to `penalisedCount` share-wei: at
    ///      Morpho's exact full-exit size `claim/(1+p)` it refuses by one wei, so the planner sizes under.
    /// @dev Not pre-flighted: a `receiveAssetsGate` excluding the account fails the final withdraw after
    ///      every pull has run (atomic, so no loss). `forceDeallocate`'s own penalty withdraw bypasses it.
    /// @dev No zero-penalty early return: the withdraw must be covered at any rate, else a panic after
    ///      every pull. Slack `+ penalisedCount` = one ceiling-rounded burn per penalised pull + withdraw.
    function _requireSolvent(
        address vault,
        address account,
        uint256 assets,
        Plan memory plan
    )
        private
        view
    {
        uint256 required =
            IMorphoVaultV2(vault).previewWithdraw(assets + plan.totalPenaltyAssets) + plan.penalisedCount;

        uint256 held = IMorphoVaultV2(vault).balanceOf(account);
        if (held < required) revert INSUFFICIENT_SHARES(held, required);
    }

    /// @dev Last execution, and what makes this an exit rather than a donation: it claims the idle the
    ///      pulls just created, in the same call. `receiver` and `onBehalf` are both the account, so no
    ///      share allowance is needed.
    function _emit(
        address vault,
        address account,
        uint256 assets,
        Pull[] memory pulls
    )
        private
        pure
        returns (Execution[] memory)
    {
        Execution[] memory executions = new Execution[](pulls.length + 1);
        for (uint256 i; i < pulls.length; ++i) {
            executions[i] = Execution({
                target: vault,
                value: 0,
                callData: abi.encodeCall(
                    IMorphoVaultV2.forceDeallocate,
                    (pulls[i].adapter, abi.encode(pulls[i].params), pulls[i].amount, account)
                )
            });
        }
        executions[pulls.length] = Execution({
            target: vault,
            value: 0,
            callData: abi.encodeCall(IERC4626.withdraw, (assets, account, account))
        });
        return executions;
    }

    /// @dev `!= 32`, not `>= 32`. Short returndata makes `abi.decode` throw AFTER the call, where the
    ///      `success` flag cannot catch it. An over-long reply does not throw, but means the target is not
    ///      the interface it claims, and believing its first word is how a look-alike gets admitted.
    function _probe(address target, bytes memory callData) private view returns (bool ok, bytes32 word) {
        if (target.code.length == 0) return (false, bytes32(0));
        (bool success, bytes memory ret) = target.staticcall{ gas: PROBE_GAS }(callData);
        if (!success || ret.length != 32) return (false, bytes32(0));
        return (true, abi.decode(ret, (bytes32)));
    }

    /*//////////////////////////////////////////////////////////////
                                 EXTERNAL METHODS
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc ISuperHookContextAware
    function decodeUsePrevHookAmount(bytes memory data) external pure returns (bool) {
        return _decodeBool(data, USE_PREV_HOOK_AMOUNT_POSITION);
    }

    /// @inheritdoc ISuperHookInflowOutflow
    function decodeAmounts(bytes memory data) external pure override returns (uint256[] memory amounts) {
        amounts = new uint256[](1);
        amounts[0] = BytesLib.toUint256(data, AMOUNT_POSITION);
    }

    /// @dev `ASSETS`, reversing both siblings: `TOKEN` is right for a config hop that converts nothing.
    ///      This performs an ERC-4626 withdraw. `SHARES` would be wrong — the amount is underlying.
    ///      Needs the `amountMeta` override in `tooling/hook-enrichment.yaml`, whose default is IN/TOKEN.
    function amountRoles(bytes memory)
        external
        pure
        override
        returns (ISuperHookInflowOutflow.AmountMeta[] memory meta)
    {
        meta = new ISuperHookInflowOutflow.AmountMeta[](1);
        meta[0] = ISuperHookInflowOutflow.AmountMeta(
            ISuperHookInflowOutflow.Direction.IN, ISuperHookInflowOutflow.Denomination.ASSETS
        );
    }

    /// @dev Implements ISuperHookInflowOutflow + ISuperHookOutflow. Pipe mode stays the default: this hook
    ///      publishes its own measured delta rather than forwarding the previous hook's. Never write the
    ///      qualified enum name here — `detectPipeMode` substring-matches source text.
    function _supportsSizingInterface() internal pure override returns (bool) {
        return true;
    }

    /// @inheritdoc ISuperHookOutflow
    /// @dev Writes bytes 52..83 only — strictly below the flag at 84 — and the layout is fixed-length, so
    ///      the payload length is preserved.
    function replaceCalldataAmounts(
        bytes memory data,
        uint256[] memory amounts
    )
        external
        pure
        override
        returns (bytes memory)
    {
        if (amounts.length != 1) revert INVALID_AMOUNTS_LENGTH();
        return _replaceCalldataAmount(data, amounts[0], AMOUNT_POSITION);
    }

    /// @dev The vault alone: a leaf does not pin adapters or markets, so a market the curator lists later
    ///      is usable without re-signing. `MAX_PENALTY_WAD` and `MAX_MARKETS` bound that authority.
    function inspect(bytes calldata data) external pure override returns (bytes memory) {
        return abi.encodePacked(data.extractYieldSource());
    }

    /*//////////////////////////////////////////////////////////////
                                 INTERNAL METHODS
    //////////////////////////////////////////////////////////////*/

    /// @dev The output FORWARDS, reversing the deallocate sibling's `outAmount = 0` rule — correct there
    ///      because the account receives nothing, wrong here because it does.
    /// @dev Measured, not declared: `outAmount` is the observed balance delta, so a fee-on-transfer
    ///      underlying is reported honestly. `usedShares` spans the whole call, penalty burns included.
    function _preExecute(address prevHook, address account, bytes calldata data) internal override {
        (address vault,) = _resolveRequest(prevHook, account, data);

        asset = IERC4626(vault).asset();
        spToken = vault;
        _setOutAmount(IERC20(asset).balanceOf(account), account);
        usedShares = IMorphoVaultV2(vault).balanceOf(account);
    }

    /// @dev Clamped: it cannot underflow today, but doing so would surface as a bare panic at the very end
    ///      of an otherwise successful exit.
    function _postExecute(address, address account, bytes calldata data) internal override {
        address vault = data.extractYieldSource();

        _setOutAmount(IERC20(asset).balanceOf(account) - getOutAmount(account), account);
        _setOutToken(asset, account);

        uint256 remaining = IMorphoVaultV2(vault).balanceOf(account);
        usedShares = usedShares > remaining ? usedShares - remaining : 0;
    }
}

lib/modulekit/src/accounts/common/interfaces/IERC7579Account.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.23 <0.9.0;

/* solhint-disable no-unused-import */

// Types
import { CallType, ExecType, ModeCode } from "../lib/ModeLib.sol";

// Structs
struct Execution {
    address target;
    uint256 value;
    bytes callData;
}

interface IERC7579Account {
    event ModuleInstalled(uint256 moduleTypeId, address module);
    event ModuleUninstalled(uint256 moduleTypeId, address module);

    /**
     * @dev Executes a transaction on behalf of the account.
     *         This function is intended to be called by ERC-4337 EntryPoint.sol
     * @dev Ensure adequate authorization control: i.e. onlyEntryPointOrSelf
     *
     * @dev MSA MUST implement this function signature.
     * If a mode is requested that is not supported by the Account, it MUST revert
     * @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
     * @param executionCalldata The encoded execution call data
     */
    function execute(ModeCode mode, bytes calldata executionCalldata) external payable;

    /**
     * @dev Executes a transaction on behalf of the account.
     *         This function is intended to be called by Executor Modules
     * @dev Ensure adequate authorization control: i.e. onlyExecutorModule
     *
     * @dev MSA MUST implement this function signature.
     * If a mode is requested that is not supported by the Account, it MUST revert
     * @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
     * @param executionCalldata The encoded execution call data
     */
    function executeFromExecutor(
        ModeCode mode,
        bytes calldata executionCalldata
    )
        external
        payable
        returns (bytes[] memory returnData);

    /**
     * @dev ERC-1271 isValidSignature
     *         This function is intended to be used to validate a smart account signature
     * and may forward the call to a validator module
     *
     * @param hash The hash of the data that is signed
     * @param data The data that is signed
     */
    function isValidSignature(bytes32 hash, bytes calldata data) external view returns (bytes4);

    /**
     * @dev installs a Module of a certain type on the smart account
     * @dev Implement Authorization control of your chosing
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     * @param module the module address
     * @param initData arbitrary data that may be required on the module during `onInstall`
     * initialization.
     */
    function installModule(
        uint256 moduleTypeId,
        address module,
        bytes calldata initData
    )
        external
        payable;

    /**
     * @dev uninstalls a Module of a certain type on the smart account
     * @dev Implement Authorization control of your chosing
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     * @param module the module address
     * @param deInitData arbitrary data that may be required on the module during `onUninstall`
     * de-initialization.
     */
    function uninstallModule(
        uint256 moduleTypeId,
        address module,
        bytes calldata deInitData
    )
        external
        payable;

    /**
     * Function to check if the account supports a certain CallType or ExecType (see ModeLib.sol)
     * @param encodedMode the encoded mode
     */
    function supportsExecutionMode(ModeCode encodedMode) external view returns (bool);

    /**
     * Function to check if the account supports installation of a certain module type Id
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     */
    function supportsModule(uint256 moduleTypeId) external view returns (bool);

    /**
     * Function to check if the account has a certain module installed
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     *      Note: keep in mind that some contracts can be multiple module types at the same time. It
     *            thus may be necessary to query multiple module types
     * @param module the module address
     * @param additionalContext additional context data that the smart account may interpret to
     *                          identifiy conditions under which the module is installed.
     *                          usually this is not necessary, but for some special hooks that
     *                          are stored in mappings, this param might be needed
     */
    function isModuleInstalled(
        uint256 moduleTypeId,
        address module,
        bytes calldata additionalContext
    )
        external
        view
        returns (bool);

    /**
     * @dev Returns the account id of the smart account
     * @return accountImplementationId the account id of the smart account
     * the accountId should be structured like so:
     *        "vendorname.accountname.semver"
     */
    function accountId() external view returns (string memory accountImplementationId);
}

lib/modulekit/src/accounts/common/lib/ModeLib.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;

/**
 * @title ModeLib
 * @author rhinestone | zeroknots.eth, Konrad Kopp (@kopy-kat)
 * To allow smart accounts to be very simple, but allow for more complex execution, A custom mode
 * encoding is used.
 *    Function Signature of execute function:
 *           function execute(ModeCode mode, bytes calldata executionCalldata) external payable;
 * This allows for a single bytes32 to be used to encode the execution mode, calltype, execType and
 * context.
 * NOTE: Simple Account implementations only have to scope for the most significant byte. Account  that
 * implement
 * more complex execution modes may use the entire bytes32.
 *
 * |--------------------------------------------------------------------|
 * | CALLTYPE  | EXECTYPE  |   UNUSED   | ModeSelector  |  ModePayload  |
 * |--------------------------------------------------------------------|
 * | 1 byte    | 1 byte    |   4 bytes  | 4 bytes       |   22 bytes    |
 * |--------------------------------------------------------------------|
 *
 * CALLTYPE: 1 byte
 * CallType is used to determine how the executeCalldata paramter of the execute function has to be
 * decoded.
 * It can be either single, batch or delegatecall. In the future different calls could be added.
 * CALLTYPE can be used by a validation module to determine how to decode <userOp.callData[36:]>.
 *
 * EXECTYPE: 1 byte
 * ExecType is used to determine how the account should handle the execution.
 * It can indicate if the execution should revert on failure or continue execution.
 * In the future more execution modes may be added.
 * Default Behavior (EXECTYPE = 0x00) is to revert on a single failed execution. If one execution in
 * a batch fails, the entire batch is reverted
 *
 * UNUSED: 4 bytes
 * Unused bytes are reserved for future use.
 *
 * ModeSelector: bytes4
 * The "optional" mode selector can be used by account vendors, to implement custom behavior in
 * their accounts.
 * the way a ModeSelector is to be calculated is bytes4(keccak256("vendorname.featurename"))
 * this is to prevent collisions between different vendors, while allowing innovation and the
 * development of new features without coordination between ERC-7579 implementing accounts
 *
 * ModePayload: 22 bytes
 * Mode payload is used to pass additional data to the smart account execution, this may be
 * interpreted depending on the ModeSelector
 *
 * ExecutionCallData: n bytes
 * single, delegatecall or batch exec abi.encoded as bytes
 */

// Custom type for improved developer experience
type ModeCode is bytes32;

type CallType is bytes1;

type ExecType is bytes1;

type ModeSelector is bytes4;

type ModePayload is bytes22;

// Default CallType
CallType constant CALLTYPE_SINGLE = CallType.wrap(0x00);
// Batched CallType
CallType constant CALLTYPE_BATCH = CallType.wrap(0x01);
CallType constant CALLTYPE_STATIC = CallType.wrap(0xFE);
// @dev Implementing delegatecall is OPTIONAL!
// implement delegatecall with extreme care.
CallType constant CALLTYPE_DELEGATECALL = CallType.wrap(0xFF);

// @dev default behavior is to revert on failure
// To allow very simple accounts to use mode encoding, the default behavior is to revert on failure
// Since this is value 0x00, no additional encoding is required for simple accounts
ExecType constant EXECTYPE_DEFAULT = ExecType.wrap(0x00);
// @dev account may elect to change execution behavior. For example "try exec" / "allow fail"
ExecType constant EXECTYPE_TRY = ExecType.wrap(0x01);

ModeSelector constant MODE_DEFAULT = ModeSelector.wrap(bytes4(0x00000000));
// Example declaration of a custom mode selector
ModeSelector constant MODE_OFFSET = ModeSelector.wrap(bytes4(keccak256("default.mode.offset")));

/**
 * @dev ModeLib is a helper library to encode/decode ModeCodes
 */
library ModeLib {
    function decode(ModeCode mode)
        internal
        pure
        returns (
            CallType _calltype,
            ExecType _execType,
            ModeSelector _modeSelector,
            ModePayload _modePayload
        )
    {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            _calltype := mode
            _execType := shl(8, mode)
            _modeSelector := shl(48, mode)
            _modePayload := shl(80, mode)
        }
    }

    function encode(
        CallType callType,
        ExecType execType,
        ModeSelector mode,
        ModePayload payload
    )
        internal
        pure
        returns (ModeCode)
    {
        return ModeCode.wrap(
            bytes32(
                abi.encodePacked(callType, execType, bytes4(0), ModeSelector.unwrap(mode), payload)
            )
        );
    }

    function encodeSimpleBatch() internal pure returns (ModeCode mode) {
        mode = encode(CALLTYPE_BATCH, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
    }

    function encodeSimpleSingle() internal pure returns (ModeCode mode) {
        mode = encode(CALLTYPE_SINGLE, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
    }

    function getCallType(ModeCode mode) internal pure returns (CallType calltype) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            calltype := mode
        }
    }
}

using { eqModeSelector as == } for ModeSelector global;
using { eqCallType as == } for CallType global;
using { neqCallType as != } for CallType global;
using { eqExecType as == } for ExecType global;

function eqCallType(CallType a, CallType b) pure returns (bool) {
    return CallType.unwrap(a) == CallType.unwrap(b);
}

function neqCallType(CallType a, CallType b) pure returns (bool) {
    return CallType.unwrap(a) == CallType.unwrap(b);
}

function eqExecType(ExecType a, ExecType b) pure returns (bool) {
    return ExecType.unwrap(a) == ExecType.unwrap(b);
}

function eqModeSelector(ModeSelector a, ModeSelector b) pure returns (bool) {
    return ModeSelector.unwrap(a) == ModeSelector.unwrap(b);
}

lib/modulekit/src/accounts/erc7579/lib/ExecutionLib.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.23 <0.9.0;

// Types
import { Execution } from "../../common/interfaces/IERC7579Account.sol";

/**
 * Helper Library for decoding Execution calldata
 * malloc for memory allocation is bad for gas. use this assembly instead
 */
library ExecutionLib {
    error ERC7579DecodingError();

    /**
     * @notice Decode a batch of `Execution` executionBatch from a `bytes` calldata.
     * @dev code is copied from solady's LibERC7579.sol
     * https://github.com/Vectorized/solady/blob/740812cedc9a1fc11e17cb3d4569744367dedf19/src/accounts/LibERC7579.sol#L146
     *      Credits to Vectorized and the Solady Team
     */
    function decodeBatch(bytes calldata executionCalldata)
        internal
        pure
        returns (Execution[] calldata executionBatch)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let u := calldataload(executionCalldata.offset)
            let s := add(executionCalldata.offset, u)
            let e := sub(add(executionCalldata.offset, executionCalldata.length), 0x20)
            executionBatch.offset := add(s, 0x20)
            executionBatch.length := calldataload(s)
            if or(shr(64, u), gt(add(s, shl(5, executionBatch.length)), e)) {
                mstore(0x00, 0xba597e7e) // `DecodingError()`.
                revert(0x1c, 0x04)
            }
            if executionBatch.length {
                // Perform bounds checks on the decoded `executionBatch`.
                // Loop runs out-of-gas if `executionBatch.length` is big enough to cause overflows.
                for { let i := executionBatch.length } 1 { } {
                    i := sub(i, 1)
                    let p := calldataload(add(executionBatch.offset, shl(5, i)))
                    let c := add(executionBatch.offset, p)
                    let q := calldataload(add(c, 0x40))
                    let o := add(c, q)
                    // forgefmt: disable-next-item
                    if or(shr(64, or(calldataload(o), or(p, q))),
                        or(gt(add(c, 0x40), e), gt(add(o, calldataload(o)), e))) {
                        mstore(0x00, 0xba597e7e) // `DecodingError()`.
                        revert(0x1c, 0x04)
                    }
                    if iszero(i) { break }
                }
            }
        }
    }

    function encodeBatch(Execution[] memory executions)
        internal
        pure
        returns (bytes memory callData)
    {
        callData = abi.encode(executions);
    }

    function decodeSingle(bytes calldata executionCalldata)
        internal
        pure
        returns (address target, uint256 value, bytes calldata callData)
    {
        target = address(bytes20(executionCalldata[0:20]));
        value = uint256(bytes32(executionCalldata[20:52]));
        callData = executionCalldata[52:];
    }

    function encodeSingle(
        address target,
        uint256 value,
        bytes memory callData
    )
        internal
        pure
        returns (bytes memory userOpCalldata)
    {
        userOpCalldata = abi.encodePacked(target, value, callData);
    }
}

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

src/hooks/BaseHook.sol

// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;

// External
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

// Superform
import { HookDataDecoder } from "../libraries/HookDataDecoder.sol";
import {
    ISuperHook,
    ISuperHookSetter,
    ISuperHookResult,
    ISuperHookInspector,
    ISuperHookInflowOutflow,
    ISuperHookOutflow
} from "../interfaces/ISuperHook.sol";

/// @title BaseHook
/// @author Superform Labs
/// @notice Base implementation for all hooks in the Superform system
/// @dev Provides core security validation and execution flow management for hooks
///      All specialized hooks should inherit from this base contract
///      Implements the ISuperHook interface defined lifecycle methods
///      Uses a transient storage pattern for stateful execution context
abstract contract BaseHook is ISuperHook, ISuperHookSetter, ISuperHookResult, ISuperHookInspector, IERC165 {
    using HookDataDecoder for bytes;

    /*//////////////////////////////////////////////////////////////
                                 STORAGE
    //////////////////////////////////////////////////////////////*/

    /// @notice The number of shares used by this hook's operation
    /// @dev Used for accounting and tracking consumption of position shares
    uint256 public transient usedShares;

    /// @notice The special token address (if any) associated with this hook's operation
    /// @dev May be used to track token addresses for various operations
    address public transient spToken;

    /// @notice The primary asset address this hook operates on
    /// @dev Typically the base token or asset being processed
    address public transient asset;

    /// @notice Execution nonce for creating unique contexts
    uint256 public transient executionNonce;

    /// @notice Last execution context caller
    address public transient lastCaller;

    // Storage offsets for different state variables
    uint256 private constant OUT_AMOUNT_OFFSET = 1;
    uint256 private constant PRE_EXECUTE_MUTEX_OFFSET = 2;
    uint256 private constant POST_EXECUTE_MUTEX_OFFSET = 3;
    uint256 private constant OUT_TOKEN_OFFSET = 4;

    /*//////////////////////////////////////////////////////////////
                                 ENUMS
    //////////////////////////////////////////////////////////////*/

    /// @notice Declares how a hook handles its output (outAmount + outToken) relative to the previous hook
    /// @dev TRANSFORM: Hook converts input to output (balance-diff pattern). Default.
    ///      PASSTHROUGH: Hook performs a side-effect only, auto-forwards prev hook's output.
    ///      SOURCE: Hook creates output from external state, ignores prev hook. Reserved for future use.
    enum PipeMode {
        TRANSFORM,
        PASSTHROUGH,
        SOURCE
    }

    /// @notice Base storage key for hook execution state
    bytes32 private constant HOOK_EXECUTION_STORAGE = keccak256("hook.execution.state");

    /// @notice Storage key for account context mapping
    bytes32 private constant ACCOUNT_CONTEXT_STORAGE = keccak256("hook.account.context");

    /// @notice The specific subtype identifier for this hook
    /// @dev Used to identify specialized hook types beyond the basic HookType enum
    bytes32 public immutable SUB_TYPE;

    /// @notice The type of hook (NONACCOUNTING, INFLOW, OUTFLOW)
    /// @dev Determines how the hook impacts accounting in the system
    ISuperHook.HookType public hookType;

    /*//////////////////////////////////////////////////////////////
                                 ERRORS
    //////////////////////////////////////////////////////////////*/
    /// @notice Thrown when a caller attempts to execute hook methods without proper authorization
    /// @dev Used by security validation to prevent unauthorized hook execution
    error NOT_AUTHORIZED();

    /// @notice Thrown when an amount parameter is invalid (e.g., zero or overflow)
    /// @dev Used in validation checks for asset amounts and share values
    error AMOUNT_NOT_VALID();

    /// @notice Thrown when an address parameter is invalid (e.g., zero address)
    /// @dev Used in validation checks for tokens, accounts, and other addresses
    error ADDRESS_NOT_VALID();

    /// @notice Thrown when a caller is not authorized to execute hook methods
    /// @dev Used by security validation to prevent unauthorized hook execution
    error UNAUTHORIZED_CALLER();

    /// @notice Thrown when preExecute is called more than once
    /// @dev Used to prevent reentrancy attacks and ensure proper execution flow
    error PRE_EXECUTE_ALREADY_CALLED();

    /// @notice Thrown when postExecute is called more than once
    /// @dev Used to prevent reentrancy attacks and ensure proper execution flow
    error POST_EXECUTE_ALREADY_CALLED();

    /// @notice Thrown when a hook execution is incomplete
    /// @dev Used to prevent incomplete hook execution
    error INCOMPLETE_HOOK_EXECUTION();

    /// @notice Thrown when trying to set outAmount after preExecute or postExecute
    /// @dev Used to prevent setting outAmount after preExecute or postExecute
    error CANNOT_SET_OUT_AMOUNT();

    /// @notice Thrown when the amounts array length doesn't match the expected count
    /// @dev Used by replaceCalldataAmounts to validate input
    error INVALID_AMOUNTS_LENGTH();

    /// @notice Initializes the hook with its type and subtype
    /// @dev Sets immutable parameters that define the hook's behavior
    /// @param hookType_ The type classification for this hook (NONACCOUNTING, INFLOW, OUTFLOW)
    /// @param subType_ The specific subtype identifier for specialized hook functionality
    constructor(ISuperHook.HookType hookType_, bytes32 subType_) {
        hookType = hookType_;
        SUB_TYPE = subType_;
    }

    modifier onlyLastCaller() {
        if (msg.sender != lastCaller) revert UNAUTHORIZED_CALLER();
        _;
    }

    /*//////////////////////////////////////////////////////////////
                          EXECUTION SECURITY
    //////////////////////////////////////////////////////////////*/
    /// @inheritdoc ISuperHook
    function setExecutionContext(address caller) external {
        _createExecutionContext(caller);
        lastCaller = msg.sender;
    }

    /// @dev Standard build pattern - MUST include preExecute first, postExecute last
    /// @inheritdoc ISuperHook
    function build(
        address prevHook,
        address account,
        bytes calldata hookData
    )
        external
        view
        virtual
        returns (Execution[] memory executions)
    {
        // Get hook-specific executions
        Execution[] memory hookExecutions = _buildHookExecutions(prevHook, account, hookData);

        // Always include pre + hook + post
        executions = new Execution[](hookExecutions.length + 2);

        // FIRST: preExecute
        executions[0] = Execution({
            target: address(this),
            value: 0,
            callData: abi.encodeCall(this.preExecute, (prevHook, account, hookData))
        });

        // MIDDLE: hook-specific operations
        for (uint256 i = 0; i < hookExecutions.length; i++) {
            executions[i + 1] = hookExecutions[i];
        }

        // LAST: postExecute
        executions[executions.length - 1] = Execution({
            target: address(this),
            value: 0,
            callData: abi.encodeCall(this.postExecute, (prevHook, account, hookData))
        });
    }

    /// @inheritdoc ISuperHook
    function preExecute(address prevHook, address account, bytes calldata data) external {
        if (msg.sender != account) revert UNAUTHORIZED_CALLER();
        uint256 context = _getCurrentExecutionContext(account);
        if (_getPreExecuteMutex(context)) revert PRE_EXECUTE_ALREADY_CALLED();
        _setPreExecuteMutex(context, true);
        _preExecute(prevHook, account, data);
    }

    /// @inheritdoc ISuperHook
    function postExecute(address prevHook, address account, bytes calldata data) external {
        if (msg.sender != account) revert UNAUTHORIZED_CALLER();
        uint256 context = _getCurrentExecutionContext(account);
        if (_getPostExecuteMutex(context)) revert POST_EXECUTE_ALREADY_CALLED();
        _setPostExecuteMutex(context, true);
        _postExecute(prevHook, account, data);
    }

    /// @inheritdoc ISuperHookSetter
    function setOutAmount(uint256 _outAmount, address caller) external {
        uint256 context = _getCurrentExecutionContext(caller);
        if (_getPreExecuteMutex(context) || _getPostExecuteMutex(context)) {
            revert CANNOT_SET_OUT_AMOUNT();
        }

        bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
        assembly ("memory-safe") {
            tstore(key, _outAmount)
        }
    }

    function getOutAmount(address caller) public view returns (uint256) {
        return _getOutAmount(_getCurrentExecutionContext(caller));
    }

    function getOutToken(address caller) public view returns (address) {
        return _getOutToken(_getCurrentExecutionContext(caller));
    }

    /// @inheritdoc ISuperHook
    function resetExecutionState(address caller) external onlyLastCaller {
        uint256 context = _getCurrentExecutionContext(caller);
        if (!_getPreExecuteMutex(context) || !_getPostExecuteMutex(context)) {
            revert INCOMPLETE_HOOK_EXECUTION();
        }

        _clearExecutionState(context);
    }

    /*//////////////////////////////////////////////////////////////
                                 VIEW METHODS
    //////////////////////////////////////////////////////////////*/
    /// @inheritdoc ISuperHook
    function subtype() external view returns (bytes32) {
        return SUB_TYPE;
    }

    /// @inheritdoc ISuperHookInspector
    function inspect(bytes calldata) external view virtual returns (bytes memory) { }

    /// @inheritdoc IERC165
    /// @dev Hooks that implement ISuperHookInflowOutflow/ISuperHookOutflow override
    ///      _supportsSizingInterface() to return true, which enables three-state detection:
    ///      S1: supportsInterface(ISuperHookInflowOutflow) == true → hook has sizing interface
    ///      S2: same as S1 but amountRoles(data).length == 0 → authoritatively sizeless
    ///      S3: supportsInterface(ISuperHookInflowOutflow) == false → legacy, no sizing interface
    function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
        if (
            interfaceId == type(ISuperHookInflowOutflow).interfaceId
                || interfaceId == type(ISuperHookOutflow).interfaceId
        ) {
            return _supportsSizingInterface();
        }
        return interfaceId == type(IERC165).interfaceId || interfaceId == type(ISuperHook).interfaceId
            || interfaceId == type(ISuperHookResult).interfaceId
            || interfaceId == type(ISuperHookInspector).interfaceId;
    }

    /// @dev Override to return true in hooks that implement ISuperHookInflowOutflow/ISuperHookOutflow
    function _supportsSizingInterface() internal pure virtual returns (bool) {
        return false;
    }

    /*//////////////////////////////////////////////////////////////
                                 INTERNAL METHODS
    //////////////////////////////////////////////////////////////*/
    /// @notice Internal implementation of build
    /// @dev Abstract function to be implemented by derived hooks
    ///      Called during build to generate hook-specific execution sequences
    /// @param prevHook The previous hook in the chain, or address(0) if first hook
    /// @param account The account that operations will be performed for
    /// @param data Hook-specific parameters and configuration data
    /// @return executions Array of execution objects containing target, value, and callData
    function _buildHookExecutions(
        address prevHook,
        address account,
        bytes calldata data
    )
        internal
        view
        virtual
        returns (Execution[] memory executions);

    /// @notice Internal implementation of preExecute
    /// @dev Default behavior for PASSTHROUGH hooks: auto-forward prevHook's outAmount + outToken.
    ///      TRANSFORM and SOURCE hooks override this entirely.
    /// @param prevHook The previous hook in the chain, or address(0) if first hook
    /// @param account The account that operations will be performed for
    function _preExecute(address prevHook, address account, bytes calldata) internal virtual {
        if (_pipeMode() == PipeMode.PASSTHROUGH && prevHook != address(0)) {
            _setOutAmount(ISuperHookResult(prevHook).getOutAmount(account), account);
            _setOutToken(ISuperHookResult(prevHook).getOutToken(account), account);
        }
    }

    /// @notice Internal implementation of postExecute
    /// @dev Abstract function to be implemented by derived hooks
    ///      Called after execution to finalize the hook's state and set output values
    ///      Typically calculates final results and sets outAmount, usedShares, etc.
    ///      May perform additional validations on execution results
    /// @param prevHook The previous hook in the chain, or address(0) if first hook
    /// @param account The account operations were performed for
    /// @param data Hook-specific parameters and configuration data
    function _postExecute(address prevHook, address account, bytes calldata data) internal virtual { }

    /// @notice Decodes a boolean value from a byte array at the specified offset
    /// @dev Helper function for extracting boolean values from packed data
    ///      Used when parsing hook-specific data parameters
    /// @param data The byte array containing the encoded data
    /// @param offset The position in the array to read from
    /// @return The decoded boolean value (true if byte is non-zero)
    function _decodeBool(bytes memory data, uint256 offset) internal pure returns (bool) {
        return data[offset] != 0;
    }

    /// @notice Replaces an amount value within a byte array at the specified offset
    /// @dev Used to modify hook calldata for amount adjustments without full re-encoding
    ///      Particularly useful for modifying amounts in multi-hook execution chains
    ///      Directly modifies the bytes in-place for gas efficiency
    /// @param data The original byte array containing encoded calldata
    /// @param amount The new amount value to insert
    /// @param offset The position in the array where the amount starts
    /// @return The modified byte array with the replaced amount
    function _replaceCalldataAmount(
        bytes memory data,
        uint256 amount,
        uint256 offset
    )
        internal
        pure
        returns (bytes memory)
    {
        bytes memory newAmountEncoded = abi.encodePacked(amount);
        for (uint256 i; i < 32; ++i) {
            data[offset + i] = newAmountEncoded[i];
        }
        return data;
    }

    /// @notice Declares the pipe semantics for this hook
    /// @dev Override to return PASSTHROUGH for side-effect-only hooks.
    ///      Default: TRANSFORM. Inlined by the compiler (pure virtual).
    function _pipeMode() internal pure virtual returns (PipeMode) {
        return PipeMode.TRANSFORM;
    }

    /// @notice Sets the output token address for this hook execution
    /// @param token The output token address
    /// @param caller The caller address for context identification
    function _setOutToken(address token, address caller) internal {
        uint256 context = _getCurrentExecutionContext(caller);
        bytes32 key = _makeKey(context, OUT_TOKEN_OFFSET);
        assembly ("memory-safe") {
            tstore(key, token)
        }
    }

    function _makeAccountContextKey(address account) private pure returns (bytes32) {
        return keccak256(abi.encodePacked(ACCOUNT_CONTEXT_STORAGE, account));
    }

    function _createExecutionContext(address caller) private returns (uint256) {
        // Always increment nonce for new execution context
        executionNonce++;
        bytes32 key = _makeAccountContextKey(caller);

        // Store this context for the current caller
        uint256 currentNonce = executionNonce; // Load into local variable for assembly
        assembly ("memory-safe") {
            tstore(key, currentNonce)
        }

        return executionNonce;
    }

    function _getCurrentExecutionContext(address caller) private view returns (uint256 context) {
        bytes32 key = _makeAccountContextKey(caller);
        assembly ("memory-safe") {
            context := tload(key)
        }
    }

    function _makeKey(uint256 context, uint256 offset) private pure returns (bytes32) {
        return keccak256(abi.encodePacked(HOOK_EXECUTION_STORAGE, context, offset));
    }

    function _getOutAmount(uint256 context) private view returns (uint256 value) {
        bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
        assembly ("memory-safe") {
            value := tload(key)
        }
    }

    function _getOutToken(uint256 context) private view returns (address value) {
        bytes32 key = _makeKey(context, OUT_TOKEN_OFFSET);
        assembly ("memory-safe") {
            value := tload(key)
        }
    }

    function _setOutAmount(uint256 value, address caller) internal {
        uint256 context = _getCurrentExecutionContext(caller);
        bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
        assembly ("memory-safe") {
            tstore(key, value)
        }
    }

    function _getPreExecuteMutex(uint256 context) private view returns (bool value) {
        bytes32 key = _makeKey(context, PRE_EXECUTE_MUTEX_OFFSET);
        assembly ("memory-safe") {
            value := tload(key)
        }
    }

    function _setPreExecuteMutex(uint256 context, bool value) private {
        bytes32 key = _makeKey(context, PRE_EXECUTE_MUTEX_OFFSET);
        assembly ("memory-safe") {
            tstore(key, value)
        }
    }

    function _getPostExecuteMutex(uint256 context) private view returns (bool value) {
        bytes32 key = _makeKey(context, POST_EXECUTE_MUTEX_OFFSET);
        assembly ("memory-safe") {
            value := tload(key)
        }
    }

    function _setPostExecuteMutex(uint256 context, bool value) private {
        bytes32 key = _makeKey(context, POST_EXECUTE_MUTEX_OFFSET);
        assembly ("memory-safe") {
            tstore(key, value)
        }
    }

    function _clearExecutionState(uint256 context) private {
        _setPreExecuteMutex(context, false);
        _setPostExecuteMutex(context, false);
    }
}

src/interfaces/ISuperHook.sol

// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;

// external
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";

/**
 * @title SuperHook System
 * @author Superform Labs
 * @notice The hook system provides a modular and composable way to execute operations on assets
 * @dev The hook system architecture consists of several interfaces that work together:
 *      - ISuperHook: The base interface all hooks implement, with lifecycle methods
 *      - ISuperHookResult: Provides execution results and output information
 *      - Specialized interfaces (ISuperHookOutflow, ISuperHookLoans, etc.) for specific behaviors
 *
 * Hooks are executed in sequence, where each hook can access the results from previous hooks.
 * The three main types of hooks are:
 *      - NONACCOUNTING: Utility hooks that don't update the accounting system
 *      - INFLOW: Hooks that process deposits or additions to positions
 *      - OUTFLOW: Hooks that process withdrawals or reductions to positions
 */
interface ISuperLockableHook {
    /// @notice The vault bank address used to lock SuperPositions
    /// @dev Only relevant for cross-chain operations where positions are locked
    /// @return The vault bank address, or address(0) if not applicable
    function vaultBank() external view returns (address);

    /// @notice The destination chain ID for cross-chain operations
    /// @dev Used to identify the target chain for cross-chain position transfers
    /// @return The destination chain ID, or 0 if not a cross-chain operation
    function dstChainId() external view returns (uint256);
}

interface ISuperHookSetter {
    /// @notice Sets the output amount for the hook
    /// @dev Used for updating `outAmount` when fees were deducted
    /// @param outAmount The amount of tokens processed by the hook
    /// @param caller The caller address for context identification
    function setOutAmount(uint256 outAmount, address caller) external;
}
/// @title ISuperHookInspector
/// @author Superform Labs
/// @notice Interface for the SuperHookInspector contract that manages hook inspection

interface ISuperHookInspector {
    /// @notice Inspect the hook
    /// @param data The hook data to inspect
    /// @return argsEncoded The arguments of the hook encoded
    function inspect(bytes calldata data) external view returns (bytes memory argsEncoded);
}

/// @title ISuperHookResult
/// @author Superform Labs
/// @notice Interface that exposes the result of a hook execution
/// @dev All hooks must implement this interface to provide standardized access to execution results.
///      These results are used by subsequent hooks in the execution chain and by the executor.
interface ISuperHookResult {
    /*//////////////////////////////////////////////////////////////
                                 VIEW METHODS
    //////////////////////////////////////////////////////////////*/

    /// @notice The type of hook
    /// @dev Used to determine how accounting should process this hook's results
    /// @return The hook type (NONACCOUNTING, INFLOW, or OUTFLOW)
    function hookType() external view returns (ISuperHook.HookType);

    /// @notice The SuperPosition (SP) token associated with this hook
    /// @dev For vault hooks, this would be the tokenized position representing shares
    /// @return The address of the SP token, or address(0) if not applicable
    function spToken() external view returns (address);

    /// @notice The underlying asset token being processed
    /// @dev For most hooks, this is the actual token being deposited or withdrawn
    /// @return The address of the asset token, or address(0) for native assets
    function asset() external view returns (address);

    /// @notice The amount of tokens processed by the hook in a given caller context, subject to fees after update
    /// @dev This is the primary output value used by subsequent hooks
    /// @param caller The caller address for context identification
    /// @return The amount of tokens (assets or shares) processed
    function getOutAmount(address caller) external view returns (uint256);

    /// @notice The output token address produced by the hook in a given caller context
    /// @dev Used by subsequent hooks to determine what token the previous hook produced
    ///      PASSTHROUGH hooks auto-forward the previous hook's outToken
    ///      TRANSFORM hooks set this to their specific output token
    /// @param caller The caller address for context identification
    /// @return The address of the output token, or address(0) if not set
    function getOutToken(address caller) external view returns (address);
}

/// @title ISuperHookContextAware
/// @author Superform Labs
/// @notice Interface for hooks that can use previous hook results in their execution
/// @dev Enables contextual awareness and data flow between hooks in a chain
interface ISuperHookContextAware {
    /// @notice Determines if this hook should use the amount from the previous hook
    /// @dev Used to create hook chains where output from one hook becomes input to the next
    /// @param data The hook-specific data containing configuration
    /// @return True if the hook should use the previous hook's output amount
    function decodeUsePrevHookAmount(bytes memory data) external pure returns (bool);
}

/// @title ISuperHookInflowOutflow
/// @author Superform Labs
/// @notice Interface for hooks that handle both inflows and outflows
/// @dev Provides standardized amount extraction for both deposit and withdrawal operations
interface ISuperHookInflowOutflow {
    /// @notice Direction of an amount slot
    /// @dev IN  = primary amount the OMS sizes (intent amount)
    ///      OUT = secondary derived amount (e.g. borrow amount in supply-and-borrow)
    enum Direction {
        IN,
        OUT
    }

    /// @notice Denomination of an amount slot
    /// @dev TOKEN  = raw ERC-20 amount (swaps, bridges, transfers, loan operations)
    ///      ASSETS = underlying asset amount (vault deposits, ERC-4626/7540 withdraw)
    ///      SHARES = vault share amount (vault redeems, ERC-4626/7540 requestRedeem)
    enum Denomination {
        TOKEN,
        ASSETS,
        SHARES
    }

    /// @notice Per-slot metadata: direction + denomination
    /// @dev Aligned 1:1 with the array from decodeAmounts.
    ///      A slot belongs in decodeAmounts/amountRoles iff the OMS can rewrite it
    ///      at execution time without invalidating any commitment (signature or proof)
    ///      embedded in the same data.
    struct AmountMeta {
        Direction dir;
        Denomination denom;
    }

    /// @notice Extracts all amounts from the hook's calldata
    /// @dev Used to determine the quantity of assets or shares being processed
    /// @param data The hook-specific calldata
    /// @return amounts Array of amounts (length 1 for single-amount hooks, 2+ for compound hooks)
    function decodeAmounts(bytes memory data) external pure returns (uint256[] memory amounts);

    /// @notice Returns per-slot metadata (direction + denomination) for each amount
    /// @dev Must return an array of the same length as decodeAmounts(data).
    ///      Enables the OMS to know which slots to size (IN vs OUT) and in what
    ///      denomination (TOKEN vs ASSETS vs SHARES).
    ///      Takes data so variable-count hooks can return the correct number of slots.
    /// @param data The hook-specific calldata (same as passed to decodeAmounts)
    /// @return meta Array of AmountMeta structs aligned index-by-index with decodeAmounts
    function amountRoles(bytes memory data) external pure returns (AmountMeta[] memory meta);
}

/// @title ISuperHookOutflow
/// @author Superform Labs
/// @notice Interface for hooks that specifically handle outflows (withdrawals)
/// @dev Provides additional functionality needed only for outflow operations
interface ISuperHookOutflow {
    /// @notice Replace amounts in the calldata
    /// @param data The data to replace amounts in
    /// @param amounts The amounts to replace (must match length from decodeAmounts)
    /// @return The data with replaced amounts
    function replaceCalldataAmounts(
        bytes memory data,
        uint256[] memory amounts
    )
        external
        pure
        returns (bytes memory);
}

/// @title ISuperHookResultOutflow
/// @author Superform Labs
/// @notice Extended result interface for outflow hook operations
/// @dev Extends the base result interface with outflow-specific information
interface ISuperHookResultOutflow is ISuperHookResult {
    /// @notice The amount of shares consumed during outflow processing
    /// @dev Used for cost basis calculation in the accounting system
    /// @return The amount of shares consumed from the user's position
    function usedShares() external view returns (uint256);
}

/// @title ISuperHookLoans
/// @author Superform Labs
/// @notice Interface for hooks that interact with lending protocols
/// @dev Extends context awareness to enable loan operations within hook chains
interface ISuperHookLoans is ISuperHookContextAware {
    /// @notice Gets the address of the token being borrowed
    /// @dev Used to identify which asset is being borrowed from the lending protocol
    /// @param data The hook-specific data containing loan information
    /// @return The address of the borrowed token
    function getLoanTokenAddress(bytes memory data) external pure returns (address);

    /// @notice Gets the address of the token used as collateral
    /// @dev Used to identify which asset is being used to secure the loan
    /// @param data The hook-specific data containing collateral information
    /// @return The address of the collateral token
    function getCollateralTokenAddress(bytes memory data) external view returns (address);

    /// @notice Gets the account's current ERC-20 wallet balance of the loan token
    /// @dev Returns the plain wallet balance (not the outstanding debt on the lending protocol).
    ///      Hooks snapshot this before execution and measure the post-execution delta to report
    ///      actual loan tokens received (borrow) or spent (repay).
    /// @param account The account to check the wallet balance for
    /// @param data The hook-specific data containing the loan token address
    /// @return The account's wallet balance of the loan token
    function getLoanTokenBalance(address account, bytes memory data) external view returns (uint256);

    /// @notice Gets the account's current ERC-20 wallet balance of the collateral token
    /// @dev Returns the plain wallet balance (not the collateral posted on the lending protocol).
    ///      Hooks snapshot this before execution and measure the post-execution delta to report
    ///      actual collateral tokens spent (supply) or received (withdraw).
    /// @param account The account to check the wallet balance for
    /// @param data The hook-specific data containing the collateral token address
    /// @return The account's wallet balance of the collateral token
    function getCollateralTokenBalance(address account, bytes memory data) external view returns (uint256);
}

/// @title ISuperHookAsyncCancelations
/// @author Superform Labs
/// @notice Interface for hooks that can cancel asynchronous operations
/// @dev Used to handle cancellation of pending operations that haven't completed
interface ISuperHookAsyncCancelations {
    /// @notice Types of cancellations that can be performed
    /// @dev Distinguishes between different operation types that can be canceled
    enum CancelationType {
        NONE, // Not a cancelation hook
        INFLOW, // Cancels a pending deposit operation
        OUTFLOW // Cancels a pending withdrawal operation

    }

    /// @notice Identifies the type of async operation this hook can cancel
    /// @dev Used to verify the hook is appropriate for the operation being canceled
    /// @return asyncType The type of cancellation this hook performs
    function isAsyncCancelHook() external pure returns (CancelationType asyncType);
}

/// @title ISuperHook
/// @author Superform Labs
/// @notice The core hook interface that all hooks must implement
/// @dev Defines the lifecycle methods and execution flow for the hook system
///      Hooks are executed in sequence with results passed between them
interface ISuperHook {
    /*//////////////////////////////////////////////////////////////

                                 ENUMS
    //////////////////////////////////////////////////////////////*/
    /// @notice Defines the possible types of hooks in the system
    /// @dev Used to determine how the hook affects accounting and what operations it performs
    enum HookType {
        NONACCOUNTING, // Hook doesn't affect accounting (e.g., a swap or bridge)
        INFLOW, // Hook processes deposits or positions being added
        OUTFLOW // Hook processes withdrawals or positions being removed

    }

    /*//////////////////////////////////////////////////////////////
                                 VIEW METHODS
    //////////////////////////////////////////////////////////////*/
    /// @notice Builds the execution array for the hook operation
    /// @dev This is the core method where hooks define their on-chain interactions
    ///      The returned executions are a sequence of contract calls to perform
    ///      No state changes should occur in this method
    /// @param prevHook The address of the previous hook in the chain, or address(0) if first
    /// @param account The account to perform executions for (usually an ERC7579 account)
    /// @param data The hook-specific parameters and configuration data
    /// @return executions Array of Execution structs defining calls to make
    function build(
        address prevHook,
        address account,
        bytes calldata data
    )
        external
        view
        returns (Execution[] memory executions);

    /*//////////////////////////////////////////////////////////////
                                 PUBLIC METHODS
    //////////////////////////////////////////////////////////////*/
    /// @notice Prepares the hook for execution
    /// @dev Called before the main execution, used to validate inputs and set execution context
    ///      This method may perform state changes to set up the hook's execution state
    /// @param prevHook The address of the previous hook in the chain, or address(0) if first
    /// @param account The account to perform operations for
    /// @param data The hook-specific parameters and configuration data
    function preExecute(address prevHook, address account, bytes memory data) external;

    /// @notice Finalizes the hook after execution
    /// @dev Called after the main execution, used to update hook state and calculate results
    ///      Sets output values (outAmount, usedShares, etc.) for subsequent hooks
    /// @param prevHook The address of the previous hook in the chain, or address(0) if first
    /// @param account The account operations were performed for
    /// @param data The hook-specific parameters and configuration data
    function postExecute(address prevHook, address account, bytes memory data) external;

    /// @notice Human-readable name for UI display
    /// @return The hook's friendly name
    function name() external pure returns (string memory);

    /// @notice One-sentence description of what this hook does
    /// @return A human-readable description for UI display
    function description() external pure returns (string memory);

    /// @notice Returns the specific subtype identification for this hook
    /// @dev Used to categorize hooks beyond the basic HookType
    ///      For example, a hook might be of type INFLOW but subtype VAULT_DEPOSIT
    /// @return A bytes32 identifier for the specific hook functionality
    function subtype() external view returns (bytes32);

    /// @notice Resets hook mutexes
    /// @param caller The caller address for context identification
    function resetExecutionState(address caller) external;

    /// @notice Sets the caller address that initiated the execution
    /// @dev Used for security validation between preExecute and postExecute calls
    /// @param caller The caller address for context identification
    function setExecutionContext(address caller) external;

    /// @notice Returns the execution nonce for the current execution context
    /// @dev Used to ensure unique execution contexts and prevent replay attacks
    /// @return The execution nonce
    function executionNonce() external view returns (uint256);

    /// @notice Returns the last caller registered by `setExecutionContext`
    /// @return The last caller address
    function lastCaller() external view returns (address);
}

src/libraries/HookDataDecoder.sol

// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;

import { BytesLib } from "../vendor/BytesLib.sol";

/// @title HookDataDecoder
/// @author Superform Labs
/// @notice Library for decoding hook data
library HookDataDecoder {
    function extractYieldSourceOracleId(bytes memory data) internal pure returns (bytes32) {
        return bytes32(BytesLib.slice(data, 0, 32));
    }

    function extractYieldSource(bytes memory data) internal pure returns (address) {
        return BytesLib.toAddress(data, 32);
    }
}

src/libraries/HookSubTypes.sol

// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;

/// @title HookSubTypes
/// @author Superform Labs
/// @notice Library for hook subtypes
library HookSubTypes {
    bytes32 public constant BRIDGE = keccak256(bytes("Bridge"));
    bytes32 public constant CANCEL_DEPOSIT = keccak256(bytes("CancelDeposit"));
    bytes32 public constant CANCEL_DEPOSIT_REQUEST = keccak256(bytes("CancelDepositRequest"));
    bytes32 public constant CANCEL_REDEEM = keccak256(bytes("CancelRedeem"));
    bytes32 public constant CANCEL_REDEEM_REQUEST = keccak256(bytes("CancelRedeemRequest"));
    bytes32 public constant CLAIM = keccak256(bytes("Claim"));
    bytes32 public constant CLAIM_CANCEL_DEPOSIT_REQUEST = keccak256(bytes("ClaimCancelDepositRequest"));
    bytes32 public constant CLAIM_CANCEL_REDEEM_REQUEST = keccak256(bytes("ClaimCancelRedeemRequest"));
    bytes32 public constant COOLDOWN = keccak256(bytes("Cooldown"));
    bytes32 public constant ETHENA = keccak256(bytes("Ethena"));
    bytes32 public constant ERC4626 = keccak256(bytes("ERC4626"));
    bytes32 public constant ERC5115 = keccak256(bytes("ERC5115"));
    bytes32 public constant ERC7540 = keccak256(bytes("ERC7540"));
    bytes32 public constant HYPERCORE = keccak256(bytes("HyperCore"));
    bytes32 public constant LOAN = keccak256(bytes("Loan"));
    bytes32 public constant LOAN_REPAY = keccak256(bytes("LoanRepay"));
    bytes32 public constant MISC = keccak256(bytes("Misc"));
    bytes32 public constant STAKE = keccak256(bytes("Stake"));
    bytes32 public constant SWAP = keccak256(bytes("Swap"));
    bytes32 public constant TOKEN = keccak256(bytes("Token"));
    bytes32 public constant UNSTAKE = keccak256(bytes("Unstake"));
    bytes32 public constant PTYT = keccak256(bytes("PTYT"));
    bytes32 public constant VAULT_BANK = keccak256(bytes("VaultBank"));

    function getHookSubType(string memory hookSubtype) internal pure returns (bytes32) {
        return keccak256(bytes(hookSubtype));
    }
}

src/vendor/BytesLib.sol

// SPDX-License-Identifier: Unlicense
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity 0.8.30;

library BytesLib {
    function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
        bytes memory tempBytes;

        assembly ("memory-safe") {
            // Get a location of some free memory and store it in tempBytes as
            // Solidity does for memory variables.
            tempBytes := mload(0x40)

            // Store the length of the first bytes array at the beginning of
            // the memory for tempBytes.
            let length := mload(_preBytes)
            mstore(tempBytes, length)

            // Maintain a memory counter for the current write location in the
            // temp bytes array by adding the 32 bytes for the array length to
            // the starting location.
            let mc := add(tempBytes, 0x20)
            // Stop copying when the memory counter reaches the length of the
            // first bytes array.
            let end := add(mc, length)

            for {
                // Initialize a copy counter to the start of the _preBytes data,
                // 32 bytes into its memory.
                let cc := add(_preBytes, 0x20)
            } lt(mc, end) {
                // Increase both counters by 32 bytes each iteration.
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } {
                // Write the _preBytes data into the tempBytes memory 32 bytes
                // at a time.
                mstore(mc, mload(cc))
            }

            // Add the length of _postBytes to the current length of tempBytes
            // and store it as the new length in the first 32 bytes of the
            // tempBytes memory.
            length := mload(_postBytes)
            mstore(tempBytes, add(length, mload(tempBytes)))

            // Move the memory counter back from a multiple of 0x20 to the
            // actual end of the _preBytes data.
            mc := end
            // Stop copying when the memory counter reaches the new combined
            // length of the arrays.
            end := add(mc, length)

            for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } { mstore(mc, mload(cc)) }

            // Update the free-memory pointer by padding our last write location
            // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
            // next 32 byte block, then round down to the nearest multiple of
            // 32. If the sum of the length of the two arrays is zero then add
            // one before rounding down to leave a blank 32 bytes (the length block with 0).
            mstore(
                0x40,
                and(
                    add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                    not(31) // Round down to the nearest 32 bytes.
                )
            )
        }

        return tempBytes;
    }

    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
        assembly ("memory-safe") {
            // Read the first 32 bytes of _preBytes storage, which is the length
            // of the array. (We don't need to use the offset into the slot
            // because arrays use the entire slot.)
            let fslot := sload(_preBytes.slot)
            // Arrays of 31 bytes or less have an even value in their slot,
            // while longer arrays have an odd value. The actual length is
            // the slot divided by two for odd values, and the lowest order
            // byte divided by two for even values.
            // If the slot is even, bitwise and the slot with 255 and divide by
            // two to get the length. If the slot is odd, bitwise and the slot
            // with -1 and divide by two.
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)
            let newlength := add(slength, mlength)
            // slength can contain both the length and contents of the array
            // if length < 32 bytes so let's prepare for that
            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
            switch add(lt(slength, 32), lt(newlength, 32))
            case 2 {
                // Since the new array still fits in the slot, we just need to
                // update the contents of the slot.
                // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                sstore(
                    _preBytes.slot,
                    // all the modifications to the slot are inside this
                    // next block
                    add(
                        // we can just add to the slot contents because the
                        // bytes we want to change are the LSBs
                        fslot,
                        add(
                            mul(
                                div(
                                    // load the bytes from memory
                                    mload(add(_postBytes, 0x20)),
                                    // zero all bytes to the right
                                    exp(0x100, sub(32, mlength))
                                ),
                                // and now shift left the number of bytes to
                                // leave space for the length in the slot
                                exp(0x100, sub(32, newlength))
                            ),
                            // increase length by the double of the memory
                            // bytes length
                            mul(mlength, 2)
                        )
                    )
                )
            }
            case 1 {
                // The stored value fits in the slot, but the combined value
                // will exceed it.
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // The contents of the _postBytes array start 32 bytes into
                // the structure. Our first read should obtain the `submod`
                // bytes that can fit into the unused space in the last word
                // of the stored array. To get this, we read 32 bytes starting
                // from `submod`, so the data we read overlaps with the array
                // contents by `submod` bytes. Masking the lowest-order
                // `submod` bytes allows us to add that value directly to the
                // stored value.

                let submod := sub(32, slength)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(
                    sc,
                    add(
                        and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00),
                        and(mload(mc), mask)
                    )
                )

                for {
                    mc := add(mc, 0x20)
                    sc := add(sc, 1)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } { sstore(sc, mload(mc)) }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
            default {
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                // Start copying to the last used word of the stored array.
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // Copy over the first `submod` bytes of the new data as in
                // case 1 above.
                let slengthmod := mod(slength, 32)
                let mlengthmod := mod(mlength, 32)
                let submod := sub(32, slengthmod)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(sc, add(sload(sc), and(mload(mc), mask)))

                for {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } { sstore(sc, mload(mc)) }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
        }
    }

    function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
        // We're using the unchecked block below because otherwise execution ends
        // with the native overflow error code.
        unchecked {
            require(_length + 31 >= _length, "slice_overflow");
        }
        require(_bytes.length >= _start + _length, "slice_outOfBounds");

        bytes memory tempBytes;

        assembly ("memory-safe") {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } { mstore(mc, mload(cc)) }

                mstore(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
        address tempAddress;

        assembly ("memory-safe") {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
        require(_bytes.length >= _start + 1, "toUint8_outOfBounds");
        uint8 tempUint;

        assembly ("memory-safe") {
            tempUint := mload(add(add(_bytes, 0x1), _start))
        }

        return tempUint;
    }

    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
        require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
        uint16 tempUint;

        assembly ("memory-safe") {
            tempUint := mload(add(add(_bytes, 0x2), _start))
        }

        return tempUint;
    }

    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
        uint32 tempUint;

        assembly ("memory-safe") {
            tempUint := mload(add(add(_bytes, 0x4), _start))
        }

        return tempUint;
    }

    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
        require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
        uint64 tempUint;

        assembly ("memory-safe") {
            tempUint := mload(add(add(_bytes, 0x8), _start))
        }

        return tempUint;
    }

    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
        require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
        uint96 tempUint;

        assembly ("memory-safe") {
            tempUint := mload(add(add(_bytes, 0xc), _start))
        }

        return tempUint;
    }

    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
        require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
        uint128 tempUint;

        assembly ("memory-safe") {
            tempUint := mload(add(add(_bytes, 0x10), _start))
        }

        return tempUint;
    }

    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
        uint256 tempUint;

        assembly ("memory-safe") {
            tempUint := mload(add(add(_bytes, 0x20), _start))
        }

        return tempUint;
    }

    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
        require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
        bytes32 tempBytes32;

        assembly ("memory-safe") {
            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
        }

        return tempBytes32;
    }

    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
        bool success = true;

        assembly ("memory-safe") {
            let length := mload(_preBytes)

            // if lengths don't match the arrays are not equal
            switch eq(length, mload(_postBytes))
            case 1 {
                // cb is a circuit breaker in the for loop since there's
                //  no said feature for inline assembly loops
                // cb = 1 - don't breaker
                // cb = 0 - break
                let cb := 1

                let mc := add(_preBytes, 0x20)
                let end := add(mc, length)

                for { let cc := add(_postBytes, 0x20) }
                // the next line is the loop condition:
                // while(uint256(mc < end) + cb == 2)
                eq(add(lt(mc, end), cb), 2) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    // if any of these checks fails then arrays are not equal
                    if iszero(eq(mload(mc), mload(cc))) {
                        // unsuccess:
                        success := 0
                        cb := 0
                    }
                }
            }
            default {
                // unsuccess:
                success := 0
            }
        }

        return success;
    }

    function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
        bool success = true;

        assembly ("memory-safe") {
            // we know _preBytes_offset is 0
            let fslot := sload(_preBytes.slot)
            // Decode the length of the stored array like in concatStorage().
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)

            // if lengths don't match the arrays are not equal
            switch eq(slength, mlength)
            case 1 {
                // slength can contain both the length and contents of the array
                // if length < 32 bytes so let's prepare for that
                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                if iszero(iszero(slength)) {
                    switch lt(slength, 32)
                    case 1 {
                        // blank the last byte which is the length
                        fslot := mul(div(fslot, 0x100), 0x100)

                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                            // unsuccess:
                            success := 0
                        }
                    }
                    default {
                        // cb is a circuit breaker in the for loop since there's
                        //  no said feature for inline assembly loops
                        // cb = 1 - don't breaker
                        // cb = 0 - break
                        let cb := 1

                        // get the keccak hash to get the contents of the array
                        mstore(0x0, _preBytes.slot)
                        let sc := keccak256(0x0, 0x20)

                        let mc := add(_postBytes, 0x20)
                        let end := add(mc, mlength)

                        // the next line is the loop condition:
                        // while(uint256(mc < end) + cb == 2)
                        for { } eq(add(lt(mc, end), cb), 2) {
                            sc := add(sc, 1)
                            mc := add(mc, 0x20)
                        } {
                            if iszero(eq(sload(sc), mload(mc))) {
                                // unsuccess:
                                success := 0
                                cb := 0
                            }
                        }
                    }
                }
            }
            default {
                // unsuccess:
                success := 0
            }
        }

        return success;
    }
}

src/vendor/morpho/IMorpho.sol

// 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.
    /// @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 go above ~1e35 (otherwise the computation of
    /// `toSharesUp` and `toSharesDown` can overflow).
    /// - 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);
}

src/vendor/morpho/IMorphoMarketV1Adapter.sol

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

/// @title IMorphoMarketV1Adapter
/// @notice Minimal read interface for Morpho Vault V2's Morpho Blue market adapters
/// @dev Covers `MorphoMarketV1Adapter` and `MorphoMarketV1AdapterV2`. Only the views a caller needs to
///      enumerate the adapter's listed markets and size a `forceDeallocate` are declared; the mutating
///      `allocate`/`deallocate` entry points are vault-only and deliberately absent.
/// @dev DO NOT ASSUME AN ADAPTER ANSWERS THIS INTERFACE. A Vault V2's adapter list is heterogeneous: a
///      `MorphoVaultV1Adapter` wraps another vault and implements none of `marketIds`, `marketIdsLength` or
///      `expectedSupplyAssets`. Because a `STATICCALL` to an address with no code SUCCEEDS with empty
///      returndata, a `try/catch` against a wrong-shaped or codeless target takes the SUCCESS branch and
///      then has to decode zero bytes. Callers must probe with `code.length` plus a low-level `staticcall`
///      and a returndata-length check, not with `try/catch`.
/// @dev Verified against the live Gauntlet WETH Prime adapter 0xc2B92c498b235516380c04879259Eb2CB1A87a35 on
///      Ethereum: every selector below is present in its deployed bytecode. `allocation(bytes32)` is NOT,
///      so the vault's per-market bookkeeping is not reachable from the adapter.
interface IMorphoMarketV1Adapter {
    /// @notice The Vault V2 this adapter belongs to.
    /// @dev The identity check that makes an adapter trustworthy to enumerate: a caller walking
    ///      `vault.adapters(i)` must assert `parentVault() == vault` before reading anything else, so a
    ///      look-alike contract registered elsewhere cannot be mistaken for this vault's adapter.
    function parentVault() external view returns (address);

    /// @notice The Morpho Blue singleton this adapter supplies into.
    function morpho() external view returns (address);

    /// @notice Number of Morpho Blue market ids this adapter lists.
    function marketIdsLength() external view returns (uint256);

    /// @notice The market id at `index`.
    /// @dev Nothing in the adapter forbids the same id appearing twice, and two adapters of one vault can
    ///      list the same id. Liquidity is a property of the MARKET, so a caller planning several pulls must
    ///      track committed liquidity per id rather than per (adapter, market) pair.
    function marketIds(uint256 index) external view returns (bytes32);

    /// @notice The adapter's own position on `marketId`, in underlying, including interest accrued to
    ///         `block.timestamp`.
    /// @dev This is the ADAPTER'S share accounting converted to assets, NOT the market's withdrawable
    ///      liquidity, and on the V2 adapter it tracks an internal `supplyShares` figure rather than the raw
    ///      Morpho position. A pull must be bounded by `min(this, market liquidity)`; either bound alone
    ///      reverts inside the adapter or inside Morpho.
    function expectedSupplyAssets(bytes32 marketId) external view returns (uint256);

    /// @notice The IRM this adapter pins its markets to, or `address(0)` when it pins none.
    /// @dev PRESENT ONLY ON `MorphoMarketV1AdapterV2`. When it returns non-zero, that adapter reverts
    ///      `IrmMismatch` on any market whose `irm` differs, so a caller must drop such markets in its view
    ///      pass or the whole transaction reverts. Probe it: on the V1 adapter the call fails and the
    ///      correct reading is "pins no IRM".
    function adaptiveCurveIrm() external view returns (address);
}

src/vendor/morpho/IMorphoVaultV2.sol

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

/// @title IMorphoVaultV2
/// @notice Minimal interface for Morpho Vault V2's forceDeallocate function
interface IMorphoVaultV2 {
    /// @notice Permissionlessly deallocates assets from an adapter back to the vault's idle balance.
    /// @dev A penalty (up to 2%) is charged as a share burn on `onBehalf`.
    /// @param adapter The adapter contract to deallocate from (must be registered).
    /// @param data Protocol-specific encoded data for the adapter's deallocate function.
    /// @param assets The amount of underlying assets to deallocate.
    /// @param onBehalf The address whose shares will be burned as penalty.
    /// @return penaltyShares The number of vault shares burned from `onBehalf` to pay the penalty.
    /// @dev SHARES, NOT ASSETS. An earlier revision of this file renamed this to `penaltyAssets` on the
    ///      reasoning that Morpho computes the penalty as an asset amount — which it does, but it then
    ///      pays it with `withdraw(penaltyAssets, address(this), onBehalf)` and RETURNS THAT CALL'S RESULT,
    ///      and ERC-4626 `withdraw` returns shares. Measured on Ethereum against Gauntlet WETH Prime: the
    ///      returned word equalled the account's share-balance delta exactly (20175036235279288) and
    ///      differed from the asset-denominated penalty (20604299106291257). Pinned by
    ///      `ForceDeallocateMorphoVaultForkE2E.test_ForceDeallocateReturnsSharesBurnedNotPenaltyAssets`,
    ///      because every caller in this repo discards the return value and so nothing else would catch
    ///      the name drifting again.
    function forceDeallocate(
        address adapter,
        bytes memory data,
        uint256 assets,
        address onBehalf
    ) external returns (uint256 penaltyShares);

    /// @notice Returns the penalty rate (in WAD, i.e. 1e18 = 100%) for forceDeallocate on a given adapter.
    /// @dev Maximum is 0.02e18 (2%).
    /// @param adapter The adapter address to query the penalty for.
    /// @return The penalty rate in WAD.
    function forceDeallocatePenalty(address adapter) external view returns (uint256);

    /// @notice Number of adapters currently registered on the vault.
    /// @dev Walked with `adapters(i)` over `[0, adaptersLength())`. Curator-managed under timelock, so the
    ///      length can change between a simulation and execution; callers must tolerate that.
    function adaptersLength() external view returns (uint256);

    /// @notice The adapter registered at `index`.
    /// @dev Adapters are heterogeneous. A Morpho Blue market adapter answers `IMorphoMarketV1Adapter`;
    ///      a `MorphoVaultV1Adapter` wraps another vault and does NOT, so it must be filtered out by probing
    ///      rather than assumed.
    function adapters(uint256 index) external view returns (address);

    /// @notice The vault's underlying asset.
    function asset() external view returns (address);

    /// @notice Vault share balance of `account`.
    function balanceOf(address account) external view returns (uint256);

    /// @notice Shares that would be burned to withdraw exactly `assets`, rounded up.
    /// @dev Pure share math: it does NOT require the vault to hold `assets` as idle, so it is valid to call
    ///      while the vault is still illiquid. That is what makes it usable as a pre-flight penalty bound.
    function previewWithdraw(uint256 assets) external view returns (uint256);
}

src/vendor/morpho/MathLib.sol

// 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;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "excessivelySafeCall/=lib/ExcessivelySafeCall/src/",
    "modulekit/=lib/modulekit/src/",
    "@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
    "@solady/=lib/solady/",
    "@account-abstraction/=lib/modulekit/node_modules/account-abstraction/contracts/",
    "@ERC4337/=lib/modulekit/node_modules/@ERC4337/",
    "@pigeon/=lib/pigeon/src/",
    "@surl/=lib/surl/src/",
    "@stringutils/=lib/solidity-stringutils/src/",
    "@pendle/=lib/pendle-core-v2-public/contracts/",
    "@safe/=lib/safe-smart-account/contracts/",
    "@safe7579/=lib/safe7579/src/",
    "@nexus/=lib/nexus/contracts/",
    "sentinellist/=lib/nexus/node_modules/sentinellist/src/",
    "solady/=lib/nexus/node_modules/solady/src/",
    "solarray/=lib/nexus/node_modules/solarray/src/",
    "account-abstraction/=lib/modulekit/node_modules/@ERC4337/account-abstraction/contracts/",
    "account-abstraction-v0.6/=lib/modulekit/node_modules/@ERC4337/account-abstraction-v0.6/contracts/",
    "excessively-safe-call/=lib/ExcessivelySafeCall/src/",
    "composability/=lib/nexus/node_modules/@biconomy/composability/contracts/",
    "erc7739Validator/=lib/nexus/node_modules/erc7739-validator-base/src/",
    "test/mock_fiattoken/=lib/evm-gateway-contracts/test/mock_fiattoken/",
    "@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
    "erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/src/",
    "forge-std/=lib/modulekit/node_modules/forge-std/src/",
    "rhinestone/checknsignatures/=lib/checknsignatures/",
    "evm-gateway/=lib/evm-gateway-contracts/src/",
    "lib/evm-gateway-contracts:src/=lib/evm-gateway-contracts/src/",
    "lib/evm-gateway-contracts:src/=lib/evm-gateway-contracts/src/",
    "lib/evm-gateway-contracts:test/=lib/evm-gateway-contracts/test/",
    "lib/evm-gateway-contracts:test/=lib/evm-gateway-contracts/test/",
    "v4-core/=lib/v4-core/src/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/@ERC4337/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/@rhinestone/erc4337-validation/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/registry/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/registry/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@rhinestone/erc4337-validation/src/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@rhinestone/erc4337-validation/src/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/@rhinestone/safe7579/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/hardhat-deploy/",
    "lib/evm-gateway-contracts/lib/memview-sol/:ds-test/=lib/evm-gateway-contracts/lib/memview-sol/lib/ds-test/src/",
    "lib/evm-gateway-contracts/lib/memview-sol/:ds-test/=lib/evm-gateway-contracts/lib/memview-sol/lib/ds-test/src/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/evm-gateway-contracts/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
    "lib/nexus/node_modules/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/erc7579/:hardhat-deploy/=lib/nexus/node_modules/erc7579/node_modules/hardhat-deploy/",
    "lib/nexus/node_modules/erc7579/:hardhat-deploy/=lib/nexus/node_modules/erc7579/node_modules/hardhat-deploy/",
    "lib/pigeon/lib/openzeppelin-contracts/:erc4626-tests/=lib/pigeon/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/pigeon/lib/openzeppelin-contracts/:erc4626-tests/=lib/pigeon/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/pigeon/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/pigeon/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/pigeon/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/pigeon/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/surl/lib/forge-std/:ds-test/=lib/surl/lib/forge-std/lib/ds-test/src/",
    "lib/surl/lib/forge-std/:ds-test/=lib/surl/lib/forge-std/lib/ds-test/src/",
    "lib/surl/lib/solidity-stringutils/:ds-test/=lib/surl/lib/solidity-stringutils/lib/ds-test/src/",
    "lib/surl/lib/solidity-stringutils/:ds-test/=lib/surl/lib/solidity-stringutils/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/ExcessivelySafeCall/:ds-test/=lib/ExcessivelySafeCall/lib/ds-test/src/",
    "lib/ExcessivelySafeCall/:ds-test/=lib/ExcessivelySafeCall/lib/ds-test/src/",
    "lib/evm-gateway-contracts/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/",
    "lib/evm-gateway-contracts/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/",
    "lib/modulekit/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/modulekit/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/modulekit/:@openzeppelin/=lib/modulekit/node_modules/@openzeppelin/",
    "lib/modulekit/:@openzeppelin/=lib/modulekit/node_modules/@openzeppelin/",
    "lib/modulekit/:@gnosis.pm/safe-contracts/=lib/modulekit/node_modules/@gnosis.pm/safe-contracts/",
    "lib/modulekit/:@gnosis.pm/safe-contracts/=lib/modulekit/node_modules/@gnosis.pm/safe-contracts/",
    "lib/modulekit/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
    "lib/modulekit/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
    "lib/modulekit/:@prb/=lib/modulekit/node_modules/@prb/math/src/",
    "lib/modulekit/:@prb/=lib/modulekit/node_modules/@prb/math/src/",
    "lib/modulekit/:@rhinestone/sentinellist/=lib/modulekit/node_modules/@rhinestone/sentinellist/",
    "lib/modulekit/:@rhinestone/sentinellist/=lib/modulekit/node_modules/@rhinestone/sentinellist/",
    "lib/modulekit/:ds-test/=lib/modulekit/node_modules/ds-test/src/",
    "lib/modulekit/:ds-test/=lib/modulekit/node_modules/ds-test/src/",
    "lib/modulekit/:hardhat-deploy/=lib/modulekit/node_modules/hardhat-deploy/",
    "lib/modulekit/:hardhat-deploy/=lib/modulekit/node_modules/hardhat-deploy/",
    "lib/modulekit/:hardhat/=lib/modulekit/node_modules/hardhat/",
    "lib/modulekit/:hardhat/=lib/modulekit/node_modules/hardhat/",
    "lib/nexus/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/nexus/:@openzeppelin/=lib/nexus/node_modules/@openzeppelin/",
    "lib/nexus/:@openzeppelin/=lib/nexus/node_modules/@openzeppelin/",
    "lib/nexus/:@gnosis.pm/safe-contracts/=lib/nexus/node_modules/@gnosis.pm/safe-contracts/",
    "lib/nexus/:@gnosis.pm/safe-contracts/=lib/nexus/node_modules/@gnosis.pm/safe-contracts/",
    "lib/nexus/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
    "lib/nexus/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
    "lib/nexus/:@prb/=lib/nexus/node_modules/@prb/math/src/",
    "lib/nexus/:@prb/=lib/nexus/node_modules/@prb/math/src/",
    "lib/nexus/:@rhinestone/checknsignatures/=lib/nexus/node_modules/@rhinestone/checknsignatures/",
    "lib/nexus/:@rhinestone/checknsignatures/=lib/nexus/node_modules/@rhinestone/checknsignatures/",
    "lib/nexus/:@rhinestone/module-bases/=lib/nexus/node_modules/@rhinestone/module-bases/",
    "lib/nexus/:@rhinestone/module-bases/=lib/nexus/node_modules/@rhinestone/module-bases/",
    "lib/nexus/:@rhinestone/modulekit/=lib/nexus/node_modules/@rhinestone/modulekit/",
    "lib/nexus/:@rhinestone/modulekit/=lib/nexus/node_modules/@rhinestone/modulekit/",
    "lib/nexus/:@rhinestone/registry/=lib/nexus/node_modules/@rhinestone/registry/",
    "lib/nexus/:@rhinestone/registry/=lib/nexus/node_modules/@rhinestone/registry/",
    "lib/nexus/:@rhinestone/safe7579/=lib/nexus/node_modules/@rhinestone/safe7579/",
    "lib/nexus/:@rhinestone/safe7579/=lib/nexus/node_modules/@rhinestone/safe7579/",
    "lib/nexus/:@rhinestone/sentinellist/=lib/nexus/node_modules/@rhinestone/sentinellist/",
    "lib/nexus/:@rhinestone/sentinellist/=lib/nexus/node_modules/@rhinestone/sentinellist/",
    "lib/nexus/:@safe-global/safe-contracts/=lib/nexus/node_modules/@safe-global/safe-contracts/",
    "lib/nexus/:@safe-global/safe-contracts/=lib/nexus/node_modules/@safe-global/safe-contracts/",
    "lib/nexus/:ds-test/=lib/nexus/node_modules/ds-test/src/",
    "lib/nexus/:ds-test/=lib/nexus/node_modules/ds-test/src/",
    "lib/nexus/:erc7579/=lib/nexus/node_modules/erc7579/",
    "lib/nexus/:erc7579/=lib/nexus/node_modules/erc7579/",
    "lib/nexus/:hardhat-deploy/=lib/nexus/node_modules/hardhat-deploy/",
    "lib/nexus/:hardhat-deploy/=lib/nexus/node_modules/hardhat-deploy/",
    "lib/nexus/:hardhat/=lib/nexus/node_modules/hardhat/",
    "lib/nexus/:hardhat/=lib/nexus/node_modules/hardhat/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/pigeon/:openzeppelin-contracts/=lib/pigeon/lib/openzeppelin-contracts/",
    "lib/pigeon/:openzeppelin-contracts/=lib/pigeon/lib/openzeppelin-contracts/",
    "lib/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/safe7579/:@openzeppelin/=lib/safe7579/node_modules/@openzeppelin/",
    "lib/safe7579/:@openzeppelin/=lib/safe7579/node_modules/@openzeppelin/",
    "lib/safe7579/:@gnosis.pm/safe-contracts/=lib/safe7579/node_modules/@gnosis.pm/safe-contracts/",
    "lib/safe7579/:@gnosis.pm/safe-contracts/=lib/safe7579/node_modules/@gnosis.pm/safe-contracts/",
    "lib/safe7579/:@rhinestone/.ignored_checknsignatures/=lib/safe7579/node_modules/@rhinestone/.ignored_checknsignatures/",
    "lib/safe7579/:@rhinestone/.ignored_checknsignatures/=lib/safe7579/node_modules/@rhinestone/.ignored_checknsignatures/",
    "lib/safe7579/:@rhinestone/.ignored_erc4337-validation/=lib/safe7579/node_modules/@rhinestone/.ignored_erc4337-validation/",
    "lib/safe7579/:@rhinestone/.ignored_erc4337-validation/=lib/safe7579/node_modules/@rhinestone/.ignored_erc4337-validation/",
    "lib/safe7579/:@rhinestone/.ignored_module-bases/=lib/safe7579/node_modules/@rhinestone/.ignored_module-bases/",
    "lib/safe7579/:@rhinestone/.ignored_module-bases/=lib/safe7579/node_modules/@rhinestone/.ignored_module-bases/",
    "lib/safe7579/:@rhinestone/.ignored_sentinellist/=lib/safe7579/node_modules/@rhinestone/.ignored_sentinellist/",
    "lib/safe7579/:@rhinestone/.ignored_sentinellist/=lib/safe7579/node_modules/@rhinestone/.ignored_sentinellist/",
    "lib/safe7579/:@rhinestone/checknsignatures/=lib/safe7579/node_modules/@rhinestone/checknsignatures/",
    "lib/safe7579/:@rhinestone/checknsignatures/=lib/safe7579/node_modules/@rhinestone/checknsignatures/",
    "lib/safe7579/:@rhinestone/module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/",
    "lib/safe7579/:@rhinestone/module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/",
    "lib/safe7579/:@rhinestone/sentinellist/=lib/safe7579/node_modules/@rhinestone/sentinellist/",
    "lib/safe7579/:@rhinestone/sentinellist/=lib/safe7579/node_modules/@rhinestone/sentinellist/",
    "lib/safe7579/:@safe-global/.ignored_safe-contracts/=lib/safe7579/node_modules/@safe-global/.ignored_safe-contracts/",
    "lib/safe7579/:@safe-global/.ignored_safe-contracts/=lib/safe7579/node_modules/@safe-global/.ignored_safe-contracts/",
    "lib/safe7579/:@safe-global/safe-contracts/=lib/safe7579/node_modules/@safe-global/safe-contracts/",
    "lib/safe7579/:@safe-global/safe-contracts/=lib/safe7579/node_modules/@safe-global/safe-contracts/",
    "lib/safe7579/:ds-test/=lib/safe7579/node_modules/ds-test/src/",
    "lib/safe7579/:ds-test/=lib/safe7579/node_modules/ds-test/src/",
    "lib/safe7579/:erc7579/=lib/safe7579/node_modules/erc7579/src/",
    "lib/safe7579/:erc7579/=lib/safe7579/node_modules/erc7579/src/",
    "lib/safe7579/:hardhat-deploy/=lib/safe7579/node_modules/hardhat-deploy/",
    "lib/safe7579/:hardhat-deploy/=lib/safe7579/node_modules/hardhat-deploy/",
    "lib/safe7579/:hardhat/=lib/safe7579/node_modules/hardhat/",
    "lib/safe7579/:hardhat/=lib/safe7579/node_modules/hardhat/",
    "lib/solidity-stringutils/:ds-test/=lib/solidity-stringutils/lib/ds-test/src/",
    "lib/solidity-stringutils/:ds-test/=lib/solidity-stringutils/lib/ds-test/src/",
    "lib/surl/:solidity-stringutils/=lib/surl/lib/solidity-stringutils/src/",
    "lib/surl/:solidity-stringutils/=lib/surl/lib/solidity-stringutils/src/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "@biconomy/=lib/nexus/node_modules/@biconomy/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@erc7579/=lib/nexus/node_modules/@erc7579/enumerablemap4337/src/",
    "@gnosis.pm/=lib/modulekit/node_modules/@gnosis.pm/",
    "@memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
    "@openzeppelin/=lib/modulekit/node_modules/@openzeppelin/",
    "@prb/=lib/modulekit/node_modules/@prb/math/src/",
    "@rhinestone/=lib/safe7579/node_modules/@rhinestone/",
    "@safe-global/=lib/nexus/node_modules/@safe-global/",
    "@zerodev/=lib/nexus/node_modules/@zerodev/kernel/src/",
    "ExcessivelySafeCall/=lib/ExcessivelySafeCall/src/",
    "checknsignatures/=lib/checknsignatures/src/",
    "ds-test/=lib/ExcessivelySafeCall/lib/ds-test/src/",
    "enumerableset4337/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@erc7579/enumerablemap4337/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "erc7579/=lib/safe7579/node_modules/erc7579/src/",
    "erc7739-validator-base/=lib/nexus/node_modules/erc7739-validator-base/src/",
    "eth-gas-reporter/=lib/nexus/node_modules/eth-gas-reporter/",
    "evm-gateway-contracts/=lib/evm-gateway-contracts/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat-deploy/=lib/modulekit/node_modules/hardhat-deploy/",
    "hardhat/=lib/modulekit/node_modules/hardhat/",
    "kernel/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@zerodev/kernel/src/",
    "memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
    "module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/src/",
    "nexus/=lib/nexus/",
    "openzeppelin-contracts-upgradeable/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/",
    "pigeon/=lib/pigeon/src/",
    "prep/=lib/nexus/node_modules/prep/src/",
    "safe-smart-account/=lib/safe-smart-account/",
    "safe7579/=lib/safe7579/",
    "solidity-stringutils/=lib/solidity-stringutils/",
    "solmate/=lib/v4-core/lib/solmate/",
    "surl/=lib/surl/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.