{
 "lead": "forcesell-shortfall",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "blocked": false,
 "hasCandidates": false,
 "summary": "No fault found. Sales driven by an untrusted taker of ratified adapter sell offers were tested on the real Midnight and VaultV2 (MidnightAdapterIntegrationTest harness) with a five-market book: 30d and 60d markets with interest, a matured 7d market, a 45d market bought at par (netRate 0), and a 50d market with bad debt (lossFactor != 0, current net credit 6000 vs stored 10000). In every non-force-sellable sale, including 256 fuzzed sales over market, size, tick and time, realAssets + vault idle never dropped. Allowance was consumed exactly when rates were cut. Stored rates and allowance stayed consistent. realAssets never exceeded current net credit. Force-sale proceeds never fell below minForceSellPrice, including with settlement fees and 1-5 unit dust fills. Nothing reaches the High/Medium bar, so there are no candidates. Four Informational notes follow.",
 "candidates": [],
 "lowInfo": [
  {
   "title": "minForceSellPrice defaults to 0 and is not tied to setForceSellable: once anyone executes the pending setForceSellable, an outstanding ratified sell offer that maxNetSellRate blocked becomes takeable at any price, with the loss realised instantly and no shortfallAllowance consumed",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:273-277",
    "src/adapters/midnight/MidnightAdapter.sol:334-338",
    "src/adapters/midnight/MidnightAdapter.sol:638-639",
    "src/adapters/midnight/MidnightAdapter.sol:54-57"
   ],
   "detail": "setForceSellable is timelocked and callable by anyone after the delay (timelocked() at L208-217). minForceSellPrice is a separate per-market value, defaults to 0 and can be changed by the curator at once (L334-338). In onSell, a force-sellable market only checks sellerAssets >= soldNetCredit*minForceSellPrice (L639). So any adapter sell offer still ratified in that market becomes executable at its tick the moment the flag flips, unless the curator set minForceSellPrice first. Test testPoC_DefaultMinForceSellPriceUnlocksBlockedOffer: an untrusted lender takes a ratified offer of 5000 units at tick 3372 (price 0.5). It first reverts with NetSellRateTooHigh. After setForceSellable is executed, the same offer fills: 2500 tokens of proceeds, 0 allowance consumed, vault value change -2344.929541849148821231 tokens. This needs curator/allocator configuration (a stale ratified offer and no minForceSellPrice). The NatSpec says force-sellable sales are bounded by minForceSellPrice instead, and the Cantina draft has a Low on a related path ('Pending force-sale authorization allows an allocator to enlarge the position before selling it at zero price'). So this is hardening only, not a finding. Suggested fix: pass minForceSellPrice in setForceSellable's timelocked data, or require it to be non-zero when the flag is set."
  },
  {
   "title": "A shortfall from a non-force-sellable sale is spread onto force-sellable (distressed) markets' unearned interest",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:649-686",
    "src/adapters/midnight/MidnightAdapter.sol:42-43"
   ],
   "detail": "The spreading loop covers every active market, including markets the curator has flagged forceSellable. It lowers their netRate and moves part of the shortfall into interest the curator already expects to lose. Test testPoC_ForceSellableAbsorbsOtherShortfall: a 5000-unit sale of A at tick 3980 (74.88-token shortfall) cut force-sellable B's rate from 8419284503 to 7906957172. B's amortized value rose from 19271.050146519676467148 to 19313.886221027019633856, so about 42.84 tokens of the shortfall now sit in B. Accounting stays consistent: the amount is realised when B is force-sold. But realAssets is propped up by a distressed market's future interest. Markets with lossFactor != 0 take part in the same way: in testPoC_ShortfallSpreadMultiMarket, bad-debt market E's rate went from 3724056321 to 3502434156. Suggested fix: leave forceSellable markets out of totalInterest and the rate reduction."
  },
  {
   "title": "Rate rounding in the shortfall spread accrues a little interest early (documented)",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:23",
    "src/adapters/midnight/MidnightAdapter.sol:145-146",
    "src/adapters/midnight/MidnightAdapter.sol:673-685"
   ],
   "detail": "Target amortized values round up and new rates round down, so post-sale value is slightly above pre-sale value. Measured: +102771377917 wei (about 1.0e-7 tokens, 18 decimals) on a 74.875-token shortfall. Across 256 fuzz runs the excess stayed under 1e12 wei. This is accepted in the NatSpec at L23 and L145-146, so it is listed only to record that it was measured."
  },
  {
   "title": "Matured markets keep a non-zero stored netRate",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:541-547",
    "src/adapters/midnight/MidnightAdapter.sol:859",
    "src/adapters/midnight/MidnightAdapter.sol:769-778"
   ],
   "detail": "After maturity, netRate stays at its last value (market C showed 9812017633 after maturity) until the market's net credit reaches zero and removeMarket clears it. realAssets ignores it because ttm = 0, and the shortfall loop skips it because amortized == netCredit. No impact on accounting. It may confuse off-chain readers of marketData."
  }
 ],
 "evidence": {
  "poc": {
   "path": "test/poc/ForceSellShortfallPoC.t.sol",
   "command": "git clone https://github.com/morpho-org/vault-v2 && cd vault-v2 && git checkout bbeda7b27ae80abcf070e0158cb8a31e87bb2286 && git submodule update --init --recursive && mkdir -p test/poc && cp <this source> test/poc/ForceSellShortfallPoC.t.sol && forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers && FOUNDRY_FUZZ_RUNS=256 forge test --match-path test/poc/ForceSellShortfallPoC.t.sol --match-test PoC -vv",
   "output": "No files changed, compilation skipped\n\nRan 7 tests for test/poc/ForceSellShortfallPoC.t.sol:ForceSellShortfallPoC\n[PASS] testFuzzPoC_SaleNeverBooksLoss(uint256,uint256,uint256,uint256) (runs: 256, \u03bc: 8398114, ~: 8476433)\n[PASS] testPoC_BoundaryAroundAmortized() (gas: 10169139)\nLogs:\n  amortized price of B (WAD), first tick >= it 963552507325983823 4032\n  tick at/above amortized 4032 964144100000000000\n    proceeds/consumed 7498148665700000000000 0\n    rate of A before/after 16838569007 16838569007\n  4600816225823805749\n  tick just below amortized 4028 963447100000000000\n    proceeds/consumed 7492728096700000000000 819752774176194251\n    rate of A before/after 16838569007 16826136496\n  47111140857\n\n[PASS] testPoC_DefaultMinForceSellPriceUnlocksBlockedOffer() (gas: 8205176)\nLogs:\n  minForceSellPrice 0\n  proceeds for 5000 units / allowance consumed 2500000000000000000000 0\n  vault value change\n  -2344929541849148821231\n\n[PASS] testPoC_ForceSaleBound() (gas: 11230999)\nLogs:\n  force sale proceeds / consumed 3109624673100000000000 0\n  proceeds per sold unit (WAD) vs minForceSellPrice 932980700000000000 932980700000000000\n  -120005359496642604232\n\n[PASS] testPoC_ForceSellableAbsorbsOtherShortfall() (gas: 7908221)\nLogs:\n  forceSellable B rate before/after A's shortfall sale 8419284503 7906957172\n  B amortized before/after 19271050146519676467148 19313886221027019633856\n\n[PASS] testPoC_ReentrantForceDeallocateMidShortfallSale() (gas: 10456040)\nLogs:\n  after reentrant sale\n    market 0\n      storedNetCredit/currentNetCredit 15000000000000000000000 15000000000000000000000\n      netRate/amortized 15757585029 14563785247604372167951\n    market 1\n      storedNetCredit/currentNetCredit 18000000000000000000000 18000000000000000000000\n      netRate/amortized 7875941411 17384837027682513752798\n    market 2\n      storedNetCredit/currentNetCredit 10000000000000000000000 10000000000000000000000\n      netRate/amortized 9812017633 10000000000000000000000\n    market 3\n      storedNetCredit/currentNetCredit 10000000000000000000000 10000000000000000000000\n      netRate/amortized 0 10000000000000000000000\n    market 4\n      storedNetCredit/currentNetCredit 10000000000000000000000 6000000000000000000000\n      netRate/amortized 3488997067 5924984526015522534008\n    realAssets 57873606801302408454757\n    shortfallAllowance 340282366920938463388499565582619390224\n  idle delta (A proceeds + B forceDeallocate) / consumed 6770054500000000000000 74875041849148821231\n  attacker shares burnt as penalty 41467577666160701094\n  72894985404857484610\n\n[PASS] testPoC_ShortfallSpreadMultiMarket() (gas: 9352619)\nLogs:\n  before\n    market 0\n      storedNetCredit/currentNetCredit 20000000000000000000000 20000000000000000000000\n      netRate/amortized 16838569007 19379718167396595284922\n    market 1\n      storedNetCredit/currentNetCredit 20000000000000000000000 20000000000000000000000\n      netRate/amortized 8419284503 19271050146519676467148\n    market 2\n      storedNetCredit/currentNetCredit 10000000000000000000000 10000000000000000000000\n      netRate/amortized 9812017633 10000000000000000000000\n    market 3\n      storedNetCredit/currentNetCredit 10000000000000000000000 10000000000000000000000\n      netRate/amortized 0 10000000000000000000000\n    market 4\n      storedNetCredit/currentNetCredit 10000000000000000000000 6000000000000000000000\n      netRate/amortized 3724056321 5919998001981279218077\n    realAssets 64570766315897550970147\n    shortfallAllowance 1000000000000000000000\n  after shortfall sale of 5000 units of A at tick 3980\n    market 0\n      storedNetCredit/currentNetCredit 15000000000000000000000 15000000000000000000000\n      netRate/amortized 15819312114 14562126348419221800243\n    market 1\n      storedNetCredit/currentNetCredit 20000000000000000000000 20000000000000000000000\n      netRate/amortized 7906957172 19313886221027019633856\n    market 2\n      storedNetCredit/currentNetCredit 10000000000000000000000 10000000000000000000000\n      netRate/amortized 9812017633 10000000000000000000000\n    market 3\n      storedNetCredit/currentNetCredit 10000000000000000000000 10000000000000000000000\n      netRate/amortized 0 10000000000000000000000\n    market 4\n      storedNetCredit/currentNetCredit 10000000000000000000000 6000000000000000000000\n      netRate/amortized 3502434156 5924699246554080913965\n    realAssets 59800711816000322348064\n    shortfallAllowance 925124958150851178769\n  proceeds 4770054500000000000000\n  allowance consumed 74875041849148821231\n  vault value change (realAssets+idle)\n  102771377917\n\nSuite result: ok. 7 passed; 0 failed; 0 skipped; finished in 249.07ms (273.46ms CPU time)\n\nRan 1 test suite in 249.74ms (249.07ms CPU time): 7 tests passed, 0 failed, 0 skipped (7 total tests)\n",
   "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {console} from \"../../lib/forge-std/src/console.sol\";\n\ninterface IMarketDataView {\n    function marketData(bytes32)\n        external\n        view\n        returns (uint128 netCredit, uint64 netRate, uint40 maturity, uint8 index, bool forceSellable, bool forceRemoved, uint256 minForceSellPrice);\n}\n\ncontract ReenteringBuyer {\n    IVaultV2 public vault;\n    address public adapter;\n    IMidnight public midnight;\n    address public token;\n    Market internal other;\n    uint256 internal amount;\n\n    constructor(IVaultV2 _vault, address _adapter, IMidnight _midnight, address _token) {\n        (vault, adapter, midnight, token) = (_vault, _adapter, _midnight, _token);\n        SafeERC20Lib.safeApprove(_token, address(_midnight), type(uint256).max);\n        SafeERC20Lib.safeApprove(_token, _adapter, type(uint256).max);\n        SafeERC20Lib.safeApprove(_token, address(_vault), type(uint256).max);\n        _midnight.setIsAuthorized(_adapter, true, address(this));\n    }\n\n    function deposit(uint256 a) external {\n        vault.deposit(a, address(this));\n    }\n\n    function attack(Offer memory o, bytes memory rd, uint256 units, Market memory _other, uint256 _amount) external {\n        (other, amount) = (_other, _amount);\n        midnight.take(o, rd, units, address(this), address(0), address(this), \"\");\n    }\n\n    function onBuy(bytes32, Market memory, uint256, uint256, uint256, address, bytes calldata) external returns (bytes32) {\n        // Mid-sale (before the adapter's onSell): force-deallocate another market of the adapter.\n        vault.forceDeallocate(adapter, abi.encode(other, address(this)), amount, address(this));\n        return keccak256(\"morpho.midnight.callbackSuccess\");\n    }\n}\n\n/// @dev Lead \"forcesell-shortfall\": sale guardrails with several markets (matured, lossFactor != 0, ~zero interest).\n/// All sales are executed by an untrusted taker (`lender`) taking ratified adapter sell offers.\ncontract ForceSellShortfallPoC is MidnightAdapterIntegrationTest {\n    Market[] internal mkts;\n    bytes32[] internal mids;\n    uint256 internal nonce;\n\n    function _taker(uint256 duration, uint256 units, uint256 tick) internal returns (Market memory market) {\n        market = _market(duration);\n        address b = makeAddr(string(abi.encode(\"borrower\", nonce++)));\n        Offer memory offer = Offer({\n            market: market,\n            buy: false,\n            maker: b,\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: tick,\n            group: keccak256(abi.encode(\"ext\", nonce)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: b,\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), b, collateral);\n        bytes32 root = HashLib.hashOffer(offer);\n        bytes32[] memory proof = new bytes32[](0);\n        vm.startPrank(b);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, b);\n        midnight.setIsAuthorized(address(setterRatifier), true, b);\n        setterRatifier.setIsRootRatified(b, root, true);\n        vm.stopPrank();\n        vm.prank(allocator);\n        adapter.take(offer, abi.encode(root, uint256(0), proof), units, abi.encode(address(0), \"\"));\n        mkts.push(market);\n        mids.push(IdLib.toId(market));\n        lastBorrower = b;\n    }\n\n    address internal lastBorrower;\n\n    /// @dev Adapter maker sell offer, ratified by the allocator, taken by the untrusted `lender`.\n    function _sellOffer(Market memory market, uint256 maxUnits, uint256 tick) internal returns (Offer memory offer, bytes memory rd) {\n        offer = Offer({\n            market: market,\n            buy: false,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: market.maturity + 365 days,\n            tick: tick,\n            group: keccak256(abi.encode(\"sell\", nonce++)),\n            callback: address(adapter),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: true,\n            maxUnits: uint128(maxUnits),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        bytes32 root = HashLib.hashPriceRatifierV1Offer(offer, address(0));\n        vm.prank(allocator);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        bytes32[] memory proof = new bytes32[](0);\n        rd = abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), proof, address(0)));\n    }\n\n    function _lenderTake(Offer memory offer, bytes memory rd, uint256 units) internal {\n        deal(address(underlyingToken), lender, 10 * initialAssets);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        midnight.take(offer, rd, units, lender, address(0), address(0), \"\");\n        vm.stopPrank();\n    }\n\n    function _md(bytes32 id) internal view returns (uint128 nc, uint64 rate, uint40 mat, bool fs) {\n        (nc, rate, mat,, fs,,) = IMarketDataView(address(adapter)).marketData(id);\n    }\n\n    function _cur(bytes32 id) internal view returns (uint256) {\n        Market memory dummy;\n        (uint128 c, uint128 p,) = midnight.updatePositionView(dummy, id, address(adapter));\n        return c - p;\n    }\n\n    function _amortized(bytes32 id) internal view returns (uint256) {\n        (uint128 nc, uint64 rate, uint40 mat,) = _md(id);\n        uint256 n = midnight.lossFactor(id) == 0 ? nc : _cur(id);\n        uint256 ttm = mat > block.timestamp ? mat - block.timestamp : 0;\n        return n * WAD / (WAD + uint256(rate) * ttm);\n    }\n\n    /// Portfolio: A 30d, B 60d, C 7d (matured later), D 45d (bought at ~par, ~zero interest), E 50d (bad debt -> lossFactor != 0).\n    function _portfolio() internal {\n        _taker(30 days, 20_000 * oneToken, 4000);\n        _taker(60 days, 20_000 * oneToken, 4000);\n        _taker(7 days, 10_000 * oneToken, 4400);\n        _taker(45 days, 10_000 * oneToken, MAX_TICK);\n        _taker(50 days, 10_000 * oneToken, 4200);\n        address eBorrower = lastBorrower;\n        vm.warp(block.timestamp + 8 days); // C matured.\n        // Bad debt in E: collateral price drops, untrusted liquidator realizes bad debt, price restored.\n        oracle.setPrice(ORACLE_PRICE_SCALE * oneToken / 1e18 * 3 / 10);\n        vm.prank(makeAddr(\"liquidator\"));\n        midnight.liquidate(mkts[4], 0, 0, 0, eBorrower, false, makeAddr(\"liquidator\"), address(0), \"\");\n        oracle.setPrice(ORACLE_PRICE_SCALE * oneToken / 1e18);\n        require(midnight.lossFactor(mids[4]) != 0, \"no loss\");\n    }\n\n    function _log(string memory tag) internal view {\n        console.log(tag);\n        for (uint256 i; i < mids.length; i++) {\n            (uint128 nc, uint64 rate,, bool fs) = _md(mids[i]);\n            console.log(\"  market\", i);\n            console.log(\"    storedNetCredit/currentNetCredit\", nc, _cur(mids[i]));\n            console.log(\"    netRate/amortized\", rate, _amortized(mids[i]));\n            if (fs) console.log(\"    forceSellable\");\n        }\n        console.log(\"  realAssets\", adapter.realAssets());\n        console.log(\"  shortfallAllowance\", adapter.shortfallAllowance());\n    }\n\n    struct Snap {\n        uint256 ra;\n        uint256 idle;\n        uint256 allowance;\n    }\n\n    function _snap() internal view returns (Snap memory s) {\n        s = Snap(adapter.realAssets(), underlyingToken.balanceOf(address(vault)), adapter.shortfallAllowance());\n    }\n\n    /// @dev Returns (proceeds, allowanceConsumed, valueAfter - valueBefore) where value = realAssets + idle.\n    function _delta(Snap memory a, Snap memory b) internal pure returns (uint256 proceeds, uint256 consumed, int256 dv) {\n        proceeds = b.idle - a.idle;\n        consumed = a.allowance - b.allowance;\n        dv = int256(b.ra + b.idle) - int256(a.ra + a.idle);\n    }\n\n    function _invariants() internal view {\n        uint256 sumCur;\n        for (uint256 i; i < mids.length; i++) {\n            (uint128 nc,,,) = _md(mids[i]);\n            uint256 n = midnight.lossFactor(mids[i]) == 0 ? nc : _cur(mids[i]);\n            assertLe(_amortized(mids[i]), n, \"amortized > net credit\");\n            if (midnight.lossFactor(mids[i]) == 0) assertEq(uint256(nc), _cur(mids[i]), \"stored != current (lf=0)\");\n            sumCur += _cur(mids[i]);\n        }\n        assertLe(adapter.realAssets(), sumCur, \"realAssets > current net credit\");\n    }\n\n    /// 1. Shortfall sale spread over A,B,D,E (C matured, D ~zero interest, E lossFactor != 0).\n    function testPoC_ShortfallSpreadMultiMarket() public {\n        _portfolio();\n        vm.prank(curator);\n        adapter.decreaseShortfallAllowance(type(uint128).max - 1000 * oneToken);\n        _log(\"before\");\n        (Offer memory o, bytes memory rd) = _sellOffer(mkts[0], 5_000 * oneToken, 3980);\n        Snap memory a = _snap();\n        _lenderTake(o, rd, 5_000 * oneToken);\n        Snap memory b = _snap();\n        _log(\"after shortfall sale of 5000 units of A at tick 3980\");\n        (uint256 proceeds, uint256 consumed, int256 dv) = _delta(a, b);\n        console.log(\"proceeds\", proceeds);\n        console.log(\"allowance consumed\", consumed);\n        console.log(\"vault value change (realAssets+idle)\");\n        console.logInt(dv);\n        assertGt(consumed, 0);\n        assertGe(dv, 0, \"sale booked a loss\");\n        _invariants();\n    }\n\n    /// 2. Sales just above / just below amortized value.\n    function testPoC_BoundaryAroundAmortized() public {\n        _portfolio();\n        bytes32 id = mids[1];\n        (uint128 nc,,,) = _md(id);\n        uint256 amortPrice = _amortized(id) * WAD / nc;\n        uint256 sp = midnight.tickSpacing(id);\n        uint256 t = TickLib.priceToTick(amortPrice, sp);\n        console.log(\"amortized price of B (WAD), first tick >= it\", amortPrice, t);\n        uint256 snap = vm.snapshotState();\n        for (uint256 k; k < 2; k++) {\n            vm.revertToState(snap);\n            uint256 tick = k == 0 ? t : t - sp;\n            (uint64 rA,,,) = _rates();\n            (Offer memory o, bytes memory rd) = _sellOffer(mkts[1], 7_777 * oneToken, tick);\n            Snap memory a = _snap();\n            _lenderTake(o, rd, 7_777 * oneToken);\n            Snap memory b = _snap();\n            (uint256 proceeds, uint256 consumed, int256 dv) = _delta(a, b);\n            (uint64 rA2,,,) = _rates();\n            console.log(k == 0 ? \"tick at/above amortized\" : \"tick just below amortized\", tick, TickLib.tickToPrice(tick));\n            console.log(\"  proceeds/consumed\", proceeds, consumed);\n            console.log(\"  rate of A before/after\", rA, rA2);\n            console.logInt(dv);\n            assertGe(dv, 0, \"sale booked a loss\");\n            if (consumed == 0) assertEq(rA, rA2, \"rates changed without consuming allowance\");\n            else assertLt(rA2, rA);\n            _invariants();\n        }\n    }\n\n    function _rates() internal view returns (uint64 a, uint64 b, uint64 d, uint64 e) {\n        (, a,,) = _md(mids[0]);\n        (, b,,) = _md(mids[1]);\n        (, d,,) = _md(mids[3]);\n        (, e,,) = _md(mids[4]);\n    }\n\n    /// 3. Fuzz: any lender-taken sale in a non-force-sellable market never lowers vault value and consumes allowance iff rates drop.\n    function testFuzzPoC_SaleNeverBooksLoss(uint256 which, uint256 units, uint256 tick, uint256 elapsed) public {\n        _portfolio();\n        elapsed = bound(elapsed, 0, 25 days);\n        vm.warp(block.timestamp + elapsed);\n        which = [uint256(0), 1, 3, 4][bound(which, 0, 3)];\n        uint256 maxUnits = _cur(mids[which]);\n        units = bound(units, 1, maxUnits);\n        tick = bound(tick, 3800, MAX_TICK);\n        tick -= tick % midnight.tickSpacing(mids[which]);\n        (uint64 a0, uint64 b0, uint64 d0, uint64 e0) = _rates();\n        (Offer memory o, bytes memory rd) = _sellOffer(mkts[which], units, tick);\n        Snap memory a = _snap();\n        deal(address(underlyingToken), lender, 10 * initialAssets);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        try midnight.take(o, rd, units, lender, address(0), address(0), \"\") {} catch { vm.stopPrank(); return; }\n        vm.stopPrank();\n        Snap memory b = _snap();\n        (, uint256 consumed, int256 dv) = _delta(a, b);\n        assertGe(dv, 0, \"sale booked a loss\");\n        (uint64 a1, uint64 b1, uint64 d1, uint64 e1) = _rates();\n        if (consumed == 0) {\n            if (which != 0) assertEq(a0, a1);\n            if (which != 1) assertEq(b0, b1);\n            if (which != 3) assertEq(d0, d1);\n            if (which != 4) assertEq(e0, e1);\n        }\n        // Interest removed beyond the consumed allowance is bounded (rounding only).\n        if (consumed > 0) {\n            console.log(\"consumed / excess value (interest accrued early)\", consumed, uint256(dv));\n            assertLe(uint256(dv), 1e12, \"excess interest reduction\");\n        }\n        _invariants();\n    }\n\n    /// 4. Force-sale mode: minForceSellPrice bound, with Midnight settlement fees, taker = untrusted lender.\n    function testPoC_ForceSaleBound() public {\n        _portfolio();\n        bytes32 id = mids[0];\n        // Executable by anyone once the (zero) timelock elapsed.\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.setForceSellable, (id)));\n        vm.startPrank(owner);\n        midnight.setFeeSetter(owner);\n        midnight.setMarketSettlementFee(id, 3, 0.00005e18);\n        midnight.setMarketSettlementFee(id, 2, 0.00005e18);\n        vm.stopPrank();\n        uint256 minPrice = TickLib.tickToPrice(3900);\n        vm.prank(curator);\n        adapter.setMinForceSellPrice(id, minPrice);\n\n        // Maker sale at exactly minForceSellPrice: OK, loss realized, no allowance consumed, rates unchanged.\n        (uint64 a0, uint64 b0,,) = _rates();\n        (Offer memory o, bytes memory rd) = _sellOffer(mkts[0], 3_333 * oneToken, 3900);\n        Snap memory a = _snap();\n        _lenderTake(o, rd, 3_333 * oneToken);\n        Snap memory b = _snap();\n        (uint256 proceeds, uint256 consumed, int256 dv) = _delta(a, b);\n        (uint64 a1, uint64 b1,,) = _rates();\n        console.log(\"force sale proceeds / consumed\", proceeds, consumed);\n        console.log(\"proceeds per sold unit (WAD) vs minForceSellPrice\", proceeds * WAD / (3_333 * oneToken), minPrice);\n        console.logInt(dv);\n        assertEq(consumed, 0);\n        assertEq(a0, a1);\n        assertEq(b0, b1);\n        assertGe(proceeds * WAD, 3_333 * oneToken * minPrice);\n        _invariants();\n\n        // One tick below: reverts.\n        (o, rd) = _sellOffer(mkts[0], 1_000 * oneToken, 3896);\n        deal(address(underlyingToken), lender, 10 * initialAssets);\n        vm.prank(lender);\n        vm.expectRevert();\n        midnight.take(o, rd, 1_000 * oneToken, lender, address(0), address(0), \"\");\n\n        // Dust units at the bound: Midnight rounds maker-seller assets up; adapter check rounds up too.\n        (o, rd) = _sellOffer(mkts[0], 1000, 3900);\n        for (uint256 u = 1; u < 6; u++) {\n            Snap memory c = _snap();\n            vm.prank(lender);\n            midnight.take(o, rd, u, lender, address(0), address(0), \"\");\n            Snap memory d = _snap();\n            assertGe((d.idle - c.idle) * WAD, u * minPrice, \"dust below bound\");\n        }\n    }\n\n    /// 5. Informational: a force-sellable market's rate is still lowered to absorb another market's shortfall.\n    function testPoC_ForceSellableAbsorbsOtherShortfall() public {\n        _portfolio();\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.setForceSellable, (mids[1])));\n        (, uint64 b0,,) = _rates();\n        uint256 amB0 = _amortized(mids[1]);\n        (Offer memory o, bytes memory rd) = _sellOffer(mkts[0], 5_000 * oneToken, 3980);\n        _lenderTake(o, rd, 5_000 * oneToken);\n        (, uint64 b1,,) = _rates();\n        console.log(\"forceSellable B rate before/after A's shortfall sale\", b0, b1);\n        console.log(\"B amortized before/after\", amB0, _amortized(mids[1]));\n        assertLt(b1, b0);\n    }\n\n    /// 6. Untrusted buyer callback force-deallocates market B in the middle of a shortfall sale of A.\n    function testPoC_ReentrantForceDeallocateMidShortfallSale() public {\n        _portfolio();\n        ReenteringBuyer att = new ReenteringBuyer(vault, address(adapter), midnight, address(underlyingToken));\n        deal(address(underlyingToken), address(att), 100_000 * oneToken);\n        att.deposit(1_000 * oneToken);\n        (Offer memory o, bytes memory rd) = _sellOffer(mkts[0], 5_000 * oneToken, 3980);\n        Snap memory a = _snap();\n        uint256 sharesBefore = vault.balanceOf(address(att));\n        att.attack(o, rd, 5_000 * oneToken, mkts[1], 2_000 * oneToken);\n        Snap memory b = _snap();\n        _log(\"after reentrant sale\");\n        (uint256 proceeds, uint256 consumed, int256 dv) = _delta(a, b);\n        console.log(\"idle delta (A proceeds + B forceDeallocate) / consumed\", proceeds, consumed);\n        console.log(\"attacker shares burnt as penalty\", sharesBefore - vault.balanceOf(address(att)));\n        console.logInt(dv);\n        assertGe(dv, 0);\n        _invariants();\n    }\n\n    /// 7. Informational: with the default minForceSellPrice (0), executing setForceSellable turns an outstanding\n    /// ratified sell offer that the rate/allowance guardrails blocked into an instant, unbounded-by-allowance loss.\n    function testPoC_DefaultMinForceSellPriceUnlocksBlockedOffer() public {\n        _portfolio();\n        bytes32 id = mids[0];\n        (Offer memory o, bytes memory rd) = _sellOffer(mkts[0], 5_000 * oneToken, 3372); // price ~0.5\n        deal(address(underlyingToken), lender, 10 * initialAssets);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        vm.expectRevert(IMidnightAdapterBase.NetSellRateTooHigh.selector);\n        midnight.take(o, rd, 5_000 * oneToken, lender, address(0), address(0), \"\");\n        vm.stopPrank();\n        // Curator submitted setForceSellable; once the timelock elapses anyone executes it.\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.setForceSellable, (id)));\n        Snap memory a = _snap();\n        _lenderTake(o, rd, 5_000 * oneToken);\n        Snap memory b = _snap();\n        (uint256 proceeds, uint256 consumed, int256 dv) = _delta(a, b);\n        console.log(\"minForceSellPrice\", adapter.marketData(id).minForceSellPrice);\n        console.log(\"proceeds for 5000 units / allowance consumed\", proceeds, consumed);\n        console.log(\"vault value change\");\n        console.logInt(dv);\n        assertEq(consumed, 0);\n        assertLt(dv, 0);\n    }\n}\n"
  },
  "toolchain": "forge 1.8.5; solc 0.8.19/0.8.21/0.8.26/0.8.27/0.8.28/0.8.34/0.8.37 (official soliditylang macOS binaries)"
 },
 "covered": [
  "Shortfall sale with 5 active markets: 30d and 60d with interest, matured 7d (ttm 0), 45d at par (netRate 0), 50d with bad debt (lossFactor != 0). Proceeds 4770.0545, allowance consumed 74.875041849148821231, vault value +1.03e11 wei; matured and zero-interest markets untouched (testPoC_ShortfallSpreadMultiMarket)",
  "Sales one tick spacing above and below amortized value: above gives 0 consumed and unchanged rates; below gives 0.819752774176194251 consumed and A's rate 16838569007 -> 16826136496 (testPoC_BoundaryAroundAmortized)",
  "256-run fuzz over market, units, tick (3800..MAX_TICK, spacing-aligned) and elapsed time (0-25d): no sale lowered realAssets+idle; allowance never stayed unconsumed while rates changed; stored and current net credit agree for lossFactor==0; amortized <= net credit; realAssets <= sum of current net credit (testFuzzPoC_SaleNeverBooksLoss)",
  "Force-sale mode with an untrusted taker and 0.5 bp settlement fees: a sale at minForceSellPrice gives proceeds/unit 0.9329807 = minForceSellPrice, 0 allowance consumed, rates unchanged; one tick below reverts; dust fills of 1-5 units never fall below the bound because Midnight rounds maker-seller assets up and the adapter's check uses mulDivUp (testPoC_ForceSaleBound)",
  "An untrusted buyer callback calls vault.forceDeallocate on another market mid-sale, before onSell: the state stays consistent, the shortfall is spread over the updated stored credit, and the vault gains 72.89 tokens from the at-par forceDeallocate (testPoC_ReentrantForceDeallocateMidShortfallSale)",
  "Code review of onSell (L617-700): maxNetSellRate bound, soldAmortizedValue floor-difference telescoping (split sales sum exactly), the proof that targetAmortizedValue <= netCredit and that floor(newRate) still covers the target, break condition, removeMarket ordering; forceRemove/setForceSellable executed by anyone mid-sale (forceRemove of the sold market makes onSell revert; other markets stay consistent); BuyAtLoss and minNetBuyRate checks in onBuy (L535-537); Midnight take ordering (onBuy before transfers before onSell) and sellerPendingFeeDecrease rounding",
  "Prior audit check: the Cantina and TrustSec drafts (2026-10-12) describe the earlier minRate/noSalesWithShortfall/noSalesBelowFaceValue design; cross-market shortfall spreading and minForceSellPrice are newer. The Cantina Low 'Pending force-sale authorization allows an allocator to enlarge the position before selling it at zero price' is related to lowInfo #1",
  "Already-known items excluded as instructed: allowance over-consumption on split shortfall sales; WhitelistEnterSubGate revocation"
 ],
 "notCovered": [
  "Taker sales (allocator take of an external buy offer) in force-sale mode with settlement fees were checked only by reading the code (sellerPrice = offerPrice - fee feeds sellerAssets, which is what the check uses); the run is allocator-driven and out of scope",
  "Shortfall sales at MAX_MARKETS (250) for gas/DoS",
  "Non-18-decimal loan tokens (DECIMALS env) were not run; tokens with an expensive smallest unit are excluded by the NatSpec",
  "Markets with a non-zero continuous fee during shortfall spreading",
  "The full existing test suite was not run (only MidnightAdapterIntegrationTest's 8 inherited tests, which pass)",
  "Step 4 independent re-run from a clean clone by a different agent was not done in this item"
 ]
}