{
 "angle": "Stateful invariant test suite for MidnightAdapter accounting (real VaultV2 + MidnightAdapter + Midnight)",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No invariant was broken. I built a Foundry invariant suite whose handler drives a real VaultV2, a real MidnightAdapter (deployed through MidnightAdapterFactory) and a real Midnight. It ran 3 markets (2 collateral families, 3 maturities), 2 duration caps and 12 actions. Over 143,400 handler calls in total (400x150 without fees, 300x150 and 256x150 with Midnight continuous and settlement fees), all 5 required invariants held. I have no candidate findings. One Informational observation was reproduced with numbers (see lowInfo). It is documented behaviour that partly overlaps Cantina draft 3.2.5, so it is not a finding.",
 "invariantSuite": {
  "path": "test/poc/MidnightAdapterInvariant.t.sol",
  "note": "This is not a PoC of a vulnerability: it is the invariant suite this item asked for, given so others can reproduce it. Put it at test/poc/ in a clone at the pinned commit with src/ and lib/ unmodified. The commit pins solc 0.8.37/0.8.34/0.8.19; if your svm directory is read-only, point XDG_DATA_HOME at a writable directory. FEES=true turns on Midnight's default continuous fee (MAX, 1%/yr) and settlement fees for the 7/30/90-day breakpoints. Without it the run is fee-free.",
  "invariants": [
   "invariant_realAssetsBelowCurrentNetCredit: adapter.realAssets() <= sum over marketIds of Midnight's current net credit (updatePositionView credit - pendingFee)",
   "invariant_capIdAllocationsMatchStoredNetCredit: vault.allocation(adapterId) == sum of stored netCredit over all markets; family ids (collateralParams/rcfThreshold/liquidatorGate/enterGate) and collateralToken ids == sum of stored netCredit of their markets",
   "invariant_durationAllocations: adapter.durationAllocations(2) equals an independent recomputation from marketData (netCredit of markets with ttm >= 7d / >= 30d), and stored maturity equals the market's maturity",
   "invariant_activeMarketList: marketIdsLength() == number of tracked markets with non-zero stored netCredit; marketIds(index) == id for each active market; inactive markets have netRate == 0 and maturity == 0",
   "invariant_noUntrustedValueExtraction: across every untrusted action (attacker deposit, redeem, forceDeallocate, borrower repay, permissionless Midnight updatePosition on the adapter), with accrueInterest called before and after, the passive depositor's previewRedeem never drops by more than 2 wei while the attacker's (shares value + token balance) rises"
  ],
  "actions": "Trusted (state-building): takerBuy (allocator take of a borrower sell offer via SetterRatifier), makerBuy (adapter buy offer via MidnightAdapterPriceRatifierV1 taken by borrower; funded from idle or self-funded by withdrawing from another adapter market), takerSell (allocator take of a lender buy offer), makerSell (adapter sell offer taken by lender), withdrawToVault (vault.deallocate bounded by Midnight withdrawable). Untrusted: repay, attackerDeposit, attackerRedeem, attackerForceDeallocate (in-kind exit at face value + settlement fee + 2% penalty), touch (midnight.updatePosition on the adapter). Environment: badDebt (oracle price set to 1-49% then a liquidation with 0 seized/0 repaid that realizes bad debt, then the price is restored), warp (1s-20d, crossing every maturity). Ticks vary over 4000..4796, so sales happen both above and below amortized value, which exercises the shortfall rate-reduction loop.",
  "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {BaseTest} from \"../BaseTest.sol\";\nimport {Test, console} from \"../../lib/forge-std/src/Test.sol\";\nimport {IMidnightAdapter, IMidnightAdapterBase, MarketData} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {IMidnightAdapterFactory} from \"../../src/adapters/midnight/interfaces/IMidnightAdapterFactory.sol\";\nimport {IMidnightAdapterPriceRatifierV1} from \"../../src/adapters/midnight/ratifiers/interfaces/IMidnightAdapterPriceRatifierV1.sol\";\nimport {IVaultV2} from \"../../src/interfaces/IVaultV2.sol\";\nimport {IERC20} from \"../../src/interfaces/IERC20.sol\";\nimport {WAD} from \"../../src/libraries/ConstantsLib.sol\";\nimport {ERC20Mock} from \"../mocks/ERC20Mock.sol\";\nimport {OracleMock} from \"../../lib/morpho-blue/test/mocks/OracleMock.sol\";\nimport {IMidnight, Market, Offer, CollateralParams} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {HashLib} from \"../../lib/midnight/src/ratifiers/libraries/HashLib.sol\";\nimport {ISetterRatifier} from \"../../lib/midnight/src/ratifiers/interfaces/ISetterRatifier.sol\";\nimport {IdLib} from \"../../lib/midnight/src/libraries/IdLib.sol\";\nimport {ORACLE_PRICE_SCALE} from \"../../lib/morpho-blue/src/libraries/ConstantsLib.sol\";\n\n/// @dev Drives a real VaultV2 + MidnightAdapter + Midnight. Every action is wrapped so that reverts are counted, not fatal.\ncontract MidnightAdapterHandler is Test {\n    IVaultV2 public vault;\n    IMidnightAdapter public adapter;\n    IMidnight public midnight;\n    IMidnightAdapterPriceRatifierV1 public priceRatifier;\n    ISetterRatifier public setterRatifier;\n    IERC20 public token;\n    address public allocator;\n    address public borrower = makeAddr(\"inv-borrower\");\n    address public lender = makeAddr(\"inv-lender\");\n    address public attacker = makeAddr(\"inv-attacker\");\n    address public passive;\n\n    Market[] internal markets;\n    OracleMock[] public oracles;\n    uint256[] public oraclePrices;\n    uint256 internal nonce;\n\n    // Ghosts.\n    mapping(bytes32 => uint256) public calls;\n    mapping(bytes32 => uint256) public successes;\n    uint256 public maxPassiveDrop;\n    uint256 public maxAttackerGain;\n\n    constructor(\n        IVaultV2 _vault,\n        IMidnightAdapter _adapter,\n        IMidnight _midnight,\n        IMidnightAdapterPriceRatifierV1 _priceRatifier,\n        ISetterRatifier _setterRatifier,\n        address _allocator,\n        address _passive,\n        Market[] memory _markets,\n        OracleMock[] memory _oracles\n    ) {\n        vault = _vault;\n        adapter = _adapter;\n        midnight = _midnight;\n        priceRatifier = _priceRatifier;\n        setterRatifier = _setterRatifier;\n        token = IERC20(_vault.asset());\n        allocator = _allocator;\n        passive = _passive;\n        for (uint256 i; i < _markets.length; i++) markets.push(_markets[i]);\n        for (uint256 i; i < _oracles.length; i++) {\n            oracles.push(_oracles[i]);\n            oraclePrices.push(_oracles[i].price());\n        }\n        vm.startPrank(borrower);\n        token.approve(address(_midnight), type(uint256).max);\n        _midnight.setIsAuthorized(address(_setterRatifier), true, borrower);\n        vm.stopPrank();\n        vm.startPrank(lender);\n        token.approve(address(_midnight), type(uint256).max);\n        _midnight.setIsAuthorized(address(_setterRatifier), true, lender);\n        vm.stopPrank();\n        vm.startPrank(attacker);\n        token.approve(address(_vault), type(uint256).max);\n        token.approve(address(_adapter), type(uint256).max);\n        _midnight.setIsAuthorized(address(_adapter), true, attacker);\n        vm.stopPrank();\n    }\n\n    function marketsLength() external view returns (uint256) {\n        return markets.length;\n    }\n\n    function getMarket(uint256 i) external view returns (Market memory) {\n        return markets[i];\n    }\n\n    function _m(uint256 i) internal view returns (Market memory) {\n        return markets[i % markets.length];\n    }\n\n    function _tick(uint256 t) internal pure returns (uint256) {\n        // Ticks around price ~0.99, multiples of the default tick spacing (4).\n        return 4000 + 4 * (t % 200);\n    }\n\n    function _credit(bytes32 id) internal view returns (uint256) {\n        Market memory dummy;\n        (uint128 c, uint128 p,) = midnight.updatePositionView(dummy, id, address(adapter));\n        return c - p;\n    }\n\n    function _passiveValue() internal view returns (uint256) {\n        return vault.previewRedeem(vault.balanceOf(passive));\n    }\n\n    function _attackerValue() internal view returns (uint256) {\n        return vault.previewRedeem(vault.balanceOf(attacker)) + token.balanceOf(attacker);\n    }\n\n    modifier untrusted() {\n        vault.accrueInterest();\n        uint256 beforeP = _passiveValue();\n        uint256 beforeA = _attackerValue();\n        _;\n        vault.accrueInterest();\n        uint256 afterP = _passiveValue();\n        uint256 afterA = _attackerValue();\n        if (afterP + 2 < beforeP && afterA > beforeA) {\n            if (beforeP - afterP > maxPassiveDrop) maxPassiveDrop = beforeP - afterP;\n            if (afterA - beforeA > maxAttackerGain) maxAttackerGain = afterA - beforeA;\n        }\n    }\n\n    function _collat(Market memory market, uint256 units) internal {\n        uint256 collateral = units * 2;\n        ERC20Mock c = ERC20Mock(market.collateralParams[0].token);\n        deal(address(c), borrower, c.balanceOf(borrower) + collateral);\n        vm.startPrank(borrower);\n        c.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, borrower);\n        vm.stopPrank();\n    }\n\n    /* ALLOCATOR ACTIONS (trusted, used to build state) */\n\n    function takerBuy(uint256 mi, uint256 units, uint256 t) external {\n        calls[\"takerBuy\"]++;\n        Market memory market = _m(mi);\n        if (block.timestamp >= market.maturity) return;\n        units = bound(units, 1e6, 20_000e18);\n        Offer memory offer = Offer({\n            market: market,\n            buy: false,\n            maker: borrower,\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: _tick(t),\n            group: keccak256(abi.encode(\"tb\", nonce++)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: borrower,\n            ratifier: address(setterRatifier),\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        _collat(market, units);\n        bytes32 root = HashLib.hashOffer(offer);\n        vm.prank(borrower);\n        setterRatifier.setIsRootRatified(borrower, root, true);\n        vm.prank(allocator);\n        try adapter.take(offer, abi.encode(root, uint256(0), new bytes32[](0)), units, abi.encode(address(0), \"\")) {\n            successes[\"takerBuy\"]++;\n        } catch {}\n    }\n\n    function makerBuy(uint256 mi, uint256 units, uint256 t, bool selfFund, uint256 fundMi) external {\n        calls[\"makerBuy\"]++;\n        Market memory market = _m(mi);\n        if (block.timestamp >= market.maturity) return;\n        units = bound(units, 1e6, 20_000e18);\n        Offer memory offer = Offer({\n            market: market,\n            buy: true,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: _tick(t),\n            group: keccak256(abi.encode(\"mb\", nonce++)),\n            callback: address(adapter),\n            callbackData: selfFund ? abi.encode(address(adapter), abi.encode(_m(fundMi))) : abi.encode(address(0), \"\"),\n            receiverIfMakerIsSeller: address(0),\n            ratifier: address(adapter),\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        bytes32 root = HashLib.hashPriceRatifierV1Offer(offer, address(0));\n        vm.prank(allocator);\n        priceRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        bytes memory rd =\n            abi.encode(address(priceRatifier), abi.encode(root, uint256(0), new bytes32[](0), address(0)));\n        _collat(market, units);\n        vm.prank(borrower);\n        try midnight.take(offer, rd, units, borrower, borrower, address(0), \"\") {\n            successes[\"makerBuy\"]++;\n        } catch {}\n    }\n\n    function takerSell(uint256 mi, uint256 units, uint256 t) external {\n        calls[\"takerSell\"]++;\n        Market memory market = _m(mi);\n        uint256 c = _credit(IdLib.toId(market));\n        if (c == 0) return;\n        units = bound(units, 1, c);\n        Offer memory offer = Offer({\n            market: market,\n            buy: true,\n            maker: lender,\n            start: block.timestamp,\n            expiry: type(uint256).max,\n            tick: _tick(t),\n            group: keccak256(abi.encode(\"ts\", nonce++)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(0),\n            ratifier: address(setterRatifier),\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        deal(address(token), lender, token.balanceOf(lender) + units);\n        bytes32 root = HashLib.hashOffer(offer);\n        vm.prank(lender);\n        setterRatifier.setIsRootRatified(lender, root, true);\n        vm.prank(allocator);\n        try adapter.take(offer, abi.encode(root, uint256(0), new bytes32[](0)), units, \"\") {\n            successes[\"takerSell\"]++;\n        } catch {}\n    }\n\n    function makerSell(uint256 mi, uint256 units, uint256 t) external {\n        calls[\"makerSell\"]++;\n        Market memory market = _m(mi);\n        uint256 c = _credit(IdLib.toId(market));\n        if (c == 0) return;\n        units = bound(units, 1, c);\n        Offer memory offer = Offer({\n            market: market,\n            buy: false,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: type(uint256).max,\n            tick: _tick(t),\n            group: keccak256(abi.encode(\"ms\", nonce++)),\n            callback: address(adapter),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: true,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        bytes32 root = HashLib.hashPriceRatifierV1Offer(offer, address(0));\n        vm.prank(allocator);\n        priceRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        bytes memory rd =\n            abi.encode(address(priceRatifier), abi.encode(root, uint256(0), new bytes32[](0), address(0)));\n        deal(address(token), lender, token.balanceOf(lender) + units);\n        vm.prank(lender);\n        try midnight.take(offer, rd, units, lender, address(0), address(0), \"\") {\n            successes[\"makerSell\"]++;\n        } catch {}\n    }\n\n    function withdrawToVault(uint256 mi, uint256 units) external {\n        calls[\"withdraw\"]++;\n        Market memory market = _m(mi);\n        bytes32 id = IdLib.toId(market);\n        uint256 c = _credit(id);\n        uint256 w = midnight.withdrawable(id);\n        uint256 maxU = c < w ? c : w;\n        units = bound(units, 0, maxU);\n        vm.prank(allocator);\n        try vault.deallocate(address(adapter), abi.encode(market), units) {\n            successes[\"withdraw\"]++;\n        } catch {}\n    }\n\n    /* UNTRUSTED ACTIONS */\n\n    function repay(uint256 mi, uint256 units) external untrusted {\n        calls[\"repay\"]++;\n        Market memory market = _m(mi);\n        uint256 d = midnight.debt(IdLib.toId(market), borrower);\n        if (d == 0) return;\n        units = bound(units, 1, d);\n        deal(address(token), borrower, token.balanceOf(borrower) + units);\n        vm.prank(borrower);\n        try midnight.repay(market, units, borrower, address(0), \"\") {\n            successes[\"repay\"]++;\n        } catch {}\n    }\n\n    function attackerDeposit(uint256 assets) external untrusted {\n        calls[\"deposit\"]++;\n        assets = bound(assets, 1, 50_000e18);\n        deal(address(token), attacker, token.balanceOf(attacker) + assets);\n        vm.prank(attacker);\n        try vault.deposit(assets, attacker) {\n            successes[\"deposit\"]++;\n        } catch {}\n    }\n\n    function attackerRedeem(uint256 shares) external untrusted {\n        calls[\"redeem\"]++;\n        uint256 bal = vault.balanceOf(attacker);\n        if (bal == 0) return;\n        shares = bound(shares, 1, bal);\n        vm.prank(attacker);\n        try vault.redeem(shares, attacker, attacker) {\n            successes[\"redeem\"]++;\n        } catch {}\n    }\n\n    function attackerForceDeallocate(uint256 mi, uint256 assets) external untrusted {\n        calls[\"forceDeallocate\"]++;\n        Market memory market = _m(mi);\n        uint256 c = _credit(IdLib.toId(market));\n        if (c == 0 || vault.balanceOf(attacker) == 0) return;\n        assets = bound(assets, 1, c);\n        deal(address(token), attacker, token.balanceOf(attacker) + assets * 2);\n        vm.prank(attacker);\n        try vault.forceDeallocate(address(adapter), abi.encode(market, attacker), assets, attacker) {\n            successes[\"forceDeallocate\"]++;\n        } catch {}\n    }\n\n    /// @dev Bad debt: drop the collateral price, liquidate with zero seized/repaid, restore the price.\n    function badDebt(uint256 mi, uint256 pct) external {\n        calls[\"badDebt\"]++;\n        uint256 i = mi % markets.length;\n        Market memory market = markets[i];\n        if (midnight.debt(IdLib.toId(market), borrower) == 0) return;\n        uint256 oi = i == 2 ? 1 : 0;\n        pct = bound(pct, 1, 49);\n        oracles[oi].setPrice(oraclePrices[oi] * pct / 100);\n        try midnight.liquidate(market, 0, 0, 0, borrower, false, address(this), address(0), \"\") {\n            successes[\"badDebt\"]++;\n        } catch {}\n        oracles[oi].setPrice(oraclePrices[oi]);\n    }\n\n    function touch(uint256 mi) external untrusted {\n        calls[\"touch\"]++;\n        vm.prank(attacker);\n        try midnight.updatePosition(_m(mi), address(adapter)) {\n            successes[\"touch\"]++;\n        } catch {}\n    }\n\n    function warp(uint256 dt) external {\n        calls[\"warp\"]++;\n        dt = bound(dt, 1, 20 days);\n        vm.warp(block.timestamp + dt);\n    }\n}\n\ncontract MidnightAdapterInvariantTest is BaseTest {\n    IMidnight internal midnight;\n    IMidnightAdapter internal adapter;\n    MidnightAdapterHandler internal handler;\n    address internal passive = makeAddr(\"passive\");\n    ERC20Mock internal collA;\n    ERC20Mock internal collB;\n    uint256[] internal durs;\n\n    function setUp() public virtual override {\n        vm.setEvmVersion(\"osaka\");\n        super.setUp();\n        vm.startPrank(owner);\n        midnight = IMidnight(deployCode(\"Midnight.sol:Midnight\"));\n        midnight.enableLltv(1e18);\n        midnight.enableLiquidationCursor(0.25e18);\n        if (vm.envOr(\"FEES\", false)) {\n            midnight.setFeeSetter(owner);\n            midnight.setDefaultContinuousFee(address(underlyingToken), uint32(uint256(0.01e18) / uint256(365 days)));\n            midnight.setDefaultSettlementFee(address(underlyingToken), 2, 0.00009e18);\n            midnight.setDefaultSettlementFee(address(underlyingToken), 3, 0.0004e18);\n            midnight.setDefaultSettlementFee(address(underlyingToken), 4, 0.0012e18);\n        }\n        vm.stopPrank();\n\n        collA = new ERC20Mock(18);\n        collB = new ERC20Mock(18);\n        OracleMock[] memory oracles = new OracleMock[](2);\n        oracles[0] = new OracleMock();\n        oracles[1] = new OracleMock();\n        oracles[0].setPrice(ORACLE_PRICE_SCALE);\n        oracles[1].setPrice(ORACLE_PRICE_SCALE);\n\n        durs = new uint256[](2);\n        durs[0] = 7 days;\n        durs[1] = 30 days;\n        IMidnightAdapterFactory factory = IMidnightAdapterFactory(\n            deployCode(\"MidnightAdapterFactory.sol:MidnightAdapterFactory\", abi.encode(address(midnight)))\n        );\n        adapter = IMidnightAdapter(factory.createMidnightAdapter(address(vault), durs, address(0), bytes32(0)));\n        IMidnightAdapterPriceRatifierV1 priceRatifier = IMidnightAdapterPriceRatifierV1(\n            deployCode(\"MidnightAdapterPriceRatifierV1.sol:MidnightAdapterPriceRatifierV1\")\n        );\n        ISetterRatifier setterRatifier =\n            ISetterRatifier(deployCode(\"SetterRatifier.sol:SetterRatifier\", abi.encode(address(midnight))));\n\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.increaseMaxTtm, (90 days)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.addAdapter, (address(adapter))));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (address(adapter), true)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setForceDeallocatePenalty, (address(adapter), 0.02e18)));\n        vm.prank(allocator);\n        vault.setMaxRate(1e18 / uint256(365 days));\n        vm.prank(allocator);\n        adapter.setIsSubRatifier(address(priceRatifier), true);\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.increaseMaxNetSellRate, (1e18 / uint256(36 days))));\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.increaseShortfallAllowance, (type(uint128).max)));\n\n        Market[] memory ms = new Market[](3);\n        ms[0] = _market(address(collA), address(oracles[0]), 10 days);\n        ms[1] = _market(address(collA), address(oracles[0]), 40 days);\n        ms[2] = _market(address(collB), address(oracles[1]), 80 days);\n        _increaseCaps(abi.encode(\"this\", address(adapter)));\n        _increaseCaps(abi.encode(\"collateralToken\", address(collA)));\n        _increaseCaps(abi.encode(\"collateralToken\", address(collB)));\n        _increaseCaps(_familyData(ms[0]));\n        _increaseCaps(_familyData(ms[2]));\n        _increaseCaps(abi.encode(\"this/duration\", address(adapter), 7 days));\n        _increaseCaps(abi.encode(\"this/duration\", address(adapter), 30 days));\n\n        uint256 initialAssets = 100_000e18;\n        deal(address(underlyingToken), passive, initialAssets);\n        vm.startPrank(passive);\n        underlyingToken.approve(address(vault), initialAssets);\n        vault.deposit(initialAssets, passive);\n        vm.stopPrank();\n\n        handler = new MidnightAdapterHandler(\n            vault, adapter, midnight, priceRatifier, setterRatifier, allocator, passive, ms, oracles\n        );\n        targetContract(address(handler));\n    }\n\n    function _familyData(Market memory market) internal pure returns (bytes memory) {\n        return abi.encode(\n            \"collateralParams/rcfThreshold/liquidatorGate/enterGate\",\n            market.collateralParams,\n            market.rcfThreshold,\n            market.liquidatorGate,\n            market.enterGate\n        );\n    }\n\n    function _market(address coll, address oracle, uint256 duration) internal view returns (Market memory market) {\n        CollateralParams[] memory collaterals = new CollateralParams[](1);\n        collaterals[0] = CollateralParams(coll, 1e18, 0.25e18, oracle);\n        market = Market({\n            chainId: block.chainid,\n            midnight: address(midnight),\n            loanToken: address(underlyingToken),\n            collateralParams: collaterals,\n            maturity: block.timestamp + duration,\n            rcfThreshold: 0,\n            enterGate: address(0),\n            liquidatorGate: address(0)\n        });\n    }\n\n    function _submitAndSet(address target, bytes memory data) internal {\n        vm.prank(curator);\n        IVaultV2(target).submit(data);\n        (bool success, bytes memory returnData) = target.call(data);\n        if (!success) {\n            assembly (\"memory-safe\") {\n                revert(add(returnData, 32), mload(returnData))\n            }\n        }\n    }\n\n    function _increaseCaps(bytes memory idData) internal {\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.increaseAbsoluteCap, (idData, type(uint128).max)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.increaseRelativeCap, (idData, 1e18)));\n    }\n\n    function _currentNetCredit(bytes32 id) internal view returns (uint256) {\n        Market memory dummy;\n        (uint128 c, uint128 p,) = midnight.updatePositionView(dummy, id, address(adapter));\n        return c - p;\n    }\n\n    /* INVARIANTS */\n\n    function invariant_realAssetsBelowCurrentNetCredit() public view {\n        uint256 sum;\n        uint256 n = adapter.marketIdsLength();\n        for (uint256 i; i < n; i++) sum += _currentNetCredit(adapter.marketIds(i));\n        assertLe(adapter.realAssets(), sum, \"realAssets > sum current net credit\");\n    }\n\n    function invariant_capIdAllocationsMatchStoredNetCredit() public view {\n        uint256 total;\n        uint256 famA;\n        uint256 famB;\n        for (uint256 i; i < handler.marketsLength(); i++) {\n            Market memory m = handler.getMarket(i);\n            uint256 nc = adapter.marketData(IdLib.toId(m)).netCredit;\n            total += nc;\n            if (i < 2) famA += nc;\n            else famB += nc;\n        }\n        assertEq(vault.allocation(keccak256(abi.encode(\"this\", address(adapter)))), total, \"adapterId\");\n        assertEq(vault.allocation(keccak256(_familyData(handler.getMarket(0)))), famA, \"family A\");\n        assertEq(vault.allocation(keccak256(_familyData(handler.getMarket(2)))), famB, \"family B\");\n        assertEq(vault.allocation(keccak256(abi.encode(\"collateralToken\", address(collA)))), famA, \"collat A\");\n        assertEq(vault.allocation(keccak256(abi.encode(\"collateralToken\", address(collB)))), famB, \"collat B\");\n    }\n\n    function invariant_durationAllocations() public view {\n        uint256[] memory a = adapter.durationAllocations(2);\n        uint256[2] memory expected;\n        for (uint256 i; i < handler.marketsLength(); i++) {\n            Market memory m = handler.getMarket(i);\n            MarketData memory d = adapter.marketData(IdLib.toId(m));\n            if (d.netCredit == 0) continue;\n            uint256 ttm = m.maturity > block.timestamp ? m.maturity - block.timestamp : 0;\n            assertEq(d.maturity, m.maturity, \"stored maturity\");\n            for (uint256 j; j < 2; j++) if (ttm >= durs[j]) expected[j] += d.netCredit;\n        }\n        assertEq(a[0], expected[0], \"duration 7d\");\n        assertEq(a[1], expected[1], \"duration 30d\");\n    }\n\n    function invariant_activeMarketList() public view {\n        uint256 n = adapter.marketIdsLength();\n        uint256 nonZero;\n        for (uint256 i; i < handler.marketsLength(); i++) {\n            bytes32 id = IdLib.toId(handler.getMarket(i));\n            MarketData memory d = adapter.marketData(id);\n            if (d.netCredit > 0) {\n                nonZero++;\n                assertEq(adapter.marketIds(d.index), id, \"index mismatch\");\n            } else {\n                assertEq(d.netRate, 0, \"rate on inactive\");\n                assertEq(d.maturity, 0, \"maturity on inactive\");\n            }\n        }\n        assertEq(n, nonZero, \"active list length\");\n    }\n\n    function invariant_noUntrustedValueExtraction() public view {\n        assertEq(handler.maxPassiveDrop(), 0, \"passive depositor lost value to an untrusted call\");\n    }\n\n    function test_coverageSmoke() public {\n        for (uint256 r; r < 300; r++) {\n            uint256 s = uint256(keccak256(abi.encode(r)));\n            uint256 a = s % 12;\n            uint256 x = s >> 8;\n            uint256 y = s >> 80;\n            uint256 z = s >> 160;\n            if (a == 0) handler.takerBuy(x, y, z);\n            else if (a == 1) handler.makerBuy(x, y, z, z % 3 == 0, y);\n            else if (a == 2) handler.takerSell(x, y, z);\n            else if (a == 3) handler.makerSell(x, y, z);\n            else if (a == 4) handler.withdrawToVault(x, y);\n            else if (a == 5) handler.repay(x, y);\n            else if (a == 6) handler.attackerDeposit(y);\n            else if (a == 7) handler.attackerRedeem(y);\n            else if (a == 8) handler.attackerForceDeallocate(x, y);\n            else if (a == 9) handler.badDebt(x, y);\n            else if (a == 10) handler.touch(x);\n            else handler.warp(y % 3 days);\n            invariant_realAssetsBelowCurrentNetCredit();\n            invariant_capIdAllocationsMatchStoredNetCredit();\n            invariant_durationAllocations();\n            invariant_activeMarketList();\n        }\n        invariant_stats();\n        console.log(\"maxPassiveDrop\", handler.maxPassiveDrop(), \"attackerGain\", handler.maxAttackerGain());\n    }\n\n    /// @dev Observation: after bad debt, the vault's cap allocation keeps the pre-loss stored net credit until someone syncs.\n    function test_staleAllocationAfterBadDebt() public {\n        handler.takerBuy(0, 10_000e18, 100);\n        bytes32 id = IdLib.toId(handler.getMarket(0));\n        bytes32 aid = keccak256(abi.encode(\"this\", address(adapter)));\n        console.log(\"stored before\", adapter.marketData(id).netCredit, \"allocation\", vault.allocation(aid));\n        handler.badDebt(0, 10);\n        console.log(\"current after bad debt\", _currentNetCredit(id));\n        console.log(\"stored after bad debt\", adapter.marketData(id).netCredit, \"allocation\", vault.allocation(aid));\n        console.log(\"realAssets\", adapter.realAssets());\n        assertGt(vault.allocation(aid), _currentNetCredit(id));\n        Market memory m0 = handler.getMarket(0);\n        vm.prank(allocator);\n        vault.deallocate(address(adapter), abi.encode(m0), 0);\n        console.log(\"after 0-withdraw sync: stored\", adapter.marketData(id).netCredit, \"allocation\", vault.allocation(aid));\n        assertEq(vault.allocation(aid), _currentNetCredit(id));\n    }\n\n    function invariant_stats() public view {\n        string[12] memory k = [\"touch\",\"takerBuy\",\"makerBuy\",\"takerSell\",\"makerSell\",\"withdraw\",\"repay\",\"deposit\",\"redeem\",\"forceDeallocate\",\"badDebt\",\"warp\"];\n        for (uint256 i; i < k.length; i++) {\n            console.log(k[i], handler.calls(bytes32(bytes(k[i]))), handler.successes(bytes32(bytes(k[i]))));\n        }\n    }\n}\n",
  "command": "FEES=true FOUNDRY_INVARIANT_RUNS=256 FOUNDRY_INVARIANT_DEPTH=150 forge test --match-path test/poc/MidnightAdapterInvariant.t.sol -vv",
  "output": "No files changed, compilation skipped\nRan 3 tests for test/poc/MidnightAdapterInvariant.t.sol:MidnightAdapterInvariantTest\n[PASS]\nMidnightAdapterInvariantTest invariants:\n[PASS] invariant_activeMarketList\n[PASS] invariant_capIdAllocationsMatchStoredNetCredit\n[PASS] invariant_durationAllocations\n[PASS] invariant_noUntrustedValueExtraction\n[PASS] invariant_realAssetsBelowCurrentNetCredit\n[PASS] invariant_stats\n MidnightAdapterInvariantTest invariants (runs: 256, calls: 38400, reverts: 0)\n| Contract               | Selector                | Calls | Reverts | Discards |\n| MidnightAdapterHandler | attackerDeposit         | 3214  | 0       | 0        |\n| MidnightAdapterHandler | attackerForceDeallocate | 3196  | 0       | 0        |\n| MidnightAdapterHandler | attackerRedeem          | 3265  | 0       | 0        |\n| MidnightAdapterHandler | badDebt                 | 3256  | 0       | 0        |\n| MidnightAdapterHandler | makerBuy                | 3167  | 0       | 0        |\n| MidnightAdapterHandler | makerSell               | 3196  | 0       | 0        |\n| MidnightAdapterHandler | repay                   | 3188  | 0       | 0        |\n| MidnightAdapterHandler | takerBuy                | 3208  | 0       | 0        |\n| MidnightAdapterHandler | takerSell               | 3205  | 0       | 0        |\n| MidnightAdapterHandler | touch                   | 3140  | 0       | 0        |\n| MidnightAdapterHandler | warp                    | 3202  | 0       | 0        |\n| MidnightAdapterHandler | withdrawToVault         | 3163  | 0       | 0        |\n[PASS] test_coverageSmoke() (gas: 471283815)\nLogs:\n  touch 29 29\n  takerBuy 24 16\n  makerBuy 21 11\n  takerSell 25 15\n  makerSell 24 15\n  withdraw 29 28\n  repay 22 20\n  deposit 26 26\n  redeem 25 25\n  forceDeallocate 28 25\n  badDebt 21 9\n  warp 26 0\n  maxPassiveDrop 0 attackerGain 0\n[PASS] test_staleAllocationAfterBadDebt() (gas: 1614273)\nLogs:\n  stored before 9997260273979840000000 allocation 9997260273979840000000\n  current after bad debt 1999452054795968000000\n  stored after bad debt 9997260273979840000000 allocation 9997260273979840000000\n  realAssets 1988462269566286526686\n  after 0-withdraw sync: stored 1999452054795968000000 allocation 1999452054795968000000\nSuite result: ok. 3 passed; 0 failed; 0 skipped; finished in 64.58s (64.91s CPU time)\nRan 1 test suite in 64.60s (64.58s CPU time): 3 tests passed, 0 failed, 0 skipped (3 total tests)\n"
 },
 "lowInfo": [
  {
   "title": "Stored netCredit, vault cap allocations and duration allocations keep the pre-loss face value after Midnight bad debt until a 0-asset withdraw resyncs them",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:26",
    "src/adapters/midnight/MidnightAdapter.sol:716-738",
    "src/adapters/midnight/MidnightAdapter.sol:817-834",
    "src/adapters/midnight/MidnightAdapter.sol:846-855"
   ],
   "detail": "After bad debt is realized in Midnight (lossFactor rises), realAssets reads the live net credit for that market (lines 848-855), so book value drops at once. But marketData.netCredit, the vault's allocation for adapterId, family and collateral ids, and durationAllocations (lines 817-834) all stay at the pre-loss face value. They update only when the adapter next touches the market, for example vault.deallocate(adapter, abi.encode(market), 0), which the NatSpec at line 717 describes as a sync. test_staleAllocationAfterBadDebt in the suite shows this: stored netCredit and allocation stay 9997260273979840000000 while current net credit is 1999452054795968000000 and realAssets is 1988462269566286526686. After the 0-asset withdraw, both become 1999452054795968000000. The effect is conservative: caps overcount, so further buys in that market family can be blocked; depositors lose no value. The duration-cap side is already covered by Cantina draft 3.2.5 ('onBuy might revert due to stale allocation checks'). The NatSpec also documents the behaviour (line 26: 'Markets with a zero loss factor use stored net credit'). Severity: Informational at most."
  },
  {
   "title": "Rounding: realAssets stayed <= current net credit in every run",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:544-547",
    "src/adapters/midnight/MidnightAdapter.sol:643-686",
    "src/adapters/midnight/MidnightAdapter.sol:837-863"
   ],
   "detail": "The buy rate is rounded down, and in the shortfall loop target amortized values are rounded up and rates rounded down. Both can recognise interest early, as the NatSpec (lines 21-23) and the audits (Cantina 3.2.8, 3.2.11, 3.6.6; TrustSec R-14) already say. The fuzzer never found a state where this makes realAssets exceed the live net credit, including after shortfall sales, bad debt and fee accrual. I report this as coverage, not as an issue."
  }
 ],
 "covered": [
  "Step 1: cloned morpho-org/vault-v2 at bbeda7b27ae80abcf070e0158cb8a31e87bb2286 with submodules; forge build succeeded; `forge test --match-contract MidnightAdapter` with FOUNDRY_FUZZ_RUNS=64: 398 passed, 0 failed (MidnightAdapterTest 314, PriceRatifierV1Test 36, RateRatifierV1Test 38, RateRatifierV1IntegrationTest 1, IntegrationTest 8, GasTest 1).",
  "Read MidnightAdapter.sol (every function), the adapter README, the IMidnightAdapter MarketData struct, MidnightAdapterIntegrationTest (its setup is reused), and the Midnight liquidate, withdraw, updatePositionView and fee code paths in lib/midnight/src/Midnight.sol.",
  "Invariant campaigns (fail_on_revert off; the handler catches reverts and counts successes): 400 runs x 150 depth without fees (60,000 calls), 300 x 150 with fees (45,000 calls), and 256 x 150 with fees (38,400 calls, output above). All 5 invariants passed every time.",
  "Coverage check (test_coverageSmoke, a 300-step deterministic sequence that asserts the invariants after every step): successful takerBuy 16, makerBuy 11 (self-funded included), takerSell 15, makerSell 15, withdraw 28, repay 20, deposit 26, redeem 25, forceDeallocate 25, badDebt 9, touch 29. Every path was exercised: shortfall, gain, market removal and re-add, post-maturity sales and withdrawals.",
  "Fairness: in no campaign did any untrusted action lower the passive depositor's redeemable value while raising the attacker's (maxPassiveDrop == 0).",
  "Prior-audit check: two reader agents read the full Cantina draft (19 findings, 3.1.1-3.6.6) and the full TrustSec draft (TRST-L-1..L-5, R-1..R-15). Neither reports a broken invariant of the kinds tested here. The stale-allocation observation partly overlaps Cantina 3.2.5."
 ],
 "notCovered": [
  "forceRemove, setForceSellable/forced sales at minForceSellPrice and sub-ratifier removal were not in the handler. They are timelocked or trusted-role actions.",
  "Enter gates (IKRCompatibleEnterGate/WhitelistEnterSubGate) and admission during forceDeallocate: all markets were ungated.",
  "Trades between several adapters of the same vault, nested vaults, and the liquidity adapter: one adapter only.",
  "Non-18-decimal and non-standard tokens (DECIMALS/TOKEN_TYPE env left at the defaults: 18 decimals, standard ERC20).",
  "More than 3 markets, so the MAX_MARKETS=250 boundary was not tested; more than 2 durations; MidnightAdapterRateRatifierV1 offers.",
  "The fairness invariant uses one passive depositor and one attacker, with previewRedeem as the value measure. It does not model multi-block MEV or the vault's maxRate interest cap as an attack lever.",
  "No second, independent re-run of the suite from a fresh clone by another agent was done in this item."
 ]
}