{
 "lead": "Vault V2 roles, caps and allocation ids: does vault.allocation(id) for every id the adapter returns (adapter, collateral, market family, duration) stay equal to stored net credit across outsider-filled maker buys and sells, withdrawToVault, forceDeallocate, loss sync and forceRemove? Can an outsider-driven path get past an absolute, relative or duration cap, or leave an allocation that blocks or underflows a later deallocate? What do live offers do after the adapter loses its allocator role or a cap is set to zero?",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No candidate. On real Midnight and a real VaultV2, vault.allocation(id) for the adapter, collateralToken and family ids always equalled the sum of stored marketData.netCredit. durationAllocations(1) always matched the stored net credit of markets with at least 7 days to maturity. This held across: maker buys and sells filled by outsiders; forceDeallocate, including a nested forceDeallocate from the buyer callback of an outsider purchase while the sale was in progress; bad debt with no sync, then synced by forceDeallocate; allocator withdrawToVault(0); withdrawToVault after maturity; forceRemove; and a fuzzed sequence of 12 random outsider actions (2048 runs x 3 suites). Root reason: every write to marketData.netCredit (onBuy L539-542, onSell L633-636, forceDeallocate L471-473, withdrawToVault L731-733, forceRemove L381-382) is paired with a vault allocate/deallocate of exactly newNetCredit - oldNetCredit on the same ids(market). Midnight only lets the adapter's credit grow through take, where the adapter is either the taker (allocator-only) or the maker with ratifier == adapter and callback == adapter, so its onBuy always runs. Stored net credit is therefore never below live net credit, and a negative change can never take an allocation below zero. Outsider-filled buys hit AbsoluteCapExceeded, DurationAbsoluteCapExceeded, RelativeCapExceeded or ZeroAbsoluteCap exactly at the cap. A fill inside the remaining headroom (90 of 100 tokens) passed.",
 "lowInfo": [
  {
   "title": "Cap and duration allocations keep pre-loss net credit until synced; any shareholder can sync for free with a 0-asset forceDeallocate",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:60",
    "src/adapters/midnight/MidnightAdapter.sol:716-737",
    "src/adapters/midnight/MidnightAdapter.sol:427-477",
    "src/adapters/midnight/MidnightAdapter.sol:816-834",
    "src/VaultV2.sol:539-560"
   ],
   "detail": "After Midnight bad debt (lossFactor > 0), stored netCredit and therefore vault.allocation of all three ids and durationAllocations stay at the pre-loss value. In testZeroAssetForceDeallocateSyncsLoss, stored = 30000e18 and live = 8000e18, so all ids are over-counted by 22000e18. This only makes cap checks stricter: buys may revert early. It never lets an allocation underflow, because later changes are computed against the stored value (verified: after the loss, a 100e18 forceDeallocate reduced every allocation from 68000e18 to 46633.33e18 with no revert). This core point is ALREADY REPORTED in the Cantina 2026-10-12 draft, finding 3.2.5 'onBuy might revert due to stale allocation checks', so it is not new. The only addition is the permissionless sync path: vault.forceDeallocate(adapter, abi.encode(market, self), 0, self) by any holder of at least 1 share (who has authorized the adapter on Midnight) pays 0 penalty shares and brings all allocations to live net credit (30000e18 -> 8000e18). The NatSpec at L717 only mentions sync with withdrawnAssets == 0 through withdrawToVault, which is allocator/sentinel-only. Worth documenting as a public sync route. Not a vulnerability."
  },
  {
   "title": "Live maker offers after a cap is zeroed or the adapter loses its allocator role (behaviour confirmed, as documented)",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:29-30",
    "src/adapters/midnight/MidnightAdapter.sol:606-611",
    "src/adapters/midnight/MidnightAdapter.sol:693-698",
    "src/VaultV2.sol:562-565"
   ],
   "detail": "Collateral id absolute cap set to 0 by the sentinel: an outsider fill of a live buy offer reverts with ZeroAbsoluteCap. Live sell offers and forceDeallocate still work, and allocations stay consistent (18000e18). Adapter allocator role removed: sell-offer fills revert with Unauthorized, because onSell's vault.deallocate needs allocator or sentinel, while forceDeallocate still works (allocation 17000e18). With only the sentinel role, sells work again and buys revert with Unauthorized. All of this matches NatSpec L29-30 and the README 'Trading' section, so it is not a finding. Operational note: removing the adapter's allocator role does not cancel ratified sell roots; they become fillable again if the role (or the sentinel role) is restored. Allocators should also cancel roots or call setConsumed."
  }
 ],
 "covered": {
  "existingSuite": "forge test on the Midnight-related suites at the pinned commit: MidnightAdapterTest 314/314, MidnightAdapterRatifiersV1Test (Price 36/36, Rate 38/38, RateIntegration 1/1), IKRCompatibleEnterGateTest 24/24, MidnightAdapterIntegrationTest 8/8. Total 446 passed, 0 failed, including the PoC suites (built with --skip test/imports/** because those imports pin older solc versions).",
  "pocPath": "test/poc/VaultRolesCapsTest.sol (inherits test/integration/MidnightAdapterIntegrationTest.sol: real Midnight, real VaultV2)",
  "command": "export XDG_DATA_HOME=<writable dir>; forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers && forge test --skip \"test/imports/**\" --match-path test/poc/VaultRolesCapsTest.sol --match-test \"testAllocationTracks|testOutsiderFilled|testLiveOffers|testFuzzOutsider|testZeroAsset|testForceDeallocateFromBuyer\" -vv",
  "result": "14 tests passed, 0 failed across 3 suites (the 4 base tests also re-run in the 2 derived suites). Fuzz testFuzzOutsiderSequence: 2048 runs per suite.",
  "tests": [
   "testAllocationTracksStoredNetCreditAcrossPaths: maker buy/sell filled by outsiders, forceDeallocate, bad debt (unsynced, then synced by forceDeallocate), withdrawToVault(0), withdrawToVault after maturity, forceRemove; each id and the 7d duration allocation are checked after every step",
   "testOutsiderFilledBuyCannotPassCaps: absolute (collateral id), duration (7d), relative (family id) caps; a 3-day market does not count toward the 7d duration",
   "testLiveOffersAfterCapZeroAndRoleLoss: zeroed cap, allocator role removed, sentinel-only",
   "testFuzzOutsiderSequence: 12 random outsider buys/sells/forceDeallocates/warps across two maturities; allocation == stored == live after every step",
   "testZeroAssetForceDeallocateSyncsLoss",
   "testForceDeallocateFromBuyerCallbackMidSale: nested forceDeallocate of another market from the outsider buyer callback during a maker sale keeps allocations consistent; on the market being sold it reverts SellInProgress"
  ],
  "outputExcerpt": "Ran 4 tests for test/poc/VaultRolesCapsTest.sol:VaultRolesCapsTest\n[PASS] testAllocationTracksStoredNetCreditAcrossPaths() (gas: 8735494)\nLogs:\n  after maker buys filled by outsider\n    stored A / B        40000000000000000000000 30000000000000000000000\n    actual A / B        40000000000000000000000 30000000000000000000000\n    vault.allocation(id) 0 70000000000000000000000\n    vault.allocation(id) 1 70000000000000000000000\n    vault.allocation(id) 2 70000000000000000000000\n    durationAllocation(7d) 70000000000000000000000\n  after maker sell filled by outsider\n    stored A / B        39000000000000000000000 30000000000000000000000\n    actual A / B        39000000000000000000000 30000000000000000000000\n    vault.allocation(id) 0 69000000000000000000000\n    vault.allocation(id) 1 69000000000000000000000\n    vault.allocation(id) 2 69000000000000000000000\n    durationAllocation(7d) 69000000000000000000000\n  after forceDeallocate in B\n    stored A / B        39000000000000000000000 29000000000000000000000\n    actual A / B        39000000000000000000000 29000000000000000000000\n    vault.allocation(id) 0 68000000000000000000000\n    vault.allocation(id) 1 68000000000000000000000\n    vault.allocation(id) 2 68000000000000000000000\n    durationAllocation(7d) 68000000000000000000000\n  lossFactor B 249540402408688206539808045449963355067\n  after bad debt in B (not yet synced: allocation == stale stored)\n    stored A / B        39000000000000000000000 29000000000000000000000\n    actual A / B        39000000000000000000000 7733333333333333333333\n    vault.allocation(id) 0 68000000000000000000000\n    vault.allocation(id) 1 68000000000000000000000\n    vault.allocation(id) 2 68000000000000000000000\n    durationAllocation(7d) 68000000000000000000000\n  after outsider forceDeallocate in B post-loss (syncs loss)\n    stored A / B        39000000000000000000000 7633333333333333333333\n    actual A / B        39000000000000000000000 7633333333333333333333\n    vault.allocation(id) 0 46633333333333333333333\n    vault.allocation(id) 1 46633333333333333333333\n    vault.allocation(id) 2 46633333333333333333333\n    durationAllocation(7d) 46633333333333333333333\n  after allocator withdrawToVault(B, 0)\n    stored A / B        39000000000000000000000 7633333333333333333333\n    actual A / B        39000000000000000000000 7633333333333333333333\n    vault.allocation(id) 0 46633333333333333333333\n    vault.allocation(id) 1 46633333333333333333333\n    vault.allocation(id) 2 46633333333333333333333\n    durationAllocation(7d) 46633333333333333333333\n  after withdrawToVault(A, 10k) post maturity\n    stored A / B        29000000000000000000000 7633333333333333333333\n    actual A / B        29000000000000000000000 7633333333333333333333\n    vault.allocation(id) 0 36633333333333333333333\n    vault.allocation(id) 1 36633333333333333333333\n    vault.allocation(id) 2 36633333333333333333333\n    durationAllocation(7d) 7633333333333333333333\n  after forceRemove(B)\n    stored A / B        29000000000000000000000 0\n    actual A / B        29000000000000000000000 7633333333333333333333\n    vault.allocation(id) 0 29000000000000000000000\n    vault.allocation(id) 1 29000000000000000000000\n    vault.allocation(id) 2 29000000000000000000000\n    durationAllocation(7d) 0\n\n[PASS] testFuzzOutsiderSequence(uint256) (runs: 2048, μ: 9220321, ~: 9254467)\n[PASS] testLiveOffersAfterCapZeroAndRoleLoss() (gas: 5952078)\nLogs:\n  cap zeroed: buy offer reverts, sell offer and forceDeallocate still work\n    stored A / B        18000000000000000000000 0\n    actual A / B        18000000000000000000000 0\n    vault.allocation(id) 0 18000000000000000000000\n    vault.allocation(id) 1 18000000000000000000000\n    vault.allocation(id) 2 18000000000000000000000\n    durationAllocation(7d) 18000000000000000000000\n  no allocator role: sell offer reverts, forceDeallocate works\n    stored A / B        17000000000000000000000 0\n    actual A / B        17000000000000000000000 0\n    vault.allocation(id) 0 17000000000000000000000\n    vault.allocation(id) 1 17000000000000000000000\n    vault.allocation(id) 2 17000000000000000000000\n    durationAllocation(7d) 17000000000000000000000\n  sentinel only: sell works, buy reverts\n    stored A / B        16000000000000000000000 0\n    actual A / B        16000000000000000000000 0\n    vault.allocation(id) 0 16000000000000000000000\n    vault.allocation(id) 1 16000000000000000000000\n    vault.allocation(id) 2 16000000000000000000000\n    durationAllocation(7d) 16000000000000000000000\n\n[PASS] testOutsiderFilledBuyCannotPassCaps() (gas: 5270316)\nLogs:\n  allocation before 10000000000000000000000\n  allocation after in-cap fill / cap 10090000000000000000000 10100000000000000000000\n  after in-cap fill\n    stored A / B        0 10090000000000000000000\n    actual A / B        0 10090000000000000000000\n    vault.allocation(id) 0 10090000000000000000000\n    vault.allocation(id) 1 10090000000000000000000\n    vault.allocation(id) 2 10090000000000000000000\n    durationAllocation(7d) 10090000000000000000000\n  7d duration alloc before / after 3d-market buy 10090000000000000000000 10090000000000000000000\n  family alloc / relCap 10590000000000000000000 106400000000000000\n\nSuite result: ok. 4 passed; 0 failed; 0 skipped; finished in 7.36s (7.37s CPU time)\n\n[PASS] testZeroAssetForceDeallocateSyncsLoss() (gas: 3775104)\nLogs:\n  after loss, before sync\n    stored A / B        0 30000000000000000000000\n    actual A / B        0 8000000000000000000000\n    vault.allocation(id) 0 30000000000000000000000\n    vault.allocation(id) 1 30000000000000000000000\n    vault.allocation(id) 2 30000000000000000000000\n    durationAllocation(7d) 30000000000000000000000\n  penalty shares paid 0\n  after 0-asset forceDeallocate by shareholder\n    stored A / B        0 8000000000000000000000\n    actual A / B        0 8000000000000000000000\n    vault.allocation(id) 0 8000000000000000000000\n    vault.allocation(id) 1 8000000000000000000000\n    vault.allocation(id) 2 8000000000000000000000\n    durationAllocation(7d) 8000000000000000000000\n\n\n[PASS] testForceDeallocateFromBuyerCallbackMidSale() (gas: 5745948)\nLogs:\n  after sale in A with nested forceDeallocate in B from the buyer callback\n    stored A / B        15000000000000000000000 17000000000000000000000\n    actual A / B        15000000000000000000000 17000000000000000000000\n    vault.allocation(id) 0 32000000000000000000000\n    vault.allocation(id) 1 32000000000000000000000\n    vault.allocation(id) 2 32000000000000000000000\n    durationAllocation(7d) 32000000000000000000000\n\n",
  "priorAuditCheck": "Both 2026-10-12 drafts were extracted to text and searched. Stale stored net credit in cap and duration allocations = Cantina 3.2.5. Mid-flight cap overshoot in self-funding = Cantina 3.2.6. Missing positive duration absolute-cap check = Cantina 3.2.3 (the code at this commit now has DurationZeroAbsoluteCap, L596). Nothing new to report as a candidate.",
  "pocSource": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {ErrorsLib} from \"../../src/libraries/ErrorsLib.sol\";\nimport {MarketData} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {console2} from \"../../lib/forge-std/src/console2.sol\";\n\n/// @dev Lead \"vault-roles-caps\": vault.allocation(id) vs stored net credit, caps on taker-driven paths,\n/// and the behaviour of live offers after cap / role changes. Real Midnight + real VaultV2.\ncontract VaultRolesCapsTest is MidnightAdapterIntegrationTest {\n    Market internal mA; // 7 days\n    Market internal mB; // 30 days\n    uint256 internal saltCounter;\n\n    function _setupMarkets() internal {\n        mA = _market(7 days);\n        mB = _market(30 days);\n        // Borrower posts ample collateral in both markets.\n        uint256 collateral = 400_000 * oneToken * 2e18 / oneToken;\n        deal(address(collateralToken), borrower, 2 * collateral);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), type(uint256).max);\n        midnight.supplyCollateral(mA, 0, collateral, borrower);\n        midnight.supplyCollateral(mB, 0, collateral, borrower);\n        vm.stopPrank();\n        deal(address(underlyingToken), lender, 1_000_000 * oneToken);\n        vm.prank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        deal(address(underlyingToken), depositor, 1_000_000 * oneToken);\n        vm.startPrank(depositor);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(adapter), type(uint256).max);\n        midnight.setIsAuthorized(address(adapter), true, depositor);\n        vm.stopPrank();\n    }\n\n    function _ratifiedAdapterOffer(Market memory market, bool buy, uint256 maxUnits)\n        internal\n        returns (Offer memory offer, bytes memory ratifierData)\n    {\n        saltCounter++;\n        offer = Offer({\n            market: market,\n            buy: buy,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: TICK,\n            group: keccak256(abi.encode(\"poc\", buy, market.maturity, saltCounter)),\n            callback: address(adapter),\n            callbackData: buy ? abi.encode(address(0), \"\") : bytes(\"\"),\n            receiverIfMakerIsSeller: buy ? address(0) : address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: !buy,\n            maxUnits: uint128(maxUnits),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        bytes32 root = HashLib.hashPriceRatifierV1Offer(offer, address(0));\n        vm.prank(allocator);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        bytes32[] memory proof = new bytes32[](0);\n        ratifierData = abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), proof, address(0)));\n    }\n\n    /// @dev Outsider (borrower) sells credit into the adapter's maker buy offer.\n    function _outsiderSellsToAdapter(Market memory market, uint256 units) internal {\n        (Offer memory offer, bytes memory rd) = _ratifiedAdapterOffer(market, true, units);\n        vm.prank(borrower);\n        midnight.take(offer, rd, units, borrower, borrower, address(0), \"\");\n    }\n\n    /// @dev Outsider (lender) buys credit from the adapter's maker sell offer.\n    function _outsiderBuysFromAdapter(Market memory market, uint256 units) internal {\n        (Offer memory offer, bytes memory rd) = _ratifiedAdapterOffer(market, false, units);\n        vm.prank(lender);\n        midnight.take(offer, rd, units, lender, address(0), address(0), \"\");\n    }\n\n    function _forceDeallocate(Market memory market, uint256 units) internal {\n        vm.prank(depositor);\n        vault.forceDeallocate(address(adapter), abi.encode(market, depositor), units, depositor);\n    }\n\n    function _stored(Market memory market) internal view returns (uint256) {\n        return adapter.marketData(IdLib.toId(market)).netCredit;\n    }\n\n    function _actual(Market memory market) internal view returns (uint256) {\n        Market memory dummy;\n        (uint128 c, uint128 p,) = midnight.updatePositionView(dummy, IdLib.toId(market), address(adapter));\n        return c - p;\n    }\n\n    /// @dev All markets used share the same collateral params, so all three vault ids sum both markets.\n    function _checkInvariant(string memory step) internal view {\n        uint256 sumStored = _stored(mA) + _stored(mB);\n        bytes32[] memory _ids = adapter.ids(mA);\n        console2.log(step);\n        console2.log(\"  stored A / B       \", _stored(mA), _stored(mB));\n        console2.log(\"  actual A / B       \", _actual(mA), _actual(mB));\n        for (uint256 i; i < _ids.length; i++) {\n            console2.log(\"  vault.allocation(id)\", i, vault.allocation(_ids[i]));\n            assertEq(vault.allocation(_ids[i]), sumStored, \"allocation != sum stored net credit\");\n        }\n        uint256[] memory d = adapter.durationAllocations(1);\n        uint256 expected7d = (mA.maturity >= block.timestamp + 7 days ? _stored(mA) : 0)\n            + (mB.maturity >= block.timestamp + 7 days ? _stored(mB) : 0);\n        console2.log(\"  durationAllocation(7d)\", d[0]);\n        assertEq(d[0], expected7d, \"duration allocation mismatch\");\n    }\n\n    /// Path coverage: maker buys and sells filled by outsiders, forceDeallocate, loss + sync, withdrawToVault, forceRemove.\n    function testAllocationTracksStoredNetCreditAcrossPaths() public {\n        _setupMarkets();\n        _outsiderSellsToAdapter(mA, 40_000 * oneToken);\n        _outsiderSellsToAdapter(mB, 30_000 * oneToken);\n        _checkInvariant(\"after maker buys filled by outsider\");\n\n        _outsiderBuysFromAdapter(mA, 1_000 * oneToken);\n        _checkInvariant(\"after maker sell filled by outsider\");\n\n        _forceDeallocate(mB, 1_000 * oneToken);\n        _checkInvariant(\"after forceDeallocate in B\");\n\n        // Bad debt in B: collateral price / 100, liquidation with 0/0 realizes the loss.\n        oracle.setPrice(ORACLE_PRICE_SCALE * oneToken / 1e18 / 100);\n        midnight.liquidate(mB, 0, 0, 0, borrower, false, lender, address(0), \"\");\n        oracle.setPrice(ORACLE_PRICE_SCALE * oneToken / 1e18);\n        console2.log(\"lossFactor B\", midnight.lossFactor(IdLib.toId(mB)));\n        assertGt(_stored(mB), _actual(mB), \"loss not visible\");\n        _checkInvariant(\"after bad debt in B (not yet synced: allocation == stale stored)\");\n\n        // Outsider forceDeallocate before any sync: change includes the loss, no underflow.\n        _forceDeallocate(mB, 100 * oneToken);\n        assertEq(_stored(mB), _actual(mB));\n        _checkInvariant(\"after outsider forceDeallocate in B post-loss (syncs loss)\");\n\n        // Allocator loss sync with 0 assets is a no-op now.\n        vm.prank(allocator);\n        vault.deallocate(address(adapter), abi.encode(mB), 0);\n        _checkInvariant(\"after allocator withdrawToVault(B, 0)\");\n\n        // Repay part of A at maturity, withdraw to vault.\n        vm.warp(mA.maturity);\n        deal(address(underlyingToken), borrower, 10_000 * oneToken);\n        vm.startPrank(borrower);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        midnight.repay(mA, 10_000 * oneToken, borrower, address(0), \"\");\n        vm.stopPrank();\n        vm.prank(allocator);\n        vault.deallocate(address(adapter), abi.encode(mA), 10_000 * oneToken);\n        _checkInvariant(\"after withdrawToVault(A, 10k) post maturity\");\n\n        // forceRemove B.\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.forceRemove, (IdLib.toId(mB))));\n        assertEq(_stored(mB), 0);\n        _checkInvariant(\"after forceRemove(B)\");\n        // Further forceDeallocate in B is refused, nothing left stale in the vault.\n        vm.prank(depositor);\n        vm.expectRevert(IMidnightAdapterBase.ForceRemoved.selector);\n        vault.forceDeallocate(address(adapter), abi.encode(mB, depositor), 1, depositor);\n    }\n\n    /// Taker-driven (outsider-filled) buys cannot pass absolute, relative or duration caps.\n    function testOutsiderFilledBuyCannotPassCaps() public {\n        _setupMarkets();\n        _outsiderSellsToAdapter(mB, 10_000 * oneToken);\n        bytes32 colId = keccak256(abi.encode(\"collateralToken\", address(collateralToken)));\n        uint256 alloc = vault.allocation(colId);\n        console2.log(\"allocation before\", alloc);\n\n        // Absolute cap on collateral id: allocation + 100 tokens.\n        vm.prank(curator);\n        vault.decreaseAbsoluteCap(abi.encode(\"collateralToken\", address(collateralToken)), alloc + 100 * oneToken);\n        (Offer memory offer, bytes memory rd) = _ratifiedAdapterOffer(mB, true, 1_000 * oneToken);\n        vm.prank(borrower);\n        vm.expectRevert(ErrorsLib.AbsoluteCapExceeded.selector);\n        midnight.take(offer, rd, 1_000 * oneToken, borrower, borrower, address(0), \"\");\n        // Within the cap it passes.\n        vm.prank(borrower);\n        midnight.take(offer, rd, 90 * oneToken, borrower, borrower, address(0), \"\");\n        assertLe(vault.allocation(colId), vault.absoluteCap(colId));\n        console2.log(\"allocation after in-cap fill / cap\", vault.allocation(colId), vault.absoluteCap(colId));\n        _checkInvariant(\"after in-cap fill\");\n\n        // Duration cap (7 days) on the 30-day market.\n        _submitAndSet(\n            address(vault),\n            abi.encodeCall(IVaultV2.increaseAbsoluteCap, (abi.encode(\"collateralToken\", address(collateralToken)), type(uint128).max))\n        );\n        uint256 dAlloc = adapter.durationAllocations(1)[0];\n        vm.prank(curator);\n        vault.decreaseAbsoluteCap(abi.encode(\"this/duration\", address(adapter), 7 days), dAlloc + 100 * oneToken);\n        vm.prank(borrower);\n        vm.expectRevert(IMidnightAdapterBase.DurationAbsoluteCapExceeded.selector);\n        midnight.take(offer, rd, 500 * oneToken, borrower, borrower, address(0), \"\");\n        // A market shorter than the duration is not counted, so it is not blocked by the 7-day cap.\n        Market memory mShort = _market(3 days);\n        uint256 collateral = 10_000 * oneToken * 2e18 / oneToken;\n        deal(address(collateralToken), borrower, collateral);\n        vm.prank(borrower);\n        midnight.supplyCollateral(mShort, 0, collateral, borrower);\n        uint256 dBefore = adapter.durationAllocations(1)[0];\n        _outsiderSellsToAdapter(mShort, 500 * oneToken);\n        console2.log(\"7d duration alloc before / after 3d-market buy\", dBefore, adapter.durationAllocations(1)[0]);\n        assertEq(adapter.durationAllocations(1)[0], dBefore);\n\n        // Relative cap on the family id.\n        bytes memory famData = abi.encode(\n            \"collateralParams/rcfThreshold/liquidatorGate/enterGate\",\n            mB.collateralParams,\n            mB.rcfThreshold,\n            mB.liquidatorGate,\n            mB.enterGate\n        );\n        uint256 famAlloc = vault.allocation(keccak256(famData));\n        uint256 relCap = (famAlloc + 50 * oneToken) * WAD / vault.totalAssets();\n        vm.prank(curator);\n        vault.decreaseRelativeCap(famData, relCap);\n        _submitAndSet(\n            address(vault),\n            abi.encodeCall(IVaultV2.increaseAbsoluteCap, (abi.encode(\"this/duration\", address(adapter), 7 days), type(uint128).max))\n        );\n        vm.prank(borrower);\n        vm.expectRevert(ErrorsLib.RelativeCapExceeded.selector);\n        midnight.take(offer, rd, 500 * oneToken, borrower, borrower, address(0), \"\");\n        console2.log(\"family alloc / relCap\", famAlloc, relCap);\n    }\n\n    /// Live offers after a cap is zeroed and after the adapter loses its allocator role.\n    function testLiveOffersAfterCapZeroAndRoleLoss() public {\n        _setupMarkets();\n        _outsiderSellsToAdapter(mA, 20_000 * oneToken);\n        (Offer memory buyOffer, bytes memory buyRd) = _ratifiedAdapterOffer(mA, true, 10_000 * oneToken);\n        (Offer memory sellOffer, bytes memory sellRd) = _ratifiedAdapterOffer(mA, false, 10_000 * oneToken);\n\n        // 1. Zero the collateral id cap (sentinel, immediate).\n        vm.prank(sentinel);\n        vault.decreaseAbsoluteCap(abi.encode(\"collateralToken\", address(collateralToken)), 0);\n        vm.prank(borrower);\n        vm.expectRevert(ErrorsLib.ZeroAbsoluteCap.selector);\n        midnight.take(buyOffer, buyRd, 1_000 * oneToken, borrower, borrower, address(0), \"\");\n        vm.prank(lender);\n        midnight.take(sellOffer, sellRd, 1_000 * oneToken, lender, address(0), address(0), \"\");\n        _forceDeallocate(mA, 1_000 * oneToken);\n        _checkInvariant(\"cap zeroed: buy offer reverts, sell offer and forceDeallocate still work\");\n\n        // 2. Remove the adapter's allocator role.\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (address(adapter), false)));\n        vm.prank(lender);\n        vm.expectRevert(ErrorsLib.Unauthorized.selector);\n        midnight.take(sellOffer, sellRd, 1_000 * oneToken, lender, address(0), address(0), \"\");\n        _forceDeallocate(mA, 1_000 * oneToken);\n        _checkInvariant(\"no allocator role: sell offer reverts, forceDeallocate works\");\n\n        // 3. Give it the sentinel role: sells work again, buys need allocator.\n        vm.prank(owner);\n        vault.setIsSentinel(address(adapter), true);\n        vm.prank(lender);\n        midnight.take(sellOffer, sellRd, 1_000 * oneToken, lender, address(0), address(0), \"\");\n        _submitAndSet(\n            address(vault),\n            abi.encodeCall(IVaultV2.increaseAbsoluteCap, (abi.encode(\"collateralToken\", address(collateralToken)), type(uint128).max))\n        );\n        vm.prank(borrower);\n        vm.expectRevert(ErrorsLib.Unauthorized.selector);\n        midnight.take(buyOffer, buyRd, 1_000 * oneToken, borrower, borrower, address(0), \"\");\n        _checkInvariant(\"sentinel only: sell works, buy reverts\");\n    }\n\n    /// Fuzz: random sequence of outsider-driven actions keeps allocation == stored net credit.\n    function testFuzzOutsiderSequence(uint256 seed) public {\n        _setupMarkets();\n        (Offer memory bA, bytes memory rbA) = _ratifiedAdapterOffer(mA, true, 60_000 * oneToken);\n        (Offer memory bB, bytes memory rbB) = _ratifiedAdapterOffer(mB, true, 60_000 * oneToken);\n        (Offer memory sA, bytes memory rsA) = _ratifiedAdapterOffer(mA, false, 60_000 * oneToken);\n        (Offer memory sB, bytes memory rsB) = _ratifiedAdapterOffer(mB, false, 60_000 * oneToken);\n        for (uint256 i; i < 12; i++) {\n            uint256 r = uint256(keccak256(abi.encode(seed, i)));\n            uint256 action = r % 7;\n            uint256 amt = bound(r >> 8, 1, 8_000 * oneToken);\n            bool okCall;\n            if (action == 0) {\n                vm.prank(borrower);\n                try midnight.take(bA, rbA, amt, borrower, borrower, address(0), \"\") {okCall = true;} catch {}\n            } else if (action == 1) {\n                vm.prank(borrower);\n                try midnight.take(bB, rbB, amt, borrower, borrower, address(0), \"\") {okCall = true;} catch {}\n            } else if (action == 2) {\n                amt = bound(amt, 0, _actual(mA));\n                vm.prank(lender);\n                try midnight.take(sA, rsA, amt, lender, address(0), address(0), \"\") {okCall = true;} catch {}\n            } else if (action == 3) {\n                amt = bound(amt, 0, _actual(mB));\n                vm.prank(lender);\n                try midnight.take(sB, rsB, amt, lender, address(0), address(0), \"\") {okCall = true;} catch {}\n            } else if (action == 4) {\n                amt = bound(amt, 0, _actual(mA));\n                vm.prank(depositor);\n                try vault.forceDeallocate(address(adapter), abi.encode(mA, depositor), amt, depositor) {okCall = true;} catch {}\n            } else if (action == 5) {\n                amt = bound(amt, 0, _actual(mB));\n                vm.prank(depositor);\n                try vault.forceDeallocate(address(adapter), abi.encode(mB, depositor), amt, depositor) {okCall = true;} catch {}\n            } else {\n                vm.warp(block.timestamp + bound(r >> 16, 1, 2 days));\n            }\n            uint256 sumStored = _stored(mA) + _stored(mB);\n            bytes32[] memory _ids = adapter.ids(mA);\n            for (uint256 j; j < _ids.length; j++) {\n                assertEq(vault.allocation(_ids[j]), sumStored);\n            }\n            assertEq(_stored(mA), _actual(mA));\n            assertEq(_stored(mB), _actual(mB));\n        }\n    }\n}\n\ncontract VaultRolesCapsZeroSyncTest is VaultRolesCapsTest {\n    /// An account holding vault shares can push a Midnight loss into the vault's cap allocations with a 0-asset forceDeallocate.\n    function testZeroAssetForceDeallocateSyncsLoss() public {\n        _setupMarkets();\n        _outsiderSellsToAdapter(mB, 30_000 * oneToken);\n        oracle.setPrice(ORACLE_PRICE_SCALE * oneToken / 1e18 / 100);\n        midnight.liquidate(mB, 0, 0, 0, borrower, false, lender, address(0), \"\");\n        _checkInvariant(\"after loss, before sync\");\n        uint256 sharesBefore = vault.balanceOf(depositor);\n        _forceDeallocate(mB, 0);\n        console2.log(\"penalty shares paid\", sharesBefore - vault.balanceOf(depositor));\n        _checkInvariant(\"after 0-asset forceDeallocate by shareholder\");\n        assertEq(_stored(mB), _actual(mB));\n    }\n}\n\n/// Buys credit from the adapter's sell offer and, from its own buyer callback (mid-sale), force deallocates another market.\ncontract ReentrantShareholderBuyer {\n    IMidnight internal midnight;\n    IVaultV2 internal vault;\n    address internal adapter;\n    Market internal other;\n    uint256 internal otherAssets;\n\n    constructor(IMidnight _midnight, IVaultV2 _vault, address _adapter, address asset) {\n        midnight = _midnight;\n        vault = _vault;\n        adapter = _adapter;\n        midnight.setIsAuthorized(_adapter, true, address(this));\n        SafeERC20Lib.safeApprove(asset, address(_midnight), type(uint256).max);\n        SafeERC20Lib.safeApprove(asset, _adapter, type(uint256).max);\n    }\n\n    function go(Offer memory offer, bytes memory rd, uint256 units, Market memory _other, uint256 _otherAssets) external {\n        other = _other;\n        otherAssets = _otherAssets;\n        midnight.take(offer, rd, units, address(this), address(0), address(this), \"\");\n    }\n\n    function onBuy(bytes32, Market memory, uint256, uint256, uint256, address, bytes calldata) external returns (bytes32) {\n        require(msg.sender == address(midnight));\n        vault.forceDeallocate(adapter, abi.encode(other, address(this)), otherAssets, address(this));\n        return keccak256(\"morpho.midnight.callbackSuccess\");\n    }\n}\n\ncontract VaultRolesCapsReentryTest is VaultRolesCapsTest {\n    function testForceDeallocateFromBuyerCallbackMidSale() public {\n        _setupMarkets();\n        _outsiderSellsToAdapter(mA, 20_000 * oneToken);\n        _outsiderSellsToAdapter(mB, 20_000 * oneToken);\n        ReentrantShareholderBuyer r =\n            new ReentrantShareholderBuyer(midnight, vault, address(adapter), address(underlyingToken));\n        uint256 shares = vault.balanceOf(depositor) / 10;\n        vm.prank(depositor);\n        vault.transfer(address(r), shares);\n        deal(address(underlyingToken), address(r), 100_000 * oneToken);\n        (Offer memory sellA, bytes memory rd) = _ratifiedAdapterOffer(mA, false, 5_000 * oneToken);\n        r.go(sellA, rd, 5_000 * oneToken, mB, 3_000 * oneToken);\n        _checkInvariant(\"after sale in A with nested forceDeallocate in B from the buyer callback\");\n        assertEq(_stored(mA), 15_000 * oneToken);\n        assertEq(_stored(mB), 17_000 * oneToken);\n        // Nested forceDeallocate in the market being sold is refused.\n        (Offer memory sellA2, bytes memory rd2) = _ratifiedAdapterOffer(mA, false, 1_000 * oneToken);\n        vm.expectRevert(IMidnightAdapterBase.SellInProgress.selector);\n        r.go(sellA2, rd2, 1_000 * oneToken, mA, 100 * oneToken);\n    }\n}\n"
 },
 "notCovered": [
  "Self-funded buys (fundingAdapter == adapter or another adapter) are allocator-chosen; I did not test them beyond reading the code (L578-584), because a deallocation ordering failure there needs allocator input and the cap overshoot is Cantina 3.2.6.",
  "Enter-gated markets (IKR admit path) under cap or role changes were not exercised here.",
  "Relative-cap behaviour with nested vaults or multiple MidnightAdapters on the same vault (README MISC notes these may not trade with each other) was not tested.",
  "Continuous-fee (pendingFee) effects: Midnight continuous fee was 0 in these tests, so the pendingFee part of currentNetCredit was only reasoned about (updatePositionView with a dummy maturity-0 market accrues no fee, so net credit stays time-invariant), not tested with numbers.",
  "MAX_MARKETS (250) saturation and forceSellable sales were not exercised for this lead."
 ]
}