{
  "lead": "rate-ratifier-fees",
  "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
  "hasCandidates": false,
  "candidates": [],
  "lowInfo": [
    {
      "title": "Documented precision limitation for expensive smallest-unit assets",
      "class": "Informational",
      "refs": [
        "src/adapters/midnight/MidnightAdapter.sol:21"
      ],
      "detail": "The NatSpec says WBTC, cbBTC and 2-decimal stablecoins are unsupported because rounding and zero-asset buys can accrue significant interest too early. This lead did not test those assets; UNVERIFIED here and not a new finding.",
      "verified": false
    }
  ],
  "covered": {
    "tests": {
      "productionBuild": {
        "command": "forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol lib/morpho-blue/src/Morpho.sol",
        "exitCode": 0
      },
      "existingSuites": [
        {
          "path": "test/MidnightAdapterTest.sol",
          "passed": 314,
          "failed": 0,
          "skipped": 0,
          "fuzzRuns": 2048
        },
        {
          "path": "test/integration/MidnightAdapterIntegrationTest.sol",
          "passed": 8,
          "failed": 0,
          "skipped": 0
        },
        {
          "path": "test/MidnightAdapterRatifiersV1Test.sol",
          "passed": 75,
          "failed": 0,
          "skipped": 0,
          "fuzzRuns": 2048
        }
      ],
      "focusedPoC": {
        "path": "test/poc/RateRatifierFeeBoundaryTest.sol",
        "sha256": "7d161b1ec0ba273d28eac093a0e9062076579b2a3ddba32bd2b67445d7de3d4d",
        "cases": [
          "testBuyAtTheRatifiedRateIsRejectedAfterContinuousFee",
          "testBuyCanFillOnceItsTtmFallsWithinMaxTtm",
          "testBuyOneSecondBeforeMaturityUsesFillTimeAndFeeAdjustedAmounts",
          "testBuyRootRemainsRateValidAtMaturityButAdapterRejectsMaturityAndAfter",
          "testSellOfferRateAndFeesAreCheckedOnMakersNetProceeds",
          "testSellRateRatifierRejectsOldPriceNearAndAfterMaturity",
          "testSharedBuyAndSellGroupAndOutsiderSetConsumed"
        ],
        "passed": 7,
        "failed": 0,
        "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Test} from \"../../lib/forge-std/src/Test.sol\";\nimport {IMidnightAdapter, IMidnightAdapterBase} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {\n    IMidnightAdapterRateRatifierV1\n} from \"../../src/adapters/midnight/ratifiers/interfaces/IMidnightAdapterRateRatifierV1.sol\";\nimport {\n    IMidnightAdapterPriceRatifierV1\n} from \"../../src/adapters/midnight/ratifiers/interfaces/IMidnightAdapterPriceRatifierV1.sol\";\nimport {IMidnightAdapterFactory} from \"../../src/adapters/midnight/interfaces/IMidnightAdapterFactory.sol\";\nimport {IMidnight, Market, Offer} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {\n    COLLATERAL_PARAMS_TYPEHASH,\n    MARKET_TYPEHASH,\n    OFFER_TYPEHASH,\n    RATE_RATIFIER_V1_OFFER_TYPEHASH,\n    PRICE_RATIFIER_V1_OFFER_TYPEHASH\n} from \"../../lib/midnight/src/ratifiers/libraries/HashLib.sol\";\nimport {ISetterRatifier} from \"../../lib/midnight/src/ratifiers/interfaces/ISetterRatifier.sol\";\nimport {TickLib} from \"../../lib/midnight/src/libraries/TickLib.sol\";\nimport {\n    MAX_CONTINUOUS_FEE,\n    MAX_SETTLEMENT_FEE_0_DAYS,\n    MAX_SETTLEMENT_FEE_1_DAY,\n    MAX_SETTLEMENT_FEE_7_DAYS\n} from \"../../lib/midnight/src/libraries/ConstantsLib.sol\";\nimport {IdLib} from \"../../lib/midnight/src/libraries/IdLib.sol\";\nimport {WAD} from \"../../src/libraries/ConstantsLib.sol\";\nimport {SafeERC20Lib} from \"../../src/libraries/SafeERC20Lib.sol\";\nimport {IVaultV2} from \"../../src/interfaces/IVaultV2.sol\";\nimport {IVaultV2Factory} from \"../../src/interfaces/IVaultV2Factory.sol\";\nimport {ERC20Mock} from \"../mocks/ERC20Mock.sol\";\nimport {OracleMock} from \"../../lib/morpho-blue/test/mocks/OracleMock.sol\";\nimport {CollateralParams} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {ORACLE_PRICE_SCALE} from \"../../lib/morpho-blue/src/libraries/ConstantsLib.sol\";\n\ncontract RateRatifierFeeBoundaryTest is Test {\n    uint256 internal constant TICK = 4400;\n    address internal owner = makeAddr(\"owner\");\n    address internal curator = makeAddr(\"curator\");\n    address internal allocator = makeAddr(\"allocator\");\n    address internal sentinel = makeAddr(\"sentinel\");\n    address internal depositor = makeAddr(\"depositor\");\n    address internal borrower = makeAddr(\"borrower\");\n    address internal lender = makeAddr(\"lender\");\n    address internal outsider = makeAddr(\"outsideAllocatorAndSentinel\");\n\n    IMidnight internal midnight;\n    IMidnightAdapter internal adapter;\n    IMidnightAdapterPriceRatifierV1 internal priceSubRatifier;\n    ISetterRatifier internal setterRatifier;\n    IVaultV2 internal vault;\n    ERC20Mock internal underlyingToken;\n    ERC20Mock internal collateralToken;\n    OracleMock internal oracle;\n    CollateralParams internal collateralParams;\n    uint256 internal oneToken = 1e18;\n    uint256 internal initialAssets = 100_000e18;\n\n    IMidnightAdapterRateRatifierV1 internal rateSubRatifier;\n\n    function setUp() public {\n        vm.setEvmVersion(\"osaka\");\n        underlyingToken = new ERC20Mock(18);\n        IVaultV2Factory vaultFactory = IVaultV2Factory(deployCode(\"out/VaultV2Factory.sol/VaultV2Factory.json\"));\n        vault = IVaultV2(vaultFactory.createVaultV2(owner, address(underlyingToken), bytes32(0)));\n\n        vm.startPrank(owner);\n        vault.setCurator(curator);\n        vault.setIsSentinel(sentinel, true);\n        vm.stopPrank();\n        vm.prank(curator);\n        vault.submit(abi.encodeCall(IVaultV2.setIsAllocator, (allocator, true)));\n        vault.setIsAllocator(allocator, true);\n\n        vm.prank(owner);\n        midnight = IMidnight(deployCode(\"out/Midnight.sol/Midnight.json\"));\n        vm.startPrank(owner);\n        midnight.enableLltv(1e18);\n        midnight.enableLiquidationCursor(0.25e18);\n        vm.stopPrank();\n\n        collateralToken = new ERC20Mock(18);\n        oracle = new OracleMock();\n        oracle.setPrice(ORACLE_PRICE_SCALE);\n        collateralParams = CollateralParams(address(collateralToken), 1e18, 0.25e18, address(oracle));\n\n        uint256[] memory durations = new uint256[](1);\n        durations[0] = 7 days;\n        IMidnightAdapterFactory factory = IMidnightAdapterFactory(\n            deployCode(\"out/MidnightAdapterFactory.sol/MidnightAdapterFactory.json\", abi.encode(address(midnight)))\n        );\n        adapter = IMidnightAdapter(factory.createMidnightAdapter(address(vault), durations, address(0), bytes32(0)));\n        priceSubRatifier = IMidnightAdapterPriceRatifierV1(\n            deployCode(\"out/MidnightAdapterPriceRatifierV1.sol/MidnightAdapterPriceRatifierV1.json\")\n        );\n        setterRatifier = ISetterRatifier(\n            deployCode(\"out/SetterRatifier.sol/SetterRatifier.json\", abi.encode(address(midnight)))\n        );\n\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.increaseMaxTtm, (90 days)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.addAdapter, (address(adapter))));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (address(adapter), true)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setForceDeallocatePenalty, (address(adapter), 0.02e18)));\n        vm.prank(allocator);\n        vault.setMaxRate(1e18 / uint256(365 days));\n        vm.prank(allocator);\n        adapter.setIsSubRatifier(address(priceSubRatifier), true);\n        _submitAndSet(\n            address(adapter), abi.encodeCall(IMidnightAdapterBase.increaseMaxNetSellRate, (1e18 / uint256(365 days)))\n        );\n        _submitAndSet(\n            address(adapter), abi.encodeCall(IMidnightAdapterBase.increaseShortfallAllowance, (type(uint128).max))\n        );\n\n        Market memory market = _market(0);\n        _increaseCaps(abi.encode(\"this\", address(adapter)));\n        _increaseCaps(abi.encode(\"collateralToken\", address(collateralToken)));\n        _increaseCaps(\n            abi.encode(\n                \"collateralParams/rcfThreshold/liquidatorGate/enterGate\",\n                market.collateralParams,\n                market.rcfThreshold,\n                market.liquidatorGate,\n                market.enterGate\n            )\n        );\n        _increaseCaps(abi.encode(\"this/duration\", address(adapter), 7 days));\n\n        deal(address(underlyingToken), depositor, initialAssets);\n        vm.startPrank(depositor);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(vault), initialAssets);\n        vault.deposit(initialAssets, depositor);\n        vm.stopPrank();\n    }\n\n    function _ensureRateRatifier() internal {\n        if (address(rateSubRatifier) != address(0)) return;\n        rateSubRatifier = IMidnightAdapterRateRatifierV1(\n            deployCode(\"out/MidnightAdapterRateRatifierV1.sol/MidnightAdapterRateRatifierV1.json\")\n        );\n        vm.prank(allocator);\n        adapter.setIsSubRatifier(address(rateSubRatifier), true);\n    }\n\n    function testBuyAtTheRatifiedRateIsRejectedAfterContinuousFee() public {\n        _ensureRateRatifier();\n        Market memory market = _market(7 days);\n        bytes32 id = midnight.touchMarket(market);\n        uint256 units = 10_000 * oneToken;\n        Offer memory offer = _adapterOffer(market, true, TICK, units, keccak256(\"buy-fee-boundary\"));\n        uint256 rate = _impliedRate(TickLib.tickToPrice(TICK), market.maturity - block.timestamp);\n        bytes32 root = _hashRateOffer(offer, rate, address(0));\n        _ratify(root);\n\n        // The offer root is valid before any fee configuration change. Midnight applies the\n        // changed continuous fee at take time, and the adapter checks the resulting net credit.\n        _setMarketFees(id);\n        _setMinNetBuyRate(rate);\n        _fundBorrower(units);\n        uint256 pendingFeeAtFill = units * MAX_CONTINUOUS_FEE * (market.maturity - block.timestamp) / WAD;\n        emit log_named_uint(\"ratified offer price (WAD)\", TickLib.tickToPrice(TICK));\n        emit log_named_uint(\"ratified rate (per second, WAD)\", rate);\n        emit log_named_uint(\"continuous fee net-credit reduction (units)\", pendingFeeAtFill);\n        emit log_named_uint(\"adapter payment at maker quote (assets)\", units * TickLib.tickToPrice(TICK) / WAD);\n        bytes memory ratifierData = _rateData(root, rate);\n        assertEq(\n            rateSubRatifier.isRatified(offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), borrower),\n            keccak256(\"morpho.midnight.callbackSuccess\")\n        );\n\n        vm.expectRevert(IMidnightAdapterBase.NetBuyRateTooLow.selector);\n        vm.prank(borrower);\n        midnight.take(offer, ratifierData, units, borrower, borrower, address(0), \"\");\n    }\n\n    function testBuyOneSecondBeforeMaturityUsesFillTimeAndFeeAdjustedAmounts() public {\n        _ensureRateRatifier();\n        Market memory market = _market(7 days);\n        bytes32 id = midnight.touchMarket(market);\n        uint256 units = 10_000 * oneToken;\n        bytes32 group = keccak256(\"buy-one-second-left\");\n        Offer memory offer = _adapterOffer(market, true, TICK, units, group);\n        uint256 rate;\n        bytes32 root = _hashRateOffer(offer, rate, address(0));\n        _ratify(root);\n        _setMarketFees(id);\n        _fundBorrower(units);\n\n        vm.warp(market.maturity - 1);\n        bytes memory ratifierData = _rateData(root, rate);\n        assertEq(\n            rateSubRatifier.isRatified(offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), borrower),\n            keccak256(\"morpho.midnight.callbackSuccess\")\n        );\n        vm.prank(borrower);\n        (uint256 buyerAssets, uint256 sellerAssets) = midnight.take(\n            offer, ratifierData, units, borrower, borrower, address(0), \"\"\n        );\n\n        emit log_named_uint(\"buyer assets one second before maturity\", buyerAssets);\n        emit log_named_uint(\"seller assets one second before maturity\", sellerAssets);\n        emit log_named_uint(\"adapter pending continuous fee\", midnight.pendingFee(id, address(adapter)));\n        emit log_named_uint(\"adapter net rate after fees\", adapter.marketData(id).netRate);\n        emit log_named_uint(\"consumed units\", midnight.consumed(address(adapter), group));\n        assertGt(buyerAssets, sellerAssets, \"settlement fee must be charged at fill time\");\n        assertGt(midnight.pendingFee(id, address(adapter)), 0, \"continuous fee must be attached to new adapter credit\");\n        assertGt(adapter.marketData(id).netRate, 0, \"adapter stores a net rate after fees\");\n        assertEq(midnight.consumed(address(adapter), group), units);\n    }\n\n    function testBuyRootRemainsRateValidAtMaturityButAdapterRejectsMaturityAndAfter() public {\n        _ensureRateRatifier();\n        Market memory market = _market(7 days);\n        bytes32 id = midnight.touchMarket(market);\n        _setMarketFees(id);\n        uint256 units = 1_000 * oneToken;\n        _giveLenderCredit(market, units);\n\n        Offer memory offer = _adapterOffer(\n            market, true, TICK, units, keccak256(\"buy-maturity-boundary\")\n        );\n        offer.expiry = market.maturity + 1 days;\n        uint256 rate;\n        bytes32 root = _hashRateOffer(offer, rate, address(0));\n        _ratify(root);\n        bytes memory ratifierData = _rateData(root, rate);\n\n        vm.warp(market.maturity);\n        assertEq(\n            rateSubRatifier.isRatified(offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), lender),\n            keccak256(\"morpho.midnight.callbackSuccess\")\n        );\n        vm.expectRevert(IMidnightAdapterBase.BuyPostMaturity.selector);\n        vm.prank(lender);\n        midnight.take(offer, ratifierData, units, lender, lender, address(0), \"\");\n\n        vm.warp(market.maturity + 1);\n        assertEq(\n            rateSubRatifier.isRatified(offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), lender),\n            keccak256(\"morpho.midnight.callbackSuccess\")\n        );\n        vm.expectRevert(bytes4(keccak256(\"CannotIncreaseDebtPostMaturity()\")));\n        vm.prank(lender);\n        midnight.take(offer, ratifierData, units, lender, lender, address(0), \"\");\n    }\n\n    function testBuyCanFillOnceItsTtmFallsWithinMaxTtm() public {\n        vm.prank(curator);\n        adapter.decreaseMaxTtm(7 days);\n        Market memory market = _market(7 days + 1);\n        bytes32 id = midnight.touchMarket(market);\n        uint256 units = 1_000 * oneToken;\n        Offer memory offer = _adapterOffer(market, true, TICK, units, keccak256(\"max-ttm-boundary\"));\n        uint256 rate = _impliedRate(TickLib.tickToPrice(TICK), market.maturity - block.timestamp);\n        bytes32 root = _hashRateOffer(offer, rate, address(0));\n        _ratify(root);\n        _fundBorrowerMarket(market, units);\n\n        emit log_named_uint(\"TTM when root is ratified\", market.maturity - block.timestamp);\n        emit log_named_uint(\"adapter maxTtm\", 7 days);\n        assertEq(\n            rateSubRatifier.isRatified(offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), borrower),\n            keccak256(\"morpho.midnight.callbackSuccess\")\n        );\n        vm.expectRevert(IMidnightAdapterBase.BuyTtmTooHigh.selector);\n        vm.prank(borrower);\n        midnight.take(offer, _rateData(root, rate), units, borrower, borrower, address(0), \"\");\n\n        vm.warp(block.timestamp + 1);\n        assertEq(market.maturity - block.timestamp, 7 days);\n        assertEq(\n            rateSubRatifier.isRatified(offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), borrower),\n            keccak256(\"morpho.midnight.callbackSuccess\")\n        );\n        vm.prank(borrower);\n        midnight.take(offer, _rateData(root, rate), units, borrower, borrower, address(0), \"\");\n        assertEq(midnight.consumed(address(adapter), offer.group), units);\n        assertGt(adapter.marketData(id).netCredit, 0);\n    }\n\n    function testSellRateRatifierRejectsOldPriceNearAndAfterMaturity() public {\n        _createAdapterCredit();\n        _ensureRateRatifier();\n        Market memory market = _market(7 days);\n        uint256 units = 1_000 * oneToken;\n        Offer memory offer = _adapterOffer(market, false, TICK, units, keccak256(\"sell-maturity-boundary\"));\n        offer.expiry = market.maturity + 1 days;\n        offer.reduceOnly = true;\n        offer.receiverIfMakerIsSeller = address(adapter);\n        uint256 rate = _impliedRate(TickLib.tickToPrice(TICK), market.maturity - block.timestamp) + 1_000_000_000;\n        bytes32 root = _hashRateOffer(offer, rate, address(0));\n        _ratify(root);\n        bytes memory ratifierData = _rateData(root, rate);\n\n        assertEq(\n            rateSubRatifier.isRatified(offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), lender),\n            keccak256(\"morpho.midnight.callbackSuccess\")\n        );\n        for (uint256 timestamp = market.maturity - 1; timestamp <= market.maturity + 1; timestamp++) {\n            vm.warp(timestamp);\n            vm.expectRevert(IMidnightAdapterRateRatifierV1.WorsePrice.selector);\n            rateSubRatifier.isRatified(\n                offer, abi.encode(root, uint256(0), new bytes32[](0), rate, address(0)), lender\n            );\n            vm.expectRevert(IMidnightAdapterRateRatifierV1.WorsePrice.selector);\n            vm.prank(lender);\n            midnight.take(offer, ratifierData, units, lender, address(0), address(0), \"\");\n        }\n    }\n\n    function testSellOfferRateAndFeesAreCheckedOnMakersNetProceeds() public {\n        Market memory seedMarket = _market(7 days);\n        bytes32 seedId = IdLib.toId(seedMarket);\n        midnight.touchMarket(seedMarket);\n        _setContinuousFee(seedId, MAX_CONTINUOUS_FEE);\n        _createAdapterCredit();\n        _ensureRateRatifier();\n        (Offer memory offer, uint256 maxSellRate, bytes32 root, bytes32 id, uint256 creditBefore) =\n            this.prepareSellOffer();\n        uint256 feeBefore = midnight.pendingFee(id, address(adapter));\n        // The market fee changes after root ratification, but the adapter's existing position keeps\n        // the continuous-fee schedule fixed when it entered.\n        _setContinuousFee(id, 0);\n        bytes memory ratifierData = _rateData(root, maxSellRate);\n        (uint256 buyerAssets, uint256 sellerAssets) =\n            this.executeSellOffer(offer, ratifierData, 1_000 * oneToken);\n        uint256 ttm = offer.market.maturity - block.timestamp;\n        uint256 feeAfter = midnight.pendingFee(id, address(adapter));\n\n        emit log_named_uint(\"outsider buyer assets on adapter sell\", buyerAssets);\n        emit log_named_uint(\"adapter seller proceeds\", sellerAssets);\n        emit log_named_uint(\"adapter pending fee before sell\", feeBefore);\n        emit log_named_uint(\"adapter pending fee after sell\", feeAfter);\n        emit log_named_uint(\"maximum accepted net sell rate (per second, WAD)\", maxSellRate);\n        assertGt(buyerAssets, sellerAssets, \"taker pays the post-change settlement spread\");\n        assertLt(feeAfter, feeBefore, \"sell realizes the pre-existing continuous fee\");\n        assertGe(\n            sellerAssets,\n            1_000 * oneToken * WAD / (WAD + maxSellRate * ttm),\n            \"adapter receives within max net sell rate\"\n        );\n        assertEq(adapter.marketData(id).netCredit, creditBefore - (1_000 * oneToken - (feeBefore - feeAfter)));\n    }\n\n    function prepareSellOffer()\n        external\n        returns (Offer memory offer, uint256 maxSellRate, bytes32 root, bytes32 id, uint256 creditBefore)\n    {\n        require(msg.sender == address(this));\n        Market memory market = _market(7 days);\n        id = IdLib.toId(market);\n        uint256 units = 1_000 * oneToken;\n        uint256 price = TickLib.tickToPrice(TICK);\n        uint256 quoteRate = _impliedRate(price, market.maturity - block.timestamp);\n        maxSellRate = quoteRate + 1_000_000_000;\n        vm.prank(curator);\n        adapter.decreaseMaxNetSellRate(maxSellRate);\n\n        bytes32 group = keccak256(\"sell-fee-boundary\");\n        offer = _adapterOffer(market, false, TICK, units, group);\n        offer.reduceOnly = true;\n        offer.receiverIfMakerIsSeller = address(adapter);\n        root = _hashRateOffer(offer, maxSellRate, address(0));\n        _ratify(root);\n\n        // The same opaque root may be marked in both independent mappings. A price-ratifier\n        // proof cannot reinterpret the rate leaf or bypass its type-specific leaf hash.\n        vm.prank(allocator);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        bytes memory priceRatifierData = abi.encode(root, uint256(0), new bytes32[](0), address(0));\n        vm.expectRevert(IMidnightAdapterPriceRatifierV1.InvalidProof.selector);\n        priceSubRatifier.isRatified(offer, priceRatifierData, lender);\n\n        _setMarketFees(id);\n        creditBefore = adapter.marketData(id).netCredit;\n    }\n\n    function executeSellOffer(Offer calldata offer, bytes calldata ratifierData, uint256 units)\n        external\n        returns (uint256 buyerAssets, uint256 sellerAssets)\n    {\n        require(msg.sender == address(this));\n        uint256 price = TickLib.tickToPrice(offer.tick);\n        uint256 takerFunds = units * WAD / price + 10 * oneToken;\n        deal(address(underlyingToken), lender, takerFunds);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), takerFunds);\n        vm.stopPrank();\n        vm.prank(lender);\n        return midnight.take(offer, ratifierData, units, lender, address(0), address(0), \"\");\n    }\n\n    function testSharedBuyAndSellGroupAndOutsiderSetConsumed() public {\n        _createAdapterCredit();\n        _ensureRateRatifier();\n        Market memory market = _market(7 days);\n        uint256 groupUnits = 1_000 * oneToken;\n        uint256 buyUnits = 200 * oneToken;\n        bytes32 group = keccak256(\"shared-buy-sell-group\");\n\n        Offer memory buyOffer = _adapterOffer(market, true, TICK, groupUnits, group);\n        uint256 buyRate;\n        bytes32 buyRoot = _hashRateOffer(buyOffer, buyRate, address(0));\n        _ratify(buyRoot);\n        _fundBorrower(buyUnits);\n        vm.prank(borrower);\n        midnight.take(buyOffer, _rateData(buyRoot, buyRate), buyUnits, borrower, borrower, address(0), \"\");\n        assertEq(midnight.consumed(address(adapter), group), buyUnits);\n\n        vm.prank(outsider);\n        (bool success,) = address(midnight).call(\n            abi.encodeCall(IMidnight.setConsumed, (group, uint128(groupUnits), address(adapter)))\n        );\n        assertFalse(success, \"untrusted taker cannot change adapter consumption\");\n\n        Offer memory sellOffer = _adapterOffer(market, false, TICK, groupUnits, group);\n        sellOffer.reduceOnly = true;\n        sellOffer.receiverIfMakerIsSeller = address(adapter);\n        uint256 sellRate = _impliedRate(TickLib.tickToPrice(TICK), market.maturity - block.timestamp) + 1_000_000_000;\n        bytes32 sellRoot = _hashRateOffer(sellOffer, sellRate, address(0));\n        _ratify(sellRoot);\n        uint256 sellUnits = groupUnits - buyUnits;\n        uint256 funds = sellUnits + 2 * oneToken;\n        deal(address(underlyingToken), lender, funds);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), funds);\n        vm.stopPrank();\n        vm.prank(lender);\n        midnight.take(sellOffer, _rateData(sellRoot, sellRate), sellUnits, lender, address(0), address(0), \"\");\n\n        assertEq(midnight.consumed(address(adapter), group), groupUnits);\n    }\n\n    function _adapterOffer(Market memory market, bool buy, uint256 tick, uint256 maxUnits, bytes32 group)\n        internal\n        view\n        returns (Offer memory)\n    {\n        return Offer({\n            market: market,\n            buy: buy,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: tick,\n            group: group,\n            callback: address(adapter),\n            callbackData: buy ? abi.encode(address(0), bytes(\"\")) : bytes(\"\"),\n            receiverIfMakerIsSeller: buy ? address(0) : address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: false,\n            maxUnits: uint128(maxUnits),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n    }\n\n    function _ratify(bytes32 root) internal {\n        _ensureRateRatifier();\n        vm.prank(allocator);\n        rateSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n    }\n\n    function _rateData(bytes32 root, uint256 rate) internal view returns (bytes memory) {\n        return abi.encode(\n            address(rateSubRatifier), abi.encode(root, uint256(0), new bytes32[](0), rate, address(0))\n        );\n    }\n\n    function _setMinNetBuyRate(uint256 rate) internal {\n        vm.prank(curator);\n        adapter.increaseMinNetBuyRate(rate);\n    }\n\n    function _setMarketFees(bytes32 id) internal {\n        vm.prank(owner);\n        midnight.setFeeSetter(owner);\n        vm.prank(owner);\n        midnight.setMarketSettlementFee(id, 0, MAX_SETTLEMENT_FEE_0_DAYS);\n        vm.prank(owner);\n        midnight.setMarketSettlementFee(id, 1, MAX_SETTLEMENT_FEE_1_DAY);\n        vm.prank(owner);\n        midnight.setMarketSettlementFee(id, 2, MAX_SETTLEMENT_FEE_7_DAYS);\n        vm.prank(owner);\n        midnight.setMarketContinuousFee(id, MAX_CONTINUOUS_FEE);\n    }\n\n    function _setContinuousFee(bytes32 id, uint256 fee) internal {\n        vm.prank(owner);\n        midnight.setFeeSetter(owner);\n        vm.prank(owner);\n        midnight.setMarketContinuousFee(id, fee);\n    }\n\n    function _fundBorrower(uint256 units) internal {\n        _fundBorrowerMarket(_market(7 days), units);\n    }\n\n    function _fundBorrowerMarket(Market memory market, uint256 units) internal {\n        uint256 collateral = units * 2;\n        deal(address(collateralToken), borrower, collateral);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, borrower);\n        vm.stopPrank();\n    }\n\n    function _createAdapterCredit() internal {\n        // Leave liquid vault assets available for settlement fees and later partial buys.\n        uint256 units = (initialAssets / 2) * WAD / TickLib.tickToPrice(TICK);\n        Market memory market = _market(7 days);\n        Offer memory offer = _adapterOffer(\n            market, true, TICK, units, keccak256(abi.encode(\"seed-buy\", market.maturity, units))\n        );\n        bytes32 root = _hashPriceOffer(offer, address(0));\n        vm.prank(allocator);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        bytes memory ratifierData = abi.encode(\n            address(priceSubRatifier), abi.encode(root, uint256(0), new bytes32[](0), address(0))\n        );\n        uint256 collateral = units * 2;\n        deal(address(collateralToken), borrower, collateral);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, borrower);\n        midnight.take(offer, ratifierData, units, borrower, borrower, address(0), \"\");\n        vm.stopPrank();\n    }\n\n    function _giveLenderCredit(Market memory market, uint256 units) internal {\n        Offer memory offer = Offer({\n            market: market,\n            buy: false,\n            maker: borrower,\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: TICK,\n            group: keccak256(\"borrower-credit-seed\"),\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        _fundBorrower(units);\n        bytes32 root = _hashOffer(offer);\n        bytes32[] memory proof = new bytes32[](0);\n        vm.startPrank(borrower);\n        midnight.setIsAuthorized(address(setterRatifier), true, borrower);\n        setterRatifier.setIsRootRatified(borrower, root, true);\n        vm.stopPrank();\n\n        uint256 assets = units + oneToken;\n        deal(address(underlyingToken), lender, assets);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), assets);\n        midnight.take(offer, abi.encode(root, uint256(0), proof), units, lender, address(0), address(0), \"\");\n        vm.stopPrank();\n    }\n\n    function _impliedRate(uint256 price, uint256 ttm) internal pure returns (uint256) {\n        return (WAD - price) * WAD / price / ttm;\n    }\n\n    function _hashCollateral(CollateralParams memory collateral) internal pure returns (bytes32) {\n        bytes32[] memory words = new bytes32[](5);\n        words[0] = COLLATERAL_PARAMS_TYPEHASH;\n        words[1] = _addressWord(collateral.token);\n        words[2] = bytes32(collateral.lltv);\n        words[3] = bytes32(collateral.liquidationCursor);\n        words[4] = _addressWord(collateral.oracle);\n        return _hashWords(words);\n    }\n\n    function _hashMarket(Market memory market) internal pure returns (bytes32) {\n        bytes32[] memory collateralHashes = new bytes32[](market.collateralParams.length);\n        for (uint256 i; i < market.collateralParams.length; i++) {\n            collateralHashes[i] = _hashCollateral(market.collateralParams[i]);\n        }\n        bytes32[] memory words = new bytes32[](9);\n        words[0] = MARKET_TYPEHASH;\n        words[1] = bytes32(market.chainId);\n        words[2] = _addressWord(market.midnight);\n        words[3] = _addressWord(market.loanToken);\n        words[4] = _hashWords(collateralHashes);\n        words[5] = bytes32(market.maturity);\n        words[6] = bytes32(market.rcfThreshold);\n        words[7] = _addressWord(market.enterGate);\n        words[8] = _addressWord(market.liquidatorGate);\n        return _hashWords(words);\n    }\n\n    function _hashOffer(Offer memory offer) internal pure returns (bytes32) {\n        bytes32[] memory words = new bytes32[](16);\n        words[0] = OFFER_TYPEHASH;\n        words[1] = _hashMarket(offer.market);\n        words[2] = _boolWord(offer.buy);\n        words[3] = _addressWord(offer.maker);\n        words[4] = bytes32(offer.start);\n        words[5] = bytes32(offer.expiry);\n        words[6] = bytes32(offer.tick);\n        words[7] = offer.group;\n        words[8] = _addressWord(offer.callback);\n        words[9] = keccak256(offer.callbackData);\n        words[10] = _addressWord(offer.receiverIfMakerIsSeller);\n        words[11] = _addressWord(offer.ratifier);\n        words[12] = _boolWord(offer.reduceOnly);\n        words[13] = bytes32(uint256(offer.maxUnits));\n        words[14] = bytes32(uint256(offer.maxAssets));\n        words[15] = bytes32(offer.continuousFeeCap);\n        return _hashWords(words);\n    }\n\n    function _hashPriceOffer(Offer memory offer, address allowedTaker) internal pure returns (bytes32) {\n        bytes32[] memory words = new bytes32[](17);\n        words[0] = PRICE_RATIFIER_V1_OFFER_TYPEHASH;\n        words[1] = _hashMarket(offer.market);\n        words[2] = _boolWord(offer.buy);\n        words[3] = _addressWord(offer.maker);\n        words[4] = bytes32(offer.start);\n        words[5] = bytes32(offer.expiry);\n        words[6] = bytes32(offer.tick);\n        words[7] = _addressWord(allowedTaker);\n        words[8] = offer.group;\n        words[9] = _addressWord(offer.callback);\n        words[10] = keccak256(offer.callbackData);\n        words[11] = _addressWord(offer.receiverIfMakerIsSeller);\n        words[12] = _addressWord(offer.ratifier);\n        words[13] = _boolWord(offer.reduceOnly);\n        words[14] = bytes32(uint256(offer.maxUnits));\n        words[15] = bytes32(uint256(offer.maxAssets));\n        words[16] = bytes32(offer.continuousFeeCap);\n        return _hashWords(words);\n    }\n\n    function _hashRateOffer(Offer memory offer, uint256 rate, address allowedTaker) internal pure returns (bytes32) {\n        bytes32[] memory words = new bytes32[](17);\n        words[0] = RATE_RATIFIER_V1_OFFER_TYPEHASH;\n        words[1] = _hashMarket(offer.market);\n        words[2] = _boolWord(offer.buy);\n        words[3] = _addressWord(offer.maker);\n        words[4] = bytes32(offer.start);\n        words[5] = bytes32(offer.expiry);\n        words[6] = bytes32(rate);\n        words[7] = _addressWord(allowedTaker);\n        words[8] = offer.group;\n        words[9] = _addressWord(offer.callback);\n        words[10] = keccak256(offer.callbackData);\n        words[11] = _addressWord(offer.receiverIfMakerIsSeller);\n        words[12] = _addressWord(offer.ratifier);\n        words[13] = _boolWord(offer.reduceOnly);\n        words[14] = bytes32(uint256(offer.maxUnits));\n        words[15] = bytes32(uint256(offer.maxAssets));\n        words[16] = bytes32(offer.continuousFeeCap);\n        return _hashWords(words);\n    }\n\n    function _addressWord(address account) internal pure returns (bytes32) {\n        return bytes32(uint256(uint160(account)));\n    }\n\n    function _boolWord(bool value) internal pure returns (bytes32) {\n        return bytes32(value ? uint256(1) : uint256(0));\n    }\n\n    function _hashWords(bytes32[] memory words) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            result := keccak256(add(words, 0x20), mul(mload(words), 0x20))\n        }\n    }\n\n    function _submitAndSet(address target, bytes memory data) internal {\n        vm.prank(curator);\n        IVaultV2(target).submit(data);\n        (bool success, bytes memory returnData) = target.call(data);\n        if (!success) {\n            assembly (\"memory-safe\") {\n                revert(add(returnData, 32), mload(returnData))\n            }\n        }\n    }\n\n    function _increaseCaps(bytes memory idData) internal {\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.increaseAbsoluteCap, (idData, type(uint128).max)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.increaseRelativeCap, (idData, 1e18)));\n    }\n\n    function _market(uint256 duration) internal view returns (Market memory market) {\n        CollateralParams[] memory collaterals = new CollateralParams[](1);\n        collaterals[0] = collateralParams;\n        market = Market({\n            chainId: block.chainid,\n            midnight: address(midnight),\n            loanToken: address(underlyingToken),\n            collateralParams: collaterals,\n            maturity: block.timestamp + duration,\n            rcfThreshold: 0,\n            enterGate: address(0),\n            liquidatorGate: address(0)\n        });\n    }\n}\n"
      },
      "priorAuditCheck": "TrustSec TRST-L-4 (p. 11) covers an allocator taking an external offer and explicitly says the adapter’s own offers are unaffected; this maker-side rate-ratifier lead is distinct. Cantina §3.2.9 (p. 10) reports the separate root-ratifier offer.ratifier identity omission; it is excluded. In this test, a rate root also stored in the price ratifier does not prove the price-ratifier typed leaf, and that call reverts InvalidProof.",
      "integrationFixtureInheritanceAttempt": {
        "command": "forge test --match-path test/poc/RateRatifierFeeBoundaryTest.sol -vv",
        "exitCode": 1,
        "output": "Error: Compiler run failed:\nError (4619): Function \"clz\" not found.\n  --> lib/midnight/src/libraries/UtilsLib.sol:49:29:\n   |\n49 |             res := sub(255, clz(bitmap))\n   |                             ^^^\n\nError (3950): Expected expression to evaluate to one value, but got 0 values instead.\n  --> lib/midnight/src/libraries/UtilsLib.sol:49:29:\n   |\n49 |             res := sub(255, clz(bitmap))\n   |                             ^^^^^^^^^^^"
      }
    },
    "command": "forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol lib/morpho-blue/src/Morpho.sol\nforge test --match-path test/MidnightAdapterTest.sol -vv\nforge test --match-path test/integration/MidnightAdapterIntegrationTest.sol -vv\nforge test --match-path test/MidnightAdapterRatifiersV1Test.sol -vv\nforge test --match-path test/poc/RateRatifierFeeBoundaryTest.sol -vv",
    "output": "BUILD\nCompiling 13 files with Solc 0.8.19\nCompiling 6 files with Solc 0.8.34\nCompiling 15 files with Solc 0.8.34\nSolc 0.8.34 finished in 56.49ms\nSolc 0.8.34 finished in 9.01s\nSolc 0.8.19 finished in 9.35s\nCompiler run successful!\n\nMIDNIGHT ADAPTER TEST (selected exact output lines)\n[PASS] testSetConsumedNotAuthorized(address) (runs: 2048, μ: 55312, ~: 55312)\nSuite result: ok. 314 passed; 0 failed; 0 skipped; finished in 410.00s (1617.09s CPU time)\nRan 1 test suite in 410.03s (410.00s CPU time): 314 tests passed, 0 failed, 0 skipped (314 total tests)\n\nINTEGRATION TEST\nNo files changed, compilation skipped\nRan 8 tests for test/integration/MidnightAdapterIntegrationTest.sol:MidnightAdapterIntegrationTest\n[PASS] testForceDeallocate() (gas: 1750522)\n[PASS] testForceSell() (gas: 1652652)\n[PASS] testMakerBuy() (gas: 1130017)\n[PASS] testMakerSell() (gas: 1920488)\n[PASS] testRepayWithdrawRedeem() (gas: 1780100)\n[PASS] testTakerBuy() (gas: 1166436)\n[PASS] testTakerSell() (gas: 1958207)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 17206411)\nSuite result: ok. 8 passed; 0 failed; 0 skipped; finished in 22.82ms (28.86ms CPU time)\nRan 1 test suite in 54.15ms (22.82ms CPU time): 8 tests passed, 0 failed, 0 skipped (8 total tests)\n\nRATIFIER TESTS (actual final summary)\nSuite result: ok. 38 passed; 0 failed; 0 skipped; finished in 7.39s (14.36s CPU time)\nSuite result: ok. 36 passed; 0 failed; 0 skipped; finished in 7.65s (13.63s CPU time)\nRan 3 test suites in 7.65s (15.05s CPU time): 75 tests passed, 0 failed, 0 skipped (75 total tests)\n\nFOCUSED RATE-RATIFIER FEE TESTS\nNo files changed, compilation skipped\nRan 7 tests for test/poc/RateRatifierFeeBoundaryTest.sol:RateRatifierFeeBoundaryTest\n[PASS] testBuyAtTheRatifiedRateIsRejectedAfterContinuousFee() (gas: 2691610)\nLogs:\n  ratified offer price (WAD): 994100700000000000\n  ratified rate (per second, WAD): 9812017633\n  continuous fee net-credit reduction (units): 1917808214112000000\n  adapter payment at maker quote (assets): 9941007000000000000000\n\n[PASS] testBuyCanFillOnceItsTtmFallsWithinMaxTtm() (gas: 3021439)\nLogs:\n  TTM when root is ratified: 604801\n  adapter maxTtm: 604800\n\n[PASS] testBuyOneSecondBeforeMaturityUsesFillTimeAndFeeAdjustedAmounts() (gas: 2998111)\nLogs:\n  buyer assets one second before maturity: 9941007000000000000000\n  seller assets one second before maturity: 9940867000000000000000\n  adapter pending continuous fee: 3170979190000\n  adapter net rate after fees: 5934307945766541\n  consumed units: 10000000000000000000000\n\n[PASS] testBuyRootRemainsRateValidAtMaturityButAdapterRejectsMaturityAndAfter() (gas: 3502458)\n[PASS] testSellOfferRateAndFeesAreCheckedOnMakersNetProceeds() (gas: 3632850)\nLogs:\n  outsider buyer assets on adapter sell: 994198700000000000000\n  adapter seller proceeds: 994100700000000000000\n  adapter pending fee before sell: 9645945396236015124\n  adapter pending fee after sell: 9454164574824815124\n  maximum accepted net sell rate (per second, WAD): 10812017633\n\n[PASS] testSellRateRatifierRejectsOldPriceNearAndAfterMaturity() (gas: 3047444)\n[PASS] testSharedBuyAndSellGroupAndOutsiderSetConsumed() (gas: 3922543)\nSuite result: ok. 7 passed; 0 failed; 0 skipped; finished in 25.01ms (39.90ms CPU time)\nRan 1 test suite in 44.28ms (25.01ms CPU time): 7 tests passed, 0 failed, 0 skipped (7 total tests)"
  },
  "notCovered": [
    "The complete repository-wide Foundry suite was not run. The pinned production build, the MidnightAdapter unit suite, the integration suite, the ratifier suites, and the focused PoC were run.",
    "The focused PoC does not inherit MidnightAdapterIntegrationTest.sol. An inheritance attempt compiled its import graph with solc 0.8.28 and failed at lib/midnight/src/libraries/UtilsLib.sol:49 with Error (4619): Function \"clz\" not found. The standalone test instead deploys the pinned production Vault V2, Midnight, adapter, and ratifier artifacts; it does not mock Midnight or Vault V2. The existing integration fixture was separately run and passed 8/8.",
    "No separate agent performed an independent clean-clone refutation. No candidate was found, so there is no finding retained pending that verification."
  ]
}
