{
 "angle": "accounting and rounding in buy, sell, hold and withdraw (MidnightAdapter.onBuy/onSell, take, allocate, deallocate, withdrawToVault, currentNetCredit, realAssets)",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": true,
 "candidates": [
  {
   "id": "ACC-1",
   "title": "shortfallAllowance consumption is path-dependent: a shortfall sale split into pieces re-counts shortfall already absorbed by the sold market, and any outside taker can split fills of the adapter's maker sell offer to exhaust the allowance early",
   "severity": "Low",
   "impact": "Low",
   "likelihood": "Medium",
   "severityReasoning": "No assets are lost or misvalued: book value and netRate end up the same, within rounding, whether a sale is done at once or in pieces. The only effect is that the curator's shortfallAllowance guardrail is used up faster than the economic shortfall. In the PoC, 20 pieces use 5.05% more allowance (52.599 vs 50.070 tokens on a 10,000-unit sale). With an allowance sized for the sale (51 tokens), the piecewise fill reverts with ShortfallAllowanceExceeded after 9,500 of 10,000 units. Further shortfall sales (allocator takes and maker-offer fills) are then blocked until the curator raises the allowance again through the timelock. Likelihood is Medium: any outside party filling an allocator-ratified maker sell offer chooses the fill size, and this costs them nothing beyond gas because they pay the same price per unit. Allocators splitting large sales for liquidity reasons hit it without any attacker. Cantina matrix: Low impact x Medium likelihood = Low. The README says these settings are for operational quality of life, not depositor guarantees, so a judge could downgrade this to Informational.",
   "files": [
    {
     "path": "src/adapters/midnight/MidnightAdapter.sol",
     "lines": "641-648 (soldAmortizedValue/shortfall measured at the market's current, possibly already reduced, netRate; allowance decremented)"
    },
    {
     "path": "src/adapters/midnight/MidnightAdapter.sol",
     "lines": "653-686 (shortfall spread includes the sold market itself, raising the amortized value of its remaining credit)"
    },
    {
     "path": "src/adapters/midnight/MidnightAdapter.sol",
     "lines": "145-148 (shortfallAllowance NatSpec: 'Total shortfall that sales can still incur. Each sale with a shortfall consumes it.')"
    }
   ],
   "description": "Root cause: in onSell, the shortfall is soldAmortizedValue - sellerAssets, where soldAmortizedValue is the difference of the sold market's amortized values at its current netRate (L643-645). A non-forceSellable shortfall is then spread over all active markets' unearned interest by lowering their netRate (L653-686). The sold market is one of them, so the remaining credit of the sold market takes part of the shortfall and its amortized value per unit rises. When that same credit is sold next at the same price, its soldAmortizedValue is measured at the lowered rate. The part of the earlier shortfall it absorbed is therefore counted again as new shortfall and taken from shortfallAllowance a second time (L647-648). Splitting one sale into k pieces consumes strictly more allowance than selling at once, even though the vault's final state (idle + realAssets, netRate) is the same within rounding. Attack steps: (1) The allocator ratifies a maker sell offer (e.g. via MidnightAdapterPriceRatifierV1) at a price slightly below amortized value. The curator has sized shortfallAllowance for this offer. (2) Any taker fills it with many small midnight.take calls instead of one. The price paid per unit is the same, so it costs the taker nothing but gas. (3) Each fill after the first re-counts the shortfall already absorbed by the sold market's remaining credit. The allowance runs out before the offer is fully filled (the PoC reverts with ShortfallAllowanceExceeded after 9,500 of 10,000 units). All other shortfall sales in every non-forceSellable market are then blocked until the curator raises the allowance again through the timelocked increaseShortfallAllowance. Who loses what: no funds are lost. The curator's guardrail is drained by about 5% more than the actual shortfall in the 20-piece example, and the effect grows with the share of the market being sold. Allocators lose the ability to make shortfall sales, for example to exit a deteriorating market before it is forceSellable, for at least the timelock duration. Numbers (real Midnight + real VaultV2, 100k assets bought at ~0.994 for 7 days, 1 day elapsed, 10,000 units sold at 0.9899322): single sale consumes 50.069921111211219809 tokens of allowance; 20 equal sales consume 52.599017994081945687 (+2.529096882870725878, +5.05%). Final netRate 8735599645 vs 8735599636 and idle+realAssets 100084.346798189681319247 vs 100084.346798608551701820, so the economic outcome is identical.",
   "poc": {
    "path": "test/poc/ShortfallAllowanceChunking.t.sol",
    "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {console2} from \"../../lib/forge-std/src/console2.sol\";\nimport {MidnightAdapterIntegrationTest} from \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {SafeERC20Lib} from \"../../src/libraries/SafeERC20Lib.sol\";\nimport {WAD} from \"../../src/libraries/ConstantsLib.sol\";\nimport {MarketData} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {Market, Offer} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {HashLib} from \"../../lib/midnight/src/ratifiers/libraries/HashLib.sol\";\nimport {IdLib} from \"../../lib/midnight/src/libraries/IdLib.sol\";\nimport {TickLib} from \"../../lib/midnight/src/libraries/TickLib.sol\";\n\n/// @dev shortfallAllowance consumption depends on how a shortfall sale is split.\n/// @dev Real Midnight + real VaultV2, setup of MidnightAdapterIntegrationTest (100k assets bought at ~0.994, 7 days).\ncontract ShortfallAllowanceChunkingPoC is MidnightAdapterIntegrationTest {\n    Market internal mkt;\n\n    function _buyAll() internal {\n        // Same as testMakerBuy: the adapter buys `units` credit maturing in 7 days at TICK (~0.994).\n        testMakerBuy();\n        mkt = _market(7 days);\n        // One day later the position has accrued interest, then it is partly sold at 0.99 (below amortized value).\n        vm.warp(block.timestamp + 1 days);\n    }\n\n    function _tick099() internal pure returns (uint256 tick) {\n        tick = TICK;\n        while (TickLib.tickToPrice(tick) > 0.99e18) tick -= 4;\n    }\n\n    function _vaultValue() internal view returns (uint256) {\n        return underlyingToken.balanceOf(address(vault)) + adapter.realAssets();\n    }\n\n    /// @dev An adapter maker sell offer, ratified by the allocator, is filled by an outside taker once or in 20 pieces.\n    function testMakerSellFilledInPiecesConsumesMoreAllowance() public {\n        _buyAll();\n        uint256 sold = 10_000 * oneToken;\n        uint256 tick = _tick099();\n        vm.prank(curator);\n        adapter.decreaseShortfallAllowance(type(uint128).max);\n        _submitAndSet(address(adapter), abi.encodeCall(adapter.increaseShortfallAllowance, (51 * oneToken)));\n        Offer memory offer = Offer({\n            market: mkt,\n            buy: false,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: mkt.maturity,\n            tick: tick,\n            group: keccak256(abi.encode(\"sell\", mkt.maturity, sold)),\n            callback: address(adapter),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: true,\n            maxUnits: uint128(sold),\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        bytes memory ratifierData =\n            abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), new bytes32[](0), address(0)));\n        deal(address(underlyingToken), lender, sold);\n        vm.prank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n\n        uint256 allowance0 = adapter.shortfallAllowance();\n        uint256 value0 = _vaultValue();\n        console2.log(\"allowance before\", allowance0);\n        console2.log(\"sale price (WAD)\", TickLib.tickToPrice(tick));\n\n        uint256 snap = vm.snapshotState();\n        vm.prank(lender);\n        midnight.take(offer, ratifierData, sold, lender, address(0), address(0), \"\");\n        uint256 usedOne = allowance0 - adapter.shortfallAllowance();\n        uint256 valueOne = _vaultValue();\n        console2.log(\"1 fill:   allowance consumed\", usedOne);\n        console2.log(\"1 fill:   idle+realAssets\", valueOne);\n\n        vm.revertToState(snap);\n        uint256 n = 20;\n        uint256 filled;\n        for (uint256 i; i < n; i++) {\n            vm.prank(lender);\n            try midnight.take(offer, ratifierData, sold / n, lender, address(0), address(0), \"\") {\n                filled += sold / n;\n            } catch (bytes memory reason) {\n                console2.log(\"fill reverted at piece\", i);\n                console2.logBytes(reason);\n                break;\n            }\n        }\n        uint256 usedMany = allowance0 - adapter.shortfallAllowance();\n        console2.log(\"20 fills: units filled\", filled);\n        console2.log(\"20 fills: allowance consumed\", usedMany);\n        console2.log(\"20 fills: idle+realAssets\", _vaultValue());\n        console2.log(\"idle+realAssets before\", value0);\n\n        // The single fill fits the 51-token allowance; the same sale in 20 pieces exhausts it before completing.\n        assertEq(usedOne < 51 * oneToken, true, \"single fill fits allowance\");\n        assertLt(filled, sold, \"pieces cannot complete the same sale\");\n    }\n\n    /// @dev Same sale through allocator takes: once vs 20 takes. Book value is preserved in both, allowance use differs.\n    function testAllocatorSaleInPiecesConsumesMoreAllowance() public {\n        _buyAll();\n        uint256 sold = 10_000 * oneToken;\n        uint256 tick = _tick099();\n        Offer memory offer = Offer({\n            market: mkt,\n            buy: true,\n            maker: lender,\n            start: block.timestamp,\n            expiry: mkt.maturity,\n            tick: tick,\n            group: keccak256(abi.encode(\"lender\", mkt.maturity, sold)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(0),\n            ratifier: address(setterRatifier),\n            reduceOnly: false,\n            maxUnits: uint128(sold),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        deal(address(underlyingToken), lender, sold);\n        bytes32 root = HashLib.hashOffer(offer);\n        bytes memory data = abi.encode(root, uint256(0), 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\n        uint256 allowance0 = adapter.shortfallAllowance();\n        uint256 value0 = _vaultValue();\n        console2.log(\"idle+realAssets before\", value0);\n\n        uint256 snap = vm.snapshotState();\n        vm.prank(allocator);\n        adapter.take(offer, data, sold, \"\");\n        uint256 usedOne = allowance0 - adapter.shortfallAllowance();\n        uint256 valueOne = _vaultValue();\n        MarketData memory a = adapter.marketData(IdLib.toId(mkt));\n        console2.log(\"1 take:   allowance consumed\", usedOne);\n        console2.log(\"1 take:   idle+realAssets\", valueOne);\n        console2.log(\"1 take:   netRate\", a.netRate);\n\n        vm.revertToState(snap);\n        for (uint256 i; i < 20; i++) {\n            vm.prank(allocator);\n            adapter.take(offer, data, sold / 20, \"\");\n        }\n        uint256 usedMany = allowance0 - adapter.shortfallAllowance();\n        uint256 valueMany = _vaultValue();\n        MarketData memory b = adapter.marketData(IdLib.toId(mkt));\n        console2.log(\"20 takes: allowance consumed\", usedMany);\n        console2.log(\"20 takes: idle+realAssets\", valueMany);\n        console2.log(\"20 takes: netRate\", b.netRate);\n        console2.log(\"extra allowance consumed\", usedMany - usedOne);\n\n        // Same economic outcome (rates and book value within 1e-6 of a token)...\n        assertApproxEqAbs(valueMany, valueOne, oneToken / 1e6, \"same book value\");\n        assertApproxEqAbs(uint256(b.netRate), uint256(a.netRate), 100, \"same rate\");\n        // ...but ~5% more allowance consumed.\n        assertGt(usedMany, usedOne + usedOne / 25, \"chunked sale consumes >4% more allowance\");\n    }\n}\n",
    "command": "forge test --offline --match-path test/poc/ShortfallAllowanceChunking.t.sol -vv   (run at the repo root of morpho-org/vault-v2 @ bbeda7b27ae80abcf070e0158cb8a31e87bb2286 with src/ and lib/ unmodified; forge 1.6.0-nightly 5e88010a; required artifacts were prebuilt with: forge build --offline lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol src/VaultV2.sol src/VaultV2Factory.sol src/adapters/midnight/MidnightAdapterFactory.sol src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol test/imports/MidnightImport.sol)",
    "output": "Compiling 1 files with Solc 0.8.28\nSolc 0.8.28 finished in 35.57s\nCompiler run successful!\n\nRan 10 tests for test/poc/ShortfallAllowanceChunking.t.sol:ShortfallAllowanceChunkingPoC\n[PASS] testAllocatorSaleInPiecesConsumesMoreAllowance() (gas: 3933897)\nLogs:\n  idle+realAssets before 100084346798178607255874\n  1 take:   allowance consumed 50069921111211219809\n  1 take:   idle+realAssets 100084346798189681319247\n  1 take:   netRate 8735599645\n  20 takes: allowance consumed 52599017994081945687\n  20 takes: idle+realAssets 100084346798608551701820\n  20 takes: netRate 8735599636\n  extra allowance consumed 2529096882870725878\n\n[PASS] testForceDeallocate() (gas: 1184052)\n[PASS] testForceSell() (gas: 1182009)\n[PASS] testMakerBuy() (gas: 881516)\n[PASS] testMakerSell() (gas: 1335294)\n[PASS] testMakerSellFilledInPiecesConsumesMoreAllowance() (gas: 3898644)\nLogs:\n  allowance before 51000000000000000000\n  sale price (WAD) 989932200000000000\n  1 fill:   allowance consumed 50069921111211219809\n  1 fill:   idle+realAssets 100084346798189681319247\n  fill reverted at piece 19\n  0x8ea54d94\n  20 fills: units filled 9500000000000000000000\n  20 fills: allowance consumed 49834436012548795750\n  20 fills: idle+realAssets 100084346798597656807086\n  idle+realAssets before 100084346798178607255874\n\n[PASS] testRepayWithdrawRedeem() (gas: 1166267)\n[PASS] testTakerBuy() (gas: 899462)\n[PASS] testTakerSell() (gas: 1362766)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 14735455)\nSuite result: ok. 10 passed; 0 failed; 0 skipped; finished in 40.84ms (96.41ms CPU time)\n\nRan 1 test suite in 43.39ms (40.84ms CPU time): 10 tests passed, 0 failed, 0 skipped (10 total tests)\n\n(0x8ea54d94 == cast sig \"ShortfallAllowanceExceeded()\". The 8 untitled PASS lines are the inherited spec tests of MidnightAdapterIntegrationTest.)"
   },
   "fix": "Make allowance consumption independent of how a sale is split. Option A: charge shortfallAllowance only with the part of the shortfall taken by markets other than the sold one, plus the sold market's share times soldNetCredit / (soldNetCredit + newNetCredit). In other words, do not charge the allowance for interest re-absorbed by credit that has itself just been sold. Option B: measure the sold market's soldAmortizedValue at a reference rate that is not lowered by earlier shortfall absorption (store e.g. a per-market buyNetRate updated only in onBuy) and consume allowance with max(0, valueAtReferenceRate - sellerAssets). At minimum, document in the shortfallAllowance NatSpec and README that consumption depends on the path and can be raised by takers splitting fills of maker sell offers. Curators should size allowances with margin, and sub-ratifiers could add a minimum fill size for sell offers. These fix options were not implemented or tested (UNVERIFIED).",
   "priorAuditCheck": "Both drafts (Cantina 2026-10-12 and TrustSec 2026-10-12, reviewed at commit 6476e9d9) predate shortfallAllowance. Neither contains the terms shortfallAllowance, netRate, minNetBuyRate or maxNetSellRate. The closest items differ. Cantina 3.1.1 says blended-rate updates hide round-trip losses: that is about the loss being deferred, not about the allowance being over-consumed. Cantina 3.2.8/3.2.11/3.6.6 and TRST-R-14 are about rate rounding, at the wei level, which is far smaller than the 5% effect shown here. Cantina 3.2.7/3.6.4 cover sale-policy flags. NatSpec L146 notes that rounding can lower interest by slightly more than the allowance consumed, which is the opposite direction and a rounding remark. Caveat: the PDF audit summaries were produced by a reader subagent and spot-checked only through its report.",
   "outOfScopeCheck": "The fill-splitting variant is driven by an untrusted outside taker of an allocator-ratified maker sell offer, so it is not just expected behaviour of a trusted role. The allocator-take variant alone would be trusted-role behaviour. Neither the README nor the NatSpec lists path-dependent allowance consumption as an accepted risk. The README does describe the guardrails as 'intended for operational quality of life, not to provide guarantees to depositors', which limits the impact to operations (no depositor loss)."
  }
 ],
 "lowInfo": [
  {
   "title": "forceDeallocate pulls the settlement fee rounded up, so dust can stay on the adapter and go to skimRecipient instead of the vault",
   "class": "Informational",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:453-456",
    "src/adapters/midnight/MidnightAdapter.sol:395-400"
   ],
   "detail": "settlementFeeAssets = assets.mulDivUp(settlementFee, WAD) is pulled from the sender. If Midnight's own fee computation for the take rounds differently, up to 1 wei per forceDeallocate stays on the adapter, and skim(asset) sends it to skimRecipient. The amount is negligible. Not checked against Midnight's take arithmetic (UNVERIFIED)."
  },
  {
   "title": "Rate rounding gives a small immediate book-value gain on each buy (documented); measured and found negligible",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:544-547",
    "src/adapters/midnight/MidnightAdapter.sol:22"
   ],
   "detail": "Measured with real Midnight + VaultV2 (scratch test test/poc/AccountingRounding.t.sol, testBuyChunking). A 100k-asset maker buy at ~0.994 for 7 days raises idle+realAssets from 100000e18 to 100000000000030600145312, an immediate gain of 3.06e7 wei (3e-11 of the position). Filling it in 50 pieces adds only 42 wei more. NatSpec L22 documents this, and the prior audits cover it (Cantina 3.2.8/3.6.6, TRST-R-14). Listed only to record that it was measured, not as a new issue."
  },
  {
   "title": "Zero-unit fills of the adapter's maker buy offer cannot move netRate down or inflate realAssets at this commit",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:544-547"
   ],
   "detail": "Unlike the audited version (Cantina 3.2.8, which rounded carried value up), the carried value is now floored (mulDivDown at L545), so the recomputed rate floor((NC-AV)/(AV*ttm)) is >= the old rate and realAssets cannot drift up. Measured: 30 zero-unit fills by an outside party were all accepted, netRate stayed 9812017633, and realAssets stayed 50042173399089303627936 (scratch test testZeroUnitFills). The 0-unit fills can still fill marketIds toward MAX_MARKETS, which L96 documents."
  }
 ],
 "covered": [
  "Build: cloned vault-v2 at bbeda7b2 with submodules. Ran the Midnight adapter integration suite (test/integration/MidnightAdapterIntegrationTest.sol) on real Midnight + real VaultV2: 8/8 passed. A full `forge build` did not finish within this machine's 10-minute command limit (via_ir, many compiler profiles), so the needed artifacts were built with targeted `forge build <paths>`.",
  "onBuy accounting (L535-562): boughtNetCredit = units - pendingFeeIncrease, the BuyAtLoss and minNetBuyRate checks, blended netRate from floored carried value plus buyerAssets, and the in-progress transient values used by realAssets during accrueInterest (pre-buy state, so the vault's interest accrual excludes the unpaid purchase). Measured chunking drift (42 wei / 100k) and 0-unit fills (no drift).",
  "onSell accounting (L633-699): soldNetCredit after pendingFeeDecrease, maxNetSellRate bound (rounded up, conservative), soldAmortizedValue as difference of floors, shortfall spreading with targets rounded up and rates floored, early break, and the require(shortfall <= totalInterest). Measured single vs 20-piece sales: book value preserved (drift under 5e-7 tokens), allowance consumption path-dependent (ACC-1).",
  "Vault interaction: VaultV2.deallocateInternal does not accrue interest (VaultV2.sol:567-586), so onSell/withdrawToVault do not create a mid-callback undercount. allocateInternal accrues interest but onBuy pre-accrues with in-progress state. Upward jumps in realAssets (gains on sale, early withdraw of repaid credit, forceDeallocate at face value) are capped by VaultV2 maxRate in accrueInterestView (VaultV2.sol:633-634). Early-withdrawal timing is already Cantina 3.6.5, and forceDeallocate accrual is TRST-R-3.",
  "Pending fees: Midnight.updatePositionView (lib/midnight/src/Midnight.sol:794-816) subtracts the accrued continuous fee from both credit and pendingFee, so credit - pendingFee is time-invariant, and the dummy maturity-0 market in currentNetCredit is safe. Each of onBuy, onSell, withdrawToVault and forceDeallocate counts the fee once, and no path double-counts it.",
  "Truncation: netCredit uint128 (from Midnight uint128 fields), netRate toUint64 (reverts, known TRST-R-2), the minNetBuyRate*ttm*buyerAssets product (checked math, reverts on overflow), and the unchecked realAssets sum (bounded as commented at L856-857).",
  "Loss paths: markets with lossFactor != 0 use currentNetCredit in realAssets and in the shortfall loop. Stored netCredit is used otherwise. withdrawToVault(0) re-syncs.",
  "Prior audit drafts (both 2026-10-12) were summarised finding by finding by a reader subagent and checked against each candidate."
 ],
 "notCovered": [
  "The unit suite test/MidnightAdapterTest.sol was not run: it needs artifacts from a full build that did not fit the 10-minute command limit here.",
  "No fuzz or invariant campaign was run. Only deterministic scenarios on one token (18 decimals, integration setup) and one market, except where the integration setup uses more.",
  "Multi-market shortfall spreading with lossy (lossFactor != 0) markets and with markets near maturity was reviewed by reading only. Not exercised.",
  "forceDeallocate settlement-fee arithmetic against Midnight's take internals was not traced (lowInfo item is UNVERIFIED).",
  "The suggested fixes for ACC-1 were not implemented or tested.",
  "No independent re-run from a fresh clone by a second agent was done in this item (Step 4 of the goal belongs to another item)."
 ]
}