{
 "lead": "stateful-extended: five-market stateful invariant campaign on the real Vault V2 + Midnight + MidnightAdapter stack (maker offers through both V1 sub-ratifiers, outsider fills whole and in pieces, allocator taker trades, repay/withdrawToVault, vault deposit/withdraw/forceDeallocate, setForceSellable + cheap sales, forceRemove, partial bad debt by liquidation, warps past maturity)",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "DISMISSED. Nothing survives: 256 runs x depth 100 (25,600 handler calls, 5,320 reverted, all reverts are expected guards or handler preconditions) plus three 150-call deterministic sequences and one directed forceSellable test all pass every invariant. No action by an account without a trusted role lowered the vault's NAV (idle + realAssets) or the idle depositor's previewRedeem value by even 1 wei outside the three recorded loss classes (bad debt, forceSellable sales, forceRemove), and each recorded loss stayed inside its bound. This is evidence of absence within the modelled space only; see notCovered.",
 "lowInfo": [
  {
   "title": "Tokens sent directly to the adapter are not counted in realAssets and stay on the adapter until skimRecipient skims them",
   "class": "Informational",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:393-400",
    "src/adapters/midnight/MidnightAdapter.sol:837-863"
   ],
   "detail": "outsiderPoke donates loan tokens to the adapter. In the three deterministic sequences the adapter balance at the end equals the donated total exactly (e.g. 1026871939340070811348 = 1026871939340070811348), so no trade, forceDeallocate or withdrawToVault path strands or sweeps any other balance, and NAV never moved on a donation. Matches the documented skim behaviour; no impact found.",
   "verified": true
  },
  {
   "title": "A sale whose shortfall exceeds the total remaining interest reverts with ShortfallTooHigh even when shortfallAllowance would cover it",
   "class": "Informational",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:646-667"
   ],
   "detail": "Seen as revert selector 0x0e0afa7b on makerSellPrice/makerSellRate fills in a diagnostic 120-call run of the same handler (that diagnostic output is not part of the delivered output). It is a liveness limit on below-book sales of non-forceSellable markets, visible in the code; the only way around it is the timelocked setForceSellable. Not a loss, and the taker simply gets a revert.",
   "verified": true
  },
  {
   "title": "Maker sell offers ratified through MidnightAdapterRateRatifierV1 stop being fillable as time passes",
   "class": "Informational",
   "refs": [
    "src/adapters/midnight/ratifiers/MidnightAdapterRateRatifierV1.sol:107-108"
   ],
   "detail": "The price floor WAD/(1+rate*ttm) rises as ttm shrinks, so a sell offer left partly filled later reverts with WorsePrice (selector 0x1768d9f2, seen on makerSellRate and fillOpen in the same diagnostic run). This is the protective direction for the vault (buy offers stay fillable, sells do not get cheaper); by design, reported only as an operational note. makerSellRate has the highest revert share of the trade actions in the campaign (511 of 1460).",
   "verified": true
  },
  {
   "title": "Stored net credit (caps, allocation ids, durationAllocations) stays at the pre-loss figure after bad debt until an allocator or sentinel syncs the market",
   "class": "Informational",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:60",
    "src/adapters/midnight/MidnightAdapter.sol:69",
    "src/adapters/midnight/MidnightAdapter.sol:716-738"
   ],
   "detail": "Invariant E asserts stored >= live net credit for every non-removed market and stored == live while the market lossFactor is 0 (including the market with a continuous fee, under outsider updatePosition calls); both held on every step. The campaign did not separately count how long stored stayed above live after a loss, so the staleness itself is UNVERIFIED here; it is documented behaviour (stored net credit is an upper bound) and realAssets reads the live figure for markets with a loss.",
   "verified": false
  }
 ],
 "covered": {
  "tests": [
   {
    "path": "test/poc/StatefulExtended.t.sol",
    "name": "invariant_statefulExtended",
    "what": "256 runs, depth 100, fail-on-revert false, one campaign checking all invariants after every call. Handler: 17 actions over 5 markets (maturities +3d, +7d, +14d, +45d, +90d; markets 0-2 collateral A, 3 collateral B, 4 both; settlement fee on markets 1 and 3, continuous fee on market 2; durations 1d/7d/30d with a finite 60,000-token absolute cap on 30d; shortfallAllowance 2,000 tokens; minNetBuyRate 0.5% APR; maxNetSellRate 100% APR; forceDeallocate penalty 2%). Invariants: A vault.allocation(id) == sum of stored netCredit behind each id (adapter id, 3 family ids, 2 collateral ids) and marketIds/index/maturity consistent; B durationAllocations(1..3) == brute-force sum; C realAssets <= stored and <= live face value; D no NAV or idle-depositor drop above 1e9 wei in any action where no loss is allowed (observed max: 0 wei), bad-debt loss <= adapter's live credit reduction, forceSellable loss <= face sold minus proceeds, forceRemove loss <= removed stored credit, vault idle delta == take's buyerAssets/sellerAssets and within the tick price, deposit/withdraw move NAV by exactly the assets, shortfallAllowance + consumed == initial, accrueInterest never reverts; E stored >= live net credit, equal while lossFactor == 0; F vault.totalAssets() <= idle + realAssets. The first call of each run only performs the five-market setup (the base setUp is not virtual), so 256 of the 25,600 calls are setup-only.",
    "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {MidnightAdapterIntegrationTest} from \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {IMidnightAdapter, IMidnightAdapterBase} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {MarketData} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {IMidnightAdapterFactory} from \"../../src/adapters/midnight/interfaces/IMidnightAdapterFactory.sol\";\nimport {\n    IMidnightAdapterPriceRatifierV1\n} 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 {TickLib, MAX_TICK} from \"../../lib/midnight/src/libraries/TickLib.sol\";\nimport {Test, console} from \"../../lib/forge-std/src/Test.sol\";\n\nstruct Cfg {\n    IVaultV2 vault;\n    IMidnightAdapter adapter;\n    IMidnight midnight;\n    IERC20 token;\n    CollateralParams pA;\n    CollateralParams pB;\n    address priceRat;\n    address rateRat;\n    address setterRat;\n    address curator;\n    address allocator;\n    address idle;\n    uint256 t0;\n}\n\nstruct OpenOffer {\n    uint8 m;\n    bool buy;\n    uint8 kind; // 0 = MidnightAdapterPriceRatifierV1, 1 = MidnightAdapterRateRatifierV1\n    uint8 bj;\n    uint256 tick;\n    bytes32 group;\n    uint128 maxUnits;\n    uint256 start;\n    uint256 rate;\n}\n\ncontract StatefulHandler is Test {\n    uint256 internal constant N = 5;\n    uint256 public constant TOL = 1e9; // wei of an 18-decimal asset\n\n    Cfg internal c;\n    uint256[5] public maturities;\n    address[2] public borrowers;\n    address public lender = makeAddr(\"h.lender\");\n    address public exiter = makeAddr(\"h.exiter\");\n    address public user = makeAddr(\"h.user\");\n    address public liquidator = makeAddr(\"h.liquidator\");\n    uint256 internal nonce;\n    OpenOffer[] internal open;\n\n    // ghosts\n    uint256 public gMaxDrop; // largest NAV / idle-depositor drop in an action where no loss is allowed\n    bytes32 public gWorst;\n    uint256[4] public gLoss; // [1] bad debt, [2] forceSellable sale, [3] forceRemove\n    uint256 public gBoundViolations; // allowed-loss action that lost more than its recorded bound\n    uint256 public gPayViolations; // vault paid more / received less than the take reported\n    uint256 public gAccrueReverts;\n    uint256 public gShortfallSales;\n    uint256 public gShortfallConsumed;\n    uint256 public gBadDebtEvents;\n    uint256 public gDonated;\n    uint256 public gRemoved;\n    uint256 public gPieces;\n    mapping(bytes32 => uint256) public ok;\n\n    address internal host = msg.sender;\n\n    /// @dev The base setUp is not virtual, so the five-market setup cannot be added by override.\n    /// @dev The first action of each invariant run only performs that setup and returns, so it is never rolled back.\n    modifier ready() {\n        if (c.t0 == 0) {\n            StatefulExtendedTest(host).lazySetup();\n            return;\n        }\n        _;\n    }\n\n    function init(Cfg memory cfg) external {\n        require(msg.sender == host && c.t0 == 0);\n        c = cfg;\n        uint256[5] memory d = [uint256(3 days), 7 days, 14 days, 45 days, 90 days];\n        for (uint256 i; i < N; i++) {\n            maturities[i] = cfg.t0 + d[i];\n        }\n        borrowers[0] = makeAddr(\"h.borrower0\");\n        borrowers[1] = makeAddr(\"h.borrower1\");\n        for (uint256 j; j < 2; j++) {\n            vm.startPrank(borrowers[j]);\n            IERC20(c.pA.token).approve(address(c.midnight), type(uint256).max);\n            IERC20(c.pB.token).approve(address(c.midnight), type(uint256).max);\n            c.token.approve(address(c.midnight), type(uint256).max);\n            c.midnight.setIsAuthorized(c.setterRat, true, borrowers[j]);\n            vm.stopPrank();\n        }\n        vm.startPrank(lender);\n        c.token.approve(address(c.midnight), type(uint256).max);\n        c.midnight.setIsAuthorized(c.setterRat, true, lender);\n        vm.stopPrank();\n        vm.prank(liquidator);\n        c.token.approve(address(c.midnight), type(uint256).max);\n        vm.startPrank(exiter);\n        c.token.approve(address(c.vault), type(uint256).max);\n        c.token.approve(address(c.adapter), type(uint256).max);\n        c.midnight.setIsAuthorized(address(c.adapter), true, exiter);\n        vm.stopPrank();\n        vm.prank(user);\n        c.token.approve(address(c.vault), type(uint256).max);\n    }\n\n    function selectors() external pure returns (bytes4[] memory s, string[] memory n) {\n        s = new bytes4[](17);\n        n = new string[](17);\n        (s[0], n[0]) = (this.makerBuyPrice.selector, \"makerBuyPrice (outsider fill)\");\n        (s[1], n[1]) = (this.makerBuyRate.selector, \"makerBuyRate (outsider fill)\");\n        (s[2], n[2]) = (this.makerSellPrice.selector, \"makerSellPrice (outsider fill)\");\n        (s[3], n[3]) = (this.makerSellRate.selector, \"makerSellRate (outsider fill)\");\n        (s[4], n[4]) = (this.fillOpen.selector, \"fillOpen (later piece)\");\n        (s[5], n[5]) = (this.takerBuy.selector, \"takerBuy (allocator)\");\n        (s[6], n[6]) = (this.takerSell.selector, \"takerSell (allocator, cheap if forceSellable)\");\n        (s[7], n[7]) = (this.repay.selector, \"repay\");\n        (s[8], n[8]) = (this.withdrawToVault.selector, \"withdrawToVault\");\n        (s[9], n[9]) = (this.vaultDeposit.selector, \"vaultDeposit\");\n        (s[10], n[10]) = (this.vaultWithdraw.selector, \"vaultWithdraw\");\n        (s[11], n[11]) = (this.forceDeallocate.selector, \"forceDeallocate\");\n        (s[12], n[12]) = (this.forceSellableCfg.selector, \"set/unsetForceSellable, minForceSellPrice\");\n        (s[13], n[13]) = (this.forceRemove.selector, \"forceRemove\");\n        (s[14], n[14]) = (this.badDebt.selector, \"badDebt (liquidation)\");\n        (s[15], n[15]) = (this.warp.selector, \"warp\");\n        (s[16], n[16]) = (this.outsiderPoke.selector, \"outsiderPoke (donate/updatePosition/accrue)\");\n    }\n\n    /* VIEWS */\n\n    function market(uint256 i) public view returns (Market memory m) {\n        CollateralParams[] memory cp;\n        if (i < 3) {\n            cp = new CollateralParams[](1);\n            cp[0] = c.pA;\n        } else if (i == 3) {\n            cp = new CollateralParams[](1);\n            cp[0] = c.pB;\n        } else {\n            cp = new CollateralParams[](2);\n            (cp[0], cp[1]) = c.pA.token < c.pB.token ? (c.pA, c.pB) : (c.pB, c.pA);\n        }\n        m = Market({\n            chainId: block.chainid,\n            midnight: address(c.midnight),\n            loanToken: address(c.token),\n            collateralParams: cp,\n            maturity: maturities[i],\n            rcfThreshold: 0,\n            enterGate: address(0),\n            liquidatorGate: address(0)\n        });\n    }\n\n    function id(uint256 i) public view returns (bytes32) {\n        return IdLib.toId(market(i));\n    }\n\n    function md(uint256 i) public view returns (MarketData memory) {\n        return c.adapter.marketData(id(i));\n    }\n\n    function stored(uint256 i) public view returns (uint256) {\n        return md(i).netCredit;\n    }\n\n    function live(uint256 i) public view returns (uint256 net, uint256 gross) {\n        (uint128 credit, uint128 pendingFee,) = c.midnight.updatePositionView(market(i), id(i), address(c.adapter));\n        return (credit - pendingFee, credit);\n    }\n\n    function nav() public view returns (uint256) {\n        return c.token.balanceOf(address(c.vault)) + c.adapter.realAssets();\n    }\n\n    function idleValue() public view returns (uint256) {\n        return c.vault.previewRedeem(c.vault.balanceOf(c.idle));\n    }\n\n    function openLength() external view returns (uint256) {\n        return open.length;\n    }\n\n    function collIndex(uint256 i) internal view returns (uint256) {\n        return (i == 4 && c.pA.token > c.pB.token) ? 1 : 0;\n    }\n\n    function collToken(uint256 i) internal view returns (address) {\n        return i == 3 ? c.pB.token : c.pA.token;\n    }\n\n    function ttmOf(uint256 i) internal view returns (uint256) {\n        return maturities[i] > block.timestamp ? maturities[i] - block.timestamp : 0;\n    }\n\n    /* INTERNALS */\n\n    function _end(bytes32 name, uint256 nav0, uint256 cls, uint256 lossBound) internal {\n        uint256 nav1 = nav();\n        if (nav1 < nav0) {\n            uint256 d = nav0 - nav1;\n            if (cls == 0) {\n                if (d > gMaxDrop) (gMaxDrop, gWorst) = (d, name);\n            } else {\n                gLoss[cls] += d;\n                if (d > lossBound + TOL) gBoundViolations++;\n            }\n        }\n        ok[name]++;\n        skip(1);\n        try c.vault.accrueInterest() {}\n        catch {\n            gAccrueReverts++;\n        }\n    }\n\n    function _heldFrom(uint256 a) internal view returns (uint256 i) {\n        for (uint256 k; k < N; k++) {\n            i = (a + k) % N;\n            MarketData memory d = md(i);\n            if (d.netCredit > 0 && !d.forceRemoved) return i;\n        }\n        revert(\"SKIP: no held market\");\n    }\n\n    function _buyableFrom(uint256 a) internal view returns (uint256 i) {\n        for (uint256 k; k < N; k++) {\n            i = (a + k) % N;\n            MarketData memory d = md(i);\n            if (ttmOf(i) > 0 && !d.forceRemoved && !d.forceSellable) return i;\n        }\n        revert(\"SKIP: no buyable market\");\n    }\n\n    function _tickForRate(uint256 r, uint256 ttm) internal pure returns (uint256) {\n        return TickLib.priceToTick(WAD * WAD / (WAD + r * ttm), 4);\n    }\n\n    function _supply(uint256 i, address br, uint256 units) internal {\n        uint256 amt = units * 2 + 1e18;\n        deal(collToken(i), br, amt);\n        vm.prank(br);\n        c.midnight.supplyCollateral(market(i), collIndex(i), amt, br);\n    }\n\n    function _makerOffer(OpenOffer memory o) internal view returns (Offer memory offer, bytes memory rd, bytes32 root) {\n        Market memory m = market(o.m);\n        offer = Offer({\n            market: m,\n            buy: o.buy,\n            maker: address(c.adapter),\n            start: o.start,\n            expiry: m.maturity + 30 days,\n            tick: o.tick,\n            group: o.group,\n            callback: address(c.adapter),\n            callbackData: o.buy ? abi.encode(address(0), \"\") : bytes(\"\"),\n            receiverIfMakerIsSeller: o.buy ? address(0) : address(c.adapter),\n            ratifier: address(c.adapter),\n            reduceOnly: !o.buy,\n            maxUnits: o.maxUnits,\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        bytes32[] memory proof = new bytes32[](0);\n        if (o.kind == 0) {\n            root = HashLib.hashPriceRatifierV1Offer(offer, address(0));\n            rd = abi.encode(c.priceRat, abi.encode(root, uint256(0), proof, address(0)));\n        } else {\n            root = HashLib.hashRateRatifierV1Offer(offer, o.rate, address(0));\n            rd = abi.encode(c.rateRat, abi.encode(root, uint256(0), proof, o.rate, address(0)));\n        }\n    }\n\n    /// @dev One outsider fill of a maker offer, with payment-integrity and loss-class bookkeeping.\n    function _fill(bytes32 name, OpenOffer memory o, uint256 units) internal {\n        (Offer memory offer, bytes memory rd,) = _makerOffer(o);\n        uint256 nav0 = nav();\n        uint256 idle0 = c.token.balanceOf(address(c.vault));\n        uint256 allow0 = c.adapter.shortfallAllowance();\n        bool fs = md(o.m).forceSellable;\n        uint256 price = TickLib.tickToPrice(o.tick);\n        uint256 buyerAssets;\n        uint256 sellerAssets;\n        if (o.buy) {\n            address br = borrowers[o.bj];\n            _supply(o.m, br, units);\n            vm.prank(br);\n            (buyerAssets, sellerAssets) = c.midnight.take(offer, rd, units, br, br, address(0), \"\");\n            uint256 idle1 = c.token.balanceOf(address(c.vault));\n            if (idle0 - idle1 != buyerAssets || buyerAssets > units * price / WAD) gPayViolations++;\n        } else {\n            deal(address(c.token), lender, units * 2);\n            vm.prank(lender);\n            (buyerAssets, sellerAssets) = c.midnight.take(offer, rd, units, lender, address(0), address(0), \"\");\n            uint256 idle1 = c.token.balanceOf(address(c.vault));\n            if (idle1 - idle0 != sellerAssets || sellerAssets < units * price / WAD) gPayViolations++;\n        }\n        uint256 allow1 = c.adapter.shortfallAllowance();\n        if (allow1 < allow0) {\n            gShortfallSales++;\n            gShortfallConsumed += allow0 - allow1;\n        }\n        gPieces++;\n        _end(name, nav0, (!o.buy && fs) ? 2 : 0, units > sellerAssets ? units - sellerAssets : 0);\n        ok[name]--; // counted once per action by the caller\n    }\n\n    function _maker(bytes32 name, bool buy, uint8 kind, uint256 a, uint256 b, uint256 x) internal {\n        x = uint256(keccak256(abi.encode(x)));\n        OpenOffer memory o;\n        o.buy = buy;\n        o.kind = kind;\n        o.bj = uint8((a >> 8) % 2);\n        uint256 units;\n        if (buy) {\n            o.m = uint8(_buyableFrom(a));\n            units = bound(b, 1e12, 15_000e18);\n        } else {\n            o.m = uint8(_heldFrom(a));\n            (, uint256 gross) = live(o.m);\n            units = (x >> 20) % 4 == 0 ? gross : bound(b, 1, gross);\n        }\n        uint256 ttm = ttmOf(o.m);\n        uint256 maxRate = 1e18 / uint256(365 days);\n        o.tick = _tickForRate(bound(x, 0, buy ? maxRate : maxRate * 11 / 10) % (maxRate * 2), ttm);\n        if (!buy && md(o.m).forceSellable) o.tick = bound(x, 3200 / 4, 5200 / 4) * 4;\n        o.group = keccak256(abi.encode(\"h\", nonce++));\n        o.maxUnits = uint128(units);\n        o.start = block.timestamp;\n        if (kind == 1) {\n            uint256 p = TickLib.tickToPrice(o.tick);\n            uint256 implied = ttm == 0 ? 0 : (WAD * WAD / p - WAD) / ttm;\n            o.rate = buy ? implied : (ttm == 0 ? 0 : implied + 1 + (implied * ((x >> 48) % 3)) / 10);\n        }\n        (,, bytes32 root) = _makerOffer(o);\n        vm.prank(c.allocator);\n        IMidnightAdapterPriceRatifierV1(kind == 0 ? c.priceRat : c.rateRat)\n            .setIsRootRatified(address(c.adapter), root, true, c.allocator);\n        uint256 pieces = 1 + (x >> 16) % 4;\n        bool leaveOpen = (x >> 24) % 2 == 1 && pieces > 1;\n        uint256 piece = units / pieces;\n        if (piece == 0) (piece, pieces, leaveOpen) = (units, 1, false);\n        for (uint256 k; k < (leaveOpen ? pieces - 1 : pieces); k++) {\n            _fill(name, o, piece);\n        }\n        if (leaveOpen) open.push(o);\n        ok[name]++;\n    }\n\n    /* ACTIONS */\n\n    function makerBuyPrice(uint256 a, uint256 b, uint256 x) external ready {\n        _maker(\"makerBuyPrice\", true, 0, a, b, x);\n    }\n\n    function makerBuyRate(uint256 a, uint256 b, uint256 x) external ready {\n        _maker(\"makerBuyRate\", true, 1, a, b, x);\n    }\n\n    function makerSellPrice(uint256 a, uint256 b, uint256 x) external ready {\n        _maker(\"makerSellPrice\", false, 0, a, b, x);\n    }\n\n    function makerSellRate(uint256 a, uint256 b, uint256 x) external ready {\n        _maker(\"makerSellRate\", false, 1, a, b, x);\n    }\n\n    function fillOpen(uint256 a, uint256 b, uint256) external ready {\n        require(open.length > 0, \"SKIP: no open offer\");\n        OpenOffer memory o = open[a % open.length];\n        uint256 remaining = o.maxUnits - c.midnight.consumed(address(c.adapter), o.group);\n        require(remaining > 0, \"SKIP: consumed\");\n        _fill(\"fillOpen\", o, bound(b, 1, remaining));\n        ok[\"fillOpen\"]++;\n    }\n\n    function takerBuy(uint256 a, uint256 b, uint256 x) external ready {\n        x = uint256(keccak256(abi.encode(x)));\n        uint256 i = _buyableFrom(a);\n        address br = borrowers[(a >> 8) % 2];\n        uint256 units = bound(b, 1e12, 15_000e18);\n        Market memory m = market(i);\n        bytes memory cbData = abi.encode(address(0), \"\");\n        if ((x >> 32) % 3 == 0) {\n            // Self-funded buy: pay from repaid credit of another market held by the adapter.\n            for (uint256 k = 1; k < N; k++) {\n                uint256 f = (i + k) % N;\n                uint256 w = c.midnight.withdrawable(id(f));\n                (, uint256 gross) = live(f);\n                if (w > gross) w = gross;\n                if (w > 1e12 && stored(f) > 0 && !md(f).forceRemoved) {\n                    if (units > w) units = w;\n                    cbData = abi.encode(address(c.adapter), abi.encode(market(f)));\n                    break;\n                }\n            }\n        }\n        Offer memory offer = Offer({\n            market: m,\n            buy: false,\n            maker: br,\n            start: block.timestamp,\n            expiry: m.maturity,\n            tick: _tickForRate(bound(x, 0, 1e18 / uint256(365 days)), ttmOf(i)),\n            group: keccak256(abi.encode(\"h\", nonce++)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: br,\n            ratifier: c.setterRat,\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        bytes32 root = HashLib.hashOffer(offer);\n        _supply(i, br, units);\n        vm.prank(br);\n        ISetterRatifier(c.setterRat).setIsRootRatified(br, root, true);\n        uint256 nav0 = nav();\n        vm.prank(c.allocator);\n        c.adapter.take(offer, abi.encode(root, uint256(0), new bytes32[](0)), units, cbData);\n        _end(\"takerBuy\", nav0, 0, 0);\n    }\n\n    function takerSell(uint256 a, uint256 b, uint256 x) external ready {\n        x = uint256(keccak256(abi.encode(x)));\n        uint256 i = _heldFrom(a);\n        (, uint256 gross) = live(i);\n        uint256 units = (x >> 20) % 4 == 0 ? gross : bound(b, 1, gross);\n        Market memory m = market(i);\n        bool fs = md(i).forceSellable;\n        uint256 maxRate = 1e18 / uint256(365 days);\n        Offer memory offer = Offer({\n            market: m,\n            buy: true,\n            maker: lender,\n            start: block.timestamp,\n            expiry: m.maturity + 30 days,\n            tick: fs ? bound(x, 3200 / 4, 5200 / 4) * 4 : _tickForRate(bound(x, 0, maxRate * 11 / 10), ttmOf(i)),\n            group: keccak256(abi.encode(\"h\", nonce++)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(0),\n            ratifier: c.setterRat,\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        bytes32 root = HashLib.hashOffer(offer);\n        deal(address(c.token), lender, units * 2);\n        vm.prank(lender);\n        ISetterRatifier(c.setterRat).setIsRootRatified(lender, root, true);\n        uint256 nav0 = nav();\n        uint256 idle0 = c.token.balanceOf(address(c.vault));\n        uint256 allow0 = c.adapter.shortfallAllowance();\n        vm.prank(c.allocator);\n        c.adapter.take(offer, abi.encode(root, uint256(0), new bytes32[](0)), units, \"\");\n        uint256 got = c.token.balanceOf(address(c.vault)) - idle0;\n        uint256 allow1 = c.adapter.shortfallAllowance();\n        if (allow1 < allow0) {\n            gShortfallSales++;\n            gShortfallConsumed += allow0 - allow1;\n        }\n        _end(\"takerSell\", nav0, fs ? 2 : 0, units > got ? units - got : 0);\n    }\n\n    function repay(uint256 a, uint256 b, uint256) external ready {\n        for (uint256 k; k < 2 * N; k++) {\n            uint256 i = (a + k) % N;\n            address br = borrowers[(a / N + k / N) % 2];\n            uint256 debt = c.midnight.debt(id(i), br);\n            if (debt == 0) continue;\n            uint256 units = (b >> 128) % 3 == 0 ? debt : bound(b, 1, debt);\n            deal(address(c.token), br, units);\n            uint256 nav0 = nav();\n            vm.prank(br);\n            c.midnight.repay(market(i), units, br, address(0), \"\");\n            _end(\"repay\", nav0, 0, 0);\n            return;\n        }\n        revert(\"SKIP: no debt\");\n    }\n\n    function withdrawToVault(uint256 a, uint256 b, uint256 x) external ready {\n        uint256 i = a % N;\n        uint256 assets;\n        for (uint256 k; k < N; k++) {\n            uint256 f = (a + k) % N;\n            uint256 w = c.midnight.withdrawable(id(f));\n            (, uint256 gross) = live(f);\n            if (w > gross) w = gross;\n            if (w > 0 && stored(f) > 0 && !md(f).forceRemoved) {\n                (i, assets) = (f, x % 4 == 0 ? w : bound(b, 0, w));\n                break;\n            }\n        }\n        uint256 nav0 = nav();\n        uint256 idle0 = c.token.balanceOf(address(c.vault));\n        vm.prank(c.allocator);\n        c.vault.deallocate(address(c.adapter), abi.encode(market(i)), assets);\n        if (c.token.balanceOf(address(c.vault)) - idle0 != assets) gPayViolations++;\n        _end(assets == 0 ? bytes32(\"withdrawToVault(0)\") : bytes32(\"withdrawToVault\"), nav0, 0, 0);\n        if (assets == 0) ok[\"withdrawToVault\"]++;\n    }\n\n    function vaultDeposit(uint256 a, uint256 b, uint256) external ready {\n        address who = a % 2 == 0 ? user : exiter;\n        uint256 assets = bound(b, 1, 50_000e18);\n        deal(address(c.token), who, assets);\n        uint256 nav0 = nav();\n        uint256 v0 = idleValue();\n        vm.prank(who);\n        c.vault.deposit(assets, who);\n        uint256 v1 = idleValue();\n        if (nav() != nav0 + assets) gPayViolations++;\n        if (v1 < v0 && v0 - v1 > gMaxDrop) (gMaxDrop, gWorst) = (v0 - v1, \"vaultDeposit:idleValue\");\n        _end(\"vaultDeposit\", nav0, 0, 0);\n    }\n\n    function vaultWithdraw(uint256 a, uint256 b, uint256) external ready {\n        address who = a % 2 == 0 ? user : exiter;\n        uint256 maxAssets = c.vault.previewRedeem(c.vault.balanceOf(who));\n        uint256 idle = c.token.balanceOf(address(c.vault));\n        if (maxAssets > idle) maxAssets = idle;\n        require(maxAssets > 0, \"SKIP: nothing to withdraw\");\n        uint256 assets = bound(b, 1, maxAssets);\n        uint256 nav0 = nav();\n        uint256 v0 = idleValue();\n        vm.prank(who);\n        c.vault.withdraw(assets, who, who);\n        uint256 v1 = idleValue();\n        if (nav() + assets != nav0) gPayViolations++;\n        if (v1 < v0 && v0 - v1 > gMaxDrop) (gMaxDrop, gWorst) = (v0 - v1, \"vaultWithdraw:idleValue\");\n        _end(\"vaultWithdraw\", nav0 - assets, 0, 0);\n    }\n\n    function forceDeallocate(uint256 a, uint256 b, uint256 x) external ready {\n        uint256 i = _heldFrom(a);\n        uint256 cap = c.vault.previewRedeem(c.vault.balanceOf(exiter)) * 40;\n        (, uint256 gross) = live(i);\n        if (cap > gross) cap = gross;\n        require(cap > 0, \"SKIP: exiter has no shares\");\n        uint256 assets = bound(b, 1, cap);\n        deal(address(c.token), exiter, assets * 2);\n        uint256 nav0 = nav();\n        uint256 v0 = idleValue();\n        vm.prank(exiter);\n        c.vault.forceDeallocate(address(c.adapter), abi.encode(market(i), exiter), assets, exiter);\n        uint256 v1 = idleValue();\n        if (v1 < v0 && v0 - v1 > gMaxDrop) (gMaxDrop, gWorst) = (v0 - v1, \"forceDeallocate:idleValue\");\n        _end(\"forceDeallocate\", nav0, 0, 0);\n        if (x % 2 == 0) {\n            uint256 w = c.vault.previewRedeem(c.vault.balanceOf(exiter));\n            if (w > assets) w = assets;\n            if (w > 0) {\n                vm.prank(exiter);\n                c.vault.withdraw(w, exiter, exiter);\n            }\n        }\n    }\n\n    function forceSellableCfg(uint256 a, uint256 b, uint256 x) external ready {\n        uint256 i = a % N;\n        uint256 nav0 = nav();\n        if (x % 8 == 0) {\n            i = _heldFrom(a);\n            bytes memory data = abi.encodeCall(IMidnightAdapterBase.setForceSellable, (id(i)));\n            vm.prank(c.curator);\n            c.adapter.submit(data);\n            c.adapter.setForceSellable(id(i));\n            ok[\"setForceSellable\"]++;\n        } else if (x % 8 < 4) {\n            vm.prank(c.curator);\n            c.adapter.unsetForceSellable(id(i));\n        } else {\n            vm.prank(c.curator);\n            c.adapter.setMinForceSellPrice(id(i), bound(b, 0, 0.9e18));\n        }\n        _end(\"forceSellableCfg\", nav0, 0, 0);\n    }\n\n    function forceRemove(uint256 a, uint256, uint256 x) external ready {\n        require(x % 4 == 0 && gRemoved < 2, \"SKIP: forceRemove throttled\");\n        uint256 i = a % N;\n        uint256 nav0 = nav();\n        uint256 old = stored(i);\n        bytes memory data = abi.encodeCall(IMidnightAdapterBase.forceRemove, (id(i)));\n        vm.prank(c.curator);\n        c.adapter.submit(data);\n        c.adapter.forceRemove(id(i));\n        gRemoved++;\n        _end(\"forceRemove\", nav0, 3, old);\n    }\n\n    function badDebt(uint256 a, uint256 b, uint256 x) external ready {\n        for (uint256 k; k < 2 * N; k++) {\n            uint256 i = (a + k) % N;\n            address br = borrowers[(a / N + k / N) % 2];\n            if (c.midnight.debt(id(i), br) == 0) continue;\n            uint256 nav0 = nav();\n            (uint256 live0,) = live(i);\n            uint256 lf0 = c.midnight.lossFactor(id(i));\n            uint256 pa = OracleMock(c.pA.oracle).price();\n            uint256 pb = OracleMock(c.pB.oracle).price();\n            uint256 f = bound(b, 20, 49);\n            OracleMock(c.pA.oracle).setPrice(pa * f / 100);\n            OracleMock(c.pB.oracle).setPrice(pb * f / 100);\n            Market memory m = market(i);\n            vm.prank(liquidator);\n            c.midnight.liquidate(m, collIndex(i), 0, 0, br, false, liquidator, address(0), \"\");\n            if (x % 2 == 0) {\n                // Also seize the whole collateral: the liquidator repays what is left of the debt.\n                uint256 coll = c.midnight.collateral(id(i), br, collIndex(i));\n                deal(address(c.token), liquidator, c.midnight.debt(id(i), br) + 1e18);\n                vm.prank(liquidator);\n                c.midnight.liquidate(m, collIndex(i), coll, 0, br, false, liquidator, address(0), \"\");\n            }\n            OracleMock(c.pA.oracle).setPrice(pa);\n            OracleMock(c.pB.oracle).setPrice(pb);\n            (uint256 live1,) = live(i);\n            if (c.midnight.lossFactor(id(i)) > lf0) gBadDebtEvents++;\n            _end(\"badDebt\", nav0, 1, md(i).forceRemoved ? 0 : live0 - live1);\n            return;\n        }\n        revert(\"SKIP: no debt\");\n    }\n\n    function warp(uint256, uint256 b, uint256) external ready {\n        uint256 nav0 = nav();\n        uint256 dt = bound(b, 1 hours, 1 days);\n        if (b % 8 == 0) {\n            // Jump just past the next maturity.\n            for (uint256 i; i < N; i++) {\n                if (maturities[i] > block.timestamp) {\n                    dt = maturities[i] - block.timestamp + bound(b >> 8, 0, 2 hours);\n                    break;\n                }\n            }\n        }\n        skip(dt);\n        _end(\"warp\", nav0, 0, 0);\n    }\n\n    function outsiderPoke(uint256 a, uint256 b, uint256 x) external ready {\n        uint256 nav0 = nav();\n        address outsider = makeAddr(\"h.outsider\");\n        uint256 kind = x % 4;\n        if (kind == 0) {\n            uint256 amt = bound(b, 1, 1_000e18);\n            deal(address(c.token), outsider, amt);\n            vm.prank(outsider);\n            c.token.transfer(address(c.adapter), amt);\n            gDonated += amt;\n        } else if (kind == 1) {\n            uint256 amt = bound(b, 1, 1_000e18);\n            deal(address(c.token), outsider, amt);\n            vm.prank(outsider);\n            c.token.transfer(address(c.vault), amt);\n        } else if (kind == 2) {\n            vm.prank(outsider);\n            c.midnight.updatePosition(market(a % N), address(c.adapter));\n        } else {\n            vm.prank(outsider);\n            c.vault.accrueInterest();\n        }\n        _end(\"outsiderPoke\", nav0, 0, 0);\n    }\n}\n\ncontract StatefulExtendedTest is MidnightAdapterIntegrationTest {\n    StatefulHandler internal h;\n    IMidnightAdapter internal adp;\n    uint256[] internal durs;\n    uint256 internal allowance0 = 2_000e18;\n\n    bool public inited;\n\n    IVaultV2 internal V;\n    IMidnight internal M;\n    IERC20 internal T;\n\n    constructor() {\n        h = new StatefulHandler();\n        (bytes4[] memory sels,) = h.selectors();\n        targetContract(address(h));\n        targetSelector(FuzzSelector({addr: address(h), selectors: sels}));\n    }\n\n    function lazySetup() public {\n        if (inited) return;\n        inited = true;\n        (V, M, T) = (vault, midnight, IERC20(address(underlyingToken)));\n        ERC20Mock collB = new ERC20Mock(18);\n        OracleMock oracleB = new OracleMock();\n        oracleB.setPrice(oracle.price());\n        CollateralParams memory pB = CollateralParams(address(collB), 1e18, 0.25e18, address(oracleB));\n\n        durs = [uint256(1 days), 7 days, 30 days];\n        IMidnightAdapterFactory factory = IMidnightAdapterFactory(\n            deployCode(\"MidnightAdapterFactory.sol:MidnightAdapterFactory\", abi.encode(address(midnight)))\n        );\n        adp = IMidnightAdapter(factory.createMidnightAdapter(address(vault), durs, address(0), bytes32(0)));\n        address rateRat = deployCode(\"MidnightAdapterRateRatifierV1.sol:MidnightAdapterRateRatifierV1\");\n\n        _submitAndSet(address(adp), abi.encodeCall(IMidnightAdapterBase.increaseMaxTtm, (90 days)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.addAdapter, (address(adp))));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (address(adp), true)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setForceDeallocatePenalty, (address(adp), 0.02e18)));\n        vm.startPrank(allocator);\n        adp.setIsSubRatifier(address(priceSubRatifier), true);\n        adp.setIsSubRatifier(rateRat, true);\n        vm.stopPrank();\n        _submitAndSet(\n            address(adp), abi.encodeCall(IMidnightAdapterBase.increaseMaxNetSellRate, (1e18 / uint256(365 days)))\n        );\n        _submitAndSet(address(adp), abi.encodeCall(IMidnightAdapterBase.increaseShortfallAllowance, (allowance0)));\n        vm.prank(curator);\n        adp.increaseMinNetBuyRate(0.005e18 / uint256(365 days));\n\n        Cfg memory cfg = Cfg({\n            vault: vault,\n            adapter: adp,\n            midnight: midnight,\n            token: IERC20(address(underlyingToken)),\n            pA: collateralParams,\n            pB: pB,\n            priceRat: address(priceSubRatifier),\n            rateRat: rateRat,\n            setterRat: address(setterRatifier),\n            curator: curator,\n            allocator: allocator,\n            idle: depositor,\n            t0: block.timestamp\n        });\n        h.init(cfg);\n\n        _increaseCaps(abi.encode(\"this\", address(adp)));\n        _increaseCaps(abi.encode(\"collateralToken\", address(collB)));\n        for (uint256 i; i < 5; i++) {\n            Market memory m = h.market(i);\n            if (i == 0 || i >= 3) {\n                _increaseCaps(\n                    abi.encode(\n                        \"collateralParams/rcfThreshold/liquidatorGate/enterGate\",\n                        m.collateralParams,\n                        m.rcfThreshold,\n                        m.liquidatorGate,\n                        m.enterGate\n                    )\n                );\n            }\n            midnight.touchMarket(m);\n        }\n        _increaseCaps(abi.encode(\"this/duration\", address(adp), uint256(1 days)));\n        _increaseCaps(abi.encode(\"this/duration\", address(adp), uint256(7 days)));\n        // Finite absolute cap on the longest duration, so that the duration-cap path is exercised.\n        bytes memory d30 = abi.encode(\"this/duration\", address(adp), uint256(30 days));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.increaseAbsoluteCap, (d30, 60_000e18)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.increaseRelativeCap, (d30, 1e18)));\n\n        // Fees: settlement fee on markets 1 and 3, continuous fee on market 2.\n        vm.startPrank(owner);\n        midnight.setFeeSetter(owner);\n        midnight.setMarketSettlementFee(h.id(1), 0, 0.000014e18);\n        midnight.setMarketSettlementFee(h.id(1), 1, 0.000014e18);\n        midnight.setMarketSettlementFee(h.id(1), 2, 0.000098e18);\n        midnight.setMarketSettlementFee(h.id(3), 3, 0.0004e18);\n        midnight.setMarketSettlementFee(h.id(3), 4, 0.001e18);\n        midnight.setMarketContinuousFee(h.id(2), uint256(0.01e18) / uint256(365 days) / 2);\n        vm.stopPrank();\n\n        address exiter = h.exiter();\n        deal(address(underlyingToken), exiter, 20_000e18);\n        vm.prank(exiter);\n        vault.deposit(20_000e18, exiter);\n    }\n\n    function _checkAll() internal view {\n        if (!inited) return;\n        uint256[5] memory st;\n        uint256 sumStored;\n        uint256 sumLive;\n        uint256 listed;\n        for (uint256 i; i < 5; i++) {\n            MarketData memory d = adp.marketData(h.id(i));\n            st[i] = d.netCredit;\n            sumStored += d.netCredit;\n            (uint256 liveNet,) = h.live(i);\n            if (d.netCredit > 0) {\n                listed++;\n                sumLive += liveNet;\n                assertEq(adp.marketIds(d.index), h.id(i), \"A: marketIds index\");\n                assertEq(d.maturity, h.maturities(i), \"A: stored maturity\");\n            }\n            if (!d.forceRemoved) {\n                // E: stored net credit is an upper bound of the live one, and exact while the market has no loss.\n                assertGe(d.netCredit, liveNet, \"E: stored < live net credit\");\n                if (M.lossFactor(h.id(i)) == 0) assertEq(d.netCredit, liveNet, \"E: stored != live, no loss\");\n            } else {\n                assertEq(d.netCredit, 0, \"A: removed market has credit\");\n            }\n        }\n        assertEq(adp.marketIdsLength(), listed, \"A: marketIds length\");\n        // A: V.allocation(id) == stored net credit behind every id.\n        for (uint256 i; i < 5; i++) {\n            bytes32[] memory idsI = adp.ids(h.market(i));\n            for (uint256 j; j < idsI.length; j++) {\n                uint256 expected;\n                for (uint256 k; k < 5; k++) {\n                    bytes32[] memory idsK = adp.ids(h.market(k));\n                    for (uint256 l; l < idsK.length; l++) {\n                        if (idsK[l] == idsI[j]) expected += st[k];\n                    }\n                }\n                assertEq(V.allocation(idsI[j]), expected, \"A: allocation != stored net credit\");\n            }\n        }\n        // B: durationAllocations == brute force.\n        uint256[] memory alloc = adp.durationAllocations(3);\n        for (uint256 j; j < 3; j++) {\n            uint256 expected;\n            for (uint256 i; i < 5; i++) {\n                uint256 mat = h.maturities(i);\n                if (st[i] > 0 && mat > block.timestamp && mat - block.timestamp >= durs[j]) expected += st[i];\n            }\n            assertEq(alloc[j], expected, \"B: durationAllocations\");\n            assertEq(adp.durationAllocations(j + 1)[j], expected, \"B: durationAllocations prefix\");\n        }\n        // C: realAssets never exceeds the face value owed.\n        uint256 ra = adp.realAssets();\n        assertLe(ra, sumStored, \"C: realAssets > stored face value\");\n        assertLe(ra, sumLive, \"C: realAssets > live face value\");\n        // D: no unexplained loss of value, losses within their recorded bounds, allowance accounting.\n        assertLe(h.gMaxDrop(), h.TOL(), string.concat(\"D: unexplained drop in \", string(abi.encode(h.gWorst()))));\n        assertEq(h.gBoundViolations(), 0, \"D: loss above recorded bound\");\n        assertEq(h.gPayViolations(), 0, \"D: payment integrity\");\n        assertEq(h.gAccrueReverts(), 0, \"D: accrueInterest reverted\");\n        assertEq(adp.shortfallAllowance() + h.gShortfallConsumed(), allowance0, \"D: shortfallAllowance accounting\");\n        // F: the vault never books more than idle + what the adapter reports.\n        assertLe(V.totalAssets(), T.balanceOf(address(vault)) + ra, \"F: totalAssets > NAV\");\n    }\n\n    function checkAll() external view {\n        _checkAll();\n    }\n\n    /// forge-config: default.invariant.runs = 256\n    /// forge-config: default.invariant.depth = 100\n    /// forge-config: default.invariant.fail-on-revert = false\n    function invariant_statefulExtended() public view {\n        _checkAll();\n    }\n\n    function _seq(uint256 seed, uint256 n) internal {\n        lazySetup();\n        (bytes4[] memory sels, string[] memory names) = h.selectors();\n        uint256[] memory calls = new uint256[](sels.length);\n        uint256[] memory reverts = new uint256[](sels.length);\n        for (uint256 k; k < n; k++) {\n            uint256 r = uint256(keccak256(abi.encode(seed, k)));\n            uint256 s = r % sels.length;\n            (bool success,) = address(h).call(\n                abi.encodeWithSelector(\n                    sels[s], uint256(keccak256(abi.encode(r, 1))), uint256(keccak256(abi.encode(r, 2))), r >> 8\n                )\n            );\n            calls[s]++;\n            if (!success) reverts[s]++;\n            this.checkAll();\n        }\n        for (uint256 s; s < sels.length; s++) {\n            console.log(\"%s: calls %d reverts %d\", names[s], calls[s], reverts[s]);\n        }\n        console.log(\"fills (pieces) %d, open offers %d\", h.gPieces(), h.openLength());\n        console.log(\"shortfall sales %d, allowance consumed %d\", h.gShortfallSales(), h.gShortfallConsumed());\n        console.log(\"bad debt events %d, NAV lost to bad debt %d\", h.gBadDebtEvents(), h.gLoss(1));\n        console.log(\"NAV lost to forceSellable sales %d, to forceRemove %d\", h.gLoss(2), h.gLoss(3));\n        console.log(\"max unexplained drop (wei) %d, adapter balance %d, donated %d\", h.gMaxDrop(), T.balanceOf(address(adp)), h.gDonated());\n        console.log(\"idle depositor value %d, NAV %d, totalAssets %d\", h.idleValue(), h.nav(), V.totalAssets());\n    }\n\n    /// @dev Directed check that the campaign's forceSellable branch does what it says: cheap sales after setForceSellable.\n    function test_forceSellable_cheapSales() public {\n        lazySetup();\n        h.makerBuyPrice(4, 10_000e18, 7);\n        h.makerBuyPrice(1, 5_000e18, 9);\n        this.checkAll();\n        uint256 nav0 = h.nav();\n        uint256 allowanceBefore = adp.shortfallAllowance();\n        h.forceSellableCfg(4, 0, 0); // x % 8 == 0: setForceSellable on market 4\n        uint256 sold;\n        for (uint256 k; k < 6; k++) {\n            try h.takerSell(4, 1_000e18 + k, k) {\n                sold++;\n            } catch {}\n            try h.makerSellPrice(4, 500e18 + k, k) {\n                sold++;\n            } catch {}\n            this.checkAll();\n        }\n        console.log(\"forceSellable sales that went through %d, NAV before %d, NAV after %d\", sold, nav0, h.nav());\n        console.log(\"NAV lost to forceSellable sales %d, loss above bound %d\", h.gLoss(2), h.gBoundViolations());\n        console.log(\"shortfallAllowance before %d, after %d\", allowanceBefore, adp.shortfallAllowance());\n        assertGt(h.gLoss(2), 0, \"no cheap sale happened\");\n        assertEq(adp.shortfallAllowance(), allowanceBefore, \"forceSellable sale consumed shortfallAllowance\");\n    }\n\n    function test_sequence_seed1() public {\n        _seq(1, 150);\n    }\n\n    function test_sequence_seed2() public {\n        _seq(2, 150);\n    }\n\n    function test_sequence_seed3() public {\n        _seq(3, 150);\n    }\n}\n"
   },
   {
    "path": "test/poc/StatefulExtended.t.sol",
    "name": "test_sequence_seed1|2|3",
    "what": "Same handler and invariants on three fixed 150-call sequences, printing calls/reverts per action and the ghost totals (fills in pieces, shortfall sales and allowance consumed, bad-debt events and NAV lost to them, forceRemove losses, max unexplained drop = 0)."
   },
   {
    "path": "test/poc/StatefulExtended.t.sol",
    "name": "test_forceSellable_cheapSales",
    "what": "Directed: buy in markets 4 and 1, setForceSellable(market 4), 12 allocator and outsider sales at ticks 3200-5200; losses are classed and bounded, shortfallAllowance untouched, invariants hold."
   }
  ],
  "command": "mkdir vault-v2 && cd vault-v2 && git init -q && git remote add origin https://github.com/morpho-org/vault-v2 && git fetch -q --depth 1 origin bbeda7b27ae80abcf070e0158cb8a31e87bb2286 && git checkout -q FETCH_HEAD && git submodule update --init --recursive --depth 1 && mkdir -p test/poc && cp <pocSource> test/poc/StatefulExtended.t.sol && forge test --match-path 'test/poc/StatefulExtended.t.sol' --match-test 'invariant_statefulExtended|test_sequence_seed|test_forceSellable_cheapSales' -vv   # forge 1.9.0; export XDG_DATA_HOME to a writable folder if the compiler store is read-only. Nothing under src/, lib/ or foundry.toml is changed. The fuzz seed is Foundry's default (not pinned), so per-action counts move a little between runs.",
  "output": "Compiler run successful!\nRan 5 tests for test/poc/StatefulExtended.t.sol:StatefulExtendedTest\n[PASS] invariant_statefulExtended() (runs: 256, calls: 25600, reverts: 5320)\n╭-----------------+------------------+-------+---------+----------╮\n| Contract        | Selector         | Calls | Reverts | Discards |\n+=================================================================+\n| StatefulHandler | badDebt          | 1533  | 736     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | fillOpen         | 1546  | 753     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | forceDeallocate  | 1554  | 199     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | forceRemove      | 1562  | 1119    | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | forceSellableCfg | 1490  | 41      | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | makerBuyPrice    | 1507  | 142     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | makerBuyRate     | 1469  | 170     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | makerSellPrice   | 1480  | 285     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | makerSellRate    | 1460  | 511     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | outsiderPoke     | 1432  | 0       | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | repay            | 1552  | 199     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | takerBuy         | 1501  | 152     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | takerSell        | 1495  | 417     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | vaultDeposit     | 1489  | 0       | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | vaultWithdraw    | 1542  | 313     | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | warp             | 1524  | 0       | 0        |\n|-----------------+------------------+-------+---------+----------|\n| StatefulHandler | withdrawToVault  | 1464  | 283     | 0        |\n╰-----------------+------------------+-------+---------+----------╯\n[PASS] test_forceSellable_cheapSales() (gas: 39785121)\nLogs:\n  forceSellable sales that went through 12, NAV before 120000000347045862088000, NAV after 120875287142218051499897\n  NAV lost to forceSellable sales 2830371531094223507, loss above bound 0\n  shortfallAllowance before 2000000000000000000000, after 2000000000000000000000\n[PASS] test_sequence_seed1() (gas: 323607103)\nLogs:\n  makerBuyPrice (outsider fill): calls 7 reverts 0\n  makerBuyRate (outsider fill): calls 11 reverts 0\n  makerSellPrice (outsider fill): calls 9 reverts 1\n  makerSellRate (outsider fill): calls 12 reverts 4\n  fillOpen (later piece): calls 6 reverts 3\n  takerBuy (allocator): calls 11 reverts 0\n  takerSell (allocator, cheap if forceSellable): calls 8 reverts 0\n  repay: calls 6 reverts 1\n  withdrawToVault: calls 12 reverts 4\n  vaultDeposit: calls 11 reverts 0\n  vaultWithdraw: calls 7 reverts 2\n  forceDeallocate: calls 7 reverts 1\n  set/unsetForceSellable, minForceSellPrice: calls 8 reverts 0\n  forceRemove: calls 14 reverts 12\n  badDebt (liquidation): calls 5 reverts 1\n  warp: calls 10 reverts 0\n  outsiderPoke (donate/updatePosition/accrue): calls 6 reverts 0\n  fills (pieces) 67, open offers 16\n  shortfall sales 20, allowance consumed 841485131054634092056\n  bad debt events 4, NAV lost to bad debt 5299754819075455052783\n  NAV lost to forceSellable sales 0, to forceRemove 6965667460118402334240\n  max unexplained drop (wei) 0, adapter balance 1026871939340070811348, donated 1026871939340070811348\n  idle depositor value 93868284673210992126399, NAV 184655524173675685617021, totalAssets 183807292723668631818588\n[PASS] test_sequence_seed2() (gas: 321144823)\nLogs:\n  makerBuyPrice (outsider fill): calls 15 reverts 0\n  makerBuyRate (outsider fill): calls 7 reverts 0\n  makerSellPrice (outsider fill): calls 5 reverts 1\n  makerSellRate (outsider fill): calls 11 reverts 4\n  fillOpen (later piece): calls 9 reverts 1\n  takerBuy (allocator): calls 10 reverts 0\n  takerSell (allocator, cheap if forceSellable): calls 6 reverts 2\n  repay: calls 7 reverts 0\n  withdrawToVault: calls 10 reverts 4\n  vaultDeposit: calls 8 reverts 0\n  vaultWithdraw: calls 8 reverts 2\n  forceDeallocate: calls 16 reverts 6\n  set/unsetForceSellable, minForceSellPrice: calls 5 reverts 0\n  forceRemove: calls 8 reverts 6\n  badDebt (liquidation): calls 9 reverts 4\n  warp: calls 8 reverts 0\n  outsiderPoke (donate/updatePosition/accrue): calls 8 reverts 0\n  fills (pieces) 74, open offers 14\n  shortfall sales 17, allowance consumed 1029180428675473627299\n  bad debt events 5, NAV lost to bad debt 1956164032959391290477\n  NAV lost to forceSellable sales 0, to forceRemove 15653383559501897332098\n  max unexplained drop (wei) 0, adapter balance 2320792872254370876381, donated 2320792872254370876381\n  idle depositor value 84972479534757022361699, NAV 117387721022587574772086, totalAssets 115045743239569797211133\n[PASS] test_sequence_seed3() (gas: 322108879)\nLogs:\n  makerBuyPrice (outsider fill): calls 8 reverts 0\n  makerBuyRate (outsider fill): calls 4 reverts 0\n  makerSellPrice (outsider fill): calls 18 reverts 3\n  makerSellRate (outsider fill): calls 6 reverts 2\n  fillOpen (later piece): calls 10 reverts 1\n  takerBuy (allocator): calls 4 reverts 0\n  takerSell (allocator, cheap if forceSellable): calls 11 reverts 6\n  repay: calls 9 reverts 0\n  withdrawToVault: calls 9 reverts 1\n  vaultDeposit: calls 8 reverts 0\n  vaultWithdraw: calls 4 reverts 1\n  forceDeallocate: calls 6 reverts 0\n  set/unsetForceSellable, minForceSellPrice: calls 8 reverts 0\n  forceRemove: calls 9 reverts 7\n  badDebt (liquidation): calls 12 reverts 4\n  warp: calls 11 reverts 0\n  outsiderPoke (donate/updatePosition/accrue): calls 13 reverts 0\n  fills (pieces) 75, open offers 9\n  shortfall sales 9, allowance consumed 30118881745253198114\n  bad debt events 8, NAV lost to bad debt 7045564449575325746458\n  NAV lost to forceSellable sales 0, to forceRemove 18286848278758126419328\n  max unexplained drop (wei) 0, adapter balance 724827832463423214187, donated 724827832463423214187\n  idle depositor value 84020777484743321414468, NAV 160300676694152988040894, totalAssets 160297887431824128912184\nSuite result: ok. 5 passed; 0 failed; 0 skipped; finished in 118.11s (120.67s CPU time)\nRan 1 test suite in 118.12s (118.11s CPU time): 5 tests passed, 0 failed, 0 skipped (5 total tests)"
 },
 "notCovered": [
  "Enter gates and whitelist sub-gates: the campaign adapter uses enterGateFactory = address(0) and ungated markets.",
  "setIsRootRatifiedWithSig, merkle trees of height > 0 and allowedTaker != address(0) in both ratifiers: roots are single leaves set by the allocator directly.",
  "Buys funded from another adapter; only idle funding and self-funding from a repaid market of the same adapter are modelled, and self-funded buys were not counted separately.",
  "Malicious taker callback contracts and reentrancy: takers are EOAs with no callback.",
  "Loan tokens other than a standard 18-decimal ERC20; relative caps below WAD; performance and management fees; more than one Midnight adapter on the vault; liquidator gates; rcfThreshold != 0; lltv < 1 (all markets use lltv 1e18, so bad debt is realised without the recovery close factor).",
  "Liquidations in postMaturityMode, and bad debt left unrealised across a warp (the handler lowers both oracle prices, liquidates one borrower and restores the prices inside one action).",
  "The campaign table reports reverts per action but not their reasons; reasons were sampled once in a diagnostic 120-call run (handler preconditions such as no buyable/held market or the forceRemove throttle, and protocol guards ForceRemoved, UnauthorizedBuy, WorsePrice, NetSellRateTooHigh, ShortfallTooHigh, ForceSellPriceTooLow, ZeroAllocation, NotLiquidatable).",
  "How often forceSellable sales, forceRemove and self-funded buys occurred inside the 256-run campaign is not aggregated (Foundry reports only calls and reverts); the three sequences and the directed test show them happening.",
  "Fuzz seed not pinned: two full runs of the final handler gave 5,178 and 5,320 reverts of 25,600 calls, both passing.",
  "The two 2026-10-12 audit drafts in audits/ were not read: there is no candidate to compare against them.",
  "Step 4 (independent re-run from a clean clone by a different agent) was not done here; the run above is from a clean shallow clone at the pinned commit on this machine only."
 ]
}