{
 "angle": "maturity and duration edge cases (PackedDurationsLib, constructor durations, durations()/durationAllocations and duration cap ids, maxTtm, time-to-maturity in buys, sales, amortization and realAssets around maturity, 250-market limit)",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No Medium/High (or provable Low-with-impact) vulnerability survived in this angle. Every edge case was exercised against the real Midnight (lib/midnight @ 4e2570e51171d09228645b2d5bdf84ef24b1720b) and the real VaultV2 with src/ and lib/ unmodified. All 9 verification tests pass (output below). The behaviours observed are either correct, documented as intended in the NatSpec/README, or already reported in the 2026-10-12 Cantina/TrustSec drafts. Four Informational notes follow; none has security impact on its own.",
 "lowInfo": [
  {
   "title": "Durations between Midnight's 100-year maximum time to maturity and type(uint32).max are accepted but can never be reached",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:161-169",
    "src/adapters/midnight/MidnightAdapterFactory.sol:26",
    "lib/midnight/src/Midnight.sol:755 (require(market.maturity <= block.timestamp + 100 * 365 days, MaturityTooFar()))",
    "src/adapters/midnight/MidnightAdapter.sol:586-603"
   ],
   "detail": "The constructor only requires 0 < d_0 < d_1 < ... and d_i <= type(uint32).max (4,294,967,295 s, about 136 years). Midnight refuses to create a market whose maturity is more than 100 * 365 days (3,153,600,000 s) ahead, so no position can ever have ttm >= d for d in (3,153,600,000; 4,294,967,295]. Such a duration takes one of the 8 slots, is returned by durations() and has a cap id, but onBuy never checks it and durationAllocations always reports 0 for it. testConstructorDurations deploys an adapter with durations [1d..7d, 4294967295] through the real factory and logs 'max duration accepted (s): 4294967295 > Midnight max ttm (s): 3153600000'. No funds at risk; a curator could believe they configured a cap that does not exist. Suggested fix: in the constructor, require each duration to be at most 100 * 365 days (Midnight's MaturityTooFar bound), or document this."
  },
  {
   "title": "PackedDurationsLib.pack OR-merges an over-wide duration into the next field, and get() returns 0 past index 7",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/libraries/PackedDurationsLib.sol:6-12",
    "src/adapters/midnight/libraries/PackedDurationsLib.sol:23-30",
    "src/adapters/midnight/MidnightAdapter.sol:161-168"
   ],
   "detail": "pack() does `packedDurations |= bytes32(durations[i] << (32 * i))` with no masking. testPackedDurationsLibEdges packs [2^32 + 4, 2] and reads back [4, 3]: the low 32 bits of the first value are kept and its carry bit is OR-ed into the second field (2 | 1 = 3). get(packed, 8) returns 0 because the shift is >= 256 bits. The adapter is not affected: the constructor rejects values above uint32 max, more than 8 entries, and non-increasing values before packing, and durationAllocations bounds length by durationsLength. A pack/unpack round-trip fuzz over all uint32[8] inputs and lengths 0..8 (1024 runs, two seeds) passes. The NatSpec states these assumptions; this matters only if the library is reused. Optional hardening: mask each value or require it to fit in 32 bits inside pack."
  },
  {
   "title": "Duration caps use an inclusive per-second threshold, so a market at ttm = d - 1 skips cap d entirely",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:64-71",
    "src/adapters/midnight/MidnightAdapter.sol:586-603",
    "src/adapters/midnight/MidnightAdapter.sol:817-834"
   ],
   "detail": "A position counts toward duration d only while maturity - now >= d. testDurationBoundary sets the 7-day duration's absolute cap to 500 tokens. Buying 1000 units at ttm = 7d - 1 s succeeds and durationAllocations(1) = [0]. The same buy at ttm = 7d reverts with DurationAbsoluteCapExceeded. After raising the cap, the 7-day position counts 1e21 and drops to 0 one second later. Because anyone can create Midnight markets with arbitrary maturities, a duration cap limits what can be bought at or above d at purchase time, and positions fall out of the bucket as time passes. The fuzz test testFuzzDurationAllocationMonotone checks that an allocation never increases with time alone and equals the sum of stored net credit with ttm >= d. This is the documented semantics ('A position counts toward every duration <= its current remaining time to maturity'); curators should choose durations with that in mind. No finding."
  },
  {
   "title": "Matured, unrepaid positions stay at face value, absorb no shortfall, and can only be sold below par once the market is force-sellable",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:641-645",
    "src/adapters/midnight/MidnightAdapter.sol:653-666",
    "src/adapters/midnight/MidnightAdapter.sol:837-863",
    "src/adapters/midnight/README.md (Force-sellable markets)"
   ],
   "detail": "At ttm = 0 the amortized value equals the stored net credit. testValuationAroundMaturityAndRemoval logs realAssets = 999999990187982463275 at T-1, then 1e21 at T and at T+365 days, with the borrower still unrepaid. A non-force-sellable sale after maturity requires sellerAssets >= soldNetCredit, because the maxNetSellRate * 0 bound means par; a sale at about 0.994 reverts with NetSellRateTooHigh. In testShortfallWithMaturedMarket a matured, unrepaid market contributes 0 unearned interest: the shortfall from selling 500 units of a 30-day market at price 0.9938625 lowered only that market's rate (2289470781 -> 2026611781) and left the matured market's rate unchanged, with no division by zero. A defaulted matured position therefore stays at face until Midnight liquidation realizes bad debt (post-maturity liquidations are always available), or until the timelocked setForceSellable allows a sale below par. The README documents this ('This permits sales for fewer assets than the sold net credit after maturity'), and the loss-realisation angle owns its economics. No finding."
  }
 ],
 "verificationTests": {
  "path": "test/poc/MaturityEdgeCases.t.sol",
  "note": "Not a PoC for a finding: these tests document coverage. They run from the root of a clean clone at the pinned commit with this file added (src/ and lib/ unmodified). The contract inherits test/integration/MidnightAdapterIntegrationTest.sol, so its setup deploys the real Midnight and VaultV2. The fuzz tests were also run with --fuzz-seed 0x1234 and passed.",
  "command": "forge test --match-path test/poc/MaturityEdgeCases.t.sol --match-test \"testDurationBoundary|testMaxTtm|testValuation|testShortfall|testMaxMarkets|testFuzz|testConstructor|testPacked\" -vv",
  "output": "Compiler run successful!\n\nRan 9 tests for test/poc/MaturityEdgeCases.t.sol:MaturityEdgeCasesTest\n[PASS] testConstructorDurations() (gas: 10116116)\nLogs:\n  max duration accepted (s): 4294967295 > Midnight max ttm (s): 3153600000\n\n[PASS] testDurationBoundary() (gas: 2981158)\nLogs:\n  alloc(7d) after buying ttm=7d-1: 0\n  alloc(7d) after buying ttm=7d: 1000000000000000000000\n\n[PASS] testFuzzDurationAllocationMonotone(uint256,uint256) (runs: 64, \u03bc: 3909207, ~: 3909953)\n[PASS] testFuzzPackRoundTrip(uint32[8],uint8) (runs: 1024, \u03bc: 4657, ~: 4077)\n[PASS] testMaxMarketsLimitAndRemoval() (gas: 464967398)\nLogs:\n  realAssets with 250 markets: 2485251750000104165258 gas: 1943564\n  durationAllocations(1) gas with 250 markets: 1176778\n\n[PASS] testMaxTtmAndMaturityBoundaries() (gas: 4250360)\nLogs:\n  netRate of 1s-ttm market (WAD/s): 5934308264746217\n\n[PASS] testPackedDurationsLibEdges() (gas: 6092)\n[PASS] testShortfallWithMaturedMarket() (gas: 2908505)\nLogs:\n  sell price (WAD): 993862500000000000\n  rateB before/after: 2289470781 2026611781\n  realAssets before/after, proceeds: 1994491820373425680941 1497560570374580013442\n  proceeds: 496931250000000000000\n  valuation drift vs proceeds (wei), bound: 1154332501 1209600002\n\n[PASS] testValuationAroundMaturityAndRemoval() (gas: 2410092)\nLogs:\n  paid / netCredit: 994100700000000000000 1000000000000000000000\n  realAssets at T-1 / T / T+1y: 999999990187982463275 1000000000000000000000\n  realAssets T+1y: 1000000000000000000000\n\n\nRan 1 test suite in 1.11s (1.11s CPU time): 9 tests passed, 0 failed, 0 skipped (9 total tests)",
  "source": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {PackedDurationsLib} from \"../../src/adapters/midnight/libraries/PackedDurationsLib.sol\";\nimport {console} from \"../../lib/forge-std/src/console.sol\";\n\n/// Maturity / duration edge cases of MidnightAdapter, run against the real Midnight and VaultV2.\ncontract MaturityEdgeCasesTest is MidnightAdapterIntegrationTest {\n    uint256 internal nonce;\n\n    /// @dev Adapter buys `units` of `market` as taker from a fresh, collateralized borrower offer.\n    function _takerBuy(Market memory market, uint256 units, bytes4 expectedError) internal {\n        nonce++;\n        Offer memory offer = Offer({\n            market: market,\n            buy: false,\n            maker: borrower,\n            start: block.timestamp,\n            expiry: type(uint256).max,\n            tick: TICK,\n            group: keccak256(abi.encode(\"poc buy\", nonce)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: borrower,\n            ratifier: address(setterRatifier),\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        uint256 collateral = units * 2e18 / oneToken;\n        deal(address(collateralToken), borrower, collateral);\n        bytes32 root = HashLib.hashOffer(offer);\n        bytes32[] memory proof = new bytes32[](0);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, borrower);\n        midnight.setIsAuthorized(address(setterRatifier), true, borrower);\n        setterRatifier.setIsRootRatified(borrower, root, true);\n        vm.stopPrank();\n        if (expectedError != bytes4(0)) vm.expectRevert(expectedError);\n        vm.prank(allocator);\n        adapter.take(offer, abi.encode(root, uint256(0), proof), units, abi.encode(address(0), \"\"));\n    }\n\n    /// @dev Adapter sells `units` of `market` as taker into a lender buy offer at `tick`.\n    function _takerSell(Market memory market, uint256 units, uint256 tick) internal {\n        nonce++;\n        Offer memory offer = Offer({\n            market: market,\n            buy: true,\n            maker: lender,\n            start: block.timestamp,\n            expiry: type(uint256).max,\n            tick: tick,\n            group: keccak256(abi.encode(\"poc sell\", nonce)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(0),\n            ratifier: address(setterRatifier),\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        deal(address(underlyingToken), lender, units);\n        bytes32 root = HashLib.hashOffer(offer);\n        bytes32[] memory proof = new bytes32[](0);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        midnight.setIsAuthorized(address(setterRatifier), true, lender);\n        setterRatifier.setIsRootRatified(lender, root, true);\n        vm.stopPrank();\n        vm.prank(allocator);\n        adapter.take(offer, abi.encode(root, uint256(0), proof), units, \"\");\n    }\n\n    function _setDurationAbsoluteCap(uint256 cap) internal {\n        bytes memory idData = abi.encode(\"this/duration\", address(adapter), 7 days);\n        vm.prank(curator);\n        vault.decreaseAbsoluteCap(idData, cap);\n    }\n\n    /* 1. Duration bucket boundary: ttm == duration counts, ttm == duration - 1 does not. */\n    function testDurationBoundary() public {\n        uint256 units = 1000 * oneToken;\n        _setDurationAbsoluteCap(500 * oneToken);\n\n        // ttm = 7 days - 1: below the only duration, no duration check, not counted.\n        _takerBuy(_market(7 days - 1), units, bytes4(0));\n        uint256 allocBelow = adapter.durationAllocations(1)[0];\n        console.log(\"alloc(7d) after buying ttm=7d-1:\", allocBelow);\n        assertEq(allocBelow, 0, \"ttm < d must not count\");\n\n        // ttm = 7 days exactly: counted, so 1000 > cap 500 reverts.\n        _takerBuy(_market(7 days), units, IMidnightAdapterBase.DurationAbsoluteCapExceeded.selector);\n\n        // Raise cap; the same buy now goes through and is counted with its full stored net credit.\n        // decreaseAbsoluteCap cannot raise: use the timelocked increase.\n        _increaseCaps(abi.encode(\"this/duration\", address(adapter), 7 days));\n        Market memory m7 = _market(7 days);\n        _takerBuy(m7, units, bytes4(0));\n        uint256 alloc = adapter.durationAllocations(1)[0];\n        console.log(\"alloc(7d) after buying ttm=7d:\", alloc);\n        assertEq(alloc, adapter.marketData(IdLib.toId(m7)).netCredit);\n\n        // One second later the 7d market has ttm 7d-1 and leaves the bucket.\n        vm.warp(block.timestamp + 1);\n        assertEq(adapter.durationAllocations(1)[0], 0, \"position leaves bucket once ttm < d\");\n        // durationAllocations bounds.\n        assertEq(adapter.durationAllocations(0).length, 0);\n        vm.expectRevert(IMidnightAdapterBase.InvalidLength.selector);\n        adapter.durationAllocations(2);\n    }\n\n    /* 2. maxTtm and maturity boundaries on buys. */\n    function testMaxTtmAndMaturityBoundaries() public {\n        uint256 units = 100 * oneToken;\n        assertEq(adapter.maxTtm(), 90 days);\n        _takerBuy(_market(90 days), units, bytes4(0)); // ttm == maxTtm allowed\n        _takerBuy(_market(90 days + 1), units, IMidnightAdapterBase.BuyTtmTooHigh.selector);\n        _takerBuy(_market(1), units, bytes4(0)); // ttm == 1 second allowed (rate ~6e15/s fits uint64)\n        Market memory m1 = _market(1);\n        console.log(\"netRate of 1s-ttm market (WAD/s):\", adapter.marketData(IdLib.toId(m1)).netRate);\n        _takerBuy(_market(0), units, IMidnightAdapterBase.BuyPostMaturity.selector); // ttm == 0\n        // maxTtm decrease by sentinel is immediate and blocks further long buys; existing positions unaffected.\n        vm.prank(curator);\n        adapter.decreaseMaxTtm(30 days);\n        _takerBuy(_market(30 days + 1), units, IMidnightAdapterBase.BuyTtmTooHigh.selector);\n        vm.expectRevert(IMidnightAdapterBase.MaxTtmTooHigh.selector);\n        vm.prank(curator);\n        adapter.decreaseMaxTtm(31 days);\n    }\n\n    /* 3. Valuation just before, at and after maturity; post-maturity sale; removal after repayment. */\n    function testValuationAroundMaturityAndRemoval() public {\n        uint256 units = 1000 * oneToken;\n        Market memory m = _market(7 days);\n        bytes32 id = IdLib.toId(m);\n        _takerBuy(m, units, bytes4(0));\n        uint256 netCredit = adapter.marketData(id).netCredit;\n        uint256 paid = initialAssets - underlyingToken.balanceOf(address(vault));\n        console.log(\"paid / netCredit:\", paid, netCredit);\n        vm.warp(m.maturity - 1);\n        uint256 rBefore = adapter.realAssets();\n        vm.warp(m.maturity);\n        uint256 rAt = adapter.realAssets();\n        vm.warp(m.maturity + 365 days);\n        uint256 rAfter = adapter.realAssets();\n        console.log(\"realAssets at T-1 / T / T+1y:\", rBefore, rAt);\n        console.log(\"realAssets T+1y:\", rAfter);\n        assertLe(rBefore, rAt);\n        assertEq(rAt, netCredit);\n        assertEq(rAfter, netCredit);\n        assertEq(adapter.durationAllocations(1)[0], 0);\n\n        // Post-maturity non-force-sellable sale below face reverts (maxNetSellRate * 0 = par floor).\n        vm.expectRevert(IMidnightAdapterBase.NetSellRateTooHigh.selector);\n        this.externalSell(m, 10 * oneToken, TICK);\n\n        // Repay and withdraw everything: the market is removed.\n        deal(address(underlyingToken), borrower, units);\n        vm.startPrank(borrower);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), units);\n        midnight.repay(m, units, borrower, address(0), \"\");\n        vm.stopPrank();\n        vm.prank(allocator);\n        vault.deallocate(address(adapter), abi.encode(m), netCredit);\n        assertEq(adapter.marketIdsLength(), 0);\n        assertEq(adapter.marketData(id).maturity, 0);\n        assertEq(adapter.realAssets(), 0);\n    }\n\n    function externalSell(Market memory market, uint256 units, uint256 tick) external {\n        _takerSell(market, units, tick);\n    }\n\n    /* 4. Shortfall sale while another market is matured (ttm 0) and unrepaid: no division by zero. */\n    function testShortfallWithMaturedMarket() public {\n        uint256 units = 1000 * oneToken;\n        Market memory a = _market(1 days);\n        Market memory b = _market(30 days);\n        _takerBuy(a, units, bytes4(0));\n        _takerBuy(b, units, bytes4(0));\n        vm.warp(block.timestamp + 2 days); // a matured, unrepaid\n        uint64 rateA = adapter.marketData(IdLib.toId(a)).netRate;\n        uint64 rateB = adapter.marketData(IdLib.toId(b)).netRate;\n        uint256 realBefore = adapter.realAssets();\n        uint256 idleBefore = underlyingToken.balanceOf(address(vault));\n        console.log(\"sell price (WAD):\", TickLib.tickToPrice(TICK - 8));\n        _takerSell(b, 500 * oneToken, TICK - 8);\n        uint256 proceeds = underlyingToken.balanceOf(address(vault)) - idleBefore;\n        uint256 realAfter = adapter.realAssets();\n        console.log(\"rateB before/after:\", rateB, adapter.marketData(IdLib.toId(b)).netRate);\n        console.log(\"realAssets before/after, proceeds:\", realBefore, realAfter);\n        console.log(\"proceeds:\", proceeds);\n        assertEq(adapter.marketData(IdLib.toId(a)).netRate, rateA, \"matured market rate untouched\");\n        assertLt(adapter.marketData(IdLib.toId(b)).netRate, rateB, \"shortfall absorbed by b\");\n        // Documented rate floor: one rate unit (1e-18/s) on ~500e18 net credit over ~26 days left is ~1.1e9 wei.\n        uint256 bound_ = 500 * oneToken * (b.maturity - vm.getBlockTimestamp()) / WAD + 2;\n        console.log(\"valuation drift vs proceeds (wei), bound:\", proceeds - (realBefore - realAfter), bound_);\n        assertApproxEqAbs(realBefore - realAfter, proceeds, bound_);\n    }\n\n    /* 5. MAX_MARKETS: 250 active markets, 251st reverts, removing one frees a slot; realAssets gas. */\n    function testMaxMarketsLimitAndRemoval() public {\n        uint256 units = 10 * oneToken;\n        for (uint256 i; i < 250; i++) {\n            _takerBuy(_market(1 days + i), units, bytes4(0));\n        }\n        assertEq(adapter.marketIdsLength(), 250);\n        _takerBuy(_market(2 days), units, IMidnightAdapterBase.TooManyMarkets.selector);\n        uint256 g = gasleft();\n        uint256 ra = adapter.realAssets();\n        console.log(\"realAssets with 250 markets:\", ra, \"gas:\", g - gasleft());\n        g = gasleft();\n        adapter.durationAllocations(1);\n        console.log(\"durationAllocations(1) gas with 250 markets:\", g - gasleft());\n\n        Market memory first = _market(1 days);\n        deal(address(underlyingToken), borrower, units);\n        vm.startPrank(borrower);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), units);\n        midnight.repay(first, units, borrower, address(0), \"\");\n        vm.stopPrank();\n        uint256 nc = adapter.marketData(IdLib.toId(first)).netCredit;\n        vm.prank(allocator);\n        vault.deallocate(address(adapter), abi.encode(first), nc);\n        assertEq(adapter.marketIdsLength(), 249);\n        _takerBuy(_market(2 days), units, bytes4(0));\n        assertEq(adapter.marketIdsLength(), 250);\n        // index bookkeeping: the last market moved into slot 0.\n        assertEq(adapter.marketData(adapter.marketIds(0)).index, 0);\n        assertEq(adapter.marketData(adapter.marketIds(249)).index, 249);\n    }\n\n    /* 6. Fuzz: a duration allocation never increases with time alone (caps cannot be exceeded passively). */\n    /// forge-config: default.fuzz.runs = 64\n    function testFuzzDurationAllocationMonotone(uint256 t1, uint256 t2) public {\n        uint256 units = 100 * oneToken;\n        uint256[4] memory ttms = [uint256(3 days), 7 days, 10 days, 30 days];\n        uint256 start = vm.getBlockTimestamp();\n        bytes32[4] memory mids;\n        for (uint256 i; i < 4; i++) {\n            Market memory m = _market(ttms[i]);\n            mids[i] = IdLib.toId(m);\n            _takerBuy(m, units, bytes4(0));\n        }\n        t1 = bound(t1, 0, 40 days);\n        t2 = bound(t2, t1, 40 days);\n        vm.warp(start + t1);\n        uint256 a1 = adapter.durationAllocations(1)[0];\n        uint256 expected;\n        for (uint256 i; i < 4; i++) {\n            if (start + ttms[i] >= start + t1 + 7 days) expected += adapter.marketData(mids[i]).netCredit;\n        }\n        assertEq(a1, expected);\n        vm.warp(start + t2);\n        assertLe(adapter.durationAllocations(1)[0], a1);\n    }\n\n    /* 7. Constructor validation of durations and PackedDurationsLib edge cases. */\n    function testConstructorDurations() public {\n        IMidnightAdapterFactory f = IMidnightAdapterFactory(\n            deployCode(\"MidnightAdapterFactory.sol:MidnightAdapterFactory\", abi.encode(address(midnight)))\n        );\n        uint256[] memory d = new uint256[](1);\n        d[0] = 0;\n        vm.expectRevert(IMidnightAdapterBase.DurationsNotIncreasing.selector);\n        f.createMidnightAdapter(address(vault), d, address(0), bytes32(\"a\"));\n        d[0] = uint256(type(uint32).max) + 1;\n        vm.expectRevert(IMidnightAdapterBase.DurationTooHigh.selector);\n        f.createMidnightAdapter(address(vault), d, address(0), bytes32(\"b\"));\n        uint256[] memory dup = new uint256[](2);\n        (dup[0], dup[1]) = (7 days, 7 days);\n        vm.expectRevert(IMidnightAdapterBase.DurationsNotIncreasing.selector);\n        f.createMidnightAdapter(address(vault), dup, address(0), bytes32(\"c\"));\n        uint256[] memory nine = new uint256[](9);\n        for (uint256 i; i < 9; i++) nine[i] = i + 1;\n        vm.expectRevert(IMidnightAdapterBase.TooManyDurations.selector);\n        f.createMidnightAdapter(address(vault), nine, address(0), bytes32(\"d\"));\n\n        // Accepted but unreachable: Midnight caps maturity at 100 * 365 days (3,153,600,000 s) < uint32 max.\n        uint256[] memory eight = new uint256[](8);\n        for (uint256 i; i < 7; i++) eight[i] = (i + 1) * 1 days;\n        eight[7] = type(uint32).max;\n        IMidnightAdapter a = IMidnightAdapter(f.createMidnightAdapter(address(vault), eight, address(0), bytes32(\"e\")));\n        uint256[] memory got = a.durations();\n        assertEq(got.length, 8);\n        for (uint256 i; i < 8; i++) assertEq(got[i], eight[i]);\n        console.log(\"max duration accepted (s):\", got[7], \"> Midnight max ttm (s):\", 100 * 365 days);\n    }\n\n    function testPackedDurationsLibEdges() public pure {\n        uint256[] memory d = new uint256[](2);\n        (d[0], d[1]) = (uint256(type(uint32).max) + 5, 2);\n        bytes32 p = PackedDurationsLib.pack(d);\n        // Out-of-range input bleeds into the next field (callers must pre-validate; the constructor does):\n        // 2^32 + 4 is read back as 4, and its carry bit is OR-ed into the second field: 2 | 1 = 3.\n        assertEq(PackedDurationsLib.get(p, 0), 4);\n        assertEq(PackedDurationsLib.get(p, 1), 3);\n        // Index past 8 reads zero.\n        uint256[] memory full = new uint256[](8);\n        for (uint256 i; i < 8; i++) full[i] = type(uint32).max - i;\n        bytes32 q = PackedDurationsLib.pack(full);\n        assertEq(PackedDurationsLib.get(q, 7), type(uint32).max - 7);\n        assertEq(PackedDurationsLib.get(q, 8), 0);\n        assertEq(PackedDurationsLib.unpack(q, 8)[0], type(uint32).max);\n    }\n\n    /// forge-config: default.fuzz.runs = 1024\n    function testFuzzPackRoundTrip(uint32[8] memory raw, uint8 len) public pure {\n        uint256 n = bound(len, 0, 8);\n        uint256[] memory d = new uint256[](n);\n        for (uint256 i; i < n; i++) d[i] = raw[i];\n        uint256[] memory out = PackedDurationsLib.unpack(PackedDurationsLib.pack(d), n);\n        for (uint256 i; i < n; i++) assertEq(out[i], d[i]);\n    }\n}\n"
 },
 "covered": [
  "Step 1: cloned morpho-org/vault-v2 at bbeda7b27ae80abcf070e0158cb8a31e87bb2286 with submodules and ran forge build (successful). Existing suites: MidnightAdapterTest (314), MidnightAdapterRatifiersV1Test (36 + 38 + 1), PackedDurationsLibTest (2) and MidnightAdapterIntegrationTest (8): 399 passed, 0 failed (fuzz runs reduced to 64 for time).",
  "PackedDurationsLib.get/unpack/pack: field width, over-wide input (corrupts the neighbouring field, prevented by the constructor), index >= 8 (returns 0, never reached), round-trip fuzz for every length 0..8.",
  "Constructor _durations: 0 reverts (DurationsNotIncreasing), duplicate reverts, unsorted reverts (strict >), more than 8 reverts (TooManyDurations), 2^32 reverts (DurationTooHigh), uint32 max accepted, durations() returns the 8 values in order.",
  "durationAllocations: length 0 returns an empty array, length > durationsLength reverts InvalidLength, bucket boundary at ttm == d (inclusive), suffix-sum correctness, monotone in time (fuzzed); duration cap ids use keccak256(abi.encode(\"this/duration\", adapter, d)) as in the integration setup; buys check only durations <= the bought market's ttm, after the funding branch, against stored net credit.",
  "maxTtm: ttm == maxTtm allowed, maxTtm + 1 reverts BuyTtmTooHigh, decreaseMaxTtm is immediate and cannot raise (MaxTtmTooHigh), increaseMaxTtm is timelocked and uses toUint128; existing positions are unaffected by a decrease.",
  "Buys near maturity: ttm = 1 s at price 0.994 works (netRate 5934308264746217 WAD/s, fits uint64); ttm = 0 reverts BuyPostMaturity (Midnight itself still allows the trade at timestamp == maturity). The uint64 rate overflow for deep discounts near maturity is already TrustSec TRST-R-2 and the Cantina rate footnote: out of scope.",
  "Overflow and division by zero: ttm arithmetic in onBuy, onSell and realAssets (uint64 rate * uint256 ttm, uint128 * WAD, denominators >= WAD; the onBuy and shortfall-loop denominators amortizedValue*ttm and targetAmortizedValue*otherTtm are non-zero whenever reached, since matured or zero-interest markets are skipped by the netCredit == amortizedValue check); maturity.toUint40 cannot overflow under Midnight's 100-year bound.",
  "Sales and valuation around maturity: realAssets is continuous up to maturity and equals net credit at and after it; a post-maturity par floor for non-force-sellable sales; a shortfall sale with a matured market in the set (no revert, matured rate unchanged, realAssets drop = proceeds within the documented rate-floor drift of 1154332501 wei for ~500e18 over ~26 days; already covered by the NatSpec 'Rates are rounded down...' and Cantina 3.2.8 / 3.6.6).",
  "Market removal: repay plus withdraw of full net credit removes the market (maturity and rate reset, marketIdsLength 0); withdraw(0) after a total loss syncs to 0 and removes it (code reading of updatePositionView with a maxed loss factor); forceRemove clears it.",
  "MAX_MARKETS: 250 active markets reached through real takes, the 251st reverts TooManyMarkets, removing one frees a slot, swap-and-pop index bookkeeping verified (uint8 index <= 249); gas at 250 markets: realAssets 1,943,564, durationAllocations(1) 1,176,778.",
  "currentNetCredit with a dummy maturity-0 market: credit - pendingFee does not depend on time (Midnight's updatePositionView accrues nothing when maturity <= lastAccrual), so stored net credit and duration allocations are not distorted by continuous-fee accrual; settlement fee lookups use zeroFloorSub(maturity, now) consistently.",
  "Prior-audit check: read audits/2026-10-12-midnight-adapter-cantina-draft.pdf (Medium 3.1.1; Lows 3.2.1-3.2.11 incl. 3.2.3 duration zero-cap, 3.2.5 stale allocation checks; uint64 rate footnote) and audits/2026-10-12-midnight-adapter-trustsec-draft.pdf (TRST-L-1..L-5; TRST-R-1 shared factory durations, R-2 maturity bits / rate overflow near maturity, R-7 per-duration min rate, R-15 maxTtm). None of the Informational notes above duplicates them."
 ],
 "notCovered": [
  "No independent clean-clone re-run by a second agent (Step 4) was done within this item; the verification tests were run on a single clone at the pinned commit.",
  "Rounding economics of rate blending, cross-adapter trading, gates, ratifiers, forceDeallocate penalties and bad-debt economics belong to other angles and were not reviewed in depth.",
  "Fuzzing of 8-duration adapters against many random maturities on the real stack was not run (only the 1-duration integration adapter was fuzzed; constructor and packing were tested with 8 durations).",
  "Behaviour with non-18-decimal tokens (DECIMALS env) was not run."
 ]
}