{
 "lead": "bad-debt-combos: adapter credit in three markets (30d/45d/60d), partial loss in market A (lossFactor>0) realized by an outsider's liquidation, then (1) outsider fills of ratified maker sell offers below amortized value in the loss market and a healthy market, before and after syncing the loss with a 0-asset deallocate; (2) vault.forceDeallocate in the loss market; (3) vault.deposit from a taker's onBuy during an adapter sale in the loss market; (4) entering or leaving at a share price that ignores a recorded loss.",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "lowInfo": [
  {
   "title": "Shortfall spread raises realAssets+idle by rate rounding only (6.4e10 to 1.5e11 wei on 8.8e22 to 1e23 total), the same with or without a loss and before or after syncing it",
   "class": "Informational (already reported: TrustSec TRST-R-14, Cantina 3.2.8 / 3.6.6; documented in NatSpec MidnightAdapter.sol:22-23 and :146)",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:643-686",
    "src/adapters/midnight/MidnightAdapter.sol:657-659",
    "src/adapters/midnight/MidnightAdapter.sol:678-679",
    "test/poc/BadDebtCombos.t.sol:testSale*"
   ],
   "detail": "An outsider fills a ratified maker sell offer of 5,000 units about 0.4% below amortized value. Every case consumes allowance exactly equal to the shortfall (A: 19220891673975227364 wei; B: 19357691573476980950 wei), and realAssets+idle does not fall. It rises by 99002934003 wei (sale in loss market A), 64450280378 wei (sale in healthy B with a loss in A) and 147793655051 wei (sale in B with no loss), whether or not A's loss has been synced. The numbers before and after the sync are identical because realAssets and the spread loop both read live net credit (currentNetCredit) for any market with lossFactor>0 (:657-659, :848-854), so the stale stored netCredit is never used for valuation. The rise comes from rounding the new rate down (:678-679); it is far below the shortfall (<1e-6 of it) and well below a sale's own price difference. Answer to lead (1): no. The book value moves by much less than the sale's price difference, and no outsider gains from it.",
   "verified": true
  },
  {
   "title": "forceDeallocate in a loss market sells post-loss credit at face value: the redeemer neither pays for slashed credit nor gets more than it pays for",
   "class": "Informational (design, README 'In-kind redemptions'; not a finding)",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:427-477",
    "src/adapters/midnight/README.md:16-20",
    "test/poc/BadDebtCombos.t.sol:testForceDeallocateInLossMarket"
   ],
   "detail": "After the loss, the adapter's live credit in A is 18106817548765431912481 while stored is 30178029247942386520802 (slashed 12071211699176954608321). An outsider holding shares calls forceDeallocate for 5,000e18: it pays 5000e18 (settlement fee 0 in the test) and receives exactly 5000e18 fresh credit units, with lastLossFactor equal to the current lossFactor, so they are not slashed. The adapter's live credit drops by exactly 5000e18. Vault idle rises by 5000e18 while adapter realAssets drops by 4975395391673975227364, so remaining holders gain the discount. The 2% penalty burns 113569063572893043550 shares (value 9999.99e18 -> 9899.99e18). The take is reduceOnly, so the outsider cannot take more credit than the adapter holds after the loss (liveNetCredit+1 reverts), even though the stale stored netCredit is larger. The stored netCredit is resynced (30178.0e18 -> 13106.8e18), so the cap allocation drops by both the sale and the slashed credit. Answer to lead (2): no mispricing beyond the documented price of 1 asset per unit.",
   "verified": true
  },
  {
   "title": "Vault calls from a taker's onBuy during an adapter sale in a loss market revert with OtherSellInProgress: only that taker's transaction is affected",
   "class": "Informational (by design; TrustSec TRST-R-13 discusses the liquidation-lock guards)",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:848-853",
    "lib/midnight/src/Midnight.sol:437-468",
    "test/poc/BadDebtCombos.t.sol:testDepositInTakerOnBuyDuringLossMarketSale",
    "test/poc/BadDebtCombos.t.sol:testDepositInTakerOnBuyDuringHealthySaleWorks"
   ],
   "detail": "A taker contract that calls vault.deposit inside onBuy while filling the adapter's ratified sell offer in loss market A reverts with OtherSellInProgress, and its whole take reverts. In separate transactions the depositor's withdraw and an outsider's deposit both succeed. A taker that wraps the deposit in try/catch fills 2500e18 units and the sale completes. A plain outsider then fills the remaining 2500e18 units. During a sale in healthy market B (lossFactor 0), the same deposit in onBuy succeeds. The revert is confined to the caller that re-enters the vault mid-sale. No griefing of other users or of the adapter was found. Answer to lead (3): confirmed, only the taker's transaction fails.",
   "verified": true
  },
  {
   "title": "Exiting in the same transaction as a loss uses the share price cached before the loss, but this gives no more than exiting just before the liquidation",
   "class": "Informational (documented VaultV2 behaviour: VaultV2.sol:28 and :33)",
   "refs": [
    "src/VaultV2.sol:28-33",
    "src/VaultV2.sol:626-627",
    "src/adapters/midnight/MidnightAdapter.sol:25-26",
    "test/poc/BadDebtCombos.t.sol:testExitInSameTxAsLossUsesCachedPrice"
   ],
   "detail": "A holder of 20,000e18 deposited assets runs vault.accrueInterest(), then the permissionless liquidation realizing the bad debt in A, then redeem, all in one transaction. The redeem returns 19999999999999999999999, the same as redeeming in a transaction before the loss. Redeeming in a later transaction returns 17999098083130871512618 (2000901916869128487381 less). firstTotalAssets caches total assets once per transaction (VaultV2.sol:627, documented at :33), so the loss recorded mid-transaction is ignored until the next transaction. This gives no extra power: the same holder can simply redeem before liquidating, which is the general first-exiter advantage over unrealized bad debt. Entering at the cached pre-loss price only hurts the entrant. Across transactions the adapter reflects the loss immediately (testLossSnapshot: realAssets drops by exactly the amortized slashed credit, 12011810212001199220233, with no sync). Answer to lead (4): nothing beyond the documented once-per-transaction accounting.",
   "verified": true
  }
 ],
 "covered": {
  "tests": [
   "testLossSnapshot: partial loss in A by outsider liquidation; realAssets drops by the amortized slashed credit with no sync",
   "testSaleInLossMarketBeforeSync / testSaleInLossMarketAfterSync: outsider fills below-amortized maker sell in loss market A",
   "testSaleInHealthyMarketBeforeSync / testSaleInHealthyMarketAfterSync: same in healthy market B with the loss in A",
   "testSaleInHealthyMarketNoLossBaseline: same sale without any loss",
   "testForceDeallocateInLossMarket: outsider IKR in loss market, plus over-size forceDeallocate reverting",
   "testDepositInTakerOnBuyDuringLossMarketSale / testDepositInTakerOnBuyDuringHealthySaleWorks: vault.deposit from taker onBuy",
   "testExitInSameTxAsLossUsesCachedPrice: exit before, within and after the loss transaction",
   "inherited MidnightAdapterIntegrationTest spec tests (6) also pass"
  ],
  "command": "export XDG_DATA_HOME=$TMPDIR/xdg; forge test --match-path test/poc/BadDebtCombos.t.sol --isolate -vv",
  "output": "No files changed, compilation skipped\nRan 18 tests for test/poc/BadDebtCombos.t.sol:BadDebtCombosTest\n[PASS] testDepositInTakerOnBuyDuringHealthySaleWorks() (gas: 5610729)\n[PASS] testDepositInTakerOnBuyDuringLossMarketSale() (gas: 7799162)\nLogs:\n  strict taker: take reverted with OtherSellInProgress\n  tolerant taker: deposit failed, take filled units 2500000000000000000000\n  outsider filled remaining units 2500000000000000000000\n[PASS] testExitInSameTxAsLossUsesCachedPrice() (gas: 5542119)\nLogs:\n  redeem before loss (separate tx)     19999999999999999999999\n  accrue+liquidate+redeem in one tx    19999999999999999999999\n  redeem after loss (separate tx)      17999098083130871512618\n  loss avoided by exiting first        2000901916869128487381\n[PASS] testForceDeallocate() (gas: 1752043)\n[PASS] testForceDeallocateInLossMarket() (gas: 5792426)\nLogs:\n  outsider paid (assets+fee)        5000000000000000000000\n  outsider credit received (units)  5000000000000000000000\n  adapter live credit decrease      5000000000000000000000\n  stored netCredit before           30178029247942386520802\n  stored netCredit after            13106817548765431912481\n  vault idle gain                   5000000000000000000000\n  adapter realAssets drop           4975395391673975227364\n  penalty shares burned             113569063572893043550\n  outsider share value before       9999999999999999999999\n  outsider share value after        9899999999999999999999\n[PASS] testForceSell() (gas: 1654160)\n[PASS] testLossSnapshot() (gas: 4637031)\nLogs:\n  A stored netCredit        30178029247942386520802\n  A live netCredit          18106817548765431912481\n  A slashed credit          12071211699176954608321\n  realAssets before loss    90063958265345065504207\n  realAssets after loss     78052148053343866283974\n  realAssets drop           12011810212001199220233\n  amortized slashed credit  12011810212001199220233\n  vault totalAssets before  100063958265345065504210\n  vault totalAssets after   88052148053343866283977\n[PASS] testMakerBuy() (gas: 1130986)\n[PASS] testMakerSell() (gas: 1922935)\n[PASS] testRepayWithdrawRedeem() (gas: 1782139)\n[PASS] testSaleInHealthyMarketAfterSync() (gas: 5248178)\nLogs:\n  sale in healthy market B, loss in A synced\n    soldAmortizedValue       4973763691573476980950\n    sellerAssets             4954406000000000000000\n    shortfall (price diff)   19357691573476980950\n    allowance consumed       19357691573476980950\n    realAssets+idle before   88052148053343866283977\n    realAssets+idle after    88052148053408316564355\n    change (+)               64450280378\n[PASS] testSaleInHealthyMarketBeforeSync() (gas: 5051252)\nLogs:\n  sale in healthy market B, loss in A NOT synced\n    soldAmortizedValue       4973763691573476980950\n    sellerAssets             4954406000000000000000\n    shortfall (price diff)   19357691573476980950\n    allowance consumed       19357691573476980950\n    realAssets+idle before   88052148053343866283977\n    realAssets+idle after    88052148053408316564355\n    change (+)               64450280378\n[PASS] testSaleInHealthyMarketNoLossBaseline() (gas: 4830003)\nLogs:\n  baseline: sale in B, no loss anywhere\n    soldAmortizedValue       4973763691573476980950\n    sellerAssets             4954406000000000000000\n    shortfall (price diff)   19357691573476980950\n    allowance consumed       19357691573476980950\n    realAssets+idle before   100063958265345065504210\n    realAssets+idle after    100063958265492859159261\n    change (+)               147793655051\n[PASS] testSaleInLossMarketAfterSync() (gas: 5241262)\nLogs:\n  sale in loss market A, loss synced\n    soldAmortizedValue       4975395391673975227364\n    sellerAssets             4956174500000000000000\n    shortfall (price diff)   19220891673975227364\n    allowance consumed       19220891673975227364\n    realAssets+idle before   88052148053343866283977\n    realAssets+idle after    88052148053442869217980\n    change (+)               99002934003\n[PASS] testSaleInLossMarketBeforeSync() (gas: 5046982)\nLogs:\n  sale in loss market A, loss NOT synced\n    soldAmortizedValue       4975395391673975227364\n    sellerAssets             4956174500000000000000\n    shortfall (price diff)   19220891673975227364\n    allowance consumed       19220891673975227364\n    realAssets+idle before   88052148053343866283977\n    realAssets+idle after    88052148053442869217980\n    change (+)               99002934003\n[PASS] testTakerBuy() (gas: 1167705)\n[PASS] testTakerSell() (gas: 1960423)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 17210269)\nSuite result: ok. 18 passed; 0 failed; 0 skipped; finished in 31.49ms (80.87ms CPU time)\nRan 1 test suite in 33.32ms (31.49ms CPU time): 18 tests passed, 0 failed, 0 skipped (18 total tests)"
 },
 "notCovered": [
  "Losses realized inside the buyer callback of a sale in a different (non-sold) market: not exercised beyond reading the code (the spread loop reads live credit of loss markets, :657-659); the sold-market case is documented at NatSpec :45-46.",
  "Total loss (lossFactor == type(uint128).max) and several losses in the same market: not exercised.",
  "Non-zero continuous fee or settlement fee in the loss market: tests use Midnight defaults (fees 0).",
  "Token decimals other than 18 (DECIMALS env) and fuzzing of loss size or sale size: not run.",
  "Full repository test suite: not run (the brief limits the build; only the PoC file and its inherited tests were compiled and run).",
  "The PoC file test/poc/BadDebtCombos.t.sol (inherits test/integration/MidnightAdapterIntegrationTest.sol) is included verbatim in the top-level field pocSource, since there is no candidate to attach it to."
 ],
 "pocPath": "test/poc/BadDebtCombos.t.sol",
 "pocSource": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {IBuyCallback} from \"../../lib/midnight/src/interfaces/ICallbacks.sol\";\nimport {MarketData} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {console} from \"../../lib/forge-std/src/console.sol\";\n\n/// @dev Lead \"bad-debt-combos\": adapter credit in three markets, a partial loss (lossFactor > 0) realized by an\n/// outsider's liquidation in market A, then (1) outsider fills of ratified maker sell offers below amortized value,\n/// (2) forceDeallocate in the loss market, (3) vault calls from a taker's onBuy during an adapter sale in the loss\n/// market, (4) exits around the loss. Run with --isolate so that every top-level call is its own transaction.\ncontract BadDebtCombosTest is MidnightAdapterIntegrationTest {\n    using MathLib for uint256;\n\n    Market internal mA;\n    Market internal mB;\n    Market internal mC;\n    bytes32 internal idA;\n    bytes32 internal idB;\n    bytes32 internal idC;\n    address internal borrowerA = makeAddr(\"borrowerA\");\n    address internal borrowerB = makeAddr(\"borrowerB\");\n    address internal borrowerC = makeAddr(\"borrowerC\");\n    address internal outsider = makeAddr(\"outsider\");\n    address internal liquidator = makeAddr(\"liquidator\");\n\n    uint256 internal constant SELL_UNITS = 5_000;\n\n    function _setupThree() internal {\n        mA = _market(30 days);\n        mB = _market(45 days);\n        mC = _market(60 days);\n        idA = IdLib.toId(mA);\n        idB = IdLib.toId(mB);\n        idC = IdLib.toId(mC);\n        _makerBuy(mA, borrowerA, 30_000 * oneToken);\n        _makerBuy(mB, borrowerB, 30_000 * oneToken);\n        _makerBuy(mC, borrowerC, 30_000 * oneToken);\n        vm.warp(block.timestamp + 5 days);\n    }\n\n    function _makerBuy(Market memory market, address b, uint256 assets) internal {\n        uint256 units = assets * WAD / TickLib.tickToPrice(TICK);\n        Offer memory offer = Offer({\n            market: market,\n            buy: true,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: TICK,\n            group: keccak256(abi.encode(\"buy\", IdLib.toId(market), units)),\n            callback: address(adapter),\n            callbackData: abi.encode(address(0), \"\"),\n            receiverIfMakerIsSeller: address(0),\n            ratifier: address(adapter),\n            reduceOnly: false,\n            maxUnits: uint128(units),\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        uint256 collateral = units * 2e18 / oneToken;\n        deal(address(collateralToken), b, collateral);\n        vm.startPrank(b);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, b);\n        midnight.take(offer, ratifierData, units, b, b, address(0), \"\");\n        vm.stopPrank();\n    }\n\n    /// @dev Outsider liquidation realizing partial bad debt in market A (collateral worth 0.6x the debt).\n    function _lossInA() internal {\n        uint256 normalPrice = ORACLE_PRICE_SCALE * oneToken / 1e18;\n        oracle.setPrice(normalPrice * 3 / 10);\n        vm.prank(liquidator);\n        midnight.liquidate(mA, 0, 0, 0, borrowerA, false, liquidator, address(0), \"\");\n        oracle.setPrice(normalPrice);\n        assertGt(midnight.lossFactor(idA), 0, \"lossFactor > 0\");\n        assertLt(midnight.lossFactor(idA), type(uint128).max, \"partial loss\");\n    }\n\n    function _liveNetCredit(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(uint256 netCredit, bytes32 id) internal view returns (uint256) {\n        MarketData memory d = adapter.marketData(id);\n        return netCredit.mulDivDown(WAD, WAD + uint256(d.netRate) * MathLib.zeroFloorSub(uint256(d.maturity), block.timestamp));\n    }\n\n    function _total() internal view returns (uint256) {\n        return adapter.realAssets() + underlyingToken.balanceOf(address(vault));\n    }\n\n    function _sellOffer(Market memory market, uint256 units, 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,\n            tick: tick,\n            group: keccak256(abi.encode(\"sell\", IdLib.toId(market), units, tick)),\n            callback: address(adapter),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: true,\n            maxUnits: uint128(units),\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        rd = abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), new bytes32[](0), address(0)));\n    }\n\n    /// @dev Tick whose price is about 0.4% below the market's current amortized price.\n    function _belowAmortizedTick(bytes32 id) internal view returns (uint256) {\n        uint256 amortizedPrice = _amortized(WAD, id);\n        return TickLib.priceToTick(amortizedPrice * 996 / 1000, midnight.tickSpacing(id));\n    }\n\n    /// @dev Outsider fills a ratified maker sell offer below amortized value and measures realAssets + idle.\n    function _outsiderSale(Market memory market, string memory label) internal {\n        bytes32 id = IdLib.toId(market);\n        uint256 units = SELL_UNITS * oneToken;\n        uint256 tick = _belowAmortizedTick(id);\n        (Offer memory offer, bytes memory rd) = _sellOffer(market, units, tick);\n\n        uint256 live = _liveNetCredit(id);\n        uint256 soldAV = _amortized(live, id) - _amortized(live - units, id);\n        uint256 sellerAssets = units.mulDivUp(TickLib.tickToPrice(tick), WAD);\n        uint256 shortfall = soldAV - sellerAssets;\n        uint256 totalBefore = _total();\n        uint256 allowanceBefore = adapter.shortfallAllowance();\n\n        deal(address(underlyingToken), outsider, sellerAssets);\n        vm.startPrank(outsider);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), sellerAssets);\n        midnight.take(offer, rd, units, outsider, address(0), address(0), \"\");\n        vm.stopPrank();\n\n        uint256 totalAfter = _total();\n        console.log(label);\n        console.log(\"  soldAmortizedValue      \", soldAV);\n        console.log(\"  sellerAssets            \", sellerAssets);\n        console.log(\"  shortfall (price diff)  \", shortfall);\n        console.log(\"  allowance consumed      \", allowanceBefore - adapter.shortfallAllowance());\n        console.log(\"  realAssets+idle before  \", totalBefore);\n        console.log(\"  realAssets+idle after   \", totalAfter);\n        assertGt(shortfall, 0, \"sale below amortized value\");\n        assertEq(allowanceBefore - adapter.shortfallAllowance(), shortfall, \"allowance consumed = shortfall\");\n        _checkChange(totalBefore, totalAfter, shortfall);\n    }\n\n    function _checkChange(uint256 totalBefore, uint256 totalAfter, uint256 shortfall) internal pure {\n        bool up = totalAfter >= totalBefore;\n        uint256 change = up ? totalAfter - totalBefore : totalBefore - totalAfter;\n        console.log(up ? \"  change (+)              \" : \"  change (-)              \", change);\n        // The book value never moves by more than the sale's own price difference.\n        assertLe(change, shortfall, \"change <= shortfall\");\n        // Shortfall spread keeps the book value up to rate rounding. Rates are rounded down (NatSpec :23, :146),\n        // so the book value may rise by rounding only, far below 1e-6 of the shortfall.\n        assertLe(change, shortfall / 1e6, \"spread keeps book value up to rounding\");\n    }\n\n    function _syncA() internal {\n        vm.prank(allocator);\n        vault.deallocate(address(adapter), abi.encode(mA), 0);\n        assertEq(adapter.marketData(idA).netCredit, _liveNetCredit(idA), \"A synced\");\n    }\n\n    /* (1) SHORTFALL SPREAD WITH A LOSS */\n\n    function testLossSnapshot() public {\n        _setupThree();\n        uint256 storedA = adapter.marketData(idA).netCredit;\n        uint256 raBefore = adapter.realAssets();\n        uint256 ftBefore = vault.totalAssets();\n        _lossInA();\n        uint256 liveA = _liveNetCredit(idA);\n        console.log(\"A stored netCredit       \", storedA);\n        console.log(\"A live netCredit         \", liveA);\n        console.log(\"A slashed credit         \", storedA - liveA);\n        console.log(\"realAssets before loss   \", raBefore);\n        console.log(\"realAssets after loss    \", adapter.realAssets());\n        console.log(\"realAssets drop          \", raBefore - adapter.realAssets());\n        console.log(\"amortized slashed credit \", _amortized(storedA, idA) - _amortized(liveA, idA));\n        // The loss is in realAssets immediately, before any sync.\n        assertEq(raBefore - adapter.realAssets(), _amortized(storedA, idA) - _amortized(liveA, idA));\n        vault.accrueInterest();\n        console.log(\"vault totalAssets before \", ftBefore);\n        console.log(\"vault totalAssets after  \", vault.totalAssets());\n        assertLt(vault.totalAssets(), ftBefore, \"loss recorded by next accrual\");\n    }\n\n    function testSaleInLossMarketBeforeSync() public {\n        _setupThree();\n        _lossInA();\n        _outsiderSale(mA, \"sale in loss market A, loss NOT synced\");\n    }\n\n    function testSaleInLossMarketAfterSync() public {\n        _setupThree();\n        _lossInA();\n        _syncA();\n        _outsiderSale(mA, \"sale in loss market A, loss synced\");\n    }\n\n    function testSaleInHealthyMarketBeforeSync() public {\n        _setupThree();\n        _lossInA();\n        _outsiderSale(mB, \"sale in healthy market B, loss in A NOT synced\");\n    }\n\n    function testSaleInHealthyMarketAfterSync() public {\n        _setupThree();\n        _lossInA();\n        _syncA();\n        _outsiderSale(mB, \"sale in healthy market B, loss in A synced\");\n    }\n\n    function testSaleInHealthyMarketNoLossBaseline() public {\n        _setupThree();\n        _outsiderSale(mB, \"baseline: sale in B, no loss anywhere\");\n    }\n\n    /* (2) FORCE DEALLOCATE IN THE LOSS MARKET */\n\n    function testForceDeallocateInLossMarket() public {\n        _setupThree();\n        _lossInA();\n        uint256 deposit = 10_000 * oneToken;\n        deal(address(underlyingToken), outsider, deposit);\n        vm.startPrank(outsider);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(vault), deposit);\n        vault.deposit(deposit, outsider);\n        vm.stopPrank();\n\n        uint256 assets = 5_000 * oneToken;\n        uint256 fee = assets.mulDivUp(midnight.settlementFee(idA, mA.maturity - block.timestamp), WAD);\n        deal(address(underlyingToken), outsider, assets + fee);\n        uint256 liveBefore = _liveNetCredit(idA);\n        uint256 storedBefore = adapter.marketData(idA).netCredit;\n        uint256 raBefore = adapter.realAssets();\n        uint256 idleBefore = underlyingToken.balanceOf(address(vault));\n        uint256 sharesBefore = vault.balanceOf(outsider);\n        uint256 shareValueBefore = vault.previewRedeem(sharesBefore);\n\n        vm.startPrank(outsider);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(adapter), assets + fee);\n        midnight.setIsAuthorized(address(adapter), true, outsider);\n        vault.forceDeallocate(address(adapter), abi.encode(mA, outsider), assets, outsider);\n        vm.stopPrank();\n\n        uint256 creditGot = midnight.credit(idA, outsider);\n        uint256 paid = assets + fee;\n        uint256 raDrop = raBefore - adapter.realAssets();\n        uint256 idleGain = underlyingToken.balanceOf(address(vault)) - idleBefore;\n        console.log(\"outsider paid (assets+fee)       \", paid);\n        console.log(\"outsider credit received (units) \", creditGot);\n        console.log(\"adapter live credit decrease     \", liveBefore - _liveNetCredit(idA));\n        console.log(\"stored netCredit before          \", storedBefore);\n        console.log(\"stored netCredit after           \", adapter.marketData(idA).netCredit);\n        console.log(\"vault idle gain                  \", idleGain);\n        console.log(\"adapter realAssets drop          \", raDrop);\n        console.log(\"penalty shares burned            \", sharesBefore - vault.balanceOf(outsider));\n        console.log(\"outsider share value before      \", shareValueBefore);\n        console.log(\"outsider share value after       \", vault.previewRedeem(vault.balanceOf(outsider)));\n        // Fresh credit is not slashed: one unit per asset paid, priced at face value.\n        assertEq(creditGot, assets, \"credit == assets\");\n        assertEq(midnight.lastLossFactor(idA, outsider), midnight.lossFactor(idA), \"bought after the loss\");\n        assertEq(liveBefore - _liveNetCredit(idA), assets, \"adapter sells exactly assets units of post-loss credit\");\n        assertEq(adapter.marketData(idA).netCredit, _liveNetCredit(idA), \"forceDeallocate syncs stored credit\");\n        // The vault receives face value for discounted credit: remaining holders do not lose.\n        assertGe(idleGain, raDrop, \"vault gains on IKR\");\n        // forceDeallocate cannot take more credit than the adapter holds after the loss (reduceOnly).\n        uint256 tooMuch = _liveNetCredit(idA) + 1;\n        deal(address(underlyingToken), outsider, tooMuch * 2);\n        vm.startPrank(outsider);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(adapter), tooMuch * 2);\n        vm.expectRevert();\n        vault.forceDeallocate(address(adapter), abi.encode(mA, outsider), tooMuch, outsider);\n        vm.stopPrank();\n    }\n\n    /* (3) VAULT CALL FROM A TAKER'S onBuy DURING AN ADAPTER SALE IN THE LOSS MARKET */\n\n    function testDepositInTakerOnBuyDuringLossMarketSale() public {\n        _setupThree();\n        _lossInA();\n        uint256 units = SELL_UNITS * oneToken;\n        (Offer memory offer, bytes memory rd) = _sellOffer(mA, units, TICK);\n\n        VaultCallingTaker strict = new VaultCallingTaker(midnight, vault, address(underlyingToken), false);\n        VaultCallingTaker tolerant = new VaultCallingTaker(midnight, vault, address(underlyingToken), true);\n        deal(address(underlyingToken), address(strict), 2 * units);\n        deal(address(underlyingToken), address(tolerant), 2 * units);\n\n        // Strict taker: its deposit reverts inside onBuy, so its whole take reverts.\n        vm.expectRevert(IMidnightAdapterBase.OtherSellInProgress.selector);\n        strict.takeOffer(offer, rd, units / 2);\n\n        // Other users are not affected, in separate transactions.\n        vm.prank(depositor);\n        vault.withdraw(oneToken, depositor, depositor);\n        deal(address(underlyingToken), outsider, oneToken);\n        vm.startPrank(outsider);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(vault), oneToken);\n        vault.deposit(oneToken, outsider);\n        vm.stopPrank();\n\n        // A taker that catches the revert fills the same offer, and the adapter's sale completes.\n        uint256 liveBefore = _liveNetCredit(idA);\n        tolerant.takeOffer(offer, rd, units / 2);\n        assertTrue(tolerant.depositFailed(), \"deposit inside onBuy failed\");\n        assertEq(tolerant.failSelector(), IMidnightAdapterBase.OtherSellInProgress.selector);\n        assertEq(liveBefore - _liveNetCredit(idA), units / 2, \"sale went through\");\n\n        // A plain outsider fills the rest of the offer.\n        uint256 rest = units - units / 2;\n        uint256 cost = rest.mulDivUp(TickLib.tickToPrice(TICK), WAD);\n        deal(address(underlyingToken), outsider, cost);\n        vm.startPrank(outsider);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), cost);\n        midnight.take(offer, rd, rest, outsider, address(0), address(0), \"\");\n        vm.stopPrank();\n        assertEq(liveBefore - _liveNetCredit(idA), units, \"offer fully filled\");\n        console.log(\"strict taker: take reverted with OtherSellInProgress\");\n        console.log(\"tolerant taker: deposit failed, take filled units\", units / 2);\n        console.log(\"outsider filled remaining units\", rest);\n    }\n\n    /// @dev Contrast: during a sale in healthy market B (lossFactor 0), the same deposit in onBuy works.\n    function testDepositInTakerOnBuyDuringHealthySaleWorks() public {\n        _setupThree();\n        _lossInA();\n        uint256 units = SELL_UNITS * oneToken;\n        (Offer memory offer, bytes memory rd) = _sellOffer(mB, units, TICK);\n        VaultCallingTaker strict = new VaultCallingTaker(midnight, vault, address(underlyingToken), false);\n        deal(address(underlyingToken), address(strict), 2 * units);\n        strict.takeOffer(offer, rd, units / 2);\n        assertGt(vault.balanceOf(address(strict)), 0, \"deposited during B sale\");\n    }\n\n    /* (4) ENTER / LEAVE AROUND A RECORDED LOSS */\n\n    function testExitInSameTxAsLossUsesCachedPrice() public {\n        _setupThree();\n        uint256 deposit = 20_000 * oneToken;\n        SameTxExiter exiter = new SameTxExiter(midnight, vault, address(underlyingToken), address(oracle));\n        deal(address(underlyingToken), address(exiter), deposit);\n        exiter.enter(deposit);\n        uint256 shares = vault.balanceOf(address(exiter));\n\n        uint256 snap = vm.snapshotState();\n        // (a) accrue first, then realize the loss, then redeem, all in one transaction.\n        uint256 normalPrice = ORACLE_PRICE_SCALE * oneToken / 1e18;\n        uint256 gotSameTx = exiter.accrueLiquidateRedeem(mA, borrowerA, normalPrice * 3 / 10, normalPrice);\n        vm.revertToState(snap);\n        // (b) redeem in a transaction before the loss: the same amount.\n        vm.prank(address(exiter));\n        uint256 gotBefore = vault.redeem(shares, address(exiter), address(exiter));\n        vm.revertToState(snap);\n        // (c) redeem in a transaction after the loss.\n        oracle.setPrice(normalPrice * 3 / 10);\n        vm.prank(liquidator);\n        midnight.liquidate(mA, 0, 0, 0, borrowerA, false, liquidator, address(0), \"\");\n        oracle.setPrice(normalPrice);\n        vm.prank(address(exiter));\n        uint256 gotAfter = vault.redeem(shares, address(exiter), address(exiter));\n\n        console.log(\"redeem before loss (separate tx)    \", gotBefore);\n        console.log(\"accrue+liquidate+redeem in one tx   \", gotSameTx);\n        console.log(\"redeem after loss (separate tx)     \", gotAfter);\n        console.log(\"loss avoided by exiting first       \", gotBefore - gotAfter);\n        assertEq(gotSameTx, gotBefore, \"same-tx exit == exit before the loss\");\n        assertLt(gotAfter, gotBefore, \"exit after the loss bears it\");\n    }\n}\n\ncontract VaultCallingTaker is IBuyCallback {\n    IMidnight internal midnight;\n    IVaultV2 internal vault;\n    address internal token;\n    bool internal tolerant;\n    bool public depositFailed;\n    bytes4 public failSelector;\n\n    constructor(IMidnight _midnight, IVaultV2 _vault, address _token, bool _tolerant) {\n        (midnight, vault, token, tolerant) = (_midnight, _vault, _token, _tolerant);\n        SafeERC20Lib.safeApprove(token, address(midnight), type(uint256).max);\n        SafeERC20Lib.safeApprove(token, address(vault), type(uint256).max);\n    }\n\n    function takeOffer(Offer memory offer, bytes memory rd, uint256 units) external {\n        midnight.take(offer, rd, units, address(this), address(0), address(this), \"\");\n    }\n\n    function onBuy(bytes32, Market memory, uint256, uint256, uint256, address, bytes memory)\n        external\n        returns (bytes32)\n    {\n        if (tolerant) {\n            try vault.deposit(1e6, address(this)) {}\n            catch (bytes memory err) {\n                depositFailed = true;\n                failSelector = bytes4(err);\n            }\n        } else {\n            vault.deposit(1e6, address(this));\n        }\n        return keccak256(\"morpho.midnight.callbackSuccess\");\n    }\n}\n\ncontract SameTxExiter {\n    IMidnight internal midnight;\n    IVaultV2 internal vault;\n    address internal token;\n    OracleMock internal oracle;\n\n    constructor(IMidnight _midnight, IVaultV2 _vault, address _token, address _oracle) {\n        (midnight, vault, token, oracle) = (_midnight, _vault, _token, OracleMock(_oracle));\n    }\n\n    function enter(uint256 assets) external {\n        SafeERC20Lib.safeApprove(token, address(vault), assets);\n        vault.deposit(assets, address(this));\n    }\n\n    /// @dev The oracle moves are test scaffolding standing in for a real price drop.\n    function accrueLiquidateRedeem(Market memory m, address borrower, uint256 lowPrice, uint256 normalPrice)\n        external\n        returns (uint256)\n    {\n        vault.accrueInterest();\n        oracle.setPrice(lowPrice);\n        midnight.liquidate(m, 0, 0, 0, borrower, false, address(this), address(0), \"\");\n        oracle.setPrice(normalPrice);\n        return vault.redeem(vault.balanceOf(address(this)), address(this), address(this));\n    }\n}\n"
}
